可能重复:
subprocess with timeout
在Python中执行以下操作的最简单方法是什么:
我想要这样的事情:
import proc
try:
status, stdout, stderr = proc.run(["ls", "-l"], timeout=10)
except proc.Timeout:
print "failed"
答案 0 :(得分:13)
我讨厌独自完成这项工作。只需将其复制到proc.py模块中即可。
import subprocess
import time
import sys
class Timeout(Exception):
pass
def run(command, timeout=10):
proc = subprocess.Popen(command, bufsize=0, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
poll_seconds = .250
deadline = time.time()+timeout
while time.time() < deadline and proc.poll() == None:
time.sleep(poll_seconds)
if proc.poll() == None:
if float(sys.version[:3]) >= 2.6:
proc.terminate()
raise Timeout()
stdout, stderr = proc.communicate()
return stdout, stderr, proc.returncode
if __name__=="__main__":
print run(["ls", "-l"])
print run(["find", "/"], timeout=3) #should timeout
答案 1 :(得分:11)
关于使用coreutils&gt; = 7.0的linux的注意事项,您可以在命令之前添加超时,如:
timeout 1 sleep 1000