【发布时间】: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