python:运行超时进程并捕获标准输出、标准错误和退出状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1556348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python: run a process with timeout and capture stdout, stderr and exit status
提问by flybywire
Possible Duplicate:
subprocess with timeout
可能的重复:
超时的子进程
What is the easiest way to do the following in Python:
在 Python 中执行以下操作的最简单方法是什么:
- Run an external process
- Capture stdout in a string, stderr, and exit status
- Set a timeout.
- 运行外部进程
- 捕获字符串中的 stdout、stderr 和退出状态
- 设置超时。
I would like something like this:
我想要这样的东西:
import proc
try:
status, stdout, stderr = proc.run(["ls", "-l"], timeout=10)
except proc.Timeout:
print "failed"
回答by flybywire
I hate doing the work by myself. Just copy this into your proc.py module.
我讨厌自己做这项工作。只需将其复制到您的 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
回答by pixelbeat
Note on linux with coreutils >= 7.0 you can prepend timeout to the command like:
请注意,在 coreutils >= 7.0 的 linux 上,您可以在命令前添加超时,例如:
timeout 1 sleep 1000