pythonpython-3.xsubprocessoutputreturn-code

Get the output with check_output even with a non-zero exit status


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"])

Solution

  • 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