【问题标题】:Get total physical memory in Python在 Python 中获取总物理内存
【发布时间】:2021-05-02 12:19:24
【问题描述】:

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

【问题讨论】:

  • 你可以阅读/proc/meminfo
  • /proc/meminfo 应该适用于几乎所有的 linux 安装。
  • 你不需要/proc/meminfo,因为sysconf has the answer
  • /proc 仅在 CONFIG_PROC_FS=y 时可用。适用于台式机、服务器、手机,但并非总是适用于嵌入式设备。
  • 你很少应该关心 物理 内存(想象一下,例如通过 docker 等的虚拟处理器......)

标签: python linux memory


【解决方案1】:

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

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

virtual_memory 的文档是 here

【讨论】:

【解决方案2】:

使用 os.sysconf 在 Linux 上:

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

【讨论】:

  • @sorin, os.sysconf('SC_PHYS_PAGES') 显然在 OS X 上不起作用。虽然sysconf 的 OS X 手册页确实记录了 _SC_PHYS_PAGES,但这似乎无法通过 Python 访问。 psutil 可能会让你更幸运。或者,参考答案here中使用的技术。
  • FWIW,os.sysconf() 方法也适用于 Python 3,甚至在 Solaris 10 下。
  • 我很高兴地报告它正在使用 Python 3.6.4 在 MacOS X 10.13 (High Sierra) 上运行。
  • /proc/meminfo 在 AWS 上似乎无法正常工作:Why does /proc/meminfo show 32GB when AWS instance has only 16GB?
  • 在 MacOs 上,在 Python 3.7 上运行良好,但在 Python 3.8.3 上却不行。为os.sysconf('SC_PHYS_PAGES') 获取ValueError: unrecognized configuration name
【解决方案3】:

正则表达式适用于这类事情,并且可能有助于解决分布之间的任何细微差异。

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])

【讨论】:

  • /proc 只存在于 Linux 上...所以不是跨平台的
  • 我误认为与分发无关的是跨平台......现在我看到它被标记为 Linux。我的坏:)
  • /proc/meminfo 在 AWS 上似乎无法正常工作:Why does /proc/meminfo show 32GB when AWS instance has only 16GB?
  • @JoshuaDetwiler 在使用这样的上下文时,您不需要显式关闭文件。当上下文(with 块)关闭时,文件将与它一起。
  • 还有@martin-thoma 你用的是什么AWS镜像,最新的amazonlinux2没有这个问题。
【解决方案4】:

此代码在 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'

我们很容易得到Used Memory和Free Memory

    """
        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'

【讨论】:

  • 免费在 Mac 上默认不安装
猜你喜欢
  • 2014-05-05
  • 2010-12-05
  • 2015-05-28
  • 1970-01-01
  • 2012-12-13
  • 2017-04-26
  • 2014-12-19
  • 1970-01-01
相关资源
最近更新 更多