Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Popen的流式输出_Python_Subprocess_Popen - Fatal编程技术网

Python Popen的流式输出

Python Popen的流式输出,python,subprocess,popen,Python,Subprocess,Popen,Popen输出总是在进程完成后立即以字节数组的形式到达,我尝试了几种配置,包括为stdout使用文件 要创建进度条,我希望逐个接收输出。在本例中,只有一个p.stdout.read()以字节数组的形式返回所有1 #shell.py 导入系统,时间 对于范围(5)内的uu: 印刷品(1) 睡眠时间(0.5) sys.stdout.flush() #code.py 从子流程导入Popen、PIPE p=Popen(['python','shell.py'], stdin=PIPE,stdout

Popen输出总是在进程完成后立即以字节数组的形式到达,我尝试了几种配置,包括为stdout使用文件

要创建进度条,我希望逐个接收输出。在本例中,只有一个
p.stdout.read()
以字节数组的形式返回所有
1

#shell.py
导入系统,时间
对于范围(5)内的uu:
印刷品(1)
睡眠时间(0.5)
sys.stdout.flush()

#code.py
从子流程导入Popen、PIPE
p=Popen(['python','shell.py'],
stdin=PIPE,stdout=PIPE,stderr=PIPE,shell=False,bufsize=1)
输出=p.stdout.read()
输出时:
打印('输出:',输出)
输出=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字符,你必须自己做一些处理。

你可以指定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字符,你必须自己进行一些处理。

想知道这是如何实现的。我还尝试过将stdout发送到一个文件,然后对该文件进行
cat
ing处理,看看会发生什么。似乎stdout没有流式传输到文件,只是在进程结束时才转储,传递BytesIO或StringIO对象似乎会产生错误。我想知道这是如何工作的。我还尝试过将stdout发送到一个文件,然后对该文件进行
cat
ing处理,看看会发生什么。似乎stdout不会流式传输到文件,而是仅在进程结束时转储,传递BytesIO或StringIO对象似乎会产生错误