我会建议采取看看
Timer类中
threading的模块。我用它来实现超时
Popen。
首先,创建一个回调:
def timeout( p ): if p.poll() is None: print 'Error: process taking too long to complete--terminating' p.kill()
然后打开过程:
proc = Popen( ... )
然后创建一个计时器,该计时器将调用回调,并将过程传递给它。
t = threading.Timer( 10.0, timeout, [proc] )t.start()t.join()
在程序后面的某个位置,您可能需要添加以下行:
t.cancel()
否则,python程序将继续运行,直到计时器运行完毕。
编辑:我被告知,
subprocess
p在
p.poll()和条件之间可能存在可能终止的竞争条件
p.kill()。我相信以下代码可以解决此问题:
import errnodef timeout( p ): if p.poll() is None: try: p.kill() print 'Error: process taking too long to complete--terminating' except OSError as e: if e.errno != errno.ESRCH: raise
尽管您可能希望清除异常处理以专门处理子过程已经正常终止时发生的特定异常。



