Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to terminate process from Python using pid?

I'm trying to write some short script in python which would start another python code in subprocess if is not already started else terminate terminal & app (Linux).

So it looks like:

#!/usr/bin/python from subprocess import Popen  text_file = open(".proc", "rb") dat = text_file.read() text_file.close()  def do(dat):      text_file = open(".proc", "w")     p = None      if dat == "x" :          p = Popen('python StripCore.py', shell=True)         text_file.write( str( p.pid ) )      else :         text_file.write( "x" )          p = # Assign process by pid / pid from int( dat )         p.terminate()      text_file.close()  do( dat ) 

Have problem of lacking knowledge to name proces by pid which app reads from file ".proc". The other problem is that interpreter says that string named dat is not equal to "x" ??? What I've missed ?

like image 995
Alex Avatar asked Jul 25 '13 11:07

Alex


People also ask

How do you kill a process using process ID in Python?

You can kill a process via its pid with the os. kill() function. The os. kill function takes two arguments, the process identifier (pid) to kill, and the signal to send to kill the process.

How do you end a Python process?

A process can be killed by calling the Process. kill() function. The call will only terminate the target process, not child processes. The method is called on the multiprocessing.

How do you kill a process with changing PID?

You can use ps to find the PID of the process, then pass that to kill : kill $(ps -C /usr/lib/gvfs/gvfsd-mtp -o pid=) The -C flag specifies a command name to search for in the list of processes, and the -o pid= option means ps will print only the PID. The result is passed as the only argument to kill .

Is it necessary to set PID in Python?

AFAIK it isn't needed in your use case. Note also that when using shell=True the pid returned by p.pid is not the pid of the python process, but the pid of the shell spawned to execute this process. +1 for your comment, but I consider it as appropriate because I need to close terminal as well.

How to terminate a subprocess created in Python?

Here is the full code to terminate a subprocess created in python. import os import signal import subprocess pro = subprocess.Popen (cmd, stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid) os.killpg (os.getpgid (pro.pid), signal.SIGTERM) In the above command, we use killpg command to send the terminate signal to all the process groups.

How to terminate a program in Python?

Let us get started with Different ways to terminate a program in Python. Using the python quit function is a simple and effective way to exit a python program. No external imports are required for this. The program ends after encountering the quit function and the last line is not printed. The python sys module can be imported and used .

How do I Kill a process using psutil?

Using the awesome psutil library it's pretty simple: p = psutil.Process (pid) p.terminate () #or p.kill () If you don't want to install a new library, you can use the os module: import os import signal os.kill (pid, signal.SIGTERM) #or signal.SIGKILL


1 Answers

Using the awesome psutil library it's pretty simple:

p = psutil.Process(pid) p.terminate()  #or p.kill() 

If you don't want to install a new library, you can use the os module:

import os import signal  os.kill(pid, signal.SIGTERM) #or signal.SIGKILL  

See also the os.kill documentation.


If you are interested in starting the command python StripCore.py if it is not running, and killing it otherwise, you can use psutil to do this reliably.

Something like:

import psutil from subprocess import Popen  for process in psutil.process_iter():     if process.cmdline() == ['python', 'StripCore.py']:         print('Process found. Terminating it.')         process.terminate()         break else:     print('Process not found: starting it.')     Popen(['python', 'StripCore.py']) 

Sample run:

$python test_strip.py   #test_strip.py contains the code above Process not found: starting it. $python test_strip.py  Process found. Terminating it. $python test_strip.py  Process not found: starting it. $killall python $python test_strip.py  Process not found: starting it. $python test_strip.py  Process found. Terminating it. $python test_strip.py  Process not found: starting it. 

Note: In previous psutil versions cmdline was an attribute instead of a method.

like image 133
Bakuriu Avatar answered Sep 26 '22 21:09

Bakuriu