基于pyinotify/Bash实现目录新增子目录时自动执行带参命令
目录新增子目录自动触发命令的监控脚本
Python 实现方案
依赖第三方库watchdog实现文件系统监控,步骤如下:
- 安装依赖
pip install watchdog
- 编写监控脚本
import os import subprocess from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler # 配置参数 MONITOR_DIR = "/home/tmp/" # 替换为你要监控的目录 TARGET_COMMAND = "my_command --target_dir {}" # 替换为你的目标命令,{}会被子目录路径替换 class DirMonitorHandler(FileSystemEventHandler): def on_created(self, event): # 仅处理新增的目录,排除文件 if event.is_directory and not event.src_path == MONITOR_DIR: # 执行目标命令 cmd = TARGET_COMMAND.format(event.src_path) print(f"执行命令: {cmd}") subprocess.run(cmd, shell=True, check=True) if __name__ == "__main__": event_handler = DirMonitorHandler() observer = Observer() observer.schedule(event_handler, MONITOR_DIR, recursive=False) # 仅监控当前目录,不深入子目录 observer.start() print(f"开始监控目录: {MONITOR_DIR}") try: while True: pass except KeyboardInterrupt: observer.stop() observer.join()
Bash 实现方案
利用Linux系统的inotifywait工具(需先安装inotify-tools包),编写循环监控脚本:
- 安装依赖
# Debian/Ubuntu 系列 sudo apt-get install inotify-tools # RHEL/CentOS 系列 sudo yum install inotify-tools
- 编写监控脚本
#!/bin/bash # 配置参数 MONITOR_DIR="/home/tmp/" # 替换为你要监控的目录 TARGET_COMMAND="my_command --target_dir {}" # 替换为你的目标命令,{}会被子目录路径替换 # 循环监控目录的create事件 inotifywait -m -e create --format '%w%f' "$MONITOR_DIR" | while read NEW_ITEM do # 判断新增的是否是目录 if [ -d "$NEW_ITEM" ]; then # 替换命令中的占位符并执行 CMD=$(printf "$TARGET_COMMAND" "$NEW_ITEM") echo "执行命令: $CMD" $CMD fi done
- 赋予脚本执行权限并运行
chmod +x monitor_dir.sh ./monitor_dir.sh
内容的提问来源于stack exchange,提问作者Sala
相关产品推荐
相关产品推荐

