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.

Create a list of all running process by Iterating over them

psutil provides a function to iterate over all the running process i.e.

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.

Output will be like,

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,

It will return the value of process attribute passed as dict i.e.

Let’s use this function on process object of each running process and generate list of dictionaries i,e,

Contents of list listOfProcessNames are as follows,

We can pass other important attributes too in as_dict() like,

Check library documentation for more attributes.

Get List of all running process sorted by Highest Memory Usage

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.

Output:

Complete code is as follows,

 

Click Here to Subscribe for more Articles / Tutorials like this.