使用Python获取计算机内存及CPU信息

废话不多说。直接整:

我们需要使用psutil 这个第三方库:直接pip 安装一下

pip install psutil

然后获取CPU内存信息代码如下:


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)

Windows 上运行结果如下:

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

Centos上运行如下图:

 两者会有些区别,区别在于云服务器和物理机实际的内存CPU情况。你们都懂得。

猜你喜欢

转载自blog.csdn.net/u012798683/article/details/105194062