如何在Python中获取当前系统状态(当前CPU、RAM、空闲磁盘空间等)?理想情况下,它可以同时适用于Unix和Windows平台。

从我的搜索中似乎有一些可能的方法:

使用像PSI这样的库(目前似乎没有积极开发,在多个平台上也不支持)或像pystatgrab这样的库(从2007年开始似乎没有活动,也不支持Windows)。 使用平台特定的代码,例如使用os.popen("ps")或*nix系统的类似代码,以及ctypes.windll中的MEMORYSTATUS。Windows平台的kernel32(请参阅ActiveState上的配方)。可以将所有这些代码片段放在一个Python类中。

这并不是说这些方法不好,而是是否已经有一种支持良好的多平台方式来做同样的事情?


当前回答

仅适用于Linux: 只有stdlib依赖的RAM使用的一行代码:

import os
tot_m, used_m, free_m = map(int, os.popen('free -t -m').readlines()[-1].split()[1:])

其他回答

使用psutil库。在Ubuntu 18.04上,pip在2019年1月30日安装了5.5.0(最新版本)。旧版本的行为可能有所不同。 你可以在Python中这样做来检查你的psutil版本:

from __future__ import print_function  # for Python2
import psutil
print(psutil.__versi‌​on__)

获取内存和CPU的统计信息:

from __future__ import print_function
import psutil
print(psutil.cpu_percent())
print(psutil.virtual_memory())  # physical memory usage
print('memory % used:', psutil.virtual_memory()[2])

virtual_memory (tuple)将包含系统范围内使用的内存百分比。对我来说,在Ubuntu 18.04上,这似乎被高估了几个百分点。

你也可以得到当前Python实例所使用的内存:

import os
import psutil
pid = os.getpid()
python_process = psutil.Process(pid)
memoryUse = python_process.memory_info()[0]/2.**30  # memory use in GB...I think
print('memory use:', memoryUse)

它给出了Python脚本的当前内存使用情况。

pypi页面上有一些更深入的psutil示例。

psutil库提供了各种平台上关于CPU、RAM等的信息:

psutil是一个模块,提供了一个接口,通过使用Python以可移植的方式检索正在运行的进程和系统利用率(CPU,内存)的信息,实现了ps、top和Windows任务管理器等工具提供的许多功能。 它目前支持Linux, Windows, OSX, Sun Solaris, FreeBSD, OpenBSD和NetBSD, 32位和64位架构,Python版本从2.6到3.5 (Python 2.4和2.5的用户可能使用2.1.3版本)。


一些例子:

#!/usr/bin/env python
import psutil
# gives a single float value
psutil.cpu_percent()
# gives an object with many fields
psutil.virtual_memory()
# you can convert that object to a dictionary 
dict(psutil.virtual_memory()._asdict())
# you can have the percentage of used RAM
psutil.virtual_memory().percent
79.2
# you can calculate percentage of available memory
psutil.virtual_memory().available * 100 / psutil.virtual_memory().total
20.8

以下是其他文档,提供了更多的概念和感兴趣的概念:

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

通过结合tqdm和psutil,可以获得实时的CPU和RAM监控。当运行繁重的计算/处理时,它可能很方便。

它也可以在Jupyter中工作,无需任何代码更改:

from tqdm import tqdm
from time import sleep
import psutil

with tqdm(total=100, desc='cpu%', position=1) as cpubar, tqdm(total=100, desc='ram%', position=0) as rambar:
    while True:
        rambar.n=psutil.virtual_memory().percent
        cpubar.n=psutil.cpu_percent()
        rambar.refresh()
        cpubar.refresh()
        sleep(0.5)

使用多处理库将这些进度条放在单独的进程中是很方便的。

此代码片段也可作为要点。

我觉得这些答案是为Python 2编写的,而且在任何情况下,都没有人提到Python 3可用的标准资源包。它提供了获取给定进程(默认为调用Python进程)的资源限制的命令。这与获取整个系统当前的资源使用情况是不同的,但它可以解决一些相同的问题,例如:“我想确保这个脚本只使用X个内存。”

这是所有好东西的汇总: psutil + os获得Unix和Windows兼容性: 这允许我们得到:

CPU 内存 磁盘

代码:

import os
import psutil  # need: pip install psutil

In [32]: psutil.virtual_memory()
Out[32]: svmem(total=6247907328, available=2502328320, percent=59.9, used=3327135744, free=167067648, active=3671199744, inactive=1662668800,     buffers=844783616, cached=1908920320, shared=123912192, slab=613048320)

In [33]: psutil.virtual_memory().percent
Out[33]: 60.0

In [34]: psutil.cpu_percent()
Out[34]: 5.5

In [35]: os.sep
Out[35]: '/'

In [36]: psutil.disk_usage(os.sep)
Out[36]: sdiskusage(total=50190790656, used=41343860736, free=6467502080, percent=86.5)

In [37]: psutil.disk_usage(os.sep).percent
Out[37]: 86.5