Python中子进程读取线超时
问题描述
我有一个小问题,我不太确定如何解决.这是一个最小的例子:
I have a small issue that I'm not quite sure how to solve. Here is a minimal example:
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)
我从子进程中读取了一行并对其进行了处理.如果在固定时间间隔后没有线路到达,我该如何退出?
I read a line from a subprocess and do something with it. How can I exit if no line arrived after a fixed time interval?
解决方案
感谢大家的回答!
我找到了一种方法来解决我的问题,只需使用 select.poll 来查看标准输出.
I found a way to solve my problem by simply using select.poll to peek into standard output.
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)
相关文章