[英]Stopping a subprocess in python
I have several python scripts that run at the same time with the use of the subprocess library.我有几个使用子进程库同时运行的 python 脚本。 However, i want to be able to stop all processes when an event happens, such as the press of a button.
但是,我希望能够在事件发生时停止所有进程,例如按下按钮。 I have tried several things, but none of them seem to work.
我已经尝试了几件事,但它们似乎都不起作用。 I'm using Windows with Python 3.8.0
我正在使用 Windows 和 Python 3.8.0
Below is my code that opens all of the processes.下面是我打开所有进程的代码。
import subprocess
subprocess.Popen("python Program1.py")
subprocess.Popen("python Program2.py")
subprocess.Popen("python Program3.py")
subprocess.Popen("python Program4.py")
subprocess.Popen("python Program5.py")
subprocess.Popen("python Program6.py")
subprocess.Popen("python Program7.py")
I cant figure out how to end the processes with the subprocess library or any other ones.我不知道如何用子进程库或任何其他库结束进程。 I have also tried the following
proc1.kill()
我也尝试过以下
proc1.kill()
p.terminate()
def pkill (process_name):
try:
killed = os.system('tskill ' + process_name)
except Exception as e:
killed = 0
return killed
pkill("PROGRAM")
And with the one above, i have tried putting except Exception, e:
And also putting pkill("PROGRAM.py")
but that doesnt seem to work either.对于上面的那个,我试过把
except Exception, e:
和pkill("PROGRAM.py")
放在一起,但这似乎也不起作用。
You could keep track of the launched Process Ids:您可以跟踪启动的进程 ID:
import os
import subprocess
processes = []
for x in range(0,9):
p = subprocess.Popen("python Program.py %s" % x)
processes.append(p.pid) # keep the processIds!
for p in processes:
os.system('taskkill /F /PID ' + p)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.