Introduction
In this tutorial, we will be looking at how to get system information such as CPU percentage, disk usage, memory usage, CPU count, and many more using python. To begin will need to install a module psutil which is a cross-platform library for system and process monitoring in python.
Table of Contents
Install module
To install our psutil module run the command below.
pip3 install psutil
Create app
Now let’s create a file called app.py and import the library below.
import psutil
CPU percentage
cpu_usage = psutil.cpu_percent()
print(f"CPU usage: {cpu_usage}%")
Output
CPU usage: 0.0%
CPU count
cpu_count = psutil.cpu_count(logical=False)
print(f"CPU count: {cpu_count}")
Output
CPU count: 2
Logged in users
try:
for user in psutil.users():
print("Username:", user.name)
except psutil.NotImplementedError:
print("Unable to retrieve user information on this platform.")
Output
Username: kali
Memory statistics
memory_stats = psutil.virtual_memory()
print(f"Total memory: {memory_stats.total / 1024 / 1024} MB")
print(f"Available memory: {memory_stats.available / 1024 / 1024} MB")
print(f"Memory usage: {memory_stats.percent}%")
Output
Total memory: 3504.26953125 MB
Available memory: 628.75 MB
Memory usage: 82.1%
Disk usage
disk_stats = psutil.disk_usage('/')
print(f"Total disk space: {disk_stats.total / 1024 / 1024 / 1024} GB")
print(f"Used disk space: {disk_stats.used / 1024 / 1024 / 1024} GB")
print(f"Free disk space: {disk_stats.free / 1024 / 1024 / 1024} GB")
print(f"Disk usage: {disk_stats.percent}%")
Output
Total disk space: 456.4401626586914 GB
Used disk space: 284.88196182250977 GB
Free disk space: 148.30224609375 GB
Disk usage: 65.8%
There you have it, Thanks for reading. Happy Coding