How to terminate process from Python using pid? How to terminate process from Python using pid? python python

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 osimport signalos.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 psutilfrom subprocess import Popenfor process in psutil.process_iter():    if process.cmdline() == ['python', 'StripCore.py']:        print('Process found. Terminating it.')        process.terminate()        breakelse:    print('Process not found: starting it.')    Popen(['python', 'StripCore.py'])

Sample run:

$python test_strip.py   #test_strip.py contains the code aboveProcess 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.


I wanted to do the same thing as, but I wanted to do it in the one file.

So the logic would be:

  • if a script with my name is running, kill it, then exit
  • if a script with my name is not running, do stuff

I modified the answer by Bakuriu and came up with this:

from os import getpidfrom sys import argv, exitimport psutil  ## pip install psutilmyname = argv[0]mypid = getpid()for process in psutil.process_iter():    if process.pid != mypid:        for path in process.cmdline():            if myname in path:                print "process found"                process.terminate()                exit()## your program starts here...

Running the script will do whatever the script does. Running another instance of the script will kill any existing instance of the script.

I use this to display a little PyGTK calendar widget which runs when I click the clock. If I click and the calendar is not up, the calendar displays. If the calendar is running and I click the clock, the calendar disappears.


So, not directly related but this is the first question that appears when you try to find how to terminate a process running from a specific folder using Python.

It also answers the question in a way(even though it is an old one with lots of answers).

While creating a faster way to scrape some government sites for data I had an issue where if any of the processes in the pool got stuck they would be skipped but still take up memory from my computer. This is the solution I reached for killing them, if anyone knows a better way to do it please let me know!

import pandas as pdimport wmifrom re import escapeimport osdef kill_process(kill_path, execs):    f = wmi.WMI()    esc = escape(kill_path)    temp = {'id':[], 'path':[], 'name':[]}    for process in f.Win32_Process():        temp['id'].append(process.ProcessId)        temp['path'].append(process.ExecutablePath)        temp['name'].append(process.Name)    temp = pd.DataFrame(temp)    temp = temp.dropna(subset=['path']).reset_index().drop(columns=['index'])    temp = temp.loc[temp['path'].str.contains(esc)].loc[temp.name.isin(execs)].reset_index().drop(columns=['index'])    [os.system('taskkill /PID {} /f'.format(t)) for t in temp['id']]