4

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?

Amos
  • 1,154
  • 1
  • 16
  • 35

1 Answers1

7

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
Andrés Pérez-Albela H.
  • 4,003
  • 1
  • 18
  • 29