简体   繁体   English

从Python中获取总/可用RAM

[英]Getting total/free RAM from within Python

From within a Python application, how can I get the total amount of RAM of the system and how much of it is currently free, in a cross-platform way? 在Python应用程序中,如何以跨平台的方式获取系统的RAM总量以及当前有多少RAM?

Ideally, the amount of free RAM should consider only physical memory that can actually be allocated to the Python process. 理想情况下,可用RAM的数量应该只考虑实际可以分配给Python进程的物理内存。

Have you tried SIGAR - System Information Gatherer And Reporter ? 您是否尝试过SIGAR - 系统信息收集器和报告器 After install 安装后

import os, sigar

sg = sigar.open()
mem = sg.mem()
sg.close() 
print mem.total() / 1024, mem.free() / 1024

Hope this helps 希望这可以帮助

For the free memory part, there is a function in the wx library: 对于空闲内存部分,wx库中有一个函数:

wx.GetFreeMemory()

Unfortunately, this only works on Windows. 不幸的是,这仅适用于Windows。 Linux and Mac ports either return "-1" or raise a NotImplementedError . Linux和Mac端口返回“-1”或引发NotImplementedError

psutil would be another good choice. psutil将是另一个不错的选择。 It also needs a library installed however. 它还需要安装一个库。

>>> import psutil
>>> psutil.virtual_memory()
vmem(total=8374149120L, available=2081050624L, percent=75.1,
     used=8074080256L, free=300068864L, active=3294920704,
     inactive=1361616896, buffers=529895424L, cached=1251086336)

You can't do this with just the standard Python library, although there might be some third party package that does it. 你不能只使用标准的Python库来做到这一点,尽管可能有一些第三方软件包可以做到这一点。 Barring that, you can use the os package to determine which operating system you're on and use that information to acquire the info you want for that system (and encapsulate that into a single cross-platform function). 除此之外,您可以使用os包来确定您所使用的操作系统,并使用该信息获取您希望用于该系统的信息(并将其封装到单个跨平台功能中)。

In windows I use this method. 在Windows中我使用这种方法。 It's kinda hacky but it works using standard os library: 它有点hacky但它​​使用标准的os库:

import os
process = os.popen('wmic memorychip get capacity')
result = process.read()
process.close()
totalMem = 0
for m in result.split("  \r\n")[1:-1]:
    totalMem += int(m)
print totalMem / (1024**3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM