Grep Equivalent for Python

Fabio FZero fabio.fzero at gmail.com
Wed Mar 14 14:45:45 EDT 2007


On Mar 14, 9:37 am, "tereglow" <tom.rectenw... at eglow.net> 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.

Ok, two things:

1. You don't need the .readlines() part. Python can iterate over the
file object itself.
2. You don't need the re module for this particular situation; you
could simply use the 'in' operator.

You could write it like this:

memFile = open('/proc/meminfo')
for line in memFile:
    if 'MemTotal' in line: print line
memFile.close()

[]s
FZero




More information about the Python-list mailing list