问题描述
Popen 输出总是在过程完成后立即以字节数组的形式到达,我尝试了几种配置,包括使用标准输出文件。
要创建进度条,我想一一接收输出。在此示例中,只有一个 p.stdout.read()
以字节数组的形式返回所有 1
。
# shell.py
import sys,time
for _ in range(5):
print(1)
time.sleep(0.5)
sys.stdout.flush()
# code.py
from subprocess import Popen,PIPE
p = Popen(['python','shell.py'],stdin = PIPE,stdout = PIPE,stderr = PIPE,shell = False,bufsize=1)
output = p.stdout.read()
while output:
print('output:',output)
output = p.stdout.read()
解决方法
您可以指定 read() 将读取多少字节。如果您在 code.py 中使用 p.stdout.read(1),您的代码将如您所愿。注意python的print函数在shell.py的输出中添加了换行符,所以code.py会打印出来:
output: b'1'
output: b'\n'
output: b'1'
output: b'\n'
output: b'1'
output: b'\n'
另外值得一提的是,这将读取字节。如果你想要一个一个的 unicode 字符,你必须自己做一些处理。