我有一个小问题,我不是很清楚如何解决。 下面是一个小例子:
是)我有的
scan_process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while(some_criterium):
line = scan_process.stdout.readline()
some_criterium = do_something(line)
我想
scan_process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while(some_criterium):
line = scan_process.stdout.readline()
if nothing_happens_after_10s:
break
else:
some_criterium = do_something(line)
我读从子行,并用它做什么。 我要的是退出,如果在固定的时间间隔后没有到达线。 任何建议?
Answer 1:
感谢所有的答案! 我找到了一种方法简单地使用select.poll窥视标准输出解决我的问题。
import select
...
scan_process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
poll_obj = select.poll()
poll_obj.register(scan_process.stdout, select.POLLIN)
while(some_criterium and not time_limit):
poll_result = poll_obj.poll(0)
if poll_result:
line = scan_process.stdout.readline()
some_criterium = do_something(line)
update(time_limit)
Answer 2:
下面是强制超时阅读使用单行便携式解决方案asyncio
:
#!/usr/bin/env python3
import asyncio
import sys
from asyncio.subprocess import PIPE, STDOUT
async def run_command(*args, timeout=None):
# start child process
# NOTE: universal_newlines parameter is not supported
process = await asyncio.create_subprocess_exec(*args,
stdout=PIPE, stderr=STDOUT)
# read line (sequence of bytes ending with b'\n') asynchronously
while True:
try:
line = await asyncio.wait_for(process.stdout.readline(), timeout)
except asyncio.TimeoutError:
pass
else:
if not line: # EOF
break
elif do_something(line):
continue # while some criterium is satisfied
process.kill() # timeout or some criterium is not satisfied
break
return await process.wait() # wait for the child process to exit
if sys.platform == "win32":
loop = asyncio.ProactorEventLoop() # for subprocess' pipes on Windows
asyncio.set_event_loop(loop)
else:
loop = asyncio.get_event_loop()
returncode = loop.run_until_complete(run_command("cmd", "arg 1", "arg 2",
timeout=10))
loop.close()
Answer 3:
我用的东西有点在Python更普遍(IIRC也从SO问题拼凑在一起,但我不记得哪一个)。
import thread
from threading import Timer
def run_with_timeout(timeout, default, f, *args, **kwargs):
if not timeout:
return f(*args, **kwargs)
try:
timeout_timer = Timer(timeout, thread.interrupt_main)
timeout_timer.start()
result = f(*args, **kwargs)
return result
except KeyboardInterrupt:
return default
finally:
timeout_timer.cancel()
被警告,虽然,这使用中断阻止你给它的任何功能。 这可能不是所有的功能是个好主意,它也可以防止您的超时期间关闭与CTRL + C程序(即CTRL + C将作为超时处理),你可以使用这个方法的调用它:
scan_process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while(some_criterium):
line = run_with_timeout(timeout, None, scan_process.stdout.readline)
if line is None:
break
else:
some_criterium = do_something(line)
可能是有点矫枉过正,但。 我怀疑有你的情况,我不知道一个简单的选择。
Answer 4:
在Python 3,超时选项已被添加到该子模块。 使用类似的结构
try:
o, e = process.communicate(timeout=10)
except TimeoutExpired:
process.kill()
o, e = process.communicate()
analyze(o)
将是一个妥善的解决办法。
由于产量预计将包含新行字符,就可以安全地假定它是文本(如打印,读取),在这种情况下universal_newlines=True
标志,强烈推荐。
如果Python2是必须的,请使用https://pypi.python.org/pypi/subprocess32/ (反向移植)
对于纯Python Python 2中的溶液,看使用模块“子”与超时 。
Answer 5:
尝试使用signal.alarm:
#timeout.py
import signal,sys
def timeout(sig,frm):
print "This is taking too long..."
sys.exit(1)
signal.signal(signal.SIGALRM, timeout)
signal.alarm(10)
byte=0
while 'IT' not in open('/dev/urandom').read(2):
byte+=2
print "I got IT in %s byte(s)!" % byte
一对夫妇的运行,以显示它的工作原理:
$ python timeout.py
This is taking too long...
$ python timeout.py
I got IT in 4672 byte(s)!
如需更详细的例子中看到pGuides 。
Answer 6:
便携式解决方案是使用一个线程来杀子过程中,如果读行时间过长:
#!/usr/bin/env python3
from subprocess import Popen, PIPE, STDOUT
timeout = 10
with Popen(command, stdout=PIPE, stderr=STDOUT,
universal_newlines=True) as process: # text mode
# kill process in timeout seconds unless the timer is restarted
watchdog = WatchdogTimer(timeout, callback=process.kill, daemon=True)
watchdog.start()
for line in process.stdout:
# don't invoke the watcthdog callback if do_something() takes too long
with watchdog.blocked:
if not do_something(line): # some criterium is not satisfied
process.kill()
break
watchdog.restart() # restart timer just before reading the next line
watchdog.cancel()
其中WatchdogTimer
类就像threading.Timer
时可以重新启动和/或封端:
from threading import Event, Lock, Thread
from subprocess import Popen, PIPE, STDOUT
from time import monotonic # use time.time or monotonic.monotonic on Python 2
class WatchdogTimer(Thread):
"""Run *callback* in *timeout* seconds unless the timer is restarted."""
def __init__(self, timeout, callback, *args, timer=monotonic, **kwargs):
super().__init__(**kwargs)
self.timeout = timeout
self.callback = callback
self.args = args
self.timer = timer
self.cancelled = Event()
self.blocked = Lock()
def run(self):
self.restart() # don't start timer until `.start()` is called
# wait until timeout happens or the timer is canceled
while not self.cancelled.wait(self.deadline - self.timer()):
# don't test the timeout while something else holds the lock
# allow the timer to be restarted while blocked
with self.blocked:
if self.deadline <= self.timer() and not self.cancelled.is_set():
return self.callback(*self.args) # on timeout
def restart(self):
"""Restart the watchdog timer."""
self.deadline = self.timer() + self.timeout
def cancel(self):
self.cancelled.set()
Answer 7:
而你(汤姆)解决方案的工作原理,使用select()
在C
成语更加紧凑。 这是你的答案相当于
from select import select
scan_process = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
bufsize=1) # line buffered
while some_criterium and not time_limit:
poll_result = select([scan_process.stdout], [], [], time_limit)[0]
其余的都是一样的。
见pydoc select.select
。
[注:这是Unix的特定的,因为有一些其他的答案。]
[注2:编辑以添加行缓冲按照OP请求]
[注3:行缓冲可能不是在所有情况下可靠,导致的ReadLine()阻挡]
文章来源: timeout on subprocess readline in python