我有来自https://pymotw.com/2/subprocess/的代码
我不知道如何解释代码,在check_output中,1>&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 stdoutEDIT2
我用stderr库(https://github.com/sickill/stderred)进行了更多的测试,它帮助shell以红色显示stderr中的字符。
当我执行这段代码(注释掉重定向)时,我可以看到黑色的to stderr,这意味着它使用stdout。
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中。

发布于 2015-09-25 20:07:23
1 >&2外壳代码仅应用于它显示的(echo)命令。它是如何告诉shell将该回声的输出定向到shell的stderr流。
python代码stderr=subprocess.STDOUT告诉子流程模块,您希望进程的stderr流与它的stdout流是相同的文件描述符,这样您就可以读取进程写到一个流中的任意流的任何内容。
shell命令中的exit 1意味着shell以错误(非零)状态退出。
代码的目的是演示python函数subprocess.check_output将检查退出状态,并在非零时引发异常。
如果退出代码为非零,则会引发CalledProcessError。CalledProcessError对象将在返回代码属性中包含返回代码,在输出属性中具有输出。
你对以下方面的描述:
运行代码,则不执行打印命令。
有一点误导,因为您忽略了提到确实发生的输出:
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 1https://stackoverflow.com/questions/32789764
复制相似问题