我想知道Python标准库是否有模块可以获取总物理内存大小。我知道可以使用psutil,但如果我的Python脚本不需要安装外部模块就能运行,那将是非常好的。谢谢!
编辑: 抱歉,我忘了提到我正在使用macOS。感谢所有Windows解决方案!
我想知道Python标准库是否有模块可以获取总物理内存大小。我知道可以使用psutil,但如果我的Python脚本不需要安装外部模块就能运行,那将是非常好的。谢谢!
编辑: 抱歉,我忘了提到我正在使用macOS。感谢所有Windows解决方案!
如果您使用的是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))
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。
split
模式更改为" \n\n"
。 - Panki根据这个讨论,Python标准库似乎没有相关的功能。以下是一些可能有用的工具: