Grep Equivalent for Python

Steve Holden steve at holdenweb.com
Wed Mar 14 08:49:11 EDT 2007


tereglow wrote:
> Hello all,
> 
> I come from a shell/perl background and have just to learn python.  To
> start with, I'm trying to obtain system information from a Linux
> server using the /proc FS.  For example, in order to obtain the amount
> of physical memory on the server, I would do the following in shell:
> 
> grep ^MemTotal /proc/meminfo | awk '{print $2}'
> 
> That would get me the exact number that I need.  Now, I'm trying to do
> this in python.  Here is where I have gotten so far:
> 
> memFile = open('/proc/meminfo')
> for line in memFile.readlines():
>     print re.search('MemTotal', line)
> memFile.close()
> 
> I guess what I'm trying to logically do is... read through the file
> line by line, grab the pattern I want and assign that to a variable.
> The above doesn't really work, it comes back with something like
> "<_sre.SRE_Match object at 0xb7f9d6b0>" when a match is found.
> 
> Any help with this would be greatly appreciated.
> Tom
> 
Regular expressions aren't really needed here. Untested code follows:

for line in open('/proc/meminfo').readlines:
     if line.startswith("Memtotal:"):
         name, amt, unit = line.split()
         print name, amt, unit
         break

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