I have a python script that calculates Memory Used on a mac. It runs fine via terminal:
ie.
$>python freeMem.py | grep 'Memory Used' | awk '{print $5 }'
14264
**
- freeMem.py:
**
# 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('[\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
#App_Memory = sysctl vm.page_pageable_internal_count - Pages Purgable (from vm_stat)
cmd = "sysctl vm.page_pageable_internal_count"
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
(out, rc) = proc.communicate()
vmpage_pageable_internal_count = out.strip().decode('ascii').split(': ')[1]
vmpage_pageable_internal_count = int(vmpage_pageable_internal_count) * 4096
#print("Purgable internal count %d" % (vmpage_pageable_internal_count))
AppMemory = (vmpage_pageable_internal_count - vmStats["Pages purgeable"])/1024/1024
WiredMemory = vmStats["Pages wired down"]/1024/1024
ActiveMemory = vmStats["Pages active"]/1024/1024
InactiveMemory = vmStats["Pages inactive"]/1024/1024
CompressedMemory = vmStats["Pages occupied by compressor"] /1024/1024
UsedMemory = AppMemory + WiredMemory + CompressedMemory
print('Memory Used: %.3f GB %d MB' % (float(UsedMemory/1024), float(UsedMemory/1024 * 1000)))
However, when i tried to call it via any shell scripts, i.e: do shell script in applescript or os.system or subproces.Popen, run, call, etc... or even via back tick `` command in bash, it will return exactly the first two digits only with the rest being zeroes?: ie.: ./doGetMemUsed.sh 14000
content of doGetMemUsed.sh:
out=$(python freeMem.py | grep 'Memory Used' | awk '{print $5 }')
echo $out
Noticed last 3 digits are all gone and converted or rounded up to 0s?
I needed to get the last 3 digits as well, as these represents MB used, to be correctly calculated. Rounding it to GB is not accurate enough for my application.
I've tried using 10# to specify decimal in my bash script to no avail. I've tried casting it as integer in my python script, still no luck.
Only way i can get it to work is call it directly in terminal. But, i can't automate this via any scripting mechanism, because it would rely on shell underneath.
Any suggestions?