In python I have opened 4 subprocess. Now I want to kill all previous process when new request is came in python script.
I am using python 2.7 and windows 7 OS.
Thanks,
In python I have opened 4 subprocess. Now I want to kill all previous process when new request is came in python script.
I am using python 2.7 and windows 7 OS.
Thanks,
Assuming you want to kill all children processes without keeping track of them, the external lib psutil makes this easy:
import os
import psutil
# spawn some child processes we can kill later
for i in xrange(4): psutil.Popen('sleep 60')
# now kill them
me = psutil.Process(os.getpid())
for child in me.get_children():
child.kill()
In your main python script where you are spawning subprocess send/pass an Event object with it and keep reference of your subprocess with event in main process
Sample Code:
from multiprocessing import Process, Event
# sub process execution point
def process_function(event):
# if event is set by main process then this process exits from the loop
while not event.is_set():
# do something
# main process
process_event = {} # to keep reference of subprocess and their events
event = Event()
p = Process(target=process_function, args=(event))
p.start()
process_event[p] = event
# when you want to kill all subprocess
for process in process_event:
event = process_event[process]
event.set()
Edit
As you commented to your question, I think its not quite useful in your scenario as you are using subprocess.Popen.But a nice trick though
You can use os.kill
function
import os
os.kill(process.pid)
If you open the subprocess using the subprocess.Popen
function already returns the process id. But be careful if you are using the shell=True
flag, because in that case the process pid will be the shell process id. If this is your case here are a posible solution.