python:运行带有超时的进程并捕获stdout,stderr和退出状态 [英] python: run a process with timeout and capture stdout, stderr and exit status
本文介绍了python:运行带有超时的进程并捕获stdout,stderr和退出状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
带有超时的子流程
Possible Duplicate:
subprocess with timeout
在Python中执行以下操作的最简单方法是什么:
What is the easiest way to do the following in Python:
- 运行外部进程
- 以字符串,stderr和退出状态捕获标准输出
- 设置超时时间.
我想要这样的东西:
import proc
try:
status, stdout, stderr = proc.run(["ls", "-l"], timeout=10)
except proc.Timeout:
print "failed"
推荐答案
我讨厌自己做这项工作.只需将其复制到您的proc.py模块中即可.
I hate doing the work by myself. Just copy this into your proc.py module.
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
这篇关于python:运行带有超时的进程并捕获stdout,stderr和退出状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文