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,

JavaScript

ps_input will be something like below,

JavaScript

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/

JavaScript

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

Advertisement