0

I am making a program that reads through a log file that is stored locally on the C drive. This log file is constantly being updated and my program only prints the new lines of text in the log, not the previously stored lines. I need the same function that prints lines in the console to return the line itself. The only way I can see of doing that is to put return in the for loop but that is not possible as it ends the function.

I need this function that read lines to return the line also because the returned line will be sent to another function that interprets the line to recognize certain data in it.

How would I loop a return in a function or pass data from a function onto another function?

I am on Windows 8.1 Python v2.7.9

1 Answers1

4

Use a generator function to produce data as you iterate. Generators can produce data endlessly while you iterate over them:

def read_log_lines(filename):
    while True:
        # code to read lines 
        if is_new(line):
            yield line

This function, when called, returns a generator object. You can then loop over that object like you can over a list, and each time you iterate the code in the generator function will be run until it reaches a yield statement. At that point the yielded value is returned as the next value for the iteration, and the generator function is paused until you iterate again.

So you'd use it like this:

for new_line in read_log_lines(filename):
    # new_line was produced by the generator function
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343