Chris K
Chris K

Reputation: 12341

Optimizing python input loop

So I'm building a log parser, which uses regular expressions, and am parsing data from stdin. I'd like the first line (the head, if you will) to go through my log detector algorithm, which tests regex.search(es) from various patterns, but I don't want to do that for every single input line.

I can do typical logic such as:

        First = True
        for inputLine in file:
            if First:
                if testLogType1(inputLine):
                    print "appears to be log 1"
                elif testLogType2(inputLine):
                    print "appears to be log 2"
                First = False
            else:
               pass

There has to be a cleaner, more pythonic way of doing this? I'm not new to programming, but I am new to Python (rank beginner). I can bludgeon my way through things in the Java, C++ ways of old, but I'm trying to be better. Any thoughts on how to improve this?

"For" loop first iteration is one possible way of addressing this. Perhaps my question here is how do I adapt that answer to a once-through reading of standard input?

Upvotes: 0

Views: 99

Answers (2)

kindall
kindall

Reputation: 184101

E.g.

firstline = next(infile)
if testLogType1(firstline):
    print "appears to be log 1"
# etc.

for inputLine in infile:
    # process the rest of the lines

Upvotes: 4

Bartlomiej Lewandowski
Bartlomiej Lewandowski

Reputation: 11170

Just read the first line and check to see which log type it is

with file as f:
   input = f.readline()
   if testLogType1(inputLine):
       print "appears to be log 1"
   elif testLogType2(inputLine):
       print "appears to be log 2"

Upvotes: 4

Related Questions