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.