首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >获取Python中的总物理内存

获取Python中的总物理内存
EN

Stack Overflow用户
提问于 2014-03-01 02:26:21
回答 3查看 55.7K关注 0票数 55

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-03-01 02:42:36

对于跨平台解决方案,最好的选择是使用PyPI上提供的psutil包。

代码语言:javascript
复制
import psutil
    
psutil.virtual_memory().total  # total physical memory in Bytes

herevirtual_memory的文档。

票数 76
EN

Stack Overflow用户

发布于 2014-03-01 02:53:33

正则表达式在这类事情上工作得很好,并且可能对不同发行版之间的细微差别有所帮助。

代码语言:javascript
复制
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])
票数 13
EN

Stack Overflow用户

发布于 2017-02-15 20:33:59

在Python 2.7.9中,这段代码在我没有任何外部库的情况下可以正常工作

代码语言:javascript
复制
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'

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

代码语言:javascript
复制
    """
        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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22102999

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档