Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start a background process in Python?

I'm trying to port a shell script to the much more readable python version. The original shell script starts several processes (utilities, monitors, etc.) in the background with "&". How can I achieve the same effect in python? I'd like these processes not to die when the python scripts complete. I am sure it's related to the concept of a daemon somehow, but I couldn't find how to do this easily.

like image 948
Artem Avatar asked Jul 28 '09 18:07

Artem


People also ask

How do you create a background process in Python?

To start a background process in Python, we call subprocess. Popen . to call subprocess. Popen with a list with the command and command arguments to run the command in the background.

How do I run a background task in Python?

We can configure a new daemon thread to execute a custom function that will perform a long-running task, such as monitor a resource or data. For example we might define a new function named background_task(). Then, we can configure a new threading. Thread instance to execute this function via the “target” argument.

How can you run a process program in the background?

To do this, you would first type ^z (hold control key and press z). That suspends the process. Then type bg to put the process in the background. That leaves you with the ability to run other commands.


1 Answers

While jkp's solution works, the newer way of doing things (and the way the documentation recommends) is to use the subprocess module. For simple commands its equivalent, but it offers more options if you want to do something complicated.

Example for your case:

import subprocess subprocess.Popen(["rm","-r","some.file"]) 

This will run rm -r some.file in the background. Note that calling .communicate() on the object returned from Popen will block until it completes, so don't do that if you want it to run in the background:

import subprocess ls_output=subprocess.Popen(["sleep", "30"]) ls_output.communicate()  # Will block for 30 seconds 

See the documentation here.

Also, a point of clarification: "Background" as you use it here is purely a shell concept; technically, what you mean is that you want to spawn a process without blocking while you wait for it to complete. However, I've used "background" here to refer to shell-background-like behavior.

like image 76
Dan Avatar answered Oct 07 '22 22:10

Dan