【问题标题】:Run subprocess in thread and stop it在线程中运行子进程并停止它
【发布时间】:2021-11-15 19:37:21
【问题描述】:

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

我想要的是

我想在线程运行test.py和我的main.py,并通过在控制台中输入stop来停止它。

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 函数停止它之后程序仍在运行,我也尝试过terminate。我需要阻止它,我该怎么做。或者,是否有任何替代模块可供 subprocess 执行此操作?

【问题讨论】:

    标签: python multithreading subprocess


    【解决方案1】:

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

    for proc in processes:
        proc.kill()
    

    这应该会杀死他们。

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

    顺便说一句,你不想要shell=True,你最好使用threading而不是_thread

    【讨论】:

    • for 循环没有帮助,但 "Incidentally, you don't want shell=True" 救了我的命!非常感谢。
    • 所以,答案是"shell=True" 防止应用被杀死。
    • Windows 进程有时很难杀死(因此更新了有关 terminate() 的说明)。我怀疑生成子shell 以某种方式使操作系统认为该过程更重要。天知道为什么。在 linux 上,无论是否使用 shell=True,我都可以毫无困难地终止或终止进程。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 2016-01-03
    • 2010-11-12
    • 2017-04-21
    • 1970-01-01
    相关资源
    最近更新 更多