Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

popen

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.

like image 752
user495511 Avatar asked Nov 03 '10 04:11

user495511


People also ask

How do you kill a Popen process in Python?

subprocess. Popen. kill(proc) is exactly the same as proc. kill() FYI.

What does subprocess Popen do in Python?

The subprocess module defines one class, Popen and a few wrapper functions that use that class. The constructor for Popen takes arguments to set up the new process so the parent can communicate with it via pipes. It provides all of the functionality of the other modules and functions it replaces, and more.

How do you terminate a subprocess?

Once you create subprocess with the above command, you can always refer to it using its id attribute as p.id and send a SIGTERM signal to it. Here is the full code to terminate a subprocess created in python. In the above command, we use killpg command to send the terminate signal to all the process groups.


2 Answers

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.

like image 99
pyfunc Avatar answered Sep 28 '22 08:09

pyfunc


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

like image 37
metanoia5 Avatar answered Sep 28 '22 07:09

metanoia5