Python get return code subprocess

Python 3: Get and Check Exit Status Code (Return Code) from subprocess.run()

When running a command using subprocess.run() , the exit status code of the command is available as the .returncode property in the CompletedProcess object returned by run() :

from subprocess import run p = run( [ 'echo', 'Hello, world!' ] ) print( 'exit status code:', p.returncode )

Check Exit Status Code and Raise Error if Non-Zero

Manual Check

If we want our script to stop running and raise an error if the subprocess returns a non-zero exit status code, we could manually check the returncode property of the CompletedProcess object that run() returns:

from subprocess import run print( 'Running command. ' ) p = run( [ 'cat', '/foo' ] ) if p.returncode != 0: raise Exception( f'Invalid result: < p.returncode >' ) # If `cat /foo` fails above, we won't get here. print( 'All done!' )

check=True Option (Shorter Code)

But the shorter way to accomplish the same thing is to just set check=True when we call run() :

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. If we run the code above on a Linux-based system, we’ll see output like this:

Running command. cat: /foo: No such file or directory Traceback (most recent call last): File "test.py", line 4, in run( [ 'cat', '/foo' ], check=True ) File "/usr/lib/python3.8/subprocess.py", line 512, in run raise CalledProcessError(retcode, process.args, subprocess.CalledProcessError: Command '['cat', '/foo']' returned non-zero exit status 1.

Note that All Done! is never printed because the script raised an error before it got to line 5.

Читайте также:  What directory is php ini

If we omit the check=True option:

from subprocess import run print( 'Running command. ' ) run( [ 'cat', '/foo' ] ) # Even if `cat /foo` fails above, we will always get here. print( 'All done!' )

check defaults to False , so we won’t see an error message, and we will see the All done! line:

Running command. cat: /foo: No such file or directory All done!

Источник

How to Get Return Code From Process in Python Subprocess Execution?

As a Python developer, you may want to get a process’s return code for multiple reasons. For instance, while handling errors, it is important to know whether a subprocess was successfully executed or triggered any error. Moreover, the returned code can also be utilized for tracking the program or subprocess execution.

Method 1: Getting Return Code From Process in Python Using “returncode” Attribute

In Python, the “returncode” attribute belongs to the “subprocess” module. This attribute contains an integer value that refers to the exit status of a subprocess upon execution. More specifically, the value “0” signifies the successful execution of the subprocess, whereas a non-zero value indicates an abnormal condition or an error.

Syntax

Here, “process” represents the process object relevant function of the “subprocess” module, and the “returncode” is its corresponding return code value.

Example

To utilize the “returncode” attribute for fetching the return code in Python subprocess execution, check out the provided code:

from subprocess import run

process = run ( [ ‘echo’ , ‘linuxhint user!’ ] )
print ( ‘return code:’ , process. returncode )

According to the given code:

  • First of all, import the “run()” function of the “subprocess” module.
  • The “run()” function runs the “echo” command and waits for it to complete, ultimately returning the process object.
  • Lastly, the “print()” function displays the “returncode” attribute value of the retrieved object:

Here, “0” has been returned, which indicates that the specified subprocess has been executed successfully.

Method 2: Getting Return Code From Process in Python Using “communicate()” Method

The “communicate()” method in Python permits the interaction with a process by passing input to it. This method outputs a tuple that comprises “std_out” (standard output) at the 0th index and “stderr_data” (error stream or messages) at the 1st index. The values of these associated variables will be returned as “None” if the standard output or the error messages have not been captured.

Syntax

In the given syntax, “input” is a byte string passed to the process’s standard input, “timeout” is the number of seconds to wait for the process completion, and “n” refers to index, where “0” outputs the standard output, and “1” indicates the error streams.

Example

Now, execute the following Python code for getting the return code using the communicate() method:

process = subprocess . Popen ( [ «echo» , «linuxhint user!» ] , stdout = subprocess . PIPE )
print ( process. communicate ( ) [ 0 ] )

  • Firstly, import the “subprocess” module.
  • Its “Popen()” method generates a Popen object that represents the newly created subprocess and returns it.
  • The first argument of the Popen() refers to the command that needs to be executed, and the value of the “stdout” is set as the “subprocess.PIPE” for capturing the subprocess output.
  • Finally, the “process.communicate()[0]” returns the standard output of the subprocess:

In our case, the “b’linuxhint user!\n’” has been displayed as the returned code.

Method 3: Getting Return Code From Process in Python Using “check_output()” Method

The “check_output()” Python method runs a command as a subprocess and saves its output. This method presents the output as a byte’s object.

Syntax

subprocess . check_output ( args , * , stdin = None , stderr = None , shell = False , universal_newlines = False , timeout = None , encoding = None , errors = None )

Here, “args” signifies the commands that need to be executed, whereas all of the other parameters are optional.

Example

We have passed the “echo” command and the respective string to the check_output() as an argument. Resultantly, this method will return the captured output:

Output

Bonus Tip: Decode the Standard Output

Python also offers the facility to decode the returned standard output with the “decode()” method. In this code, we will decode the byte string utilizing the “utf-8” encoding scheme:

Output

That was all about getting the return code in Python.

Conclusion

To get the return code from a process in Python subprocess execution, use the “returncode” attribute, “communicate()”, or the “check_output()” method. The “returncode” attribute returns “0” in case of successful execution, and the “communicate()[0]” outputs the standard output stored at the zero index. Moreover, the “check_output()” method also works the same. This blog covered multiple methods for getting return code in Python.

About the author

Abdul Mannan

I am curious about technology and writing and exploring it is my passion. I am interested in learning new skills and improving my knowledge and I hold a bachelor’s degree in computer science.

Источник

Оцените статью