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

Python如何无需无限循环即可在文件变更时触发对应处理函数

解决方案

你需要的是操作系统级的文件系统事件监听机制,替代无限轮询。这种机制由内核在文件发生写入、修改等操作时主动向应用推送通知,全程不需要应用主动循环检查,CPU占用极低,完全匹配你要的类似PUSH通知的效果。

推荐实现方案(跨平台,无需手动处理系统差异)

用Python通用的文件系统监控库watchdog实现,步骤如下:

  • 第一步安装依赖:pip install watchdog
  • 第二步适配需求的实现代码:
import os
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

# 替换为你的目标文件实际路径
TARGET_FILE = "/path/to/your/target.txt"

def functionInative():
    # 此处写入你原本的业务处理逻辑
    print("文件大小符合要求,触发处理函数")
    # 处理完成后清空文件,等待下一次写入
    with open(TARGET_FILE, 'w', encoding='utf-8') as f:
        f.truncate(0)

class FileChangeHandler(FileSystemEventHandler):
    def on_modified(self, event):
        # 仅处理目标文件的修改事件,忽略目录变更
        if not event.is_directory and os.path.abspath(event.src_path) == os.path.abspath(TARGET_FILE):
            file_size = os.stat(TARGET_FILE).st_size
            # 满足≥1KB(1024字节)条件时触发处理
            if file_size >= 1024:
                functionInative()

if __name__ == "__main__":
    event_handler = FileChangeHandler()
    observer = Observer()
    # 监控目标文件所在的目录
    observer.schedule(event_handler, path=os.path.dirname(os.path.abspath(TARGET_FILE)), recursive=False)
    observer.start()
    print("文件监控已启动,等待写入触发...")
    try:
        # 此处仅用于阻塞主进程不退出,sleep的CPU消耗可忽略,无主动轮询逻辑
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

无第三方依赖的原生方案(仅Linux适用)

如果不想安装第三方库,Linux环境下可以直接通过标准库fcntl调用inotify系统接口实现,但跨平台兼容性差,更推荐上述watchdog方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 04:06:01