How to get the system info with Python?

2020-05-11 20:15发布

I need to get the info under what environment the software is running. Does python have a library for this purpose?

I want to know the following info.

  • OS name/version
  • Name of the CPU, clock speed
  • Number of CPU core
  • Size of memory

3条回答
对你真心纯属浪费
2楼-- · 2020-05-11 20:28

The os module has the uname function to get information about the os & version:

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

For my system, running CentOS 5.4 with 2.6.18 kernel this returns:

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

查看更多
家丑人穷心不美
3楼-- · 2020-05-11 20:37

some of these could be obtained from the platform module:

>>> 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'
查看更多
对你真心纯属浪费
4楼-- · 2020-05-11 20:40
#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())

Output Sample:

{'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'}
查看更多
登录 后发表回答