I wanted to initiate a process from my python script (main.py)
, specifically I want to run the below command
`nohup python ./myfile.py &`
and this file myfile.py
should even after my main python script exits.
Additionally I wish to get the pid
of the new process.
I tried os.spawnl*
, os.exec*
& subprocess.Popen
methods, all are terminating my myfile.py
if my main.py script exits.
I may be missing something.
Update: Can I use os.startfile
with xdg-open
? Is it a right approach?
Example
a = subprocess.Popen([sys.executable, "nohup /usr/bin/python25 /long_process.py &"],\
stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
print a.pid
If I check ps aux | grep long_process
, I could not see any process running.
long_process.py which keeps on printing some text: no exit.
Am I doing anything wrong here?
You can use
os.fork()
.You don't see any process running because the child
python
process exits immediately. ThePopen
arguments are incorrect as @user4815162342 says in the comment.To launch a completely independent process, you could use
python-daemon
package or use systemd/supervisord/etc:Though it might be enough in your case, to start the child with correct
Popen
arguments:If the child process doesn't require
python2.5
then you could usesys.executable
instead (to use the same Python version as the parent).Note: the code closes
DEVNULL
in the parent without waiting for the child process to finish (it has no effect on the child).You open your long-running process and keep a pipe to it. So you expect to talk to it. When yor launcher script exits, you can no longer talk to it.
The long-running process receives aSIGPIPE
and exits.The following just worked for me (Linux, Python 2.7).
Create a long-running executable:
Run Python REPL:
Exit the REPL and see the process still running:
If you want to first communicate to the started process and then leave it alone to run further, you have a few options:
SIGPIPE
in your long-running process, do not die on it. Live without stdin after the launcher process exits.