在我可以访问的所有系统中,我注意到一件事:带有选项 -P 的 df 在空白对齐的列中打印。这意味着标题与其余项目的宽度相同(用空格填充)。基于7erm 的答案,这使用标头的大小来确保它获得整个安装点,即使其中有空格也是如此。
这已经在 Ubuntu 14.04、16.04 和 FreeBSD 9.2 上进行了测试。
我已经解决了这两种不同的方法,第一种是对 OP 问题的直接回答,给出 6 列,每列以标题开头,然后在其下方按顺序排列每个挂载点:
import pprint
import subprocess
import re
DF_OPTIONS = "-PlaTh" # remove h if you want bytes.
# Get the entire output of df
dfdata = subprocess.getoutput("df " + DF_OPTIONS)
# Split it based on newlines
lines = dfdata.split("\n")
dfout = {}
headers = []
# Grab the headers, retain whitespace!
# df formats in such a way that each column header has trailing whitespace
# so the header is equal to the maximum column width. We want to retain
# this for len()
headersplit = re.split(r'(\s+)', lines[0].replace("Mounted on","Mounted_on "))
headers = [i+j for i,j in zip(headersplit[0::2],headersplit[1::2])]
for hi,head in enumerate(headers):
dfout[hi] = [head.strip()]
for line in lines[1:]:
pos = 0
dfstruct = {}
for hi,head in enumerate(headers):
# For the last item, grab the rest of the line
if head == headers[-1]:
item = line[pos:]
else:
# Get the current item
item = line[pos:pos+len(head)]
pos = pos + len(head)
#Strip whitespace and add it to the list
dfstruct[head.strip()] = item.strip()
dfout[hi].append(item.strip())
pprint.pprint(dfout)
第二个对我更有用,并且解决了我首先偶然发现这个问题的原因。这会将信息放入一个字典数组中:
import pprint
import subprocess
import re
DF_OPTIONS = "-PlaTh" # remove h if you want bytes.
# Get the entire output of df
dfdata = subprocess.getoutput("df " + DF_OPTIONS)
# Split it based on newlines
lines = dfdata.split("\n")
dfout = []
headers = []
# Grab the headers, retain whitespace!
# df formats in such a way that each column header has trailing whitespace
# so the header is equal to the maximum column width. We want to retain
# this for len()
headersplit = re.split(r'(\s+)', lines[0].replace("Mounted on","Mounted_on "))
headers = [i+j for i,j in zip(headersplit[0::2],headersplit[1::2])]
for line in lines[1:]:
pos = 0
dfstruct = {}
for head in headers:
# For the last item, grab the rest of the line
if head == headers[-1]:
item = line[pos:]
else:
# Get the current item
item = line[pos:pos+len(head)]
pos = pos + len(head)
#Strip whitespace for our own structure
dfstruct[head.strip()] = item.strip()
dfout.append(dfstruct)
pprint.pprint(dfout)