How to Terminate Process from Python Using Pid

How to terminate process from Python using pid?

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.

Getting Python to kill a pid

Read this answer.

BTW a more pythonic solution may be this:

    import re
import psutil

convicted = re.compile(r'student|daemon')

for p in psutil.process_iter():
if convicted.search(p.name):
p.terminate()

Edit: To be more accurate I changed the line p.kill() to p.terminate(). The common kill in bash is actually the same as p.terminate() (it sends the TERM signal). But the p.kill() corresponds to kill -9 in bash (it sends the KILL signal).

How do you kill a process in multi-processing with it's PID?

You should probably save the processes in a dict keyed by the process id (pid attribute) for fast lookup. Then you can call terminate on the Process instance:

import multiprocessing as mp

def func():
...

process_dict = {}
for _ in range(10):
process = mp.Process(target=func)
process.start()
process_dict[process.pid] = process
...
# Kill a process given a pid:
# This also removes the key from the dictionary:
process = process_dict.pop(pid)
process.terminate()
...
# Wait for remaining processes to end:
for process in process_dict.values():
process.join()

The assumption is that the pid belongs to one of the processes that you created (otherwise the pop operation will raise a KeyError exception.

The above code assumes you are running under a platform that uses fork to create new processes (such as Linux) and therefore you do not need to place code that creates new processes within a if __name__ == '__main__': block. But you really should tag your question with the platform.

How to kill process on GPUs with PID in nvidia-smi using keyword?

You can grep python in the nvidia-smi and then pass the PID to
the kill -9 command, e.g.

sudo kill -9 $( nvidia-smi | grep 'python' | sed -n
's/|\s*[0-9]\s([0-9])\s.*/\1/p' | sed '/^$/d')

Terminate Python Process and halt it's underlying os.system command line

You can use taskkill but you have to use the /T (and maybe /F) switch so all child processes of the cmd process are killed too. You get the process id of the cmd task via process.pid.



Related Topics



Leave a reply



Submit