Skip to content
Advertisement

“Fire and forget” a process from a Python script

How do I start a process (another Python script, for example) from a Python script so the “child” process is completely detached from the “parent”, so the parent can a) continue on its merry way without waiting for child to finish and b) can be terminated without terminating the child process?

Parent:

import os

print "Parent started"
os.system("./child.py")
print "Parent finished"

Child:

import time

print "Child started"
time.sleep(10)
print "Child finished"

Running parent.py prints:

Parent started
Child started
Child finished
Parent finished

What I want it to print:

Parent started
Child started
Parent finished
(seconds later)
Child finished

Advertisement

Answer

Answering my own question: I ended up simply using os.system with & at the end of command as suggested by @kevinsa. This allows the parent process to be terminated without the child being terminated.

Here’s some code:

child.py

#!/usr/bin/python

import time
print "Child started"
time.sleep(10)
print "Child finished"

parent.py, using subprocess.Popen:

#!/usr/bin/python

import subprocess
import time

print "Parent started"
subprocess.Popen("./child.py")
print "(child started, sleeping)"

time.sleep(5)

print "Parent finished"

Output:

$ ./parent.py
Parent started
(child started, sleeping)
Child started
^CTraceback (most recent call last):
Traceback (most recent call last):
  File "./child.py", line 5, in <module>
  File "./parent.py", line 13, in <module>
        time.sleep(10)
time.sleep(5)
KeyboardInterrupt
KeyboardInterrupt
  • note how the child never finishes if the parent is interrupted with Ctrl-C

parent.py, using os.system and &

#!/usr/bin/python

import os
import time

print "Parent started"
os.system("./child.py &")
print "(child started, sleeping)"

time.sleep(5)

print "Parent finished"

Output:

$ ./parent.py
Parent started
(child started, sleeping)
Child started
^CTraceback (most recent call last):
  File "./parent.py", line 12, in <module>
    time.sleep(5)
KeyboardInterrupt

$ Child finished

Note how the child lives beyond the Ctrl-C.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement