5

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.

mdml
  • 22,442
  • 8
  • 58
  • 66
Mero
  • 1,280
  • 4
  • 15
  • 25

3 Answers3

3

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!

Giupo
  • 413
  • 2
  • 9
1

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
jfs
  • 399,953
  • 195
  • 994
  • 1,670
0

subprocess.call waits for the process to be completed and returns the exit code (integer) value , hence there is no way of knowing the process id of the child process. YOu should consider using subprocess.Popen which forks() child process.

Arovit
  • 3,579
  • 5
  • 20
  • 24