6

I use subprocess.check_output a number of times in a script of mine, but I just ran into an issue with an external application. OpenVPN in this case.

When openvpn is called with the --help parameter, which I want to parse in my script, it returns 1 as its exit code. check_ouput chokes on the non-zero exit code and fails with the following message:

subprocess.CalledProcessError: Command '['openvpn', '--help']' returned non-zero exit status 1

Q: I don't understand why openvpn does this, but how can I have check_output give me the output, even with a non-zero return code?

edit: I used the exact same code with --show-digests or other parameters and all seemed to work just fine.

output = check_output(["openvpn", "--show-digests"])
boolean.is.null
  • 831
  • 2
  • 12
  • 19
  • 1
    Python 3.5+ has `subprocess.run()` which is a more versatile overall design. It takes some getting used to, but it will produce an object which contains the output, the exit code, and a smattering of additional state information for the process you ran. In brief, you want `result = subprocess.run(['openvpn', '--help'], stdout=subprocess.PIPE, universal_newlines=True).stdout` (no `check=True` because you *expect* it to fail). – tripleee Sep 18 '17 at 04:29

1 Answers1

8

According to the docs the output is available in the .output attribute of the CalledProcessError exception.

So something like this should work:

try:
    result = subprocess.check_output(...).stdout
except subprocess.CalledProcessError as exc:
    result = exc.output
Ethan Furman
  • 63,992
  • 20
  • 159
  • 237