A process monitor is a tool that displays the system information like processes, memory, network, and other stuff. There are plenty of tools available, but we can make our own process monitor using Python. In Python, there is a module called psutil that we can use to grab various information about our system
- psutil: Type the below command in the terminal to install this module.
python3 -m pip install psutil
- Prettytable: To print the data on console, we can use a formatter module PrettyTable:
python3 -m pip install prettytable
psutil provides lots of features to monitor the system. We will see some of them in brief:
- First, we need to import psutil:
- List the process ids:
psutil.pids() # [1,2,.....4352]
- Fetch process information:
process_id = 1 psutil.Process(process_id) # psutil.Process(pid=1, name='systemd', status='sleeping', started='19:49:25')
- We can access various keys of this process:
process = psutil.Process(process_id) process.name() process.status()
- Accessing battery status:
- Accessing Network Interfaces:
psutil.net_if_stats() psutil.net_if_stats()['wlo1'].isup # True
- We can also check the memory:
psutil.virtual_memory() psutil.virtual_memory().total # 8180498432 (In Bytes) psutil.virtual_memory().used # 2155720704 psutil.virtual_memory().available # 5563060224
Now that we know some basic features, we can implement the process monitor. Create a new python file and add the following code in it. The code below works on Linux distributions. For other operating systems, some functions may slightly differ.
- Import the required packages.
- Clear the console using the call() function of the subprocess module. We can use the ‘clear’ or ‘cls’ command depending on OS.
- Fetch the battery information
- Fetch the network information and print it as PrettyTable
- Fetch the memory information
- Fetch the process information
- Create a delay. We have created a 1-second delay using time.sleep(1)
- Press CTRL+C to stop the program.
Below is the implementation:
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course