如何在Python中获取当前CPU和RAM使用情况?

496

如何在Python中获取当前系统状态(当前CPU、RAM、可用磁盘空间等)?最好能在Unix和Windows平台上都能使用。

我在搜索中发现有几种可能的提取方式:

  1. 使用类似于PSI(看起来目前没有积极开发并且在多个平台上不受支持)或者类似于pystatgrab(似乎自2007年以来没有活动,也不支持Windows)的库。

  2. 使用特定于平台的代码,例如对于*nix系统使用os.popen("ps")或类似方法,对于Windows平台使用ctypes.windll.kernel32中的MEMORYSTATUS(参见ActiveState上的此代码示例)。可以将所有这些代码片段放在一个Python类中。

这些方法并不差,但是否已经有一个良好支持、跨平台的方式来完成同样的事情呢?


你可以使用动态导入来构建自己的多平台库:“如果 sys.platform == 'win32':import win_sysstatus as sysstatus; else”... - John Fouhy
1
在App Engine上也有一个能够工作的东西会很酷。 - Attila O.
1
软件包的年龄是否重要?如果有人第一次就正确地获取了它们,为什么它们不仍然是正确的呢? - Paul Smith
21个回答

6

根据第一次反馈做了一些小修改。

#!/usr/bin/env python
#Execute commond on windows machine to install psutil>>>>python -m pip install psutil
import psutil

print ('                                                                   ')
print ('----------------------CPU Information summary----------------------')
print ('                                                                   ')

# gives a single float value
vcc=psutil.cpu_count()
print ('Total number of CPUs :',vcc)

vcpu=psutil.cpu_percent()
print ('Total CPUs utilized percentage :',vcpu,'%')

print ('                                                                   ')
print ('----------------------RAM Information summary----------------------')
print ('                                                                   ')
# you can convert that object to a dictionary 
#print(dict(psutil.virtual_memory()._asdict()))
# gives an object with many fields
vvm=psutil.virtual_memory()

x=dict(psutil.virtual_memory()._asdict())

def forloop():
    for i in x:
        print (i,"--",x[i]/1024/1024/1024)#Output will be printed in GBs

forloop()
print ('                                                                   ')
print ('----------------------RAM Utilization summary----------------------')
print ('                                                                   ')
# you can have the percentage of used RAM
print('Percentage of used RAM :',psutil.virtual_memory().percent,'%')
#79.2
# you can calculate percentage of available memory
print('Percentage of available RAM :',psutil.virtual_memory().available * 100 / psutil.virtual_memory().total,'%')
#20.8

5
"...当前系统状态(当前CPU,RAM,可用磁盘空间等)"而*nix和Windows平台可能很难结合起来。
操作系统在管理这些资源的方式上根本不同。实际上,它们在核心概念上也有所不同,例如定义什么算作系统时间和什么算作应用程序时间。
"可用磁盘空间"?什么算作"磁盘空间"?所有设备的所有分区?多重引导环境中的外部分区呢?
我认为Windows和*nix之间没有足够清晰的共识使其成为可能。实际上,甚至在被称为Windows的各种操作系统之间也可能没有任何共识。是否有一个适用于XP和Vista的单个Windows API?"

4
еңЁWindowsе’Ң*nixзі»з»ҹдёҠпјҢиҫ“е…Ҙdf -hе‘Ҫд»ӨеҸҜд»ҘжҹҘиҜўзЈҒзӣҳз©әй—ҙдҝЎжҒҜгҖӮ - jfs
4
@J.F.Sebastian:是哪个版本的Windows?我在Windows XP Pro中收到“df不是可识别的…”错误消息,我错过了什么? - S.Lott
3
你也可以在Windows上安装新程序。 - jfs

4

这是一个关于 CPU 使用率的脚本:

import os

def get_cpu_load():
    """ Returns a list CPU Loads"""
    result = []
    cmd = "WMIC CPU GET LoadPercentage "
    response = os.popen(cmd + ' 2>&1','r').read().strip().split("\r\n")
    for load in response[1:]:
       result.append(int(load))
    return result

if __name__ == '__main__':
    print get_cpu_load()

无法在Win11上工作,read()返回的结果不同。 - Putnik

3
  • 要获取 CPU 详情,请使用 psutil

    https://psutil.readthedocs.io/en/latest/#cpu

  • 要获取 RAM 频率(以 MHz 为单位),请使用内置的 Linux 库 dmidecode 并对输出进行一些处理;该命令需要 root 权限,因此请提供密码。请复制以下命令,将 mypass 替换为您的密码

import os

os.system("echo mypass | sudo -S dmidecode -t memory | grep 'Clock Speed' | cut -d ':' -f2")

------------------- 输出 ---------------------------
1600 MT/s
Unknown
1600 MT/s
Unknown 0

  • 更具体地说
    [i for i in os.popen("echo mypass | sudo -S dmidecode -t memory | grep 'Clock Speed' | cut -d ':' -f2").read().split(' ') if i.isdigit()]

-------------------------- 输出 -------------------------
['1600', '1600']


请添加更多描述 - Paras Korat

3

你可以读取 /proc/meminfo 文件来获取已使用的内存

file1 = open('/proc/meminfo', 'r') 

for line in file1: 
    if 'MemTotal' in line: 
        x = line.split()
        memTotal = int(x[1])
        
    if 'Buffers' in line: 
        x = line.split()
        buffers = int(x[1])
        
    if 'Cached' in line and 'SwapCached' not in line: 
        x = line.split()
        cached = int(x[1])
    
    if 'MemFree' in line: 
        x = line.split()
        memFree = int(x[1])

file1.close()

percentage_used = int ( ( memTotal - (buffers + cached + memFree) ) / memTotal * 100 )
print(percentage_used)

2
这显然是特定于Linux的。 - tripleee

1

基于 @Hrabal 的 CPU 使用率代码,这是我使用的:

from subprocess import Popen, PIPE

def get_cpu_usage():
    ''' Get CPU usage on Linux by reading /proc/stat '''

    sub = Popen(('grep', 'cpu', '/proc/stat'), stdout=PIPE, stderr=PIPE)
    top_vals = [int(val) for val in sub.communicate()[0].split('\n')[0].split[1:5]]

    return (top_vals[0] + top_vals[2]) * 100. /(top_vals[0] + top_vals[2] + top_vals[3])

1
你可以使用psutil或psmem与subprocess一起使用 示例代码
import subprocess
cmd =   subprocess.Popen(['sudo','./ps_mem'],stdout=subprocess.PIPE,stderr=subprocess.PIPE) 
out,error = cmd.communicate() 
memory = out.splitlines()

参考资料

https://github.com/Leo-g/python-flask-cmd


1
这不是使用subprocess库的好例子。正如其文档所说,应该避免使用裸的Popen,而是使用更高级别的函数之一subprocess.check_outputsubprocess.run。这里不清楚./ps_mem是什么。 - tripleee

1

您可以使用命令pip install SystemScripter来安装最近发布的SystemScripter库。这是一个使用其他库(如psutil)创建系统信息全库的库,涵盖了从CPU到磁盘信息的所有内容。 要获取当前CPU使用情况,请使用以下函数:

SystemScripter.CPU.CpuPerCurrentUtil(SystemScripter.CPU()) #class init as self param if not work

这个函数获取使用百分比或使用情况:

SystemScripter.CPU.CpuCurrentUtil(SystemScripter.CPU())

https://pypi.org/project/SystemScripter/#description


0

使用crontab运行不会打印pid

设置:*/1 * * * * sh dog.sh 将此行添加到crontab -e

import os
import re

CUT_OFF = 90

def get_cpu_load():
    cmd = "ps -Ao user,uid,comm,pid,pcpu --sort=-pcpu | head -n 2 | tail -1"
    response = os.popen(cmd, 'r').read()
    arr = re.findall(r'\S+', response)
    print(arr)
    needKill = float(arr[-1]) > CUT_OFF
    if needKill:
        r = os.popen(f"kill -9 {arr[-2]}")
        print('kill:', r)

if __name__ == '__main__':
    # Test CPU with 
    # $ stress --cpu 1
    # crontab -e
    # Every 1 min
    # */1 * * * * sh dog.sh
    # ctlr o, ctlr x
    # crontab -l
    print(get_cpu_load())

0

不需要进行Shell-out,使用@CodeGenchsolution即可,因此假设您使用Linux和Python的标准库:

def cpu_load(): 
    with open("/proc/stat", "r") as stat:
        (key, user, nice, system, idle, _) = (stat.readline().split(None, 5))
    assert key == "cpu", "'cpu ...' should be the first line in /proc/stat"
    busy = int(user) + int(nice) + int(system)
    return 100 * busy / (busy + int(idle))


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