由于您想要一个跨平台(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"