Onway

我是一只菜菜菜菜鸟...
posts - 61, comments - 56, trackbacks - 0, articles - 34

python子进程时间限制

Posted on 2013-05-10 21:26 Onway 阅读(2717) 评论(0)  编辑 收藏 引用 所属分类: 码儿快跑
python程序里面需要执行一个系统命令程序,如果命令在限定时间之内结束,则python程序读取其输出(如果有)并马上返回,否则强行终止命令程序。
原本这个功能是用系统信号SIGALARM和python的异常解决的,但这不能用在多线程的环境里。然后考虑用threading.Timer进行计时,但这个计时是在一个单独线程进行的,如何将超时信息传给主线程也是一个问题。
百度一下,用select可以解决需求:
但select并不完美,当命令程序输出的内容多于管道容量的时候,select就会返回,如果此时命令程序再进入阻塞,则时间限制就不起作用了。

select.py:
import select
import subprocess

popen = subprocess.Popen("./test.sh", stdout=subprocess.PIPE)
fs = select.select([popen.stdout], [], [], 3)
if popen.stdout in fs[0]:
    output = popen.stdout.read()
    print len(output)
else:
    print "timeout"

test.sh:
#!/bin/bash

# a.txt contains 65536 characters

cat a.txt
sleep 10
cat a.txt

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理