0

我创建了一个虚拟数据管道,它从日志文件中读取数据并将其应用来过滤器(虚拟过滤器)。我很难理解这个程序的输出(流程)。

问题 在 'process' 函数的 for 循环中,我们遍历每个过滤器。现在在循环中,当我们在 filter1 时,我希望程序流将被转移到 filter1 函数,并且它将在移动到循环内的下一个过滤器之前执行。因此,根据我在 filter1 之后的循环中的说法,程序流程应该进入 filter1 函数,但输出显示程序只是生成了一个 filter1 生成器对象,然后直接循环到下一个过滤器,而无需先执行 filter1。同样,在进程函数中退出 for 循环后,程序进入 filter2,然后进入 filter1 并执行它。我不明白这里到底发生了什么。如果您能解释此代码的工作原理及其与输出相关的控制流程,那就太好了。

代码:日志类有两个过滤功能,可以做一些过滤工作。首先,我正在初始化一个虚拟文件,这里它只是两个字符串的列表,然后我添加了两个虚拟过滤器,它们在进程函数内的循环中应用于文件

class LogProcessor(object): 
    def __init__(self, file):
        self._file = file
        self._filters = []
        
    def add_filter(self, new_filter):
        if callable(new_filter):
            self._filters.append(new_filter)
            
    def process(self):
        print("inside process function")
        pipeline = self._file
        print("pipeline = ", pipeline)
        
        #looping over filters
        for new_filter in self._filters:
            print("inside for loop looping over filters with current filter = ", new_filter)
            pipeline = new_filter(pipeline)
        print("outside filter loop")
        return pipeline

    def filter1(lines):
        print("inside filter1 function with lines = ", lines)
        for line in lines:
            print("inside for loop parser with line = ", line)
            yield line
        print("outside parser filter for loop")

    def filter2(lines):
        print("inside filter2 function with lines = ", lines)
        for line in lines:
            print("inside lo0p status filter, line - ", line)
            yield line
        print("outside status filter for loop")


log = ['honey', 'ankita']
processor = LogProcessor(log)

# this is the order we want the functions to run
processor.add_filter(filter1)
processor.add_filter(filter2)

#process() returns the generator pipeline

print("starting  the main loop")
for line in processor.process():
    print("inside the main loop")
    print(line)enter code here

这是程序的输出

在此处输入图像描述

4

0 回答 0