Rakesh
Rakesh

Reputation: 19

Unable to extract information from Linux shell command using python

I am creating a Python script to collect data on underlying hardware from cat /proc/cpuinfo I am trying to extract information i need. But I am having a problem. Here is the script

import os
p=os.popen ("cat /proc/cpuinfo")
string=[]
i=0
for line in p.readlines():
   string.append(line.split(":"))
   if(string[i][0]=='model name'): 
        fout = open("information.txt", "w")
        fout.write("processor:")
        fout.write(string[i][1])
        fout.close()
   i+=1

My program does not enter if loop at all why? Thanks in advance for help

Upvotes: 1

Views: 274

Answers (4)

Ellioh
Ellioh

Reputation: 5330

Hard to say what exactly is wrong. I could not figure that out at a glance, though on my Ubuntu 12.10 it also fails in the same way. Anyway, use the subprocess module since popen is deprecated.

subprocess.check_output(['cat', '/proc/cpuinfo']) returns a string quite successfully, at least on my system. And subprocess.check_output(['cat', '/proc/cpuinfo']).split('\n') will give you a list you may iterate through.

Also note that string[i][0]=='model name' won't work. There are tabs after splitting that line by ':'. Do not forget to call strip(): string[i][0].strip()=='model name'

Then, on Python 2.6+ (or even 2.5+, though 2.5 requires from __future__ import with_statement) it's almost always a good practice to use with for dealing with a file you need to open:

with open("information.txt", "w") as fout:
    fout.write("processor:")
    fout.write(string[i][1])

And finally, those saying you may just open a file and read it, are quite right. That is the best solution:

with open('/proc/cpuinfo') as f:
    #Here you may read the file directly.

Upvotes: 0

jfs
jfs

Reputation: 414655

it probably does enter the loop but there might be a whitespace around "model name". You could call .strip() to remove it.

You can open /proc/cpuinfo as a file:

with open("/proc/cpuinfo") as file:
    for line in file:
        key, sep, value = line.partition(":")
        if sep and key.strip() == "model name":
           with open("information.txt", "w") as outfile:
               outfile.write("processor:" + value.strip())
           break

Upvotes: 1

asheeshr
asheeshr

Reputation: 4114

You could try doing it as :

for line in p.readlines():
    line=line.split(":")
    if(line[0]=='model name\t') :
            #Do work

If you dont need the complete list string.

Upvotes: -1

wim
wim

Reputation: 363173

There is no point to use cat at all here. Refactor it like this:

with open("/proc/cpuinfo") as f:
  for line in f:
    # potato potato ...

Upvotes: 2

Related Questions