#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Sun Jul  8 22:20:31 2012

@author: root
"""

from optparse import OptionParser,OptionGroup
import subprocess
import re
import sys

def free(opt):
    # 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 )




if __name__ =="__main__":

    parser = OptionParser(usage="usage: %prog [-b|-k|-m|-g] [-l] [-o] [-t] [-s delay] [-c count] [-V]",
                          epilog="free tool on Mac OS"
                         )


    group=OptionGroup(parser,"show output in bytes, KB, MB, or GB",
                      description=None)
    group.add_option("-b", action="store_true", help="show output in bytes.")
    group.add_option("-k", action="store_true", help="show output in KB.")
    group.add_option("-m", action="store_true", help="show output in MB.")
    group.add_option("-g", action="store_true", help="show output in GB.")
    parser.add_option_group(group)


    parser.add_option("-l",action="store_true",help= "show detailed low and high memory statistics")
    parser.add_option("-o",
                      action="store_true",
                      help="use old format (no -/+buffers/cache line)")
    parser.add_option("-t",action="store_true",help= "display total for RAM + swap")
    parser.add_option("-s",action="store",dest="delay",type='int',
                      help= "update every [delay] seconds")
    parser.add_option("-c",action="store",dest="count",type='int',
                      help= "update [count] times")
    parser.add_option("-V",action="store_true",default="Version 1.0",
                      help= "display version information and exit",
                      )


    (options, args) = parser.parse_args()
    print options,args
    free(args)


@@ -193,16 +193,21 @@
 free(opt
+,args
 ):%0A    #
@@ -1068,17 +1068,40 @@
  * 4096%0A
-%0A
+    if opt.vm_stat:%0A    
     prin
@@ -1171,24 +1171,28 @@
 /1024 )%0A    
+  
+  
 print 'Activ
@@ -1243,32 +1243,36 @@
 e%22%5D/1024/1024 )%0A
+    
     print 'Inact
@@ -1284,16 +1284,18 @@
 emory:%5Ct
+%5Ct
 %25d MB' %25
@@ -1327,32 +1327,36 @@
 e%22%5D/1024/1024 )%0A
+    
     print 'Free 
@@ -1407,24 +1407,28 @@
 1024/1024 )%0A
+    
     print 'R
@@ -1482,16 +1482,482 @@
 /1024 )%0A
+    else:%0A        total=(vmStats%5B%22Pages wired down%22%5D+vmStats%5B%22Pages active%22%5D+ %5C%0A              vmStats%5B%22Pages inactive%22%5D+vmStats%5B%22Pages free%22%5D)/1024%0A        free=(vmStats%5B%22Pages inactive%22%5D+vmStats%5B%22Pages free%22%5D)/1024%0A        used=total-free%0A        shared=0%0A        print    '%5Ct%5Ct total  %5Ct used  %5Ct free  %5Ct shared  %5Ct buffers %5Ct cached'%0A        print 'Mem: %5Ct%5Ct%25d  %5Ct %25d %5Ct%25d %5Ct %25d '%25(total,used,free,shared)%0A        print %22-/+ buffers/cache:%22%0A        print %22Swap:%22
 %0A%0A%0A%0Aif _
@@ -2023,13 +2023,12 @@
 ge: 
-%25prog
+free
  %5B-b
@@ -2743,16 +2743,17 @@
 n(%22-o%22,%0A
+%0A
         
@@ -3348,24 +3348,181 @@
           )%0A
+    parser.add_option(%22-v%22,%22--vm_stat%22,action=%22store_true%22,dest=%22vm_stat%22,%0A                      help= %22display format like vm_stat%22,%0A                      )
 %0A%0A    (optio
@@ -3557,22 +3557,21 @@
 s()%0A    
-print 
+free(
 options,
@@ -3578,21 +3578,7 @@
 args
-%0A    free(args
 )%0A%0A

add -v option and finish free no opt mode