Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a python subprocess as daemon and exit

I'm using a pair of python programs, one of which should call the second.

But this should be done in a way that the first program makes the second one a daemon (or running in the background process), then exits, without waiting for the second program to end.

Is this possible in Python?

I've been looking at os.fork, subprocess module, but I'm quite confused as the correct way to achieve this...

like image 468
Javier Novoa C. Avatar asked Jan 20 '12 20:01

Javier Novoa C.


People also ask

What is difference between subprocess Popen and call?

Popen is more general than subprocess. call . Popen doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen returns a Popen object.

What is Popen in subprocess?

The subprocess module defines one class, Popen and a few wrapper functions that use that class. The constructor for Popen takes arguments to set up the new process so the parent can communicate with it via pipes. It provides all of the functionality of the other modules and functions it replaces, and more.

What does Python subprocess call return?

Return Value of the Call() Method from Subprocess in Python The Python subprocess call() function returns the executed code of the program. If there is no program output, the function will return the code that it executed successfully. It may also raise a CalledProcessError exception.


2 Answers

You can use subprocess.Popen for this:

import subprocess

cmd = ['/usr/bin/python', '/path/to/my/second/pythonscript.py']
subprocess.Popen(cmd)

You might want to redirect stdout and stderr somewhere, you can do that by passing stdout=<file_obj> to the Popen constructor.

like image 96
Rob Wouters Avatar answered Oct 16 '22 10:10

Rob Wouters


A "daemon" carries a more specific definition than just "background process". By default Popen will execute a subprocess and give control back to your program to continue running. However, that says nothing about dealing with signals (notably, SIGHUP if the user exits their shell before your background process finished) or disconnecting from stdin, stderr, stdout and any other file descriptors opened at the time you invoke Popen. If you truly mean that you want a daemon, you should use the python-daemon module, an implementation of PEP 3143. This takes care of the gross parts you don't want to think about.

like image 39
Dave Avatar answered Oct 16 '22 09:10

Dave