获取Python中的总物理内存

时间:2022-01-27 16:57:38

How can I get the total physical memory within Python in a distribution agnostic fashion? I don't need used memory, just the total physical memory.

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

4 个解决方案

#1


36  

your best bet for a cross-platform solution is to use the psutil package (available on PyPI).

对于跨平台解决方案,您最好的选择是使用psutil包(可在PyPI上获得)。

from psutil import virtual_memory

mem = virtual_memory()
mem.total  # total physical memory available

Documentation for virtual_memory is here.

virtual_memory的文档在这里。

#2


30  

Using os.sysconf on Linux:

在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

Note:

注意:

  • SC_PAGE_SIZE is often 4096.
  • SC_PAGE_SIZE通常为4096。
  • SC_PAGESIZE and SC_PAGE_SIZE are equal.
  • SC_PAGESIZE和SC_PAGE_SIZE相等。
  • For more info, see man sysconf.
  • 有关更多信息,请参阅man sysconf。
  • For MacOS, per an unverified user report, this may work only with MacOS ≥ 10.13 (High Sierra) with Python ≥ 3.6.4.
  • 对于MacOS,根据未经验证的用户报告,这可能仅适用于MacOS≥10.13(High Sierra)且Python≥3.6.4。

Using /proc/meminfo on Linux:

在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

#3


10  

Regular expressions work well for this sort of thing, and might help with any minor differences across distributions.

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

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

#4


1  

This code worked for me without any external library at Python 2.7.9

这段代码在我没有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'

Easily we can get the Used Memory and 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'

#1


36  

your best bet for a cross-platform solution is to use the psutil package (available on PyPI).

对于跨平台解决方案,您最好的选择是使用psutil包(可在PyPI上获得)。

from psutil import virtual_memory

mem = virtual_memory()
mem.total  # total physical memory available

Documentation for virtual_memory is here.

virtual_memory的文档在这里。

#2


30  

Using os.sysconf on Linux:

在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

Note:

注意:

  • SC_PAGE_SIZE is often 4096.
  • SC_PAGE_SIZE通常为4096。
  • SC_PAGESIZE and SC_PAGE_SIZE are equal.
  • SC_PAGESIZE和SC_PAGE_SIZE相等。
  • For more info, see man sysconf.
  • 有关更多信息,请参阅man sysconf。
  • For MacOS, per an unverified user report, this may work only with MacOS ≥ 10.13 (High Sierra) with Python ≥ 3.6.4.
  • 对于MacOS,根据未经验证的用户报告,这可能仅适用于MacOS≥10.13(High Sierra)且Python≥3.6.4。

Using /proc/meminfo on Linux:

在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

#3


10  

Regular expressions work well for this sort of thing, and might help with any minor differences across distributions.

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

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

#4


1  

This code worked for me without any external library at Python 2.7.9

这段代码在我没有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'

Easily we can get the Used Memory and 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'