使用带有 traceroute 的子进程时没有错误输出

No error output when using subprocess with traceroute

我正在尝试获取 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