(slightly OT): Python and linux - very cool

Just just at xs4all.nl
Thu Aug 8 13:41:02 EDT 2002


In article <o58uia-q8q.ln at drebbelstraat20.dyndns.org>,
 Mart van de Wege <mvdwege.usenet at drebbelstraat20.dyndns.org> wrote:

> For example, this is what I recently did to extract all IPs from my
> access.log:
> 
> ----- BEGIN SCRIPT -----
> #!/usr/bin/perl
> 
> use warnings; # Make Perl picky about syntax.
> use strict; # Make Perl *really* picky.
> 
> my @iplist; # Declare an array to hold all IP addresses.
> 
> open (FILE, '/var/log/apache/access.log');
> 
> while (<FILE>) {
> 	/^(\d+\.\d+\,\d+\.\d+)?/;
> 	next unless $1; # Skip if the first field is somehow empty.
> 	next if $1 eq '127.0.0.1'; # Skip localhost.
> 	push @iplist, $1;
> }
> # @iplist now holds all IPs in the first field of access.log.
> 
> ----- END SCRIPT -----
> 
> Python can do this too of course, but somehow this is the sort of task
> that comes naturally to me in Perl. Note the use of the regexp:
> 
> 1. I don't have to explicitly declare and compile it.
> 2. It operates on the default input variable ($_), so I don't have to
> specify its target, I just use a bare regexp.


import re

iplist = []

for line in open("/var/log/httpd/access_log"):
   m = re.match(r"^(\d+\.\d+\.\d+\.\d+)", line)
   if m:
      ip = m.group(1)
      if ip != "127.0.0.1":
         iplist.append(ip)


I don't thinkthat's significantly worse (or better...) than the Perl 
version?


Just



More information about the Python-list mailing list