Python子进程超时? [英] Python subprocess timeout?
问题描述
是否有任何参数或选项可为Python的subprocess.Popen方法设置超时?
Is there any argument or options to setup a timeout for Python's subprocess.Popen method?
类似这样的东西:
subprocess.Popen(['..'], ..., timeout=20)
?
推荐答案
我建议您看一下 Timer
类.我用它来实现Popen
的超时.
I would advise taking a look at the Timer
class in the threading
module. I used it to implement a timeout for a Popen
.
首先,创建一个回调:
def timeout( p ):
if p.poll() is None:
print 'Error: process taking too long to complete--terminating'
p.kill()
然后打开该过程:
proc = Popen( ... )
然后创建一个计时器,该计时器将调用回调并将流程传递给它.
Then create a timer that will call the callback, passing the process to it.
t = threading.Timer( 10.0, timeout, [proc] )
t.start()
t.join()
程序后面的某个地方,您可能要添加以下行:
Somewhere later in the program, you may want to add the line:
t.cancel()
否则,python程序将一直运行,直到计时器完成运行为止.
Otherwise, the python program will keep running until the timer has finished running.
我被告知存在一个竞争条件,subprocess
p
可能在p.poll()
和p.kill()
调用之间终止.我相信以下代码可以解决此问题:
I was advised that there is a race condition that the subprocess
p
may terminate between the p.poll()
and p.kill()
calls. I believe the following code can fix that:
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
尽管您可能希望清除异常处理以专门处理子流程已经正常终止时发生的特定异常.
Though you may want to clean the exception handling to specifically handle just the particular exception that occurs when the subprocess has already terminated normally.
这篇关于Python子进程超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!