Use Python to get computer memory and CPU information

Not much nonsense. Direct adjustment:

We need to use the third-party library psutil: install it directly with pip

pip install psutil

Then get the CPU memory information code as follows:


import psutil


def cpuInfo():
    cpuTimes = psutil.cpu_times()
    # 获取CPU信息中的内存信息
    def memoryInfo(memory):
        print(memory)
        return {
            '总内存(total)': str(round((float(memory.total) / 1024 / 1024 / 1024), 2)) + "G",
            '已使用(used)': str(round((float(memory.used) / 1024 / 1024 / 1024), 2)) + "G",
            '空闲(free)': str(round((float(memory.free) / 1024 / 1024 / 1024), 2)) + "G",
            '使用率(percent)': str(memory.percent) + '%',
            '可用(available)': (memory.available) if hasattr(memory, 'available') else '',
            '活跃(active)': (memory.active) if hasattr(memory, 'active') else '',
            '非活跃(inactive)': (memory.inactive) if hasattr(memory, 'inactive') else '',
            '内核使用(wired)': (memory.wired) if hasattr(memory, 'wired') else ''
        }
    return {
        '物理CPU个数': psutil.cpu_count(logical=False),
        '逻辑CPU个数': psutil.cpu_count(),
        'CPU使用情况': psutil.cpu_percent(percpu=True),
        '虚拟内存': memoryInfo(psutil.virtual_memory()),
        '交换内存': memoryInfo(psutil.swap_memory()),
        '系统启动到当前时刻': {
            pro: getattr(cpuTimes, pro) for pro in dir(cpuTimes) if pro[0:1] != '_' and pro not in ('index', 'count')
        },
    }


if __name__ == '__main__':
    computer_info = cpuInfo()
    print(computer_info)

The results of running on Windows are as follows:

svmem(total=17129988096, available=9869836288, percent=42.4, used=7260151808, free=9869836288)
sswap(total=18203729920, used=8945336320, free=9258393600, percent=49.1, sin=0, sout=0)
{'物理CPU个数': 4, '逻辑CPU个数': 4, 'CPU使用情况': [0.0, 0.0, 0.0, 0.0], '虚拟内存': {'总内存(total)': '15.95G', '已使用(used)': '6.76G', '空闲(free)': '9.19G', '使用率(percent)': '42.4%', '可用(available)': 9869836288, '活跃(active)': '', '非活跃(inactive)': '', '内核使用(wired)': ''}, '交换内存': {'总内存(total)': '16.95G', '已使用(used)': '8.33G', '空闲(free)': '8.62G', '使用率(percent)': '49.1%', '可用(available)': '', '活跃(active)': '', '非活跃(inactive)': '', '内核使用(wired)': ''}, '系统启动到当前时刻': {'dpc': 47.234375, 'idle': 18348.3125, 'interrupt': 89.890625, 'system': 2117.0625, 'user': 2326.578125}}

Run on Centos as shown below:

 There will be some differences between the two, the difference lies in the actual memory and CPU conditions of the cloud server and the physical machine. You all understand.

Guess you like

Origin blog.csdn.net/u012798683/article/details/105194062