1

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

4 Answers 4

2

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 ...
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

Comments

-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.