我在Python2.7中使用sub.Popen
但是,Python3有超时,而Python2.7不行。
这是我的片段。
proc = sub.Popen(['some command', 'some params'], stdout=sub.PIPE)
try:
for row in proc.stdout:
print row.rstrip() # process here
result = str(row.rstrip())
count += 1
if count > 10:
break
except:
print 'tcpdump error'
proc.terminate()
如何设置超时。
最佳答案
基于this blog post代码进行了一些更改,您可以使用 threading.Thread:
from threading import Thread
from subprocess import PIPE, Popen
def proc_timeout(secs, *args):
proc = Popen(args, stderr=PIPE, stdout=PIPE)
proc_thread = Thread(target=proc.wait)
proc_thread.start()
proc_thread.join(secs)
if proc_thread.is_alive():
try:
proc.kill()
except OSError:
return proc.returncode
print('Process #{} killed after {} seconds'.format(proc.pid, secs))
return proc
您应该只在 try/except 中捕获特定的异常,而不是 try catch 所有异常。
关于python - 使用子进程时如何超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29316426/