有没有办法轮询subprocess.Popen返回的文件句柄?
假设我写了这个:
from subprocessing import Popen, STDOUT, PIPE
p = Popen(["myproc"], stderr=STDOUT, stdout=PIPE)
现在如果我执行
line = p.stdout.readline()
我的程序会等到子进程输出下一行内容。
有没有什么办法可以让我处理 p.stdout
,这样我就能在有输出的时候读取它,但如果没有输出就继续执行?我想要的功能有点像 Queue.get_nowait()
。
我知道我可以创建一个线程来读取 p.stdout
,但假设我不能创建新的线程。
2 个回答
8
使用 p.stdout.read(1)
这个方法可以一个一个字符地读取数据。
下面是一个完整的例子:
import subprocess
import sys
process = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
while True:
out = process.stdout.read(1)
if out == '' and process.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
5
在Python的标准库中使用select
模块,具体可以查看这个链接:http://docs.python.org/library/select.html。使用select.select([p.stdout.fileno()], [], [], 0)
这行代码,会立刻返回一个包含三个列表的元组:第一个列表如果有内容可读的话,就会有东西在里面。