回答我自己的问题:我最终只是按照@kevinsa的建议在命令末尾使用os.system
with 。这允许在不终止子进程的情况下终止父进程。&
这是一些代码:
孩子.py
#!/usr/bin/python
import time
print "Child started"
time.sleep(10)
print "Child finished"
parent.py,使用 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"
输出:
$ ./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
- 注意如果父母被 Ctrl-C 打断,孩子永远不会完成
parent.py,使用 os.system 和 &
#!/usr/bin/python
import os
import time
print "Parent started"
os.system("./child.py &")
print "(child started, sleeping)"
time.sleep(5)
print "Parent finished"
输出:
$ ./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
注意孩子在 Ctrl-C 之外是如何生活的。