Skip to content
Advertisement

Python code for finding top 5 processes using cpu

I am new to python and I have a simple problem of finding the top processes using the CPU. I was able to do it in shell using ps and sort.

I have checked few but links but it do not help partly because the function is defined as below,

define find_proc(ps_input)

ps_input will be something like below,

PID        CPU          PROG
12658       20             ABC
19265       80             BCD
21265       60             BAD
19655       11             BCE

Can someone help me in this program..

Thanks in advance.

Advertisement

Answer

psutil is the one I would recommend. From the PyPI site, here is the package description,

psutil (process and system utilities) is a cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network, sensors) in Python. It is useful mainly for system monitoring, profiling and limiting process resources and management of running processes. It implements many functionalities offered by UNIX command line tools such as: ps, top, lsof, netstat, ifconfig, who, df, kill, free, nice, ionice, iostat, iotop, uptime, pidof, tty, taskset, pmap.

To address your problem statement, here is the sample I took from the site which list outs process sorted by memory – https://thispointer.com/python-get-list-of-all-running-processes-and-sort-by-highest-memory-usage/

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

Complete code is available in the above site; you may need to tweak accordingly to list based on cpu usage. Hope this helps.

Advertisement