Killing a process created with Python's subprocess.Popen()

PythonPopen

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

In your code it should be

proc1.kill()

Both kill or terminate are methods of the Popen object. On macOS and Linux, kill sends the signal signal.SIGKILL to the process and terminate sends signal.SIGTERM. On Windows they both call Windows' TerminateProcess() function.

Solution 2 - Python

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

Solution 3 - Python

Only use Popen kill method

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

Solution 4 - Python

How about using os.kill? See the docs here: http://docs.python.org/library/os.html#os.kill

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser495511View Question on Stackoverflow
Solution 1 - PythonpyfuncView Answer on Stackoverflow
Solution 2 - Pythonmetanoia5View Answer on Stackoverflow
Solution 3 - PythonJorge Niedbalski R.View Answer on Stackoverflow
Solution 4 - PythonMichael PattersonView Answer on Stackoverflow