Python案例如何获取系统信息?

wen python案例 26

本文目录导读:

Python案例如何获取系统信息?

  1. 使用内置模块获取基本信息
  2. 使用psutil库 - 最全面的系统信息库
  3. 跨平台兼容的CPU信息获取
  4. 图形化系统信息显示
  5. 简洁版系统报告函数
  6. 主要库说明

在Python中获取系统信息有多种方法,我为你整理了几个常用案例:

使用内置模块获取基本信息

os模块 - 基础系统信息

import os
import platform
# 操作系统类型
print(f"操作系统: {os.name}")  # 'posix', 'nt', 'java'
print(f"系统名称: {platform.system()}")  # Windows, Linux, Darwin等
print(f"系统版本: {platform.version()}")
# 主机信息
print(f"主机名: {os.uname().nodename}")
print(f"体系结构: {platform.machine()}")
print(f"处理器: {platform.processor()}")
# 环境变量
print(f"PATH: {os.environ.get('PATH', 'N/A')}")
print(f"HOME: {os.environ.get('HOME', os.environ.get('USERPROFILE', 'N/A'))}")

使用psutil库 - 最全面的系统信息库

首先安装:pip install psutil

import psutil
import datetime
# CPU信息
print(f"CPU核心数: {psutil.cpu_count()}")
print(f"CPU逻辑核心数: {psutil.cpu_count(logical=True)}")
print(f"CPU使用率: {psutil.cpu_percent(interval=1)}%")
print(f"CPU频率: {psutil.cpu_freq().current} MHz")
# 内存信息
memory = psutil.virtual_memory()
print(f"总内存: {memory.total / (1024**3):.2f} GB")
print(f"可用内存: {memory.available / (1024**3):.2f} GB")
print(f"内存使用率: {memory.percent}%")
# 磁盘信息
for partition in psutil.disk_partitions():
    print(f"分区: {partition.device}")
    usage = psutil.disk_usage(partition.mountpoint)
    print(f"  总空间: {usage.total / (1024**3):.2f} GB")
    print(f"  已使用: {usage.used / (1024**3):.2f} GB")
    print(f"  使用率: {usage.percent}%")
# 网络信息
net_io = psutil.net_io_counters()
print(f"发送字节: {net_io.bytes_sent / (1024**2):.2f} MB")
print(f"接收字节: {net_io.bytes_recv / (1024**2):.2f} MB")
# 进程信息
print(f"进程数量: {len(psutil.pids())}")
# 系统启动时间
boot_time = datetime.datetime.fromtimestamp(psutil.boot_time())
print(f"系统启动时间: {boot_time}")
print(f"系统运行时间: {datetime.datetime.now() - boot_time}")

跨平台兼容的CPU信息获取

import platform
import os
def get_cpu_info():
    system = platform.system()
    cpu_info = {}
    if system == "Windows":
        # Windows下使用wmic
        try:
            import subprocess
            result = subprocess.check_output(
                'wmic cpu get name,NumberOfCores,NumberOfLogicalProcessors,MaxClockSpeed',
                shell=True
            ).decode()
            cpu_info['raw'] = result
        except:
            cpu_info['raw'] = "无法获取Windows CPU信息"
    elif system == "Linux":
        # Linux下读取 /proc/cpuinfo
        try:
            with open('/proc/cpuinfo', 'r') as f:
                lines = f.readlines()
                for line in lines:
                    if 'model name' in line:
                        cpu_info['model'] = line.split(':')[1].strip()
                        break
                # 统计CPU核心数
                core_count = sum(1 for line in lines if 'processor' in line)
                cpu_info['cores'] = core_count
        except FileNotFoundError:
            cpu_info['raw'] = "无法读取/proc/cpuinfo"
    elif system == "Darwin":  # macOS
        try:
            import subprocess
            result = subprocess.check_output(['sysctl', '-n', 'machdep.cpu.brand_string'])
            cpu_info['model'] = result.decode().strip()
        except:
            cpu_info['raw'] = "无法获取macOS CPU信息"
    return cpu_info
# 使用
print(get_cpu_info())

图形化系统信息显示

import psutil
import tkinter as tk
from tkinter import ttk
import threading
import time
class SystemMonitorApp:
    def __init__(self, root):
        self.root = root
        self.root.title("系统监控器")
        self.root.geometry("400x500")
        # 创建显示标签
        self.labels = {}
        info_fields = ['CPU使用率', '内存使用率', '磁盘使用率']
        for i, field in enumerate(info_fields):
            frame = ttk.LabelFrame(root, text=field, padding=10)
            frame.pack(fill='x', padx=10, pady=5)
            self.labels[field] = ttk.Label(frame, text="等待数据...")
            self.labels[field].pack()
        # 开始更新
        self.update_data()
    def update_data(self):
        # CPU信息
        cpu_percent = psutil.cpu_percent(interval=1)
        self.labels['CPU使用率'].config(
            text=f"CPU使用率: {cpu_percent}%\n"
                 f"CPU核心数: {psutil.cpu_count()}"
        )
        # 内存信息
        memory = psutil.virtual_memory()
        self.labels['内存使用率'].config(
            text=f"总内存: {memory.total / (1024**3):.2f} GB\n"
                 f"已使用: {memory.used / (1024**3):.2f} GB\n"
                 f"使用率: {memory.percent}%"
        )
        # 磁盘信息
        disk_info = ""
        for partition in psutil.disk_partitions():
            usage = psutil.disk_usage(partition.mountpoint)
            disk_info += f"{partition.device}: {usage.percent}%\n"
        self.labels['磁盘使用率'].config(text=disk_info.strip())
        # 每秒更新一次
        self.root.after(2000, self.update_data)
# 运行GUI应用
root = tk.Tk()
app = SystemMonitorApp(root)
root.mainloop()

简洁版系统报告函数

import psutil
import platform
import datetime
def get_system_report():
    """生成系统信息报告"""
    report = []
    # 系统基本信息
    report.append("=" * 50)
    report.append("系统信息报告")
    report.append("=" * 50)
    report.append(f"时间: {datetime.datetime.now()}")
    # 操作系统
    report.append(f"\n--- 操作系统 ---")
    report.append(f"系统: {platform.system()} {platform.version()}")
    report.append(f"架构: {platform.machine()}")
    report.append(f"主机名: {platform.node()}")
    # CPU
    report.append(f"\n--- CPU信息 ---")
    report.append(f"物理核心: {psutil.cpu_count(logical=False)}")
    report.append(f"逻辑核心: {psutil.cpu_count(logical=True)}")
    report.append(f"当前使用率: {psutil.cpu_percent()}%")
    # 内存
    mem = psutil.virtual_memory()
    report.append(f"\n--- 内存信息 ---")
    report.append(f"总计: {mem.total / (1024**3):.2f} GB")
    report.append(f"可用: {mem.available / (1024**3):.2f} GB")
    report.append(f"使用率: {mem.percent}%")
    # 磁盘
    report.append(f"\n--- 磁盘信息 ---")
    for part in psutil.disk_partitions():
        usage = psutil.disk_usage(part.mountpoint)
        report.append(f"{part.device}: {usage.percent}% 已使用")
    # 网络
    net = psutil.net_io_counters()
    report.append(f"\n--- 网络信息 ---")
    report.append(f"发送: {net.bytes_sent / (1024**2):.2f} MB")
    report.append(f"接收: {net.bytes_recv / (1024**2):.2f} MB")
    # 运行时间
    boot_time = datetime.datetime.fromtimestamp(psutil.boot_time())
    uptime = datetime.datetime.now() - boot_time
    report.append(f"\n--- 运行时间 ---")
    report.append(f"启动时间: {boot_time}")
    report.append(f"已运行: {uptime.days}天 {uptime.seconds//3600}小时")
    return "\n".join(report)
# 打印报告
print(get_system_report())

主要库说明

库/模块 用途 安装
os 基础操作系统接口 内置
platform 平台信息 内置
psutil 全面系统和进程信息 pip install psutil
subprocess 执行系统命令 内置
tkinter GUI界面 通常内置

推荐使用psutil,它是获取系统信息最全面、跨平台兼容性最好的Python库。

抱歉,评论功能暂时关闭!