Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.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流子进程stdout和stderr zip不起作用_Python_Python 3.x_Subprocess - Fatal编程技术网

python流子进程stdout和stderr zip不起作用

python流子进程stdout和stderr zip不起作用,python,python-3.x,subprocess,Python,Python 3.x,Subprocess,已经有很多答案解决了如何做这件事,但我的主要问题是为什么这种方法不起作用 我正在尝试从子流程“实时流”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.readl

已经有很多答案解决了如何做这件事,但我的主要问题是为什么这种方法不起作用

我正在尝试从子流程“实时流”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不起作用?

当其中一个迭代器完成时,zip停止

在您给出的每个示例中,有一个流(stdout/stderr)是空的。所以zip不会产生任何效果


要解决这个问题,您应该使用itertools.zip_longest

您是否希望stdout和stderr行之间始终有一对一的对应关系?您正在尝试成对地获取行。如果stdout/stderr不产生相同数量的输出(大于阈值),这两个代码示例都可能导致死锁@J.F.Sebastian如何?我已经测试过了,它似乎有效。你能举一个死锁是如何发生的例子吗?@NickHumrich:如果你不能创建一个产生死锁的例子,请另外问一个问题。@NickHumrich:
zip\u longest()
在一般情况下不会修复死锁。问题中的代码被破坏了。如果您想将stdout/stderr单独读取为“实时流”;您应该同时阅读管道,例如,或使用