无法使用python从Linux shell命令中提取信息

时间:2013-02-18 05:20:44

标签: python

我正在创建一个Python脚本来从cat /proc/cpuinfo收集底层硬件上的数据 我正在尝试提取我需要的信息。但我遇到了问题。这是脚本

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

我的程序如果循环完全没有进入原因?在此先感谢您的帮助

4 个答案:

答案 0 :(得分:2)

这里根本没有必要使用cat。像这样重写:

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

答案 1 :(得分:1)

它可能确实进入了循环,但“模型名称”周围可能有一个空格。您可以致电.strip()将其删除。

您可以将/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

答案 2 :(得分:0)

很难说究竟是什么错。我无法一眼就看出来,虽然在我的Ubuntu 12.10上它也以同样的方式失败了。无论如何,使用subprocess模块,因为popen已被弃用。

subprocess.check_output(['cat', '/proc/cpuinfo'])非常成功地返回一个字符串,至少在我的系统上。 subprocess.check_output(['cat', '/proc/cpuinfo']).split('\n')将为您提供一个可以迭代的列表。

另请注意string[i][0]=='model name'无效。按':'分割该行后有标签。不要忘记致电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.

答案 3 :(得分:-1)

你可以尝试这样做:

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

如果您不需要完整列表string

相关问题