Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run Python's subprocess and leave it in background

I have seen A LOT of posts regarding my topic, but actually I didn't find a solution for my problem. I'm trying to run a subprocess in a background, without wait for subprocess execution. The called subprocess is a shell script, which does a lot of different things. This is a small piece of my code:

print "Execute command:", full_command
subprocess.Popen(full_command, stdin=None, stdout=None, stderr=None, close_fds=True).communicate()
print "After subprocess"

And my problem is that Python waits until subprocess.Popen finishes it's job. I read, that stdin(-out, -err)=None should solve this problem, but it's not. Also close_fds=True, doesn't help here.

like image 627
mchfrnc Avatar asked Jan 11 '16 09:01

mchfrnc


People also ask

How do I keep a python program running in the background?

The easiest way of running a python script to run in the background is to use cronjob feature (in macOS and Linux). In windows, we can use Windows Task Scheduler. You can then give the path of your python script file to run at a specific time by giving the time particulars.

How do you store output of subprocess run?

To capture the output of the subprocess. run method, use an additional argument named “capture_output=True”. You can individually access stdout and stderr values by using “output. stdout” and “output.

Does python wait for subprocess run to finish?

Most of your interaction with the Python subprocess module will be via the run() function. This blocking function will start a process and wait until the new process exits before moving on. The documentation recommends using run() for all cases that it can handle.

How do you wait for a subprocess to finish?

wait() method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status). If you use this method, you'll prevent that the process zombies are lying around for too long. (Alternatively, you can use subprocess. call() or subprocess.


1 Answers

From the Popen.communicate documentation (emphasis mine):

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child.

If you don't want to wait for the process to terminate, then simply don't call communicate:

subprocess.Popen(full_command, close_fds=True)
like image 123
Thomas Orozco Avatar answered Sep 19 '22 02:09

Thomas Orozco