我觉得必须有一种更容易(更清晰)的方法来使用理解来解析linux上的meminfo文件。该文件的格式为:
MemTotal: 3045588 kB
MemFree: 1167060 kB
Buffers: 336752 kB
Cached: 721980 kB
SwapCached: 0 kB
Active: 843592 kB
Inactive: 752920 kB
Active(anon): 539968 kB
Inactive(anon): 134472 kB
我尝试重写for
循环id,用于使用理解,发现我需要3个...
def parse_mem_file(memfile = '/proc/meminfo'):
lines = open(memfile, 'r').readlines()
lines = [line.strip('kB\n') for line in lines if line[-3:] == 'kB\n']
lines = [line.split(':') for line in lines]
return dict((key, int(value)) for (key, value) in lines)
print parse_mem_file()
我做错了什么?有没有合理的方法来简化这个?
答案 0 :(得分:6)
d = {}
with open(f) as fin:
for l in fin:
x = l.split()
d[x[0][:-1]] = int(x[1])
return d
答案 1 :(得分:1)
我觉得这个版本更具可读性:
def parse_mem_file(memfile='/proc/meminfo'):
data = {}
with open(memfile, 'r') as f:
for line in f:
key, value, size = line.split()
if size == 'kB':
data[key[:-1]] = int(value)
return data
答案 2 :(得分:0)
另一个解决方案(注意我已经使用了字符串数据 - 因此在您的情况下,您需要修改代码以从文件中读取数据):
data = """
MemTotal: 3045588 kB
MemFree: 1167060 kB
Buffers: 336752 kB
Cached: 721980 kB
SwapCached: 0 kB
Active: 843592 kB
Inactive: 752920 kB
Active(anon): 539968 kB
Inactive(anon): 134472 kB
"""
res = {}
for line in [x for x in d.split('\n') if x.strip() and ':' in x and 'kB' in x]:
details = line.split()
res[details[0][:-1]] = details[-2]
答案 3 :(得分:0)
使用正则表达式和列表解析:
def parse_mem_file(memfile = '/proc/meminfo'):
with open(memfile, 'r') as meminfo:
return dict(
(m.group(1), int(m.group(2)))
for m in [re.match('(.+):\\s*(\\d+)', line) for line in meminfo]
if m is not None)