python - python中的子进程终止

标签 python subprocess

我有一个 Python 脚本,它使用 subprocess.Popen() 启动另一个 Python 脚本的子进程。此子进程使用 Popen 启动另一个子进程(另一个 Python 脚本)。 脚本 A 调用脚本 B,脚本 B 调用脚本 C。 如果我使用 os.kill() 终止进程脚本 B,它会终止运行脚本 C 的进程。 如果没有,有什么办法可以做到这一点。

最佳答案

就目前而言,如果脚本 A 使用 os.kill 杀死 B 那么 C 本身将不会杀了。

为了确保这一点,脚本 B 可以在退出时负责杀死 C

# this is in script B
import functools, atexit

def kill_children(*pids):
    import os, signal

    for pid in pids or []:
        os.kill(pid, signal.SIGTERM)

# we start a process for C
c_pid = ...

# kill C when we we exit
atexit.register(functools.partial(kill_children, c_pid)) 

关于python - python中的子进程终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40166227/

相关文章:

python - 如何使用子进程拦截 "pipenv install"spinner-like 输出消息?

python - 如何在保存数据的同时在 for 循环中使用多处理池?

python - 在 if 条件下使用 for 循环迭代器

python : Multiple Inheritance : Why is instance variable of super's super class is not accessible?

python - Python While 循环中的动态变量

python - 从 Python 解析 subprocess.call() 的输出

Python 子进程 Popen : Why does "ls *.txt" not work?

multithreading - 防止Ctrl+C打断Golang中的exec.Command

python - 使用 python/popen 通过管道处理大量数据

python - 在 Windows 8.1 上安装 lxml、libxml2、libxslt