Grep Equivalent for Python

Steve Holden steve at holdenweb.com
Wed Mar 14 14:18:23 EDT 2007


tereglow wrote:
> Okay,
> 
> It is now working as follows:
> 
> memFile = open('/proc/meminfo')
> for line in memFile.readlines():
> 	if line.startswith("MemTotal"):
> 		memStr = line.split()
> 		memTotal = memStr[1]
> memFile.close()
> print "Memory: " + memTotal + "kB"
> 
> I'm learning the whole try, finally exception stuff so will add that
> in as well.  Now, I'm trying to figure out the CPU speed.  In shell,
> I'd do:
> 
> grep "^cpu MHz" /proc/cpuinfo | awk '{print $4}' | head -1
> 
> The "head -1" is added because if the server has 2 or more processors,
> 2 or more lines will result, and I only need data from the first
> line.  So, now I'm looking for the equivalent to "head (or tail" in
> Python.  Is this a case where I'll need to break down and use the re
> module?  No need to give me the answer, a hint in the right direction
> would be great though.
> 
> Thanks again,
> Tom
> 
If you are interested in a number of fields I'd create a dict or set 
containing the keys you are interested in. For each line, if the text 
indicates you are interested in the value then extract the value and 
store it in a dict against the text as a key.

Something like (untested):

kwdlist = "cpu MHz|MemTotal"
d = dict((x, None) for x in kwdlist.split("|"))
memFile = open('/proc/meminfo')
for line in memFile.readlines():
     keyword = line.split(":")[0]
     if keyword in d and d[keyword] is None:
         d[keyword] = line.split()[1]
memFile.close()

This should give you a dict with non-None values against the keywords 
you have found. Because of the "and d[keyword] is None" test you won;t 
overwrite an existing value, meaning you only see the first value for 
any given keyword.

Again, bear in mind this code is untested.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb     http://del.icio.us/steve.holden
Blog of Note:          http://holdenweb.blogspot.com
See you at PyCon?         http://us.pycon.org/TX2007




More information about the Python-list mailing list