[OSX-SHELL] Get Memory Informations

A simple python script to get your RAM status faster on MAC OSx.

MacBook-di-alberto:Desktop albertop$ mem
Wired Memory:		757 MB
Active Memory:		2566 MB
Inactive Memory:	556 MB
Free Memory:		654 MB
Real Mem Total (ps):	2234.562 MB
MacBook-di-alberto:Desktop albertop$ 

Open VIM or Text edit and copy paste these lines. Save as *.py, that is a phyton extension. Not important on unix, but is easy to read.

[code lang=”bash” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]#!/usr/bin/python[/code]

[code lang=”bash” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]import subprocess
import re

# Get process info
ps = subprocess.Popen([‘ps’, ‘-caxm’, ‘-orss,comm’], stdout=subprocess.PIPE).communicate()[0]
vm = subprocess.Popen([‘vm_stat’], stdout=subprocess.PIPE).communicate()[0]

# Iterate processes
processLines = ps.split(‘\n’)
sep = re.compile(‘[\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(‘:[\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(‘\.’)) * 4096

print ‘Wired Memory:\t\t%d MB’ % ( vmStats["Pages wired down"]/1024/1024 )
print ‘Active Memory:\t\t%d MB’ % ( vmStats["Pages active"]/1024/1024 )
print ‘Inactive Memory:\t%d MB’ % ( vmStats["Pages inactive"]/1024/1024 )
print ‘Free Memory:\t\t%d MB’ % ( vmStats["Pages free"]/1024/1024 )
print ‘Real Mem Total (ps):\t%.3f MB’ % ( rssTotal/1024/1024 )[/code]

Save and launch the script from Terminal App:

[code lang=”bash” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]python /Users/albertop/Work/Labs/Memory.py[/code]

Here a tricks to abbreviate command:

[code lang=”bash” autolinks=”false” collapse=”false” firstline=”1″ gutter=”true” htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false”]alias mem=’python /Users/albertop/Work/Labs/Memory.py'[/code]

Now, if you type mem executing the memory script.

PS: if you want to type mem every time that you open terminal, you need to edit the .bash_profile file located (if not, create it!) in home folder (~/), adding alias trick script.
Save and restart terminal.

have fun.

Alberto Pasca
Latest posts by Alberto Pasca (see all)