当前位置:首页>python>最新神器:Rust+Python 的高性能文件热重载 watchfiles

最新神器:Rust+Python 的高性能文件热重载 watchfiles

  • 2026-09-08 09:34:38
最新神器:Rust+Python 的高性能文件热重载 watchfiles

看见文件变动,就自动重启?你是不是还在不停地按 Ctrl+C 、然后重启脚本?或者修改了一个小细节,等半天才生效?别慌,watchfiles 来拯救你。它是一款简单、现代、高性能的 Python 文件监控和代码热重载工具(前身是 watchgod),底层用 Rust 写的 Notify 库,跨平台、响应迅速,让你专注写代码,不用管手动重启,省时又省心。

它能帮你解决什么痛点?

  • • 开发迭代太慢:每次改完都重启,像走了回头路。
  • • 脚本自动化:想监控某个目录,一有变化就跑一段逻辑?老版本靠 while 循环自己写,复杂又难维护。
  • • 跨平台兼容:Linux、macOS、Windows,都能无感切换。

安装超简单,三步搞定只要你装了 Python 3.9–3.14,就能用:

pip install watchfiles

如果想用二进制版本(大多数架构都支持),直接跑上面命令也行;要是你偏爱「从源码编译」的成就感,先装好 Rust,然后:

git clone https://github.com/samuelcolvin/watchfilescd watchfilespip install .

搞定!

怎么玩转 watchfiles (示例代码)

  • • 同步监控(watch)
    from watchfiles import watchfor changes in watch('./path/to/dir'):print('文件变动啦:', changes)
    只要目录里有新改动,changes 就是一个集合,告诉你哪些文件增删改。
  • • 异步监控(awatch)
    import asynciofrom watchfiles import awatchasyncdefmain():asyncfor changes in awatch('src'):print('Async 改动:', changes)asyncio.run(main())
    配合异步框架也没问题,超轻量、不卡壳。
  • • 自动重启进程(run_process)
    from watchfiles import run_processdefmy_app():print('执行业务逻辑…')if __name__ =='__main__':    run_process('src', target=my_app)
    代码有变动,底层自动 kill + 重启,开发效率直接翻倍。
  • • 异步自动重启(arun_process)
    import asynciofrom watchfiles import arun_processasyncdefasync_app():print('Async 业务跑起来!')if __name__ =='__main__':    asyncio.run(arun_process('src', target=async_app))
  • • CLI 小贴士
    watchfiles "python main.py" src
    监控 src,一改保存就重新执行 python main.py,立刻反馈。

工具对比:watchfiles vs 其他方案

工具
语言支持
性能
依赖
特点
watchfiles
Python 3.9+
⭐⭐⭐⭐⭐ (Rust)
Notify(Rust)
轻量、零配置、高性能
watchdog
Python 3.6+
⭐⭐⭐
pure Python
支持多种后端,但性能一般
watchgod
Python 3.6+
⭐⭐⭐⭐
pure Python
watchfiles
 前身,简单好用
entr
Shell 脚本
⭐⭐⭐⭐
C 库
适合 Unix,无法直接 Python API

优缺点小结

  • • 优点
    • • 性能超群:Rust 底层,延迟低、资源占用少。
    • • API 丰富:同步/异步/进程重启/CLI,全家桶式体验。
    • • 跨平台:Linux/Mac/Win 都支持,二进制免编译。
  • • 缺点
    • • Python 版本限制:3.9 以上才能用。
    • • 对 Rust 不熟的同学,从源码安装有点小门槛。
    • • 功能专注:不支持高级过滤/插件扩展(但够用)。

结语:为什么选 watchfiles?简单来说,如果你是个追求「代码改完就立刻看到效果」的开发者,watchfiles 就像你的贴身管家:既高效又省心。无论是搞小脚本,还是大型项目热加载,都能稳、快、准。不用再手动重启,专注业务逻辑,释放你的开发效率。快去试试吧!

项目地址:https://github.com/samuelcolvin/watchfiles

最新文章

随机文章