Grep Equivalent for Python

Paul Boddie paul at boddie.org.uk
Wed Mar 14 13:55:07 CET 2007


On 14 Mar, 13:37, "tereglow" <tom.rectenw... at eglow.net> wrote:
> Hello all,
>
> I come from a shell/perl background and have just to learn python.

Welcome aboard!

>  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)

You could even use the regular expression '^MemTotal' as seen in your
original, or use the match function instead of search. However...

> 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.

This is because re.search and re.match (and other things) return match
objects if the regular expression has been found in the provided
string. See this page in the library documentation:

http://docs.python.org/lib/match-objects.html

> Any help with this would be greatly appreciated.

The easiest modification to your code is to replace the print
statement with this:

    match = re.search('MemTotal', line)
    if match is not None:
        print match.group()

You can simplify this using various idioms, I imagine, but what you
have to do is to test for a match, then to print the text that
matched. The "group" method lets you get the whole matching text (if
you don't provide any arguments), or individual groups (applicable
when you start putting groups in your regular expressions).

Paul




More information about the Python-list mailing list