繁体   English   中英

Python subprocess.check_output stderr用法

[英]Python subprocess.check_output stderr usage

嗨,我是Python的新手,我试图了解stderr如何与子进程check_output一起使用。 我已经阅读了子进程文档,并且很难理解stderr的使用方式以及subprocess.STDOUT实际完成的内容。

我可以请一些帮助解释stderr如何在这里使用的示例或参考资料吗?

我已经使用stderr和没有看到任何真正的差异尝试了这些命令。

码:

#!/usr/bin/python3
import subprocess

print(subprocess.check_output("echo Hello World!",
                              stderr=subprocess.STDOUT,
                              shell=True))

输出:

# ./ex.py
b'Hello World!\n'

码:

#!/usr/bin/python3
import subprocess

print(subprocess.check_output("gecho Hello World!",
                              stderr=subprocess.STDOUT,
                              shell=True))

输出:

# ./ex.py
Traceback (most recent call last):
  File "./ex.py", line 6, in <module>
    shell=True))
  File "/usr/lib64/python3.3/subprocess.py", line 589, in check_output
    raise CalledProcessError(retcode, process.args, output=output)
subprocess.CalledProcessError: Command 'gecho Hello World!' returned non-zero exit status 127

如果存在非零退出代码, subprocess.check_output将引发您看到的异常。 这听起来像你想要的是一个简单的方法来读取STDERR,在这种情况下最简单的方法是使用subprocess.run和管道STDOUT和STDERR(例子在Windows中):

>>> p = subprocess.run(['cmd','/C','echo','hello','world'], stdout = subprocess.PIPE, stderr=subprocess.PIPE)
>>> p.stdout
b'hello world\r\n'

>>> p.stderr
b''

>>> p = subprocess.run(['cmd','/C','gecho','hello','world'], stdout = subprocess.PIPE, stderr=subprocess.PIPE)
>>> p.stdout
b''

>>> p.stderr
b"'gecho' is not recognized as an internal or external command,\r\noperable program or batch file.\r\n"

如果您真的需要使用check_output,以下将忽略echo调用中的错误代码并仍然打印错误(示例几乎逐字地从文档中获取):

>>> print(subprocess.check_output('gecho hello& exit 0', stderr=subprocess.STDOUT, shell=True))
b"'gecho' is not recognized as an internal or external command,\r\noperable program or batch file.\r\n"

或者在Linux中:

>>> print(subprocess.check_output('gecho hello; exit 0', stderr=subprocess.STDOUT, shell=True))
b'/bin/sh: 1: gecho: not found\n'

作为旁注,使用选项shell = True的子进程函数几乎不是一个好主意。 这主要是出于安全考虑; 阅读文档以获得完整的解释。

暂无
暂无

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

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