1
votes

I call an external binary using the subprocess module:

try:
    subprocess.check_output([param1, param2], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
    print(e.output)

This outputs an error both when the check_output runs and in the except statement. What I really want to have is to print the output only if I catch an exception. So that means I want to have stderr in the exception object.

The problem is that if I suppress the stdout:

subprocess.check_output(..., stdout=open(sys.os.devnull, 'wb'))

Then e.output sure becomes empty. Also I tried setting stderr to None - the same effect.

How to add stderr to the subprocess.CalledProcessError instance without redirecting stderr to stdout because I do not need stdout at all.

1
don't print e.output id you only want to see the error once,subprocess.check_output([param1, param2]) and use a pass instead of a print - Padraic Cunningham
That's just an example. In a real application I reraise exception which then is used to produce jsonified error message. - Glueon

1 Answers

2
votes

check_output is a convenience function with limited functionality. If it doesn't do what you want, roll your own:

proc = subprocess.Popen([param1, param2],
    stderr=subprocess.PIPE)
out, err = proc.communicate()
if proc.returncode != 0:
    print(err)