In this article we will discuss a cross platform way to get a list of all running processes in system and then sort them by memory usage.
Python provides a cross platform library psutil to fetch sunning system details like process and system details.
How to install psutil python library
To install psutil using pip execute following command,
pip install psutil
It will install the psutil. To use that in code import the module i.e.
import psutil
Create a list of all running process by Iterating over them
psutil provides a function to iterate over all the running process i.e.
psutil.process_iter(attrs=None, ad_value=None)
It will yield an Process class Iterator for all running processes and we can fetch other details from that Process object iterator.
For example, let’s iterate over all the running process and fetch Process Name and Process ID i.e.
Frequently Asked:
import psutil # Iterate over all running process for proc in psutil.process_iter(): try: # Get process name & pid from process object. processName = proc.name() processID = proc.pid print(processName , ' ::: ', processID) except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): pass
Output will be like,
svchost.exe ::: 420 smss.exe ::: 448 notepad.exe ::: 488 WUDFHost.exe ::: 520 svchost.exe ::: 544 fontdrvhost.exe ::: 612 .... ....
Output will vary system to system based on current running process.
Each process object yielded by process_iter() has information about that running process like, id , name, user name, parent id, memory usage and cpu usage etc.
Process object also provides a function to get the process detail as dictionary,
as_dict(attrs=None, ad_value=None)
It will return the value of process attribute passed as dict i.e.
pInfoDict = processObj.as_dict(attrs=['pid', 'name', 'cpu_percent'])
Let’s use this function on process object of each running process and generate list of dictionaries i,e,
import psutil listOfProcessNames = list() # Iterate over all running processes for proc in psutil.process_iter(): # Get process detail as dictionary pInfoDict = proc.as_dict(attrs=['pid', 'name', 'cpu_percent']) # Append dict of process detail in list listOfProcessNames.append(pInfoDict)
Contents of list listOfProcessNames are as follows,
{'cpu_percent': 0.0, 'pid': 4, 'name': 'System'} {'cpu_percent': 0.0, 'pid': 120, 'name': 'Registry'} {'cpu_percent': 0.0, 'pid': 420, 'name': 'svchost.exe'} {'cpu_percent': 0.0, 'pid': 448, 'name': 'smss.exe'} {'cpu_percent': 0.0, 'pid': 488, 'name': 'notepad.exe'} {'cpu_percent': 0.0, 'pid': 520, 'name': 'WUDFHost.exe'} .... ....
We can pass other important attributes too in as_dict() like,
'pid', 'memory_percent', 'name', 'cpu_times', 'create_time', 'memory_info'
Check library documentation for more attributes.
Get List of all running process sorted by Highest Memory Usage
import psutil def getListOfProcessSortedByMemory(): ''' Get list of running process sorted by Memory Usage ''' listOfProcObjects = [] # Iterate over the list for proc in psutil.process_iter(): try: # Fetch process details as dict pinfo = proc.as_dict(attrs=['pid', 'name', 'username']) pinfo['vms'] = proc.memory_info().vms / (1024 * 1024) # Append dict to list listOfProcObjects.append(pinfo); except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): pass # Sort list of dict by key vms i.e. memory usage listOfProcObjects = sorted(listOfProcObjects, key=lambda procObj: procObj['vms'], reverse=True) return listOfProcObjects
It will iterate over the list of all running process and fetch memory usage along with id and name as dict.
Process class provides the memory info of process, it fetches the virtual memory usage from it, then appends the dict for each process to a list. In the end sort the list of dictionary by key vms, so list of process will be sorted by memory usage.
Let’s call this function and print top 5 process by memory usage i.e.
listOfRunningProcess = getListOfProcessSortedByMemory() for elem in listOfRunningProcess[:5] : print(elem)
Output:
{'name': 'pycharm64.exe', 'username': 'varun', 'pid': 2092, 'vms': 662.62109375} {'name': 'chrome.exe', 'username': 'varun', 'pid': 4276, 'vms': 230.421875} {'name': 'SearchUI.exe', 'username': 'varun', 'pid': 11996, 'vms': 94.2890625} {'name': 'chrome.exe', 'username': 'varun', 'pid': 2604, 'vms': 89.8828125} {'name': 'chrome.exe', 'username': 'varun', 'pid': 9616, 'vms': 83.5546875}
Complete code is as follows,
import psutil def getListOfProcessSortedByMemory(): ''' Get list of running process sorted by Memory Usage ''' listOfProcObjects = [] # Iterate over the list for proc in psutil.process_iter(): try: # Fetch process details as dict pinfo = proc.as_dict(attrs=['pid', 'name', 'username']) pinfo['vms'] = proc.memory_info().vms / (1024 * 1024) # Append dict to list listOfProcObjects.append(pinfo); except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): pass # Sort list of dict by key vms i.e. memory usage listOfProcObjects = sorted(listOfProcObjects, key=lambda procObj: procObj['vms'], reverse=True) return listOfProcObjects def main(): print("*** Iterate over all running process and print process ID & Name ***") # Iterate over all running process for proc in psutil.process_iter(): try: # Get process name & pid from process object. processName = proc.name() processID = proc.pid print(processName , ' ::: ', processID) except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): pass print('*** Create a list of all running processes ***') listOfProcessNames = list() # Iterate over all running processes for proc in psutil.process_iter(): # Get process detail as dictionary pInfoDict = proc.as_dict(attrs=['pid', 'name', 'cpu_percent']) # Append dict of process detail in list listOfProcessNames.append(pInfoDict) # Iterate over the list of dictionary and print each elem for elem in listOfProcessNames: print(elem) print('*** Top 5 process with highest memory usage ***') listOfRunningProcess = getListOfProcessSortedByMemory() for elem in listOfRunningProcess[:5] : print(elem) if __name__ == '__main__': main()
Pingback: Python : Check if a process is running by name and find it’s Process ID (PID) – thispointer.com
Pingback: Python Code Snippets #12 – Python Coder