使用watchdog与rsync迁移文件时同步多余目录的问题
问题分析与解决:Watchdog监控下Rsync同步空目录的问题
问题描述
我使用watchdog监控文件,通过rsync将文件从源目录迁移至目标目录/home/pi/Desktop/destination,重写了on_modified方法,每次传入单个源文件(如/home/pi/Desktop/source/one.txt等)。执行的rsync命令参数为['rsync','-hav','/home/pi/Desktop/source/one.txt','/home/pi/Desktop/destination','--remove-source-files'],所有文件均已成功迁移,但最后会同步空的源目录,而源目录从未通过touch更新时间,请问哪里操作有误?
核心原因
问题出在watchdog的事件触发逻辑和rsync的目录处理行为的叠加:
- 当
rsync --remove-source-files删除源文件后,源目录的元数据(比如目录的修改时间mtime)会自动更新——因为目录下的文件列表发生了变化,这会触发watchdog的on_modified事件。 - 你的
on_modified方法没有做文件类型判断,当事件触发的对象是源目录本身时,执行rsync命令会把空目录同步到目标路径。
解决方案
1. 在on_modified中过滤目录,只处理文件
修改事件处理方法,先判断触发事件的路径是否为文件,仅对文件执行rsync操作:
from watchdog.events import FileSystemEventHandler import os import subprocess class MyHandler(FileSystemEventHandler): def on_modified(self, event): # 跳过目录事件,只处理文件 if event.is_directory: return # 执行rsync迁移文件 source_file = event.src_path dest_dir = "/home/pi/Desktop/destination" rsync_cmd = [ 'rsync', '-hav', source_file, dest_dir, '--remove-source-files' ] subprocess.run(rsync_cmd, check=True)
2. 给rsync加参数,禁止同步空目录
如果想从命令层面避免误同步目录,添加--no-dirs参数,强制rsync只处理文件,即使传入目录也不会创建空目录:
rsync -hav --no-dirs /home/pi/Desktop/source/one.txt /home/pi/Desktop/destination --remove-source-files
3. 改用on_created事件(更适合新文件迁移场景)
如果你的需求是监控新创建的文件并迁移,on_created事件比on_modified更精准,能避免因目录元数据变化触发的误操作:
class MyHandler(FileSystemEventHandler): def on_created(self, event): if event.is_directory: return source_file = event.src_path dest_dir = "/home/pi/Desktop/destination" rsync_cmd = [ 'rsync', '-hav', source_file, dest_dir, '--remove-source-files' ] subprocess.run(rsync_cmd, check=True)
内容的提问来源于stack exchange,提问作者newdeveloper
相关产品推荐
相关产品推荐

