python watchdog monitoring file for changes
伙计们,我需要查看一个日志文件以了解更改。在研究了stackoverflow问题之后,我看到有人推荐"看门狗"。因此,我正在尝试测试,不确定在文件更改时在何处添加代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | #!/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() |
如果文件已经添加/更改,在while循环中,我应该在哪里添加"got it"?
而不是
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #!/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() |
修改文件或目录时调用