繁体   English   中英

Python:readline()使用Popen()调用进程时收到垃圾邮件

[英]Python: Junk received when readline() a process called with Popen()

我需要将文件的输出流式传输到列表中,我获得了正确的数据,但是最后却有很多垃圾,并且不了解我在做什么错。

(我认为很简单)popen代码是:

stream = []
p = Popen(["python", "-u", "test.py"], stdout=PIPE, bufsize=1)

while p.poll() is None:
    stream.append(p.stdout.readline())

print stream
print 'Returned: {0}'.format(p.returncode)

调用此命令的输出是:

运行它的输出是:

['[INDEX 0] Current index position\n', '[INDEX 1] Current index position\n', '[INDEX 2] Current index position\n', '[INDEX 3] Current index position\n', '[INDEX 4] Current index position\n', 'exiting.
...\n', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '']
Returned: -4

Test.py是:

index = 0

while True:
    print '[INDEX {0}] Current index position'.format(index)
    index += 1
    if index == 5: break

import sys
print 'exiting....'
sys.exit(-4)

这里的问题是您的if条件不正确:

while p.poll() is None:
    stream.append(p.stdout.readline())

这意味着“在进程运行时,请读一行”。 但这不是您想要的。 您真正想要的是“当有更多输出时,请读一行”。 您编写的代码在进程关闭时读取空行,因此所有空字符串都来自此行。

相反,您应该做的是:

for line in p.stdout:
    stream.append(line)

当没有更多输出时,这将正确停止读取行,并保证读取所有输出。 (理论上,如果该过程产生的输出比您处理它的速度更快,则您的代码可能会在处理完所有输出之前退出循环。您可以通过在循环中添加time.sleep(0.1)来模拟此过程。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM