Question regarding lists and regex

Prabhu Gurumurthy pgurumur at
Thu Nov 9 07:29:57 CET 2006

Here is a simple program, which queries /var/log/daemon on my OpenBSD box and 
gets the list of valid ntp peers.

what is the easiest way for me to create lists on the fly, by that I mean like perl

push my @foo, something_from_say_stderr. The reason is as you can ip = [""] 
statement before the for loop, I want to avoid that and use list within the 
second ip loop, where I extract the ip address. Am I confusing?

regex: I presume this is rather a dumb question, anyways here it comes! as you 
can see from my program, pattIp = r\d{1,3}\.... etc, is there any other easy way 
to group the reptitions, instead of typing the same regex 4 times.


amazon: [~/working/programs/python/regex]
ttyp4: [109]$ cat
#!/usr/bin/env python
# $Id:,v 1.6 2006/11/09 06:24:03 pgurumur Exp $

import getopt, re, os, string, sys, time
(dirname, program) = os.path.split(sys.argv[0])
argc = len(sys.argv)

def usage():
    print program + ": options"
    print "options: "
    print "          --filename | -f [ name of the file ]"
    print "          --help | -h [ prints this help ]"

if __name__ == "__main__":
    if (argc <= 1):
          opts, args = getopt.getopt(sys.argv[1:], "f:h", ["help", "filename="])
       except getopt.GetoptError:
          filename = ""
          for optind, optarg in opts:
             if optind in ("-f", "--filename"):
                filename = optarg
             elif optind in ("-h", "--help"):

          if len(filename):
             fh = 0
                fh = open(filename, "r")
             except IOError, (error, message):
                print program + ": cannot open " + filename + ": " + message

             pattNtp = r'.*ntpd(?=.*now\s+valid)'
             count = 0
             ip = [""]
             pid = 0
             for line in fh.readlines():
                if re.match(pattNtp, line.strip(), re.IGNORECASE):
                   string = line.strip()
                   pattPid = r'\[\d{1,5}\]'
                   pidMatch =, string, re.IGNORECASE)
                   if pidMatch is not None:
                      pid = int(re.sub(r'\[|\]', "",

                   pattIp = r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
                   match =, string, re.IGNORECASE)
                   if match is not None:
                      count += 1

             print "NTP program started with pid:", pid
             print "Number of valid peers:", count
             for x in ip:
                if len(x):
                   print x


More information about the Python-list mailing list