如何使用Python获取系统信息?

77

我需要获取软件运行的环境信息。Python中有没有适用于此目的的库?

我想了解以下信息:

  • 操作系统名/版本
  • CPU名称、时钟速度
  • CPU核心数
  • 内存大小

我从这里得到的只有os.name:http://docs.python.org/library/os.html#miscellaneous-system-information - jhleath
psutil: http://code.google.com/p/psutil/ - Wayne Werner
6个回答

121

一些可以从platform模块获取:

>>> import platform
>>> platform.machine()
'x86'
>>> platform.version()
'5.1.2600'
>>> platform.platform()
'Windows-XP-5.1.2600-SP2'
>>> platform.uname()
('Windows', 'name', 'XP', '5.1.2600', 'x86', 'x86 Family 6 Model 15 Stepping 6, GenuineIntel')
>>> platform.system()
'Windows'
>>> platform.processor()
'x86 Family 6 Model 15 Stepping 6, GenuineIntel'

2
你打败了我。此外,我不知道其他操作系统如何,但在Unix上运行platform.dist()可能更简洁。 - Nikhil
platform.dist() 在 Python 3.5 中已被弃用。 - varnothing
platform.dist()在Python 3.8中已被移除。 - phoenix
好事我们有了这个。它是非常缺失的。 - Harlin

45
#Shamelessly combined from google and other stackoverflow like sites to form a single function

import platform,socket,re,uuid,json,psutil,logging

def getSystemInfo():
    try:
        info={}
        info['platform']=platform.system()
        info['platform-release']=platform.release()
        info['platform-version']=platform.version()
        info['architecture']=platform.machine()
        info['hostname']=socket.gethostname()
        info['ip-address']=socket.gethostbyname(socket.gethostname())
        info['mac-address']=':'.join(re.findall('..', '%012x' % uuid.getnode()))
        info['processor']=platform.processor()
        info['ram']=str(round(psutil.virtual_memory().total / (1024.0 **3)))+" GB"
        return json.dumps(info)
    except Exception as e:
        logging.exception(e)

json.loads(getSystemInfo())

输出示例:

{
 'platform': 'Linux',
 'platform-release': '5.3.0-29-generic',
 'platform-version': '#31-Ubuntu SMP Fri Jan 17 17:27:26 UTC 2020',
 'architecture': 'x86_64',
 'hostname': 'naret-vm',
 'ip-address': '127.0.1.1',
 'mac-address': 'bb:cc:dd:ee:bc:ff',
 'processor': 'x86_64',
 'ram': '4 GB'
}

在Windows中获取GPU名称,import wmi # pip install wmi computer = wmi.WMI() gpu_info = computer.Win32_VideoController()[0].name - Ayush Mandowara
可以不要在Python中使用Java的命名风格吗?比如,回答中的函数名。使用get_system_info()这样的命名方式更符合Python习惯,而不是Java的驼峰式方法命名。 - Amin Pial

14

os模块中有一个uname函数,可获取操作系统和版本信息:

>>> import os
>>> os.uname()

对于我的系统,运行着CentOS 5.4和2.6.18内核,这将返回:

('Linux','mycomputer.domain.user','2.6.18-92.1.22.el5PAE','#1 SMP Tue Dec 16 12:36:25 EST 2008','i686')


5
注意:此方法仅适用于*nix操作系统。官方文档中说明:“可用性:新版Unix系统。” - Mohan Raj
注意:这也适用于ProductName: Mac OS X | ProductVersion: 10.14.2 | BuildVersion: 18C54。 - JayRizzo

8
import psutil
import platform
from datetime import datetime
import cpuinfo
import socket
import uuid
import re


def get_size(bytes, suffix="B"):
    """
    Scale bytes to its proper format
    e.g:
        1253656 => '1.20MB'
        1253656678 => '1.17GB'
    """
    factor = 1024
    for unit in ["", "K", "M", "G", "T", "P"]:
        if bytes < factor:
            return f"{bytes:.2f}{unit}{suffix}"
        bytes /= factor

def System_information():
    print("="*40, "System Information", "="*40)
    uname = platform.uname()
    print(f"System: {uname.system}")
    print(f"Node Name: {uname.node}")
    print(f"Release: {uname.release}")
    print(f"Version: {uname.version}")
    print(f"Machine: {uname.machine}")
    print(f"Processor: {uname.processor}")
    print(f"Processor: {cpuinfo.get_cpu_info()['brand_raw']}")
    print(f"Ip-Address: {socket.gethostbyname(socket.gethostname())}")
    print(f"Mac-Address: {':'.join(re.findall('..', '%012x' % uuid.getnode()))}")


    # Boot Time
    print("="*40, "Boot Time", "="*40)
    boot_time_timestamp = psutil.boot_time()
    bt = datetime.fromtimestamp(boot_time_timestamp)
    print(f"Boot Time: {bt.year}/{bt.month}/{bt.day} {bt.hour}:{bt.minute}:{bt.second}")


    # print CPU information
    print("="*40, "CPU Info", "="*40)
    # number of cores
    print("Physical cores:", psutil.cpu_count(logical=False))
    print("Total cores:", psutil.cpu_count(logical=True))
    # CPU frequencies
    cpufreq = psutil.cpu_freq()
    print(f"Max Frequency: {cpufreq.max:.2f}Mhz")
    print(f"Min Frequency: {cpufreq.min:.2f}Mhz")
    print(f"Current Frequency: {cpufreq.current:.2f}Mhz")
    # CPU usage
    print("CPU Usage Per Core:")
    for i, percentage in enumerate(psutil.cpu_percent(percpu=True, interval=1)):
        print(f"Core {i}: {percentage}%")
    print(f"Total CPU Usage: {psutil.cpu_percent()}%")


    # Memory Information
    print("="*40, "Memory Information", "="*40)
    # get the memory details
    svmem = psutil.virtual_memory()
    print(f"Total: {get_size(svmem.total)}")
    print(f"Available: {get_size(svmem.available)}")
    print(f"Used: {get_size(svmem.used)}")
    print(f"Percentage: {svmem.percent}%")



    print("="*20, "SWAP", "="*20)
    # get the swap memory details (if exists)
    swap = psutil.swap_memory()
    print(f"Total: {get_size(swap.total)}")
    print(f"Free: {get_size(swap.free)}")
    print(f"Used: {get_size(swap.used)}")
    print(f"Percentage: {swap.percent}%")



    # Disk Information
    print("="*40, "Disk Information", "="*40)
    print("Partitions and Usage:")
    # get all disk partitions
    partitions = psutil.disk_partitions()
    for partition in partitions:
        print(f"=== Device: {partition.device} ===")
        print(f"  Mountpoint: {partition.mountpoint}")
        print(f"  File system type: {partition.fstype}")
        try:
            partition_usage = psutil.disk_usage(partition.mountpoint)
        except PermissionError:
            # this can be catched due to the disk that
            # isn't ready
            continue
        print(f"  Total Size: {get_size(partition_usage.total)}")
        print(f"  Used: {get_size(partition_usage.used)}")
        print(f"  Free: {get_size(partition_usage.free)}")
        print(f"  Percentage: {partition_usage.percent}%")
    # get IO statistics since boot
    disk_io = psutil.disk_io_counters()
    print(f"Total read: {get_size(disk_io.read_bytes)}")
    print(f"Total write: {get_size(disk_io.write_bytes)}")

    ## Network information
    print("="*40, "Network Information", "="*40)
    ## get all network interfaces (virtual and physical)
    if_addrs = psutil.net_if_addrs()
    for interface_name, interface_addresses in if_addrs.items():
        for address in interface_addresses:
            print(f"=== Interface: {interface_name} ===")
            if str(address.family) == 'AddressFamily.AF_INET':
                print(f"  IP Address: {address.address}")
                print(f"  Netmask: {address.netmask}")
                print(f"  Broadcast IP: {address.broadcast}")
            elif str(address.family) == 'AddressFamily.AF_PACKET':
                print(f"  MAC Address: {address.address}")
                print(f"  Netmask: {address.netmask}")
                print(f"  Broadcast MAC: {address.broadcast}")
    ##get IO statistics since boot
    net_io = psutil.net_io_counters()
    print(f"Total Bytes Sent: {get_size(net_io.bytes_sent)}")
    print(f"Total Bytes Received: {get_size(net_io.bytes_recv)}")


if __name__ == "__main__":

    System_information()

4

发现了这段简单的代码

import platform

print("="*40, "System Information", "="*40)
uname = platform.uname()
print(f"System: {uname.system}")
print(f"Node Name: {uname.node}")
print(f"Release: {uname.release}")
print(f"Version: {uname.version}")
print(f"Machine: {uname.machine}")
print(f"Processor: {uname.processor}")

1
#This should work

import os
for item in os.environ:

    print(f'{item}{" : "}{os.environ[item]}')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接