Python本地信息获取案例?

wen python案例 1

本文目录导读:

  1. 获取系统基本信息
  2. 获取网络信息
  3. 获取磁盘信息
  4. 获取内存和CPU信息
  5. 获取进程信息
  6. 综合信息获取类
  7. 保存信息到文件
  8. 运行要求

我来提供几个Python获取本地信息的实用案例:

获取系统基本信息

import platform
import os
import sys
import socket
def get_system_info():
    """获取系统基本信息"""
    info = {
        "操作系统": platform.system(),
        "操作系统版本": platform.version(),
        "系统架构": platform.machine(),
        "处理器": platform.processor(),
        "主机名": socket.gethostname(),
        "Python版本": sys.version,
        "当前工作目录": os.getcwd(),
        "用户名": os.getenv('USERNAME') or os.getenv('USER'),
    }
    for key, value in info.items():
        print(f"{key}: {value}")
get_system_info()

获取网络信息

import socket
import netifaces
import psutil
def get_network_info():
    """获取网络信息"""
    print("=== 网络接口信息 ===")
    # 获取所有网络接口
    interfaces = netifaces.interfaces()
    for iface in interfaces:
        print(f"\n接口: {iface}")
        addrs = netifaces.ifaddresses(iface)
        if netifaces.AF_INET in addrs:
            for addr in addrs[netifaces.AF_INET]:
                print(f"  IP地址: {addr['addr']}")
                print(f"  子网掩码: {addr['netmask']}")
        if netifaces.AF_INET6 in addrs:
            for addr in addrs[netifaces.AF_INET6]:
                print(f"  IPv6地址: {addr['addr']}")
    print("\n=== 网络连接信息 ===")
    try:
        # 使用psutil获取网络连接
        connections = psutil.net_connections()
        print(f"当前连接数: {len(connections)}")
    except:
        print("需要管理员权限查看网络连接")
# 注意:需要安装 netifaces 和 psutil
# pip install netifaces psutil

获取磁盘信息

import psutil
import shutil
def get_disk_info():
    """获取磁盘信息"""
    print("=== 磁盘信息 ===")
    # 获取磁盘分区信息
    partitions = psutil.disk_partitions()
    for partition in partitions:
        print(f"\n分区: {partition.device}")
        print(f"挂载点: {partition.mountpoint}")
        print(f"文件系统: {partition.fstype}")
        try:
            usage = shutil.disk_usage(partition.mountpoint)
            total_gb = usage.total / (1024**3)
            used_gb = usage.used / (1024**3)
            free_gb = usage.free / (1024**3)
            print(f"总大小: {total_gb:.2f} GB")
            print(f"已用: {used_gb:.2f} GB")
            print(f"可用: {free_gb:.2f} GB")
            print(f"使用率: {(usage.used/usage.total*100):.1f}%")
        except:
            print("无法获取使用情况")
get_disk_info()

获取内存和CPU信息

import psutil
def get_performance_info():
    """获取性能信息"""
    print("=== 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:.2f} MHz")
    print("\n=== 内存信息 ===")
    memory = psutil.virtual_memory()
    total_gb = memory.total / (1024**3)
    available_gb = memory.available / (1024**3)
    used_gb = memory.used / (1024**3)
    print(f"总内存: {total_gb:.2f} GB")
    print(f"可用内存: {available_gb:.2f} GB")
    print(f"已用内存: {used_gb:.2f} GB")
    print(f"内存使用率: {memory.percent}%")
    print("\n=== 交换分区信息 ===")
    swap = psutil.swap_memory()
    print(f"交换分区使用率: {swap.percent}%")
get_performance_info()

获取进程信息

import psutil
def get_process_info():
    """获取进程信息"""
    print("=== 进程信息 ===")
    # 获取所有进程列表
    processes = []
    for proc in psutil.process_iter(['pid', 'name', 'memory_percent', 'cpu_percent']):
        try:
            processes.append(proc.info)
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            pass
    # 按内存使用排序
    processes.sort(key=lambda x: x['memory_percent'], reverse=True)
    print(f"\n前10个内存占用最高的进程:")
    print(f"{'PID':<10} {'进程名':<30} {'CPU%':<10} {'内存%':<10}")
    print("-" * 60)
    for proc in processes[:10]:
        print(f"{proc['pid']:<10} {proc['name'][:28]:<30} "
              f"{proc.get('cpu_percent', 0):<10.2f} "
              f"{proc['memory_percent']:<10.2f}")
get_process_info()

综合信息获取类

import platform
import psutil
import socket
import datetime
import cpuinfo
class LocalInfoCollector:
    """本地信息收集器"""
    def __init__(self):
        self.info = {}
    def collect_basic_info(self):
        """收集基本信息"""
        self.info['hostname'] = socket.gethostname()
        self.info['system'] = platform.system()
        self.info['version'] = platform.version()
        self.info['architecture'] = platform.machine()
        self.info['processor'] = platform.processor()
        self.info['python_version'] = platform.python_version()
        self.info['current_time'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    def collect_performance(self):
        """收集性能信息"""
        self.info['cpu_count'] = psutil.cpu_count()
        self.info['cpu_percent'] = psutil.cpu_percent(interval=1)
        memory = psutil.virtual_memory()
        self.info['memory_total'] = f"{memory.total / (1024**3):.2f} GB"
        self.info['memory_used'] = f"{memory.used / (1024**3):.2f} GB"
        self.info['memory_percent'] = memory.percent
        disk = psutil.disk_usage('/')
        self.info['disk_total'] = f"{disk.total / (1024**3):.2f} GB"
        self.info['disk_used'] = f"{disk.used / (1024**3):.2f} GB"
        self.info['disk_percent'] = disk.percent
    def print_all_info(self):
        """打印所有信息"""
        print("=" * 50)
        print("         本地系统信息报告")
        print("=" * 50)
        for category, data in self.info.items():
            if isinstance(data, dict):
                print(f"\n{category}:")
                for key, value in data.items():
                    print(f"  {key}: {value}")
            else:
                print(f"{category}: {data}")
    def get_info_dict(self):
        """返回信息字典"""
        return self.info
# 使用示例
collector = LocalInfoCollector()
collector.collect_basic_info()
collector.collect_performance()
collector.print_all_info()

保存信息到文件

import json
import datetime
def save_info_to_file(info_dict, filename=None):
    """保存信息到JSON文件"""
    if not filename:
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"system_info_{timestamp}.json"
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(info_dict, f, ensure_ascii=False, indent=4)
    print(f"信息已保存到: {filename}")
# 使用
collector = LocalInfoCollector()
collector.collect_basic_info()
collector.collect_performance()
save_info_to_file(collector.get_info_dict())

运行要求

大多数基础功能不需要额外安装,但以下功能需要安装第三方库:

# 安装psutil(推荐)
pip install psutil
# 安装netifaces(网络接口信息)
pip install netifaces
# 安装cpuinfo(详细CPU信息)
pip install py-cpuinfo

这些示例涵盖了获取本地系统信息的主要方面,你可以根据自己的需求组合使用,如果是首次运行,建议从简单的开始,逐步增加功能。

标签: 系统调用

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