我正在尝试获取traceroute失败时返回的错误消息.例如:
from subprocess import CalledProcessError, check_output
try:
output = check_output(["traceroute", "error"])
except CalledProcessError as error:
output = error.output
print "error: {}".format(output)
输出:
error:
我尝试使用output = str(error.output)但输出保持为空.执行上述代码时会向终端打印一条错误消息,因此应该可以将其分配给变量,对吧?
解决方法:
如:https://docs.python.org/2/library/subprocess.html#subprocess.check_output中所述
To also capture standard error in the result, use
stderr=subprocess.STDOUT
尝试:
import subprocess
from subprocess import CalledProcessError, check_output
try:
output = check_output(["traceroute", "error"], stderr=subprocess.STDOUT)
except CalledProcessError as error:
output = error
print "error: {}".format(output.output)
输出:
error: traceroute: unknown host error