Reputation: 422
I have several python scripts that run at the same time with the use of the subprocess library. 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
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()
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.
Upvotes: 0
Views: 291
Reputation: 18106
You could keep track of the launched Process Ids:
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)
Upvotes: 1