How to Run Background Process in Python

09/16/2021

Contents

In this article, you will learn how to run background process in Python.

How to run background process

In Python, you can run a process in the background by using the subprocess module. The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.

Here’s an example of how you can run a process in the background:

import subprocess

# start the process in the background
process = subprocess.Popen(["python", "my_script.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

# do other stuff here while the process is running in the background

# wait for the process to finish and get the output
stdout, stderr = process.communicate()

# print the output
print(stdout.decode())

In this example, we use the Popen function to start the process in the background. The Popen function takes a list of arguments that specify the command and any arguments to pass to it.

We also pass two arguments, stdout=subprocess.PIPE and stderr=subprocess.PIPE, which redirect the standard output and standard error streams of the process to pipes that we can read later.

After starting the process, we can do other things while the process is running in the background. When we’re ready to get the output of the process, we use the communicate method to wait for the process to finish and obtain the output.

Finally, we decode the output and print it to the console.