MacOS Activity Monitor commands (cached files) in Python

637 views Asked by At

The goal of the script is to generate logs that monitor a macOS machines RAM, CPU, Disk and Network Statistics.

I'm successfully able to display some memory stats using psutil.virtual_memory() or the vm_stat command in terminal.

psutil - https://psutil.readthedocs.io/en/latest/

However I would like to specifically display the 'cached files' stat shown in Activity Monitor (below).

macOS activity monitor cached files

I don't want to do this a ghetto way like clearing the cache and then measuring the available RAM before and after and subtracting.

Here's what what I'm playing with:

import psutil

mem = str(psutil.virtual_memory())
mem = mem.replace(',', '')
mem = mem.split()

mem_total = mem[0].split("=")
mem_total = mem_total[1]
mem_total = round(int(mem_total)/1024**3, ndigits=1)

mem_used = mem[3].split("=")
mem_used = mem_used[1]
mem_used = round(int(mem_used)/1024**3, ndigits=1)

mem_free = mem[4].split("=")
mem_free = mem_free[1]
mem_free = round(int(mem_free)/1024**3, ndigits=1)

print(mem_total)
print(mem_used)
print(mem_free)

Thanks

1

There are 1 answers

1
felipe On

I programmed a tool exactly like this a little while ago called Tocco, which I would encourage you to check out its code on Github. It also uses psutil to pull OSX system information. Here is the specific part of the code you are asking for, using psutil.virtual_memory():

import psutil

def humansize(nbytes):
    """ Appends prefix to bytes for human readability. """

    suffixes = ["B", "KB", "MB", "GB", "TB", "PB"]
    i = 0
    while nbytes >= 1024 and i < len(suffixes) - 1:
        nbytes /= 1024.0
        i += 1
    f = ("%.2f" % nbytes).rstrip("0").rstrip(".")
    return "%s %s" % (f, suffixes[i])

mem = psutil.virtual_memory()

print(humansize(mem.used))
print(humansize(mem.free))
print(humansize(mem.active))
print(humansize(mem.inactive))
print(humansize(mem.wired))

Outputs:

4.06 GB
16.57 MB
2.02 GB
1.95 GB
2.04 GB