tMC
tMC

Reputation: 19325

Python comprehension consolidation

I feel there must be an easier (cleaner) way to use comprehensions to parse the meminfo file on linux. The format of the file is:

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

I tried to rewrite the for loop id been using to use a comprehension and found I needed 3 of them...

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()

What am I doing wrong? Is there a reasonable way to simplify this?

Upvotes: 1

Views: 209

Answers (4)

Kru
Kru

Reputation: 4235

Using a regex and a list comprehension:

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)

Upvotes: 0

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29103

Another one solution(note that i have used string data - so in your case you need to modify code to read data from a file):

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]

Upvotes: 0

GWW
GWW

Reputation: 44093

d = {}
with open(f) as fin:
    for l in fin:
        x = l.split()
        d[x[0][:-1]] = int(x[1])
return d

Upvotes: 6

Daenyth
Daenyth

Reputation: 37441

I find this version much more readable:

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

Upvotes: 1

Related Questions