You can also read the source of free
's information, /proc/meminfo
:
~ head /proc/meminfo
MemTotal: 4039168 kB
MemFree: 2567392 kB
MemAvailable: 3169436 kB
Buffers: 81756 kB
Cached: 712808 kB
SwapCached: 0 kB
Active: 835276 kB
Inactive: 457436 kB
Active(anon): 499080 kB
Inactive(anon): 17968 kB
In Python, for example:
with open('/proc/meminfo') as file:
for line in file:
if 'MemFree' in line:
free_mem_in_kb = line.split()[1]
break
will get you the free memory in KB in the free_mem_in_kb
variable. With something similar for total memory, you can subtract the values (or add up buffers, cached, etc.).
You could also create a dictionary of the values in the file:
from collections import namedtuple
MemInfoEntry = namedtuple('MemInfoEntry', ['value', 'unit'])
meminfo = {}
with open('/proc/meminfo') as file:
for line in file:
key, value, *unit = line.strip().split()
meminfo[key.rstrip(':')] = MemInfoEntry(value, unit)
Then retrieve the values with meminfo['MemAvailable'].value
, for example.
psutil
python module seems like the right way to go.