【问题标题】:subprocess.CalledProcessError not giving error messagesubprocess.CalledProcessError 没有给出错误信息
【发布时间】:2017-07-03 11:48:02
【问题描述】:

我正在使用下面的代码来获取 shell 命令的输出。

import subprocess
exitcode, err, out = 0, None, None
try:
    out = subprocess.check_output(cmd, shell=True, universal_newlines=True)
except subprocess.CalledProcessError as e:
    exitcode, err = e.returncode, e.output

print("x{} e{} o{}".format(exitcode, err, out))

当为cmd 传递有效命令时,例如echo hello,程序运行良好并输出为(0, None, "hello\n")

但是,如果我给出了错误的命令,我希望错误消息应该出现在err,但它会直接打印出来。例如,如果我在cmd 中传递ls -lrt foo,则输出为

anirban@desktop> python mytest.py
ls: cannot access foo: No such file or directory
x2 e oNone

所以我希望ls: cannot access foo: No such file or directory 应该加入err。该怎么做?

【问题讨论】:

    标签: python python-3.x subprocess


    【解决方案1】:

    要捕获错误输出,您需要将另一个参数传递给subprocess.check_output() 函数。您需要设置stderr=subprocess.STDOUT。这会将标准错误输出引导至e.output

    subprocess.check_output()subprocess.run() 的包装器。通过传递一些合理的默认值,它使我们的生活更轻松。其中之一是制作stdout=subprocess.PIPE。这会将您正在运行的命令的标准输出引导回您的程序。同样,您可以通过传入参数stderr=subprocess.PIPE 将标准错误输出定向到您的程序,这将填充e.stderr,其中e 是例外。

    如果不清楚,请告诉我。

    【讨论】:

      猜你喜欢
      • 2022-01-17
      • 2011-05-16
      • 1970-01-01
      • 2016-03-15
      • 1970-01-01
      • 2016-08-23
      • 2015-06-22
      • 1970-01-01
      • 2019-07-31
      相关资源
      最近更新 更多