1

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.

Glueon
  • 3,727
  • 4
  • 23
  • 32

1 Answers1

2

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)
tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • As far a I understand in case of non-zero return code check_output will raise an exception and I will never reach `print(err)` part. – Glueon Jan 08 '15 at 10:58
  • Seems you you ment `subprocess.Popen` insted of `subprocess.check_output`. I thought it's possible to do that with the default check_output. Just supress stdout and have stderr in a exception. Strange .. – Glueon Jan 08 '15 at 11:56