You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu EC2挂载EFS后,Watchdog无法检测mv命令移动的.txt文件

问题:Watchdog监控EFS文件夹时mv命令移动文件无法触发事件

在AWS EC2的Ubuntu实例上,使用Watchdog监控挂载的EFS文件夹,需处理新建的.txt文件。当前异常:手动拖拽.txt文件可被正常检测,但执行mv命令移动文件时,on_created和on_moved事件均无法触发。

现有代码片段:

class FileCreationEventHandler(FileSystemEventHandler):
    def on_created(self, event):
        cron = CronTab(user='ubuntu')
        file_name = event.src_path.split('/')[-1]
        if file_name.endswith(".txt") and not file_name.startswith('temp_file'):
            time.sleep(2)
            print(event.src_path)
            input_file = open(event.src_path, "r")

解决思路及方案

1. 补全on_moved事件处理

mv操作本质触发的是移动事件而非创建事件,当前代码仅实现了on_created,需添加on_moved逻辑:

class FileCreationEventHandler(FileSystemEventHandler):
    def on_created(self, event):
        cron = CronTab(user='ubuntu')
        file_name = event.src_path.split('/')[-1]
        if file_name.endswith(".txt") and not file_name.startswith('temp_file'):
            time.sleep(3)  # 延长等待时间适配EFS元数据延迟
            print(f"Created file: {event.src_path}")
            with open(event.src_path, "r") as input_file:
                # 这里添加文件处理逻辑
                pass

    def on_moved(self, event):
        # 检查移动后的目标文件是否符合规则
        file_name = event.dest_path.split('/')[-1]
        if file_name.endswith(".txt") and not file_name.startswith('temp_file'):
            time.sleep(3)
            print(f"Moved file: {event.dest_path}")
            with open(event.dest_path, "r") as input_file:
                # 这里添加文件处理逻辑
                pass

2. 改用PollingObserver适配EFS文件系统

EFS是网络文件系统,默认的inotify机制可能无法高效捕获事件,改用轮询模式的PollingObserver更可靠:

from watchdog.observers.polling import PollingObserver

# 替换原Observer初始化代码
event_handler = FileCreationEventHandler()
observer = PollingObserver()
# 替换为你的EFS挂载路径
observer.schedule(event_handler, path='/mnt/efs', recursive=True)
observer.start()

3. 调整元数据等待时长

EFS的元数据同步存在网络延迟,原time.sleep(2)可能不足以让文件状态稳定,可调整为3-5秒,避免因文件未完全同步导致读取失败或事件未触发。

4. 权限验证

确保运行Watchdog的ubuntu用户对EFS挂载目录拥有读写权限,可通过sudo chown -R ubuntu:ubuntu /mnt/efs(替换为你的挂载路径)调整权限。

内容的提问来源于stack exchange,提问作者suki_1216

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 11:42:43