Python standard library for getting total memory

I am wondering if there is a module in the python standard library that 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 the external module. Thank!

Edited: Sorry guys, I forgot to mention that I am using Mac OSX. Thanks for all Windows tho solutions!

+3


source to share


3 answers


If you are on Windows, you can use GlobalMemoryStatusEx which only requires ctypes and 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 on MAC OS X / other UNIX systems.

+2


source


Based on this discussion , there is nothing in the Python standard library that can do this. Here are a few that might help:



0


source


I have used this feature earlier on Windows environment.

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)

      


The wmic

following command is also used here wmic memorychip get capacity

, which you can run from the command line to see the 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 that I have two 4GB chips.

> python get_totalmemory.py
8

      

Adding these two modules and a quick conversion shows that this computer has 8GB of RAM.

0


source







All Articles