65

我需要查看日志文件的更改。在查看了 stackoverflow 问题后,我看到人们推荐watchdog. 所以我正在尝试测试,并且不确定在文件更改时在哪里添加代码:

import time
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

if __name__ == "__main__":
    event_handler = LoggingEventHandler()
    observer = Observer()
    observer.schedule(event_handler, path='.', recursive=False)
    observer.start()
    try:
        while True:
            time.sleep(1)
        else:
            print "got it"
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

while如果文件已被添加/更改,我在哪里添加“得到它” - 在循环中?

4

3 回答 3

119

而不是LoggingEventHandler定义您的处理程序:

#!/usr/bin/python
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler


class MyHandler(FileSystemEventHandler):
    def on_modified(self, event):
        print(f'event type: {event.event_type}  path : {event.src_path}')


if __name__ == "__main__":
    event_handler = MyHandler()
    observer = Observer()
    observer.schedule(event_handler, path='/data/', recursive=False)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

on_modified当文件或目录被修改时调用。

于 2013-09-03T18:48:40.877 回答
10

这是一个片段,以防止它运行两次,因为其他人在@alecxe 答案中发表了评论:

from datetime import datetime, timedelta

class MyHandler(FileSystemEventHandler):
    def __init__(self):
        self.last_modified = datetime.now()

    def on_modified(self, event):
        if datetime.now() - self.last_modified < timedelta(seconds=1):
            return
        else:
            self.last_modified = datetime.now()
        print(f'Event type: {event.event_type}  path : {event.src_path}')
        print(event.is_directory) # This attribute is also available
于 2019-07-26T13:36:16.583 回答
0

您可以使用 src_path 检查逻辑而不是日期时间,因为如果检查超过 1 秒的日期时间逻辑之后的逻辑将失败。

class EventHandler(FileSystemEventHandler):
    def __init__(self):
        self.src_path = ''

    def on_modified(self, event):
        if self.src_path == event.src_path:
            return
        else:
            self.src_path = event.src_path
        logger.info(f"{event.event_type} occured on file {self.src_path}")
        #your long processing logics goes here.
于 2021-02-05T16:17:39.523 回答