pythonerror-handlingsubprocesstraceroute

No error output when using subprocess with traceroute


I'm trying to get the error message that is returned when a traceroute fails. For example:

from subprocess import CalledProcessError, check_output

try: 
    output = check_output(["traceroute", "error"])
except CalledProcessError as error:
    output = error.output

print "error: {}".format(output)

Output:

error:

I've tried using output = str(error.output) but output stays empty. An error message is printed to the terminal when executing the above code, so it should be possible to assign it to a variable, right?


Solution

  • As stated in: https://docs.python.org/2/library/subprocess.html#subprocess.check_output

    To also capture standard error in the result, use stderr=subprocess.STDOUT

    Try:

    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)
    

    Output:

    error: traceroute: unknown host error