【发布时间】:2023-01-19 22:01:27
【问题描述】:
概括:我想从 Python(3.6 版)启动一个外部进程,非阻塞地轮询结果,并在超时后终止。
细节:有一个外部过程有两个“坏习惯”:
- 它在未定义的时间后打印出相关结果。
- 打印出结果后不停止。
例子:也许下面的简单应用程序大部分类似于要调用的实际程序(
mytest.py;源代码不可用):import random import time print('begin') time.sleep(10*random.random()) print('result=5') while True: pass这就是我试图称呼它的方式:
import subprocess, time myprocess = subprocess.Popen(['python', 'mytest.py'], stdout=subprocess.PIPE) for i in range(15): time.sleep(1) # check if something is printed, but do not wait to be printed anything # check if the result is there # if the result is there, then break myprocess.kill()我想在评论中实现逻辑。
分析
以下是不合适的:
- 使用
myprocess.communicate(),因为它等待终止,而子进程不会终止。 - 杀掉进程然后调用
myprocess.communicate(),因为我们不知道具体什么时候打印出结果 - 使用
process.stdout.readline()因为那是一个 blocikg 语句,所以它会一直等到打印出一些东西。但这里最后不打印任何东西。
myprocess.stdout的类型是io.BufferedReader。所以问题实际上是:有没有办法检查是否有东西打印到io.BufferedReader,如果是,请阅读它,否则不要等待? - 使用
【问题讨论】:
标签: python subprocess