系统相关
首页 > 系统相关> > python – 将子进程与traceroute一起使用时没有错误输出

python – 将子进程与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

标签:python,error-handling,subprocess,traceroute
来源: https://codeday.me/bug/20190829/1762197.html