Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # Filename: system_info_collector.py
- # Version: 1.0.0
- # Author: Jeoi Reqi
- """
- Description:
- - This script collects various system information such as CPU, memory, disk, GPU, and system details.
- - It then formats the collected information as plain text and optionally saves it to a text file.
- Requirements:
- - Python 3.x
- - psutil
- - GPUtil
- Functions:
- - get_cpu_info():
- Retrieves CPU information.
- - get_memory_info():
- Retrieves memory information.
- - get_disk_info():
- Retrieves disk information.
- - get_gpu_info():
- Retrieves GPU information.
- - get_system_info():
- Retrieves system information.
- - format_data_as_text(data):
- Formats collected system information as plain text.
- - main():
- Main function to collect and save system information.
- Usage:
- - Run the script.
- - Follow the on-screen prompts to save the information to a text file if desired.
- Additional Notes:
- - Ensure that 'psutil' and 'GPUtil' libraries are installed.
- - The script may take some time to collect system information depending on the system's configuration.
- """
- import psutil
- import GPUtil
- import os
- def get_cpu_info():
- """Retrieve CPU information.
- Returns:
- tuple: A tuple containing a dictionary with CPU information and a boolean indicating success.
- """
- try:
- cpu_info = {
- "Physical Cores": psutil.cpu_count(logical=False),
- "Total Cores": psutil.cpu_count(logical=True),
- "Max Frequency (MHz)": psutil.cpu_freq().max,
- "Min Frequency (MHz)": psutil.cpu_freq().min,
- "Current Frequency (MHz)": psutil.cpu_freq().current,
- "CPU Usage per Core (%)": psutil.cpu_percent(percpu=True),
- "Total CPU Usage (%)": psutil.cpu_percent()
- }
- return cpu_info, True
- except Exception as e:
- return str(e), False
- def get_memory_info():
- """Retrieve memory information.
- Returns:
- tuple: A tuple containing a dictionary with memory information and a boolean indicating success.
- """
- try:
- svmem = psutil.virtual_memory()
- memory_info = {
- "Total Memory (bytes)": svmem.total,
- "Available Memory (bytes)": svmem.available,
- "Used Memory (bytes)": svmem.used,
- "Memory Usage (%)": svmem.percent
- }
- return memory_info, True
- except Exception as e:
- return str(e), False
- def get_disk_info():
- """Retrieve disk information.
- Returns:
- tuple: A tuple containing a list of dictionaries with disk information for each partition and a boolean indicating success.
- """
- try:
- partitions = psutil.disk_partitions()
- disk_info = []
- for partition in partitions:
- partition_info = {
- "Device": partition.device,
- "Mountpoint": partition.mountpoint,
- "File System Type": partition.fstype
- }
- try:
- partition_usage = psutil.disk_usage(partition.mountpoint)
- partition_info.update({
- "Total Size (bytes)": partition_usage.total,
- "Used Size (bytes)": partition_usage.used,
- "Free Size (bytes)": partition_usage.free,
- "Usage (%)": partition_usage.percent
- })
- except PermissionError:
- continue
- disk_info.append(partition_info)
- return disk_info, True
- except Exception as e:
- return str(e), False
- def get_gpu_info():
- """Retrieve GPU information.
- Returns:
- tuple: A tuple containing a list of dictionaries with GPU information for each GPU and a boolean indicating success.
- """
- try:
- gpus = GPUtil.getGPUs()
- gpu_info = []
- for gpu in gpus:
- gpu_info.append({
- "ID": gpu.id,
- "Name": gpu.name,
- "Driver Version": gpu.driver,
- "Total Memory (MB)": gpu.memoryTotal,
- "Free Memory (MB)": gpu.memoryFree,
- "Used Memory (MB)": gpu.memoryUsed,
- "GPU Load (%)": gpu.load * 100,
- "Temperature (C)": gpu.temperature
- })
- return gpu_info, True
- except Exception as e:
- return str(e), False
- def get_system_info():
- """Retrieve system information using 'systeminfo' command.
- Returns:
- tuple: A tuple containing the system information as a string and a boolean indicating success.
- """
- try:
- system_info = os.popen('systeminfo').read()
- return system_info, True
- except Exception as e:
- return str(e), False
- def format_data_as_text(data):
- """Format system information data as plain text.
- Args:
- data (dict): A dictionary containing various system information.
- Returns:
- str: Formatted system information data as plain text.
- """
- formatted_data = []
- def add_section(title, info, success):
- formatted_data.append(f"{title}\n" + "="*len(title) + "\n")
- if success:
- if isinstance(info, dict):
- for key, value in info.items():
- formatted_data.append(f"{key}: {value}")
- else:
- formatted_data.append(info)
- else:
- formatted_data.append(f"Error: {info}")
- formatted_data.append("\n")
- add_section("CPU Information", *data["cpu_info"])
- add_section("Memory Information", *data["memory_info"])
- formatted_data.append("Disk Information\n" + "="*15 + "\n")
- for idx, disk in enumerate(*data["disk_info"]):
- formatted_data.append(f"Disk {idx + 1}\n" + "-"*6)
- for key, value in disk.items():
- formatted_data.append(f"{key}: {value}")
- formatted_data.append("\n")
- formatted_data.append("GPU Information\n" + "="*14 + "\n")
- for idx, gpu in enumerate(*data["gpu_info"]):
- formatted_data.append(f"GPU {idx + 1}\n" + "-"*5)
- for key, value in gpu.items():
- formatted_data.append(f"{key}: {value}")
- formatted_data.append("\n")
- add_section("System Information", *data["system_info"])
- return "\n".join(formatted_data)
- def main():
- """Main function to collect and save system information."""
- print("\n" + "-" * 60 + "\n\t Welcome To The System Info Collector\n\n[This may take some time to collect your system information]\n\n\t Thank you for your patience\n" + "-" * 60)
- data = {
- "cpu_info": get_cpu_info(),
- "memory_info": get_memory_info(),
- "disk_info": get_disk_info(),
- "gpu_info": get_gpu_info(),
- "system_info": get_system_info()
- }
- print("\n\t System information collected:\n")
- for info_name, (_, success) in data.items():
- status = "Success" if success else "Failed"
- print(f"\t - {info_name.ljust(18)}: {status}")
- # Check if the user wants to save the data
- save = input("\nWould you like to save this info to a text file? (y/n): ").strip().lower()
- if save == 'y':
- file_name = "system_info.txt"
- formatted_text = format_data_as_text(data)
- with open(file_name, "w", encoding='utf-8') as file:
- file.write(formatted_text)
- print(f"\nFILE: {{{file_name}}} has been saved in the cwd.")
- print("\n" + "-" * 60 + "\n\t Exiting Program... Goodbye!\n" + "-" * 60 + "\n")
- else:
- print("\n" + "-" * 60 + "\n\t Exiting Program... Goodbye!\n" + "-" * 60 + "\n")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement