Python - 从 class 生成一个方法

Python -Spawn a methode from a class

我完全是 python 的新手,我正在寻找“thread”来自 class[ 的方法=32=]。 不幸的是,它似乎很难理解。

所以: 我有一个 class 方法:

First methode named "readLog" : will read a log file, and return true if it found a specific string (txt)
Second methode named "checkLog" : will check if there is a new one log file, (txt)

我不知道怎么办:

运行 这两个并行的方法:

如果 readLog 找到一个特定的字符串,调用另一个方法

并在“checkLog”中找到一个新的日志文件,将停止“readlog”进程,并启动 一个新文件新的“日志路径”(传入参数)

您可以使用 threading 模块来获得类似的响应

import threading
import os
import time

class SomeClass(object):

    def __init__(self):
        self.continue_reading = True


    def readLog(self, logpath, searchstring):
        with open(logpath, "r") as f:
            data = f.readlines()

        for line in data:
            if self.continue_reading:
                if searchstring in line:
                    # Other method here
                    return line
            else:
                return None

    def checkLog(self, new_filename, directory, searchstring):
        # If new file is found
        if new_filename in os.listdir(directory):
            self.continue_reading = False
            # Wait for some time to let the readlog be finished
            time.sleep(1)
            self.continue_reading = True
            th = threading.Thread(
                target=self.readLog,
                args=(os.path.join(directory, new_filename), searchstring)
            )
            th.start()

        

当您调用 checkLog 方法时,它会为新文件生成新线程,并会在检测到新文件时立即关闭它们。