在Python中获取总物理内存

75

如何以Python分发无关的方式获取总物理内存?我不需要已使用的内存,只需要总物理内存。


你可以读取 /proc/meminfo - Lee Duhem
/proc/meminfo 应该在几乎所有的 Linux 安装中都可以使用。 - Marc B
1
你不需要使用/proc/meminfo,因为sysconf已经有答案了 - Asclepius
只有当CONFIG_PROC_FS=y时,/proc才可用。对于桌面、服务器、手机是正确的,但对于嵌入式设备并非总是如此。 - rsaxvc
1
你很少需要关心物理内存(例如,通过Docker等虚拟处理器...)。 - Basile Starynkevitch
@BasileStarynkevitch,您能在为什么/proc/meminfo显示32GB而AWS实例只有16GB?这个话题上进行更详细的阐述吗? - Martin Thoma
4个回答

100

跨平台解决方案最好的选择是使用psutil软件包(在PyPI上可用)。

import psutil
    
psutil.virtual_memory().total  # total physical memory in Bytes

virtual_memory 的文档在这里


1
mem = virtual_memory() 然后 # total physical memory?听起来不错。 - Thomas Weller
已于2018/12/18进行了未来验证:https://web.archive.org/web/20181228093919/https://psutil.readthedocs.io/en/latest/#psutil.virtual_memory - Lorem Ipsum
int(np.round(psutil.virtual_memory().total / (1024. **3))),附带@Asclepius的提示。 - user1098761

75

在Linux上使用 os.sysconf:

import os
mem_bytes = os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES')  # e.g. 4015976448
mem_gib = mem_bytes/(1024.**3)  # e.g. 3.74

注意:

  • SC_PAGE_SIZE通常为4096。
  • SC_PAGESIZESC_PAGE_SIZE相等。
  • 更多信息请参见man sysconf
  • 对于MacOS,根据用户报告,这适用于Python 3.7但不适用于Python 3.8。

在Linux上使用/proc/meminfo:

meminfo = dict((i.split()[0].rstrip(':'),int(i.split()[1])) for i in open('/proc/meminfo').readlines())
mem_kib = meminfo['MemTotal']  # e.g. 3921852

1
@sorin,os.sysconf('SC_PHYS_PAGES')在OS X上似乎无法使用。虽然OS X的sysconf man页面确实提到了_SC_PHYS_PAGES,但是这在Python中似乎无法访问。您可以尝试使用psutil。另外,您还可以参考此处的答案中使用的技术。 - Asclepius
2
FWIW,os.sysconf()方法在Python 3甚至Solaris 10下也适用。 - maxschlepzig
1
我很高兴地报告,它在MacOS X 10.13(High Sierra)上使用Python 3.6.4可以正常工作。 - John Difool
1
在MacOS上,Python 3.7可以正常工作,但是Python 3.8.3无法正常工作。在os.sysconf('SC_PHYS_PAGES')中出现了ValueError: unrecognized configuration name的错误。 - Nick Korostelev
1
理想情况下,我希望能够在没有外部依赖项(如psutil)的情况下解决这个问题。 - Nick Korostelev
显示剩余2条评论

14

正则表达式对于这种情况非常有效,并且可能有助于处理各个发行版之间的任何小差异。

import re
with open('/proc/meminfo') as f:
    meminfo = f.read()
matched = re.search(r'^MemTotal:\s+(\d+)', meminfo)
if matched: 
    mem_total_kB = int(matched.groups()[0])

5
/proc 只存在于 Linux 上,因此不是跨平台的。 - Corey Goldberg
我把distribution-agnostic误认为是跨平台...现在我看到它被标记为Linux了。我的错 :) - Corey Goldberg
在AWS上,“/proc/meminfo”似乎不能按预期工作:为什么“/proc/meminfo”显示32GB,而AWS实例只有16GB? - Martin Thoma
1
@JoshuaDetwiler 当使用这样的上下文时,您不需要显式关闭文件。当上下文(即with块)关闭时,文件也将随之关闭。 - ThisGuyCantEven
还有@martin-thoma,你在使用哪个AWS镜像?我在最新的amazonlinux2上没有这个问题。 - ThisGuyCantEven

0

这段代码在 Python 2.7.9 中没有使用任何外部库对我有效。

import os
mem=str(os.popen('free -t -m').readlines())
"""
Get a whole line of memory output, it will be something like below
['             total       used       free     shared    buffers     cached\n', 
'Mem:           925        591        334         14         30        355\n', 
'-/+ buffers/cache:        205        719\n', 
'Swap:           99          0         99\n', 
'Total:        1025        591        434\n']
 So, we need total memory, usage and free memory.
 We should find the index of capital T which is unique at this string
"""
T_ind=mem.index('T')
"""
Than, we can recreate the string with this information. After T we have,
"Total:        " which has 14 characters, so we can start from index of T +14
and last 4 characters are also not necessary.
We can create a new sub-string using this information
"""
mem_G=mem[T_ind+14:-4]
"""
The result will be like
1025        603        422
we need to find first index of the first space, and we can start our substring
from from 0 to this index number, this will give us the string of total memory
"""
S1_ind=mem_G.index(' ')
mem_T=mem_G[0:S1_ind]

print 'Summary = ' + mem_G
print 'Total Memory = ' + mem_T +' MB'

我们很容易地可以获取已使用内存和空闲内存

    """
        Similarly we will create a new sub-string, which will start at the second value. 
        The resulting string will be like
        603        422
        Again, we should find the index of first space and than the 
        take the Used Memory and Free memory.
        """
        mem_G1=mem_G[S1_ind+8:]
        S2_ind=mem_G1.index(' ')
        mem_U=mem_G1[0:S2_ind]

        mem_F=mem_G1[S2_ind+8:]
    print 'Used Memory = ' + mem_U +' MB'
    print 'Free Memory = ' + mem_F +' MB'

1
在 Mac 上,free 命令不是默认安装的。 - Martin Thoma

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