python watchdog monitoring file for changes

 ̄綄美尐妖づ 提交于 2019-12-28 07:39:27

问题


Folks, I have a need to watch a log file for changes. After looking through stackoverflow questions, I see people recommending 'watchdog'. So i'm trying to test, and am not sure where to add the code for when files change:

#!/usr/bin/python
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()

Where do I add the "got it", in the while loop if the files have been added/changed?


回答1:


Instead of LoggingEventHandler define your handler:

#!/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 is called when a file or directory is modified.




回答2:


Here's a snippet to prevent it running twice as others have commented in @alecxe answer:

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


来源:https://stackoverflow.com/questions/18599339/python-watchdog-monitoring-file-for-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!