I am using:
grepOut = subprocess.check_output("grep " + search + " tmp", shell=True)
To run a terminal command, I know that I can use a try/except to catch the error but how can I get the value of the error code?
I found this on the official documentation:
exception subprocess.CalledProcessError
Exception raised when a process run by check_call() or check_output() returns a non-zero exit status.
returncode
Exit status of the child process.
But there are no examples given and Google was of no help.
You can get the error code and results from the exception that is raised.
This can be done through the fields
returncode
andoutput
.For example:
check_output
raises an exception if it receives non-zero exit status because it frequently means that a command failed.grep
may return non-zero exit status even if there is no error -- you could use.communicate()
in this case:You don't need to call an external command to filter lines, you could do it in pure Python:
If you don't need the output; you could use
subprocess.call()
:Python 3.5 introduced the
subprocess.run()
method. The signature looks like:The returned result is a
subprocess.CompletedProcess
. In 3.5, you can access theargs
,returncode
,stdout
, andstderr
from the executed process.Example: