python watchdog如何监视文件的变化?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (521)

在查看了堆栈溢出问题之后,我看到人们推荐“watchdag”。因此,我正在尝试测试,并且不确定在文件更改时在哪里添加代码:

#!/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循环中将“get it”添加到哪里?

提问于
用户回答回答于

试一下:

#!/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在修改文件或目录时调用。

扫码关注云+社区

领取腾讯云代金券