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

1

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"])
Florey answered 6/3, 2017 at 14:42 Comment(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).Narcotize
I
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
Interfile answered 6/3, 2017 at 15:50 Comment(3)
With this I get the following error, when handling the exception: NameError: name 'CalledProcessError' is not definedFlorey
@boolean.is.null: Updated answer. CalledProcessError lives in the subprocess module.Interfile
I should have realised that on my own, thank you for the help!Florey

© 2022 - 2024 — McMap. All rights reserved.