已经有很多答案可以解决如何做这件普通的事情,但我的主要问题是,为什么这种方法不起作用?
我试图从子进程中“动态流”stdout和stderr。我可以这样做:
import sys
import subprocess
def run_command(cmd):
process = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
for out in iter(process.stdout.readline, b''):
print(out)
for err in iter(process.stderr.readline, b''):
print(err)
run_command(['echo', 'hello', 'world']) # should print hello world
run_command(['rm', 'blarg223']) # Should print to stderr (file doesnt exist)这个工作给了我一个结果:
b'hello world\n'
b'rm: cannot remove \xe2\x80\x98blarg223\xe2\x80\x99: No such file or directory\n'然而,这会导致一个问题,因为它实际上只运行流的stdout,然后打印所有的错误作为结束。所以我想我可以用:
def run_command(cmd):
process = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
for out, err in zip(iter(process.stdout.readline, b''), iter(process.stderr.readline, b'')):
print(out)
print(b'Error: ' + err)但是,这不会产生任何产出。为什么使用zip不起作用?
发布于 2016-01-13 21:52:10
当一个迭代器完成时,zip就停止了。
在您给出的每个示例中,一个流(stdout/stderr)为空。所以拉链不会产生任何结果。
要解决这个问题,您应该使用itertools.zip_longest
https://stackoverflow.com/questions/34777660
复制相似问题