2013-02-18 78 views
1

我正在創建一個Python腳本來收集基礎硬件上的數據cat /proc/cpuinfo 我試圖提取我需要的信息。但我有問題。這裏是腳本無法使用python從Linux shell命令提取信息

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 

我的程序不會進入如果循環在所有原因?在此先感謝幫助

回答

0

很難說什麼是錯的。我無法一目瞭然,但在我的Ubuntu 12.10上,它也以相同的方式失敗。無論如何,使用subprocess模塊,因爲popen已棄用。

subprocess.check_output(['cat', '/proc/cpuinfo'])返回一個字符串相當成功,至少在我的系統上。 subprocess.check_output(['cat', '/proc/cpuinfo']).split('\n')會給你一個你可能會遍歷的列表。請注意0​​將不起作用。在將該行分割爲':'之後有一些標籤。不要忘記調用strip()string[i][0].strip()=='model name'

然後,關於Python 2.6+(甚至2.5+,雖然2.5需要from __future__ import with_statement)它幾乎總是使用with用於處理文件的好習慣,你需要打開:

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

最後,那些說你可能只是打開一個文件並閱讀它的文章,是非常正確的。這是最好的解決方案:

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

感謝得到它的工作.. – Rakesh 2013-02-18 05:47:28

2

根本沒有必要在這裏使用cat。重構它是這樣的:

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

+1/proc/cpuinfo是一個文件。 – 2013-02-18 05:49:00

1

它可能會進入循環,但可能會有「模型名稱」周圍的空白。您可以撥打.strip()將其刪除。如果你不需要完整列表string

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

您可以打開/proc/cpuinfo作爲一個文件:

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