Skip to content

WebNinjaDeveloper.com

Programming Tutorials




Menu
  • Home
  • Youtube Channel
  • Sitemap
Menu

Python 3 Script to Build Realtime CPU & Memory Usage Monitor in Terminal Using psutil Library

Posted on February 12, 2023

 

 

Welcome folks today in this blog post we will be displaying realtime cpu & memory usage monitor in terminal using psutil library in python. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to install the below library using the pip command as shown below

 

 

pip install psutil

 

 

After installing this you need to make an app.py file and copy paste the following code

 

 

app.py

 

 

1
2
3
4
5
6
import time
import psutil
 
while True:
    display_usage(psutil.cpu_percent(),psutil.virtual_memory().percent,30)
    time.sleep(0.5)

 

 

As you can see we are importing the psutil and time module at the very top and then we are using the infinite while loop to show the realtime cpu usage in command line. And for this we are calling the external function called display_usage() here we are passing threee arguments first one is the cpu usage percent and secondly we are passing the memory usage and thirdly we are passing the no of bars for the animation.

 

Now we need to define this function which will display the bar animation of realtime usage as shown below

 

 

Python
1
2
3
4
5
6
7
def display_usage(cpu_usage,mem_usage,bars=50):
    cpu_percent = (cpu_usage/100.0)
    cpu_bar = '▉' * int(cpu_percent*bars) + '-' * (bars - int(cpu_percent*bars))
    mem_percent = (mem_usage/100.0)    
    mem_bar = '▉' * int(mem_percent*bars) + '-' * (bars - int(mem_percent*bars))
    print(f"\r CPU Usage: | |{cpu_bar}| {cpu_usage:.2f}%",end="")
    print(f" Mem Usage: | |{mem_bar}| {mem_usage:.2f}%",end="\r")

 

 

As you can see we are getting the cpu usage percentage by dividing the result by 100 and then we are constructing the animation bar for showing the animation and same thing we are doing for the memory usage also and lastly we are printing the bar animation which will contain the cpu usage and memory usage.

 

 

 

Recent Posts

  • Build a Fixed Deposit Interest Calculator Using Amount and Time in Browser Using HTML5 & Javascript
  • How to Download Files From URL in Node.js Using Node-Downloader-Helper Library
  • Angular 10 Image Carousel and Video Gallery Lightbox Modal Slider Using ng-image-slider Library
  • React Unsplash Api Photo Search App
  • React Form Validation Using Formik and Yup
  • Angular
  • Bunjs
  • C#
  • Deno
  • django
  • Electronjs
  • javascript
  • Koajs
  • Laravel
  • meteorjs
  • Nestjs
  • Nextjs
  • Nodejs
  • PHP
  • Python
  • React
  • Svelte
  • Tutorials
  • Vuejs




©2023 WebNinjaDeveloper.com | Design: Newspaperly WordPress Theme