0

I have started a command line program in linux using python with the following command

  os.system()

I want to keep track of the program and kill it while necessary within the same python program.

Would be cool if somebody could tell the safest way of doing it.

Thanks

Shan
  • 18,563
  • 39
  • 97
  • 132
  • 6
    Avoid using `os.system`. The [`subprocess` module](http://docs.python.org/2/library/subprocess.html) addresses this need (and much more), so you should read its (fine) documentation – loopbackbee Feb 13 '14 at 13:43
  • Also the answer may depend on your OS. – hivert Feb 13 '14 at 13:44

1 Answers1

1

Use subprocess.Popen and Popen.pid, you can get the pid of the process you started.

Like this:

>>> s = subprocess.Popen(["/bin/sleep"," 100 &"])
>>> print s.pid
34934

In the other shell, run ps -ef|grep sleep, you can see:

WKPlus@mac:~/workspace/test >ps -ef|grep sleep
  501 34934 34904   0 10:53下午 ttys000    0:00.00 /bin/sleep  100 &
  501 34938   238   0 10:54下午 ttys002    0:00.00 grep sleep

Yes, s.pid is exactly the pid of the process you just started.

And, be careful not to add an shell=True to the subprocess.Popen(["/bin/sleep"," 100 &"]), or you will get the pid of a shell, which is the parent process of /bin/sleep. The official explanation for this:

Note that if you set the shell argument to True, this is the process ID of the spawned shell.

Once you got the pid, you can kill the specified process by using os.kill(pid) after that.

WKPlus
  • 6,955
  • 2
  • 35
  • 53