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.

Answer rating: 442

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

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.

Get Solution for free from DataCamp guru