Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"])
like image 872
boolean.is.null Avatar asked Mar 06 '17 14:03

boolean.is.null


People also ask

What is the output of subprocess Check_output?

The subprocess. check_output() is used to get the output of the calling program in python. It has 5 arguments; args, stdin, stderr, shell, universal_newlines. The args argument holds the commands that are to be passed as a string.

What is nonzero exit code?

A non-zero exit status indicates failure. This seemingly counter-intuitive scheme is used so there is one well-defined way to indicate success and a variety of ways to indicate various failure modes. When a command terminates on a fatal signal whose number is N , Bash uses the value 128+ N as the exit status.

What does Check_output return?

New in version 3.3. Subclass of SubprocessError , raised when a process run by check_call() , check_output() , or run() (with check=True ) returns a non-zero exit status. Exit status of the child process.

How do I get my subprocess return code?

from subprocess import run print( 'Running command...' ) run( [ 'cat', '/foo' ], check=True ) # If `cat /foo` fails above, we won't get here. print( 'All done! ' ) Assuming we don't have a file /foo on our system, cat /foo will return a non-zero exit status code.


1 Answers

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
like image 51
Ethan Furman Avatar answered Oct 19 '22 23:10

Ethan Furman