【发布时间】: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