Python标准库以获取总内存大小

时间:2015-07-21 17:56:49

标签: python

我想知道我是否可以使用python标准库中的模块来获取总物理内存大小。我知道我可以使用psutil,但如果我的python脚本可以在不安装外部模块的情况下运行,那将会很棒。谢谢!

编辑: 对不起,伙计们,我忘了提到我使用的是mac OSX。感谢所有的Windows解决方案!

3 个答案:

答案 0 :(得分:2)

如果您使用的是Windows,则可以使用GlobalMemoryStatusEx,这只需要ctypes而不需要其他模块。

from ctypes import Structure, c_int32, c_uint64, sizeof, byref, windll
class MemoryStatusEx(Structure):
    _fields_ = [
        ('length', c_int32),
        ('memoryLoad', c_int32),
        ('totalPhys', c_uint64),
        ('availPhys', c_uint64),
        ('totalPageFile', c_uint64),
        ('availPageFile', c_uint64),
        ('totalVirtual', c_uint64),
        ('availVirtual', c_uint64),
        ('availExtendedVirtual', c_uint64)]
    def __init__(self):
        self.length = sizeof(self)

像这样使用:

>>> m = MemoryStatusEx()
>>> assert windll.kernel32.GlobalMemoryStatusEx(byref(m))
>>> print('You have %0.2f GiB of RAM installed' % (m.totalPhys / (1024.)**3))

有关MAC OS X /其他UNIX系统的信息,请参阅hereherehere

答案 1 :(得分:0)

基于此discussion,Python的标准库中似乎没有任何内容可以做到这一点。这里有一些可能会有所帮助:

  • Python System Information
  • Psutil(最新,好十字架 平台支持,我之前使用过这个,而不是在Blender中使用)
  • SIGAR(看起来很公平 最近,支持多个平台)

答案 2 :(得分:0)

我之前在Windows环境中使用过此功能。

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)

这利用wmic和以下命令wmic memorychip get capacity,您可以从命令行运行以查看以字节为单位的输出。

此命令读取计算机中每个内存模块的容量(以字节为单位),然后将总数转换为千兆字节。

示例:

> wmic memorychip get capacity
Capacity
4294967296
4294967296

这表明我有两个4 GB的芯片。

> python get_totalmemory.py
8

添加这两个模块容量并进行快速转换显示我在这台机器上有8 GB的RAM。