在 for 循环中使用 Return

2022-01-19 00:00:00 python function return logfile for-loop

问题描述

我正在编写一个程序来读取本地存储在 C 驱动器上的日志文件.这个日志文件不断更新,我的程序只打印日志中的新文本行,而不是以前存储的行.我需要在控制台中打印行的相同函数来返回行本身.我能看到的唯一方法是将 return 放在 for 循环中,但这是不可能的,因为它结束了函数.

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?

我使用的是 Windows 8.1Python v2.7.9

I am on Windows 8.1 Python v2.7.9


解决方案

使用 生成器函数 在您迭代时生成数据.生成器可以在您对其进行迭代时无休止地生成数据:

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

该函数在调用时返回一个生成器对象.然后,您可以像遍历列表一样遍历该对象,并且每次迭代生成器函数中的代码都会运行,直到它到达 yield 语句.此时,产生的值将作为迭代的下一个值返回,并且生成器函数将暂停,直到您再次迭代.

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.

所以你会这样使用它:

for new_line in read_log_lines(filename):
    # new_line was produced by the generator function

相关文章