3

I'm wondering if there is a module in python standard library I can use to get the total physical memory size. I know I can use psutil, but it would be great if my python script can run without installing external module. Thanks!

Edited: Sorry guys, I forgot to mention that I'm using a mac OSX. Thanks for all the windows solutions tho!

JACK ZHANG
  • 600
  • 1
  • 7
  • 16

3 Answers3

2

If you're on Windows, you can use GlobalMemoryStatusEx, which requires only ctypes and no additional modules.

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)

Used like this:

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

See here, here, and here for information for MAC OS X/other UNIX systems.

Community
  • 1
  • 1
Alyssa Haroldsen
  • 3,652
  • 1
  • 20
  • 35
1

I've utilized this function in a Windows environment previously.

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)

This utilizes wmic and the following command wmic memorychip get capacity, which you can run from your command line to see output in bytes.

This command reads the capacity of each memory module in the machine (in bytes) and then converts the total to gigabytes.


Example:

> wmic memorychip get capacity
Capacity
4294967296
4294967296

This shows I have two 4 GB chips.

> python get_totalmemory.py
8

Adding those two module capacities and doing a quick conversion shows I have 8 GB of RAM on this machine.

Andy
  • 49,085
  • 60
  • 166
  • 233
0

Based on this discussion there seems to nothing in Python's standard library that'll do that. Here's a few that might help:

  • Python System Information
  • Psutil (Up-to-date, good cross
    platform support, I've used this before, not in Blender though)
  • SIGAR (looks fairly recent, supports a number of platforms)
LSchueler
  • 1,414
  • 12
  • 23
romants
  • 3,660
  • 1
  • 21
  • 33
  • Ya I saw that discussion when I googled it. I didn't count on it because it was 5 yrs ago, so I decided to post it here again. Psutil definitely works, it's just I don't want the users to have to install external libs when using my script. – JACK ZHANG Jul 21 '15 at 18:43