| by Arround The Web | No comments

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.

This blog will cover:

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

process.returncode

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

process.communicate(input=None, timeout=None)[n]

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:

import subprocess

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

Here:

  • 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:

process = subprocess.check_output(["echo", "Hello from linuxhint!"])
print(process)

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:

print(process.decode("utf-8"))

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.

Share Button

Source: linuxhint.com

Leave a Reply