python 用watchdog observer监听多个文件夹
时间: 2023-09-20 22:05:56 浏览: 197
python中watchdog文件监控与检测上传功能
5星 · 资源好评率100%
可以使用watchdog的多个observer实例来监听多个文件夹。下面是一个示例代码:
```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__":
path1 = '/path/to/folder1'
path2 = '/path/to/folder2'
event_handler = MyHandler()
observer1 = Observer()
observer2 = Observer()
observer1.schedule(event_handler, path1, recursive=True)
observer2.schedule(event_handler, path2, recursive=True)
observer1.start()
observer2.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer1.stop()
observer2.stop()
observer1.join()
observer2.join()
```
这个示例代码使用了两个observer实例,分别监听了`/path/to/folder1`和`/path/to/folder2`两个文件夹。当文件夹中的文件被修改时,会调用`MyHandler`类的`on_modified`方法。
阅读全文