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

如何不使用logging模块使用Python watchdog?求触发程序动作的示例

使用Python Watchdog不依赖logging模块的实现方案

Absolutely! You don’t need to tie Watchdog to the logging module at all — the official docs use logging just for demonstration purposes to show what’s happening under the hood. The core functionality of Watchdog works completely independently of logging, and you can easily hook up custom actions to file system events instead.

Let me walk you through a practical example that skips logging entirely and triggers your own program logic when events occur:

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class CustomFileHandler(FileSystemEventHandler):
    # 处理文件/文件夹创建事件
    def on_created(self, event):
        if not event.is_directory:
            print(f"Detected new file: {event.src_path}")
            # 在这里触发你的自定义动作,比如调用外部程序、更新数据等
            self.trigger_processing(event.src_path)
    
    # 处理文件修改事件
    def on_modified(self, event):
        if not event.is_directory:
            print(f"File updated: {event.src_path}")
            # 执行另一个自定义业务逻辑
            self.sync_to_remote(event.src_path)
    
    # 自定义动作1:模拟文件处理流程
    def trigger_processing(self, file_path):
        print(f"Starting processing for {file_path}...")
        # 替换成你的实际代码:比如调用脚本、解析文件内容、写入数据库等
        # example: subprocess.run(["python", "my_processor.py", file_path])
    
    # 自定义动作2:模拟同步到远程服务
    def sync_to_remote(self, file_path):
        print(f"Initiating sync of {file_path} to remote server...")
        # 替换成你的同步逻辑:比如调用API、FTP上传等

if __name__ == "__main__":
    # 设置要监控的目录
    target_directory = "./my-watched-folder"
    
    # 初始化自定义处理器和观察者
    event_handler = CustomFileHandler()
    observer = Observer()
    observer.schedule(event_handler, target_directory, recursive=True)
    
    # 启动监控
    observer.start()
    print(f"Now monitoring directory: {target_directory}")
    
    # 保持程序运行,直到按下Ctrl+C
    try:
        while True:
            pass
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

关键说明:

  • Watchdog的核心组件(Observer和FileSystemEventHandler)没有硬依赖logging模块,官方示例用logging只是为了直观展示事件发生情况。
  • 你只需要继承FileSystemEventHandler,重写对应事件的方法(比如on_created、on_modified、on_deleted等),在方法内部直接执行你需要的动作即可。
  • 示例中的trigger_processing和sync_to_remote只是占位,你可以替换成任何业务逻辑:调用外部脚本、发送通知、更新缓存、触发ETL流程等等。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:03:28