68
votes

Here is my thought:

First of all, I created a process by using subprocess.Popen

Second, after certain amount of time, I tried to kill it by Popen.kill()

import subprocess
import os, signal
import time

proc1 = subprocess.Popen("kvm -hda /path/xp.img", shell = True)
time.sleep(2.0)
print 'proc1 = ', proc1.pid
subprocess.Popen.kill(proc1)

However, "proc1" still exists after Popen.kill(). Could any experts tell me how to solve this issue? I appreciate your considerations.

Thanks to the comments from all experts, I did all you recommended, but result still remains the same.

proc1.kill() #it sill cannot kill the proc1

os.kill(proc1.pid, signal.SIGKILL) # either cannot kill the proc1

Thank you all the same.

And I am still waiting for your precious experience on solving this delicate issue.

4
Why do you need the "shell = True"? Without this it seems to work exactly how you would expect. - Michael Patterson
Instead of putting [Solved] in the title, please choose the correct answer clicking on the check symbol. - bluish
subprocess.Popen.kill(proc) is exactly the same as proc.kill() FYI. - Erik Kaplun
it is unlikely that kill -9 doesn't work. Your issue could be that you need to kill the whole process tree. - jfs

4 Answers

39
votes

In your code it should be

proc1.kill()

Both kill or terminate are methods of the Popen object which sends the signal signal.SIGKILL to the process.

28
votes

process.terminate() doesn't work when using shell=True. This answer will help you.

12
votes

Only use Popen kill method

process = subprocess.Popen(
    task.getExecutable(), 
    stdout=subprocess.PIPE, 
    stderr=subprocess.PIPE, 
    shell=True
)
process.kill()