如何从看门狗的事件处理程序中获取返回值

时间:2019-04-03 09:13:48

标签: python watchdog

如果某个文件夹目标中有新添加的txt文件,我正在尝试使用看门狗提取文件名。当有新的txt文件时,它将触发on_created函数并返回文件名。

# Watchdog API
class EventHandler(FileSystemEventHandler):
    def on_created(self, event):
        print(event)
        fileDir = str(event)
        fileName = fileDir.split('\\')
        fileName = fileName[len(fileName) - 1]
        fileName = fileName[:len(fileName)-2]    # remove '>
        print(fileName)
        return fileName

问题是如何从on_created输入返回值到我自己定义的函数readfile()?

def readfile(fileName):
    # Read Error Msg FileName
    filePath=""
    if fileName is not None:
        filePath = fileName
        fhand = open(filePath)
        for line in fhand:
            line = line.rstrip()
            if not line.startswith(r'\\'):
            continue
            else:
                fileDir = line
                print("fileDir" + fileDir)
        filePathList = fileDir.split('\\')
        print(filePathList)
        for item in filePathList:
            if item.endswith('csv'):
                fileName = item
                print("fileName" + fileName)

        # Read Error Msg Content
        fhand2 = open(filePath)
        content = fhand2.read()
        print(content)
        txtcontent = [content, fileName]
        return txtcontent
        fhand.close()
        fhand2.close()

要在main方法中运行readfile()(第二行缺少输入),

if __name__ == "__main__":
    txtcontent = readfile(#how to input the return value from eventhandler?) # to run the readfile()

    path = "\\\\folder\\folder\\folder"
    event_handler = EventHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    print("observer started")
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

谢谢!

0 个答案:

没有答案