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"])
1
  • 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). Commented Sep 18, 2017 at 4:29

1 Answer 1

9

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
Sign up to request clarification or add additional context in comments.

3 Comments

With this I get the following error, when handling the exception: NameError: name 'CalledProcessError' is not defined
@boolean.is.null: Updated answer. CalledProcessError lives in the subprocess module.
I should have realised that on my own, thank you for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.