Skip to main content
 首页 » 编程设计

python之在 Python 中,如何获取 Mac OS X 中所有分区的列表

2025年05月04日15thcjp

我有一个与此处提出的问题类似的问题:Find size and free space of the filesystem containing a given file ,但该问题假定您已经了解该系统。

我有一个任务:对于不确定数量的机器,包括定期部署的新机器,我有/需要一个 python 脚本,如果任何分区太满,它可以向我报告。 (是的,它是由 icinga2 部署的)。

我不做的是手工制作和个性化每台机器的脚本参数,以通知它我要检查的分区;我运行脚本,它只向我报告系统上所有现存的分区。我让系统本身成为自己的权威,而不是从外部定义要检查的分区。这在 linux 中工作正常,并且如上面链接的答案所示,在 linux 中我们可以解析/proc 中的文件以获得权威列表。

但我缺少的是一种从 python 获取 Mac OS X 中可靠的分区列表的方法。

Mac OS X 没有/proc,所以无法进行解析。我宁愿不调用外部二进制文件,因为我的目标是构建我的 python 脚本以在 linux 和 mac 客户端上运行。有什么想法吗?

请您参考如下方法:

由于您需要跨平台(Mac 和 Linux)选项,您可以使用 df在两个平台上都可用的命令。您可以通过 subprocess 访问它.

我已经在 OS X 10.11 和 Ubuntu Linux 15 上测试过了

import subprocess 
 
process = subprocess.Popen(['df -h | awk \'{print $(NF-1),$NF}\''], stdout=subprocess.PIPE, shell=True) 
out, err = process.communicate() 
out = out.splitlines()[1:] # grab all the lines except the header line 
results = {} 
for i in out: 
    tmp = i.split(' ') 
    results[tmp[1]] = tmp[0] 
 
for key, value in results.items(): 
    print key + " is " + str(value) +" full" 

在 Mac 上输出

/dev is 100% full 
/net is 100% full 
/ is 82% full 
/home is 100% full 

Linux 上的输出

/dev is 1% full 
/run/lock is 0% full 
/run is 1% full 
/ is 48% full 

这是不用 awk 的方法

import subprocess 
 
process = subprocess.Popen(['df', '-h'], stdout=subprocess.PIPE) 
out, err = process.communicate() 
out = out.splitlines()[1:] # grab all the lines except the header line 
 
for i in out: 
    tmp = i.split(' ') 
    tmp2 = [] 
    for x in tmp: 
        if x != '': 
            tmp2.append(x) 
    print tmp2[-1] + " is " + tmp2[-2] + " full"