杀死调用shell进程的Python脚本是否也会杀死shell进程?

时间:2016-03-21 18:24:58

标签: python subprocess multiprocessing python-multiprocessing kill-process

如果我在文件this_script.py中有这样的代码:

import subprocess
subprocess.Popen(["python", "another_script.py"])

我打电话

python this_script.py

并在进程运行时终止进程,是否会终止子进程?

编辑:我对此进行了测试,如果this_script被终止,则子进程继续运行。有没有办法确保后台进程在主Python进程发生时终止?

1 个答案:

答案 0 :(得分:2)

是的,您可以抓住KeyboardInterruptSystemExit,并确保kill子流程。

from subprocess import Popen

try:
    p = Popen(args)
    p.wait()  # wait for the process to finish
except KeyboardInterrupt,  SystemExit:
    p.kill()
    raise
相关问题