【发布时间】:2017-01-09 05:13:34
【问题描述】:
我正在运行一个解析df 命令输出的实用程序。我捕获输出并将其发送到我的解析器。这是一个示例:
Filesystem 512-blocks Used Available Capacity iused ifree %iused Mounted on
/dev/disk2 1996082176 430874208 1564695968 22% 2429281 4292537998 0% /
devfs 668 668 0 100% 1156 0 100% /dev
map -hosts 0 0 0 100% 0 0 100% /net
map auto_home 0 0 0 100% 0 0 100% /home
函数如下:
def parse_df(self, content):
"""Parse the `df` content output
:param content: The command content output
:return: (list) A list of objects of the type being parsed
"""
entries = []
if not content:
return entries
# Split the content by line and check if we should ignore first line
for line in content.split("\n"):
if line.startswith("Filesystem"):
continue
tokens = line.split()
print tokens
但是我得到以下输出:
['/dev/disk2', '1996082176', '430876480', '1564693696', '22%', '2429288', '4292537991', '0%', '/']
['devfs', '668', '668', '0', '100%', '1156', '0', '100%', '/dev']
['map', '-hosts', '0', '0', '0', '100%', '0', '0', '100%', '/net']
['map', 'auto_home', '0', '0', '0', '100%', '0', '0', '100%', '/home']
问题是 map -host 应该是单个元素(对于 Filesystem 列)。
我尝试应用正则表达式tokens = re.split(r'\s{2,}', line),但结果仍然不正确:
['/dev/disk2', '1996082176 430869352 1564700824', '22% 2429289 4292537990', '0%', '/']
解析输出的正确方法是什么?
【问题讨论】:
-
您需要使用不同的分隔符,比如
\t?甚至多个空格也可以。 -
每一列都有固定的宽度。您可以尝试基于此拆分
-
@Nishant:按
\t拆分:['/dev/disk2 1996082176 430874728 1564695448 22% 2429300 4292537979 0% /'] -
听起来像是正则表达式的工作;或
os.statvfs. -
不相关,但有一些系统调用(例如 statvfs)可能会更直接地得到你想要的。