Python 带有“1>&2”和 stderr=STDOUT 的子进程

Python's subprocess with "1>&2" and stderr=STDOUT

我有来自 https://pymotw.com/2/subprocess/

的代码

我不确定如何解释代码,在 check_output1>&2 输出被重定向到 stderr,但在参数中,stderr 返回到 stdout stderr=subprocess.STDOUT.

output = subprocess.check_output(
    'echo to stdout; echo to stderr 1>&2; exit 1',
    shell=True,  
    stderr=subprocess.STDOUT, 
    )
print "*****************"
print 'Have %d bytes in output' % len(output)
print output

运行 代码,不执行打印命令意味着没有捕获任何内容。

这段代码试图完成什么?

编辑

根据回答和评论,我可以运行这段代码得到

try:
    output = subprocess.check_output(
        'echo to stdout; echo to stderr 1>&2; exit 1',
        shell=True,  # No such file or directory error without, maybe 1>&2 requires shell=True
        stderr=subprocess.STDOUT,  
        )

except subprocess.CalledProcessError as e:

    print "*****************"
    print 'Have %d bytes in output' % len(e.output)
    print e.output

这个输出:

*****************
Have 20 bytes in output
to stdout
to stderr

然而,当我注释掉 stderr=subprocess.STDOUT 行时,我得到的是

to stderr
*****************
Have 10 bytes in output
to stdout

编辑2

我使用 stderr 库 (https://github.com/sickill/stderred) 进行了更多测试,它帮助 shell 以红色显示来自 stderr 的字符。

当我执行此代码(注释掉重定向)时,我可以看到黑色的 to stderr,这意味着它使用标准输出。

output = subprocess.check_output(
        'echo to stdout; echo to stderr 1>&2; exit 1',
        shell=True,  
        #stderr=subprocess.STDOUT, 
        )

据此,我猜想(如果我错了请纠正我)Python 的 check_output 方法将数据打印到 stderr 重定向到 stdout,以便它打印出错误消息到 stderr。

1 >&2 shell 代码仅适用于它出现的 (echo) 命令。它是如何告诉 shell 将该回显的输出定向到 shell 的标准错误流。

python 代码 stderr=subprocess.STDOUT 告诉子进程模块您希望进程的 stderr 流与其 stdout 流是相同的文件描述符,以便您将读取进程写入任一流的任何内容在一个流中交织在一起。

shell命令中的exit 1表示shell以错误(非零)状态退出。

该代码的目的是演示 python 函数 subprocess.check_output 将检查退出状态并在非零时引发异常。

If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute.

您的描述:

Running the code, the print commands are not executed

有点误导,因为您忽略了确实发生的输出:

Traceback (most recent call last):
  File "t.py", line 6, in <module>
    stderr=subprocess.STDOUT, 
  File "/usr/lib/python2.7/subprocess.py", line 573, in check_output
    raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command 'echo to stdout; echo to stderr 1>&2; exit 1' returned non-zero exit status 1