Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill a process been created by subprocess in python?

Under Linux Ubuntu operating system, I run the test.py scrip which contain a GObject loop using subprocess by:

subprocess.call(["test.py"])

Now, this test.py will creat process. Is there a way to kill this process in Python? Note: I don't know the process ID.

I am sorry if I didn't explain my problem very clearly as I am new to this forms and new to python in general.

like image 430
Mero Avatar asked Oct 02 '22 06:10

Mero


2 Answers

I would suggest not to use subprocess.call but construct a Popen object and use its API: http://docs.python.org/2/library/subprocess.html#popen-objects

In particular: http://docs.python.org/2/library/subprocess.html#subprocess.Popen.terminate

HTH!

like image 142
Giupo Avatar answered Oct 06 '22 00:10

Giupo


subprocess.call() is just subprocess.Popen().wait():

from subprocess import Popen
from threading import Timer

p = Popen(["command", "arg1"])
print(p.pid) # you can save pid to a file to use it outside Python

# do something else..

# now ask the command to exit
p.terminate()
terminator = Timer(5, p.kill) # give it 5 seconds to exit; then kill it
terminator.start()
p.wait()
terminator.cancel() # the child process exited, cancel the hit
like image 42
jfs Avatar answered Oct 06 '22 00:10

jfs