- Simplify Windows Process Management with Python: Find PIDs and End Processes
- Bare Minimum
- Using os.system
- Using subprocess
- Using psutil
- Bonus: Find Open Port (for socket connection)
- Bonus: Find Main Window Title
- Reference
- Python : Check if a process is running by name and find it’s Process ID (PID)
- Check if a process is running
- Frequently Asked:
- Find PID (Process ID) of a running process by Name
- Related posts:
- How to Get the Process PID in Python
- Need To Get a Process PID
- What is a PID
- How to Get a Process PID
- PID via Process Instance
Simplify Windows Process Management with Python: Find PIDs and End Processes
but to gain more flexibility, using python is probably a better idea.
- os.system is not the most elegant way to use, and it is meant to be replaced by subprocess
- subprocess comes with Python standard library and allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes
- psutil (python system and process utilities) is a cross-platform library for retrieving information on running processes and system utilization. However, it is a third-party library
Bare Minimum
the bare minimum command to kill process utilizes window’s taskkill ; which doesn’t matter if you use os.system or subprocess
import os
PROCESS = ‘notepad.exe’
STATUS = ‘running’ # running or not responding
CMD = r’taskkill /fi «IMAGENAME eq {}» /fi «STATUS eq {}» ‘.format(PROCESS, STATUS)
os.system(CMD)
Using os.system
Now consider a more flexible case where you want to gather information about the processes like its PID, and then proceed on ending the process. One of the downside of window shell command is that the output can’t be passed on to other command, the output is just text. Therefore, we output the text to a csv file which we will later process.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import csv
import os
import signal
import subprocess
PROCESS = ‘notepad.exe’
STATUS = ‘running’ # running or not responding
TMP = r'{}/Desktop/tmp.txt’.format(os.environ[‘userprofile’])
CMD = r’tasklist /fi «IMAGENAME eq {}» /fi «STATUS eq {}» /fo «csv» > «{}»‘.format(PROCESS, STATUS, TMP)
# output as csv format
os.system(CMD)
with open(TMP, ‘r’) as temp:
reader = csv.reader(temp)
header = next(reader)
pids = [int(row[1]) for row in reader]
# kill process
for pid in pids:
os.kill(pid, signal.SIGTERM) # or signal.SIGKILL
print(‘killed process with pid: {}’.format(pid))
if os.path.exists(TMP):
os.remove(TMP)
Using subprocess
With subprocess , we no longer need to create a temp file to store the output.
Using psutil
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import psutil
PROGRAM = r’maya.exe’
def findProcess(name):
procs = list()
#Iterate over the all the running process
for proc in psutil.process_iter():
try:
if proc.name() == name and proc.status() == psutil.STATUS_RUNNING:
pid = proc.pid
procs.append(pid)
except:
pass
return procs
processes = findProcess(PROGRAM)
we can find process start time by using
import time
startTime = time.strftime(‘%Y-%m-%d %H:%M:%S’, time.localtime(proc.create_time()))
to kill process, either kill() or terminate() will work respectfully, SIGKILL or SIGTERM
p = psutil.Process(PID)
p.terminate()
p.kill()
p.wait
Bonus: Find Open Port (for socket connection)
process = psutil.Process(pid=PID)
connections = process.connections(kind=‘tcp4’)
for c in [x for x in connections if x.status == psutil.CONN_LISTEN]:
# gets the port number
print(‘port opened: {}’.format(c.laddr[-1]))
Bonus: Find Main Window Title
ctypes is a foreign function library for python, resulting a not-pythonic function
Reference
- Shared Link:https://www.xingyulei.com/post/py-end-process/
- Copyright Notice: This post is licensed under a Creative Commons Attribution 4.0 International License . Please give appropriate credit.
- Disclaimer: The information contained in this post is provided on an «as is» basis. The author assumes no responsibility or liability for any errors or omissions in the content of this post.
Python : Check if a process is running by name and find it’s Process ID (PID)
In this article we will discuss a cross platform way to find a running process PIDs by name using psutil.
To install python’s psutil library use,
Check if a process is running
To check if process is running or not, let’s iterate over all the running process using psutil.process_iter() and match the process name i.e.
import psutil def checkIfProcessRunning(processName): ''' Check if there is any running process that contains the given name processName. ''' #Iterate over the all the running process for proc in psutil.process_iter(): try: # Check if process name contains the given name string. if processName.lower() in proc.name().lower(): return True except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): pass return False;
Let’s use this function to check if any process with ‘chrome’ substring in name is running or not i.e.
Frequently Asked:
# Check if any chrome process was running or not. if checkIfProcessRunning('chrome'): print('Yes a chrome process was running') else: print('No chrome process was running')
Yes a chrome process was running
As in my system many chrome instances are running. So it will return True. But how to get the process ID of all the running ‘chrome.exe’ process ?
Find PID (Process ID) of a running process by Name
As there may be many running instances of a given process. So, we will iterate over all the running process and for each process whose name contains the given string, we will keep it’s info in a list i.e.
import psutil def findProcessIdByName(processName): ''' Get a list of all the PIDs of a all the running process whose name contains the given string processName ''' listOfProcessObjects = [] #Iterate over the all the running process for proc in psutil.process_iter(): try: pinfo = proc.as_dict(attrs=['pid', 'name', 'create_time']) # Check if process name contains the given name string. if processName.lower() in pinfo['name'].lower() : listOfProcessObjects.append(pinfo) except (psutil.NoSuchProcess, psutil.AccessDenied , psutil.ZombieProcess) : pass return listOfProcessObjects;
Let’s call this function to get the PIDs of all the running chrome.exe process
# Find PIDs od all the running instances of process that contains 'chrome' in it's name listOfProcessIds = findProcessIdByName('chrome') if len(listOfProcessIds) > 0: print('Process Exists | PID and other details are') for elem in listOfProcessIds: processID = elem['pid'] processName = elem['name'] processCreationTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(elem['create_time'])) print((processID ,processName,processCreationTime )) else : print('No Running Process found with given text')
Contents of the list will be,
(2604, 'chrome.exe', '2018-11-10 19:12:13') (4276, 'chrome.exe', '2018-11-10 19:12:14') (9136, 'chrome.exe', '2018-11-10 19:12:14') (9616, 'chrome.exe', '2018-11-10 19:43:41') (12904, 'chrome.exe', '2018-11-10 19:12:13') (13476, 'chrome.exe', '2018-11-10 20:03:04') (15520, 'chrome.exe', '2018-11-10 20:02:22')
We can do the same in a single line using list comprehension i.e.
# Find PIDs od all the running instances of process that contains 'chrome' in it's name procObjList = [procObj for procObj in psutil.process_iter() if 'chrome' in procObj.name().lower() ]
procObjList is a list of Process class objects. Let’s iterate over it and print them i.e.
for elem in procObjList: print (elem)
psutil.Process(pid=2604, name='chrome.exe', started='19:12:13') psutil.Process(pid=4276, name='chrome.exe', started='19:12:14') psutil.Process(pid=9136, name='chrome.exe', started='19:12:14') psutil.Process(pid=9616, name='chrome.exe', started='19:43:41') psutil.Process(pid=12904, name='chrome.exe', started='19:12:13') psutil.Process(pid=13476, name='chrome.exe', started='20:03:04') psutil.Process(pid=15520, name='chrome.exe', started='20:02:22')
Complete example is as follows,
import psutil import time def checkIfProcessRunning(processName): ''' Check if there is any running process that contains the given name processName. ''' #Iterate over the all the running process for proc in psutil.process_iter(): try: # Check if process name contains the given name string. if processName.lower() in proc.name().lower(): return True except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): pass return False; def findProcessIdByName(processName): ''' Get a list of all the PIDs of a all the running process whose name contains the given string processName ''' listOfProcessObjects = [] #Iterate over the all the running process for proc in psutil.process_iter(): try: pinfo = proc.as_dict(attrs=['pid', 'name', 'create_time']) # Check if process name contains the given name string. if processName.lower() in pinfo['name'].lower() : listOfProcessObjects.append(pinfo) except (psutil.NoSuchProcess, psutil.AccessDenied , psutil.ZombieProcess) : pass return listOfProcessObjects; def main(): print("*** Check if a process is running or not ***") # Check if any chrome process was running or not. if checkIfProcessRunning('chrome'): print('Yes a chrome process was running') else: print('No chrome process was running') print("*** Find PIDs of a running process by Name ***") # Find PIDs od all the running instances of process that contains 'chrome' in it's name listOfProcessIds = findProcessIdByName('chrome') if len(listOfProcessIds) > 0: print('Process Exists | PID and other details are') for elem in listOfProcessIds: processID = elem['pid'] processName = elem['name'] processCreationTime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(elem['create_time'])) print((processID ,processName,processCreationTime )) else : print('No Running Process found with given text') print('** Find running process by name using List comprehension **') # Find PIDs od all the running instances of process that contains 'chrome' in it's name procObjList = [procObj for procObj in psutil.process_iter() if 'chrome' in procObj.name().lower() ] for elem in procObjList: print (elem) if __name__ == '__main__': main()
*** Check if a process is running or not *** Yes a chrome process was running *** Find PIDs of a running process by Name *** Process Exists | PID and other details are (2604, 'chrome.exe', '2018-11-10 19:12:13') (4276, 'chrome.exe', '2018-11-10 19:12:14') (9136, 'chrome.exe', '2018-11-10 19:12:14') (9616, 'chrome.exe', '2018-11-10 19:43:41') (12904, 'chrome.exe', '2018-11-10 19:12:13') (13476, 'chrome.exe', '2018-11-10 20:03:04') (15520, 'chrome.exe', '2018-11-10 20:02:22') ** Find running process by name using List comprehension ** psutil.Process(pid=2604, name='chrome.exe', started='19:12:13') psutil.Process(pid=4276, name='chrome.exe', started='19:12:14') psutil.Process(pid=9136, name='chrome.exe', started='19:12:14') psutil.Process(pid=9616, name='chrome.exe', started='19:43:41') psutil.Process(pid=12904, name='chrome.exe', started='19:12:13') psutil.Process(pid=13476, name='chrome.exe', started='20:03:04') psutil.Process(pid=15520, name='chrome.exe', started='20:02:22')
Related posts:
How to Get the Process PID in Python
You can get the process pid via the multiprocessing.Process.pid attribute or via the os.getpid() and os.getppid() functions.
In this tutorial you will discover how to get the process pid in Python.
Need To Get a Process PID
A process is a running instance of a computer program.
Every Python program is executed in a Process, which is a new instance of the Python interpreter. This process has the name MainProcess and has one thread used to execute the program instructions called the MainThread. Both processes and threads are created and managed by the underlying operating system.
Sometimes we may need to create new child processes in our program in order to execute code concurrently.
Python provides the ability to create and manage new processes via the multiprocessing.Process class.
You can learn more about multiprocessing in the tutorial:
In multiprocessing, we may need to get the process identifier or PID of a process.
- We may need the pid of the current process.
- We may need the pid of a child process.
- We may need the pid of the parent process.
How can we get the pid of a process in Python?
Run your loops using all CPUs, download my FREE book to learn how.
What is a PID
A process identifier is a unique number assigned to a process by the underlying operating system.
Each time a process is started, it is assigned a unique positive integer identifier and the identifier may be different each time the process is started.
The pid uniquely identifies one process among all active processes running on the system, managed by the operating system.
As such, the pid can be used to interact with a process, e.g. to send a signal to the process to interrupt or kill a process.
Confused by the multiprocessing module API?
Download my FREE PDF cheat sheet
How to Get a Process PID
We can get the pid from the multiprocessing.Process instance or via os module functions such as os.getpid() and os.getppid().
Let’s take a closer look at each approach in turn.
PID via Process Instance
We can get the pid of a process via its multiprocessing.Process instance.
When we create a child process, we may hang on to the process instance.
Alternatively, we may get the process instance for the parent process via the multiprocessing.parent_process() function or for child process via the multiprocessing.active_children() function.
We may also get the process instance for the current process via the multiprocessing.current_process() function.