运行 线程中的子进程并停止它

Run subprocess in thread and stop it

我正在尝试 运行 一个 python 文件与另一个 python 文件在线程与子进程中。我可以 运行 文件,但无法停止它。

我要的是

I want to run the test.py with my main.py in thread and stop it by entering stop in the console.

test.py

import time

while True:
    print("Hello from test.py")
    time.sleep(5)

main.py

import subprocess
import _thread

processes = []

def add_process(file_name):
    p = subprocess.Popen(["python", file_name], shell=True)
    processes.append(p)
    print("Waiting the process...")
    p.wait()

while True:
    try:
        # user input
        ui = input("> ")

        if ui == "start":
            _thread.start_new_thread(add_process, ("test.py",))
            print("Process started.")
        elif ui == "stop":
            if len(processes) > 0:
                processes[-1].kill()
                print("Process killed.")
        else:
            pass
    except KeyboardInterrupt:
        print("Exiting Program!")
        break

输出

C:\users\me>python main2.py
> start
Process started.
> Waiting the process...
Hello from test.py, after 0 seconds
Hello from test.py, after 4 seconds

> stop
Process killed.
> Hello from test.py, after 8 seconds
Hello from test.py, after 12 seconds
    
> stopHello from test.py, after 16 seconds

Process killed.
> Hello from test.py, after 20 seconds

>

即使我用 kill 函数停止它,程序仍然 运行ning,我也试过 terminate。我需要停止它,我该怎么做。或者,子进程是否有任何替代模块来执行此操作?

我怀疑您刚刚启动了多个进程。如果你用这个替换你的停止代码会发生什么:

for proc in processes:
    proc.kill()

这应该会杀死他们。

请注意,您在 windows 和 windows terminate() is an alias for kill() 上。无论如何,依靠优雅地终止进程不是一个好主意,如果你需要停止你的 test.py 你最好有一些与之通信的方式并让它优雅地退出。

顺便说一下,您不想要 shell=True,并且 threading_thread 更好。