Skip to content

Instantly share code, notes, and snippets.

@singularitti
Last active July 9, 2018 02:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save singularitti/e192573b75123daa564a5717338cc029 to your computer and use it in GitHub Desktop.
Save singularitti/e192573b75123daa564a5717338cc029 to your computer and use it in GitHub Desktop.
A Python script that can show the wired, active, inactive and free memory amounts #macOS #memory
#!/usr/bin/env python3
"""
Code referenced from `Stack Exchange \
<https://apple.stackexchange.com/questions/4286/is-there-a-mac-os-x-terminal-version-of-the-free-command-in-linux-systems>`_.
**Note**: One need to use Python 3 to run this file!
"""
import re
import subprocess
# Get process info
ps = subprocess.Popen(['ps', '-caxm', '-orss,comm'],
stdout=subprocess.PIPE).communicate()[0].decode()
vm = subprocess.Popen(['vm_stat'], stdout=subprocess.PIPE).communicate()[
0].decode()
# Iterate processes
processLines = ps.split('\n')
sep = re.compile(r'[\s]+')
rssTotal = 0 # kB
for row in range(1, len(processLines)):
rowText = processLines[row].strip()
rowElements = sep.split(rowText)
try:
rss = float(rowElements[0]) * 1024
except:
rss = 0 # Ignore...
rssTotal += rss
# Process vm_stat
vmLines = vm.split('\n')
sep = re.compile(r':[\s]+')
vmStats = {}
for row in range(1, len(vmLines)-2):
rowText = vmLines[row].strip()
rowElements = sep.split(rowText)
vmStats[(rowElements[0])] = int(rowElements[1].strip(r'\.')) * 4096
GB = 1024**3
print('Wired Memory:{:10.2f} GB'.format(vmStats["Pages wired down"]/GB))
print('Active Memory:{:10.2f} GB'.format(vmStats["Pages active"]/GB))
print('Inactive Memory:{:10.2f} GB'.format(vmStats["Pages inactive"]/GB))
print('Free Memory:{:10.2f} GB'.format(vmStats["Pages free"]/GB))
print('Real Mem Total (ps):{:10.2f} GB'.format(rssTotal/GB))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment