如何监听Python源码文件并在保存时重启?有无类似nodemon的命令?
当然有!Python生态里有不少类似Node.js中nodemon的工具,能帮你监听源码文件变化、保存后自动重启脚本,下面给你几种实用的方案,都是我平时开发里常用的:
1. 直接用
nodemon(没错,它支持Python!) 很多人不知道,nodemon不仅能管Node.js脚本,也能轻松适配Python。步骤很简单:
- 首先确保你已经安装了Node.js/npm,然后全局安装nodemon:
npm install -g nodemon - 然后直接用它来运行你的Python脚本:
nodemon --exec python3 your_script.py - 如果想监听特定文件类型(比如只监听
.py文件),可以加参数:nodemon --ext py --exec python3 your_script.py - 还可以创建
nodemon.json配置文件,自定义监听规则、忽略目录等,比如:
之后直接运行{ "watch": ["src/"], "ext": "py", "exec": "python3 src/main.py" }nodemon就会读取这个配置。
2. Python专属工具:
watchdog + watchmedo watchdog是Python生态里专门处理文件系统事件的库,它附带的watchmedo命令行工具可以直接实现自动重启:
- 先安装watchdog:
pip install watchdog - 然后用watchmedo监听文件并重启脚本:
这个命令会监听当前目录下所有watchmedo auto-restart --directory ./ --pattern "*.py" --command "python3 your_script.py".py文件,一旦有修改就重启指定脚本。
3. 轻量自制脚本(无额外依赖)
如果不想装任何第三方工具,也可以自己写个简单的监听脚本,核心思路是定期检查文件的修改时间,变化就重启进程:
import os import time import subprocess from sys import argv def main(): script_path = argv[1] last_modified = os.path.getmtime(script_path) process = subprocess.Popen(["python3", script_path]) while True: time.sleep(1) current_modified = os.path.getmtime(script_path) if current_modified != last_modified: last_modified = current_modified process.terminate() process.wait() process = subprocess.Popen(["python3", script_path]) print("Script restarted due to file change!") if __name__ == "__main__": if len(argv) != 2: print("Usage: python watcher.py your_script.py") exit(1) main()
把这个脚本存为watcher.py,然后运行:
python watcher.py your_script.py
就能实现基本的监听重启功能了,要是需要监听目录可以结合os.walk扩展一下。
4. 其他可选工具
还有一些其他工具也能实现类似功能,比如:
watchgod:一个更简洁的文件监听库,CLI用法也很简单:pip install watchgod,然后watchgod python3 your_script.pyentr:这是一个跨平台的命令行工具,不是Python专属,但也能配合Python用:比如ls *.py | entr -r python3 your_script.py
根据自己的需求选就行,我个人平时用nodemon或者watchmedo比较多,足够应付大部分场景了。
内容的提问来源于stack exchange,提问作者bkinsey808
相关产品推荐
相关产品推荐

