Python 子进程 shell 脚本仍在后台运行

Python subprocess shell scripts still runs in background

我 运行 两个 python 使用子进程的脚本,其中一个仍在运行。

import subprocess
subprocess.run("python3 script_with_loop.py & python3 scrip_with_io.py", shell=True)

script_with_loop 仍在后台运行。

如果其中一个脚本死了,如何杀死两个脚本?

所以,您在这里基本上没有使用 python,您使用的是 shell。

a & b 运行 a,拒绝它,然后运行 ​​b。由于您使用的是 shell,如果您想终止后台任务,则必须使用 shell 命令来完成。

当然,既然你用的是python,还有更好的办法。

with subprocess.Popen(["somecommand"]) as proc:
  try:
    subprocess.run(["othercommand"])
  finally:
    proc.terminate()

虽然看看你的代码 - python3 script_with_loop.pypython3 script_with_io.py - 我猜你最好使用 asyncio 模块,因为它基本上完成了这两个模块的名称文件正在描述。

你应该为这种事情使用线程。试试这个。

import threading

def script_with_loop():
    
    try:
        # script_with_loop.py code goes here
    except:
         _exit()


def script_with_io():
    
    try:
        # script_with_io.py code goes here
    except:
         _exit()


threading.Thread(target=script_with_loop, daemon=True).start()
threading.Thread(target=script_with_io, daemon=True).start()