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

Will killing Python script that called shell processes also kill the shell processes?

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

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

我打电话给

python this_script.py

并在进程运行时杀死进程,它会杀死子进程吗?

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

是的,您可以捕获 KeyboardInterruptSystemExit 并确保 kill 子进程。

from subprocess import Popen

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