I'm launching a subprocess with the following command:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
However, when I try to kill using:
p.terminate()
or
p.kill()
The command keeps running in the background, so I was wondering how can I actually terminate the process.
Note that when I run the command with:
p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
It does terminate successfully when issuing the p.terminate()
.
Use a process group so as to enable sending a signal to all the process in the groups. For that, you should attach a session id to the parent process of the spawned/child processes, which is a shell in your case. This will make it the group leader of the processes. So now, when a signal is sent to the process group leader, it's transmitted to all of the child processes of this group.
Here's the code:
what i feel like we could use:
this will not kill all your task but the process with the p.pid
I could do it using
it killed the
cmd.exe
and the program that i gave the command for.(On Windows)
I know this is an old question but this may help someone looking for a different method. This is what I use on windows to kill processes that I've called.
/IM is the image name, you can also do /PID if you want. /T kills the process as well as the child processes. /F force terminates it. si, as I have it set, is how you do this without showing a CMD window. This code is used in python 3.
When
shell=True
the shell is the child process, and the commands are its children. So anySIGTERM
orSIGKILL
will kill the shell but not its child processes, and I don't remember a good way to do it. The best way I can think of is to useshell=False
, otherwise when you kill the parent shell process, it will leave a defunct shell process.None of this answers worked for me so Im leaving the code that did work. In my case even after killing the process with
.kill()
and getting a.poll()
return code the process didn't terminate.Following the
subprocess.Popen
documentation:In my case I was missing the
proc.communicate()
after callingproc.kill()
. This clean the process stdin, stdout ... and does terminate the process.