Getting total/free RAM from within Python

只谈情不闲聊 提交于 2019-12-12 07:51:49

问题


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?

Ideally, the amount of free RAM should consider only physical memory that can actually be allocated to the Python process.


回答1:


Have you tried SIGAR - System Information Gatherer And Reporter? After install

import os, sigar

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

Hope this helps




回答2:


psutil would be another good choice. 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)



回答3:


For the free memory part, there is a function in the wx library:

wx.GetFreeMemory()

Unfortunately, this only works on Windows. Linux and Mac ports either return "-1" or raise a NotImplementedError.




回答4:


You can't do this with just the standard Python library, although there might be some third party package that does it. 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).




回答5:


In windows I use this method. It's kinda hacky but it works using standard os library:

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)


来源:https://stackoverflow.com/questions/1204378/getting-total-free-ram-from-within-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!