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"])
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With