我会建议采取看看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 errno
def 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
尽管您可能希望清除异常处理以专门处理子过程已经正常终止时发生的特定异常。