Skip to content

Instantly share code, notes, and snippets.

@quwubin
Created January 28, 2014 15:18
Show Gist options
  • Save quwubin/8669454 to your computer and use it in GitHub Desktop.
Save quwubin/8669454 to your computer and use it in GitHub Desktop.
Get machine free memory both on Mac OS and Linux.
#!/usr/bin/python
# Author: Wubin Qu <quwubin@gmail.com>
# Tue Jan 28 23:17:08 2014
import platform
import subprocess
import re
def get_free_memory():
if platform.system() == 'Darwin':
# Get process info
vm = subprocess.Popen(['vm_stat'], stdout=subprocess.PIPE).communicate()[0]
installed_memory = float(subprocess.Popen(['sysctl', '-n', 'hw.memsize'], stdout=subprocess.PIPE).communicate()[0])
# 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
total_comsumed = vmStats["Pages wired down"] + vmStats["Pages active"] + vmStats["Pages inactive"]
return (installed_memory - total_comsumed) / installed_memory * 100
elif platform.system() == 'Linux':
items = subprocess.Popen(['free', '-m'], stdout=subprocess.PIPE).communicate()[0].splitlines()[1].strip().split()
free = float(items[3]) + float(items[5]) + float(items[6])
total = float(items[1])
return free / total * 100
else:
print "Sorry, currently only support Mac OS and Linux."
return 0
print get_free_memory()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment