python - Python中子进程读取线超时

标签 python timeout subprocess

我有一个小问题,我不太确定如何解决。这是一个最小的例子:

我有什么

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)

我从子进程中读取了一行并对其进行了处理。如果在固定时间间隔后没有线路到达,我该如何退出?

最佳答案

感谢大家的回答!

我找到了一种方法来解决我的问题,只需使用 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)

关于python - Python中子进程读取线超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10756383/

相关文章:

python - 使用 Python 的 Autodesk Inventor API

python - 查找列表条目 Python 的公分母

https - 在 Angular2 http 模块中增加一个 http get 请求连接超时

python - 如何统一stdout和stderr,同时又能够区分它们?

Python 'subprocess' CalledProcessError : Command '[...]' returned non-zero exit status 1

python - 检测灰度图像中是否存在黑色区域

python - Google API 客户端 secret 错误(Python)

linux - Odoo超时杀死cron

java - 如何在不暂停整个程序的情况下暂停方法?

python - 如何确定通过 Python 运行的程序(最好是子进程)是否崩溃或成功结束