Python利用watchdog监控目录文件创建

需求是要实现自动监控上传目录,一旦有指定格式的文件传完,就调用其他进程处理这个文件。这里不能采取遍历目录的方式,因为会获取到没有上传完毕的文件。因为获取文件名与写文件不是互斥操作,没有原子性。这当然可以通过先传后改后缀名的方式避免获取到未传完的文件(因为mv操作是原子操作)。

不过python有个好用的库叫watchdog可以做到文件系统事件监听:

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

class EmlHandler(FileSystemEventHandler):
    def on_created(self, event):
        if event.src_path.endswith(".eml"):
            print(event.src_path)
          # process_it(event.src_path)

def start_monitoring(path_to_watch):
    event_handler = EmlHandler()
    observer = Observer()
    observer.schedule(event_handler, path=path_to_watch, recursive=False)
    observer.start()  # 启动观察者线程
    try:
        print(f"开始监控目录: {path_to_watch}")
        while True:  # 主线程保持运行
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

if __name__ == "__main__":
    start_monitoring("./data")  # 修改为实际监控目录

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注