Grep Equivalent for Python

BJörn Lindqvist bjourne at gmail.com
Wed Mar 14 09:57:51 EDT 2007


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

import sys
sys.stdout.write(L.split()[1] + '\n' for L in open('/proc/meminfo') if
L.startswith('MemTotal'))

-- 
mvh Björn



More information about the Python-list mailing list