Exercise
Retrieving System Information
Objective
Develop a Python program that retrieves and displays system information, such as the operating system, CPU details, memory usage, and disk space. The program should use libraries like platform, psutil, or os to gather this information and present it in a user-friendly format. Include error handling for unsupported systems or missing libraries.
Example Python Exercise
Show Python Code
import platform
import psutil
import os
def get_system_info():
"""Retrieve and display system information."""
# Get operating system information
try:
os_info = platform.system()
os_version = platform.version()
os_release = platform.release()
except Exception as e:
print(f"Error retrieving OS information: {e}")
os_info = os_version = os_release = "N/A"
# Get CPU information
try:
cpu_count = psutil.cpu_count(logical=True)
cpu_percent = psutil.cpu_percent(interval=1) # Get CPU usage percentage
except Exception as e:
print(f"Error retrieving CPU information: {e}")
cpu_count = cpu_percent = "N/A"
# Get memory usage information
try:
memory = psutil.virtual_memory()
memory_total = memory.total / (1024 ** 3) # Convert to GB
memory_used = memory.used / (1024 ** 3) # Convert to GB
memory_percent = memory.percent
except Exception as e:
print(f"Error retrieving memory information: {e}")
memory_total = memory_used = memory_percent = "N/A"
# Get disk space information
try:
disk = psutil.disk_usage('/')
disk_total = disk.total / (1024 ** 3) # Convert to GB
disk_used = disk.used / (1024 ** 3) # Convert to GB
disk_free = disk.free / (1024 ** 3) # Convert to GB
except Exception as e:
print(f"Error retrieving disk information: {e}")
disk_total = disk_used = disk_free = "N/A"
# Display the system information
print("\nSystem Information:")
print(f"Operating System: {os_info} {os_release} ({os_version})")
print(f"CPU: {cpu_count} cores, {cpu_percent}% usage")
print(f"Memory: {memory_total:.2f} GB Total, {memory_used:.2f} GB Used, {memory_percent}% Used")
print(f"Disk: {disk_total:.2f} GB Total, {disk_used:.2f} GB Used, {disk_free:.2f} GB Free")
def main():
"""Main function to display system information."""
try:
get_system_info()
except Exception as e:
print(f"Error in retrieving system information: {e}")
if __name__ == "__main__":
main()
Output
System Information:
Operating System: Windows 10 Pro (10.0.19042)
CPU: 8 cores, 23.4% usage
Memory: 16.00 GB Total, 8.56 GB Used, 53% Used
Disk: 500.00 GB Total, 150.00 GB Used, 350.00 GB Free
Share this Python Exercise