0

该脚本的目标是生成监控 macOS 机器 RAM、CPU、磁盘和网络统计信息的日志。

我可以在终端中使用 psutil.virtual_memory() 或 vm_stat 命令成功显示一些内存统计信息。

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

但是,我想专门显示活动监视器(下)中显示的“缓存文件”统计信息。

macOS 活动监视器缓存文件

我不想像清除缓存然后测量前后的可用 RAM 并减去这样的贫民窟方式。

这就是我正在玩的东西:

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)

谢谢

4

1 回答 1

1

不久前,我编写了一个与此类似的工具,名为Tocco,我鼓励您在 Github 上查看它的代码。它还用于psutil提取 OSX 系统信息。这是您要求的代码的特定部分,使用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))

输出:

4.06 GB
16.57 MB
2.02 GB
1.95 GB
2.04 GB
于 2020-04-27T15:55:55.697 回答