Skip to content

Instantly share code, notes, and snippets.

@jagaudin
Last active April 17, 2020 18:56
Show Gist options
  • Save jagaudin/30ba6eda936b48aeae3646918b4ba602 to your computer and use it in GitHub Desktop.
Save jagaudin/30ba6eda936b48aeae3646918b4ba602 to your computer and use it in GitHub Desktop.
Get mem info
import platform
from subprocess import check_output, PIPE, CalledProcessError
# Linux man page for `/proc`:
# http://man7.org/linux/man-pages/man5/proc.5.html
# Windows documentation for `wmic OS`:
# https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/cim-operatingsystem
# MacOS man page for `sysctl`:
# https://www.unix.com/man-page/osx/3/sysctl/
# MacOS man page for `vm_stat`:
# https://www.unix.com/man-page/osx/1/vm_stat/
# These params could be in a json file in the script directory?
os_params = {
'Linux': {
'cmd': [('cat', '/proc/meminfo')],
'kwds': {
# output string fragment -> result dict key
'MemTotal:': 'MemTotal',
'MemAvailable:': 'MemAvailable',
},
},
'Windows': {
'cmd': [
('wmic', 'OS','get', 'TotalVirtualMemorySize'),
('wmic', 'OS', 'get', 'FreeVirtualMemory'),
],
'kwds': {
# output string fragment -> result dict key
'TotalVirtualMemorySize': 'MemTotal',
'FreeVirtualMemory': 'MemAvailable',
},
},
'Darwin': {
'cmd': [
('sysctl', 'hw.memsize'),
('vm_stat'),
],
'kwds': {
# output string fragment -> result dict key
'hw.memsize:': 'MemTotal',
'free:': 'MemAvailable',
},
'units': {
'MemTotal': 1, # Size is given in bytes.
'MemAvailable': 4096, # Size is given in 4kB pages.
},
},
}
system_name = platform.system()
params = os_params.get(system_name, {})
output = []
for cmd in params.get('cmd', []):
try:
out = check_output(cmd, stderr=PIPE)
except (OSError, CalledProcessError) as e:
print(f'Error: {e}')
continue
if system_name == 'Windows':
# Windows output is spread over several lines, join them.
out = b''.join(line for line in out.splitlines()) + b'\n'
output.extend(out.decode().splitlines())
sys_info = {}
kwds = params.get('kwds', {})
for line in output:
match = kwds.keys() & line.split()
if match and len(match) == 1:
k = kwds[match.pop()]
v = int(''.join(c for c in str(line) if c.isdigit()) or 0)
# MacOSX units for total and free differ, get fancy unit or assume kB.
v *= params.get('units', {k: 1024})[k]
# Store memory size in bytes
sys_info[k] = v
elif len(match) > 1:
print(f'Ambiguous output: {line}')
print(sys_info)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment