Get total physical memory in Python
your best bet for a cross-platform solution is to use the psutil package (available on PyPI).
import psutil
psutil.virtual_memory().total # total physical memory in Bytes
Documentation for virtual_memory
is here.
Using os.sysconf
on Linux:
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_PAGESIZE
andSC_PAGE_SIZE
are equal. - For more info, see
man sysconf
. - For MacOS, as per user reports, this works with Python 3.7 but not with Python 3.8.
Using /proc/meminfo
on Linux:
meminfo = dict((i.split()[0].rstrip(':'),int(i.split()[1])) for i in open('/proc/meminfo').readlines())
mem_kib = meminfo['MemTotal'] # e.g. 3921852
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])