我正在使用下面的代碼獲取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
到來。怎麼做?