Узнать запущенные процессы python

How to Find and List All Running Processes in Python

In this tutorial, we are going to learn how to find and list all running processes in Python. It is a very simple program.

Python program to find and list all running processes

To do this, we need psutil library. Let us install it.

Now, we need to import it into our program.

We have a method called process_iter which iterates all the running processes. This method is present within the psutil library. That’s the reason we have imported it into our program.

c=0 for process in psutil.process_iter (): c=c+1 Name = process.name () # Name of the process # ID of the process print ("Process name =", Name ,",","Process \nTotal number of running process are ", c)

For every process that is running, we are getting its name and ID using the name and pid methods.

To count the total number of running processes, I used the variable ‘c’ and incremented it for every process.

Process name = System Idle Process , Process name = System , Process name = Registry , Process name = RuntimeBroker.exe , Process name = smss.exe , Process name = svchost.exe , Process name = csrss.exe , Process . . Process name = chrome.exe , Process name = svchost.exe , Process name = svchost.exe , Process name = svchost.exe , Process name = csrss.exe , Process name = ApntEx.exe , Process number of running process are 145

The output varies from system to system. It depends on the processes that are running at that moment. At this moment there are 145 running processes in my system.

Читайте также:  Поиск минимума python алгоритм

Источник

Python : Get List of all running processes and sort by highest memory usage

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,

It will install the psutil. To use that in code import the module i.e.

Frequently Asked:

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.

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
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,

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)

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()

Источник

Оцените статью