我正在使用下面的代码获取shell命令的输出。subprocess.CalledProcessError没有给出错误信息
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
输出来作为
[email protected]> 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
到来。怎么做?