如何用Python获取系统信息?

77 投票
6 回答
153976 浏览
提问于 2025-04-16 00:20

我需要了解软件运行的环境信息。
Python有没有相关的库可以做到这一点?

我想知道以下信息:

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

6 个回答

14

在Python的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')

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'
}
122

这些信息可以通过 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'

撰写回答