pre-commit报错找不到python3.10解释器,虚拟环境路径存疑
问题背景
在已开发数周的项目中首次使用pre-commit,配置好.pre-commit-config.yaml后运行时出现虚拟环境创建失败的错误。
配置文件内容
--- # See https://pre-commit.com for more information # See https://pre-commit.com/hooks.html for more hooks repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.5.0 hooks: - id: check-json - id: check-merge-conflict - id: end-of-file-fixer - id: check-yaml - id: trailing-whitespace - repo: https://github.com/ambv/black rev: 23.11.0 hooks: - id: black language_version: python3.10 - repo: https://github.com/astral-sh/ruff-pre-commit # Ruff version. rev: v0.1.6 hooks: # Run the linter. - id: ruff # Run the formatter. - id: ruff-format - repo: https://github.com/igorshubovych/markdownlint-cli rev: v0.37.0 hooks: - id: markdownlint args: ["--config", ".github/linters/.markdownlint.json"] - repo: https://github.com/pre-commit/mirrors-mypy rev: v1.7.0 hooks: - id: mypy name: mypy tests files: ^tests/
报错信息
[INFO] Installing environment for https://github.com/ambv/black.
[INFO] Once installed this environment will be reused.
[INFO] This may take a few minutes...
An unexpected error has occurred: CalledProcessError: command: ('/usr/local/Cellar/pre-commit/3.4.0/libexec/bin/python', '-mvirtualenv', '/Users/redacted/.cache/pre-commit/repoljj12k4y/py_env-python3.10', '-p', 'python3.10')
return code: 1
stdout:
RuntimeError: failed to find interpreter for Builtin discover of python_spec='python3.10'
stderr: (none)
Check the log at /Users/jamiethomson/.cache/pre-commit/pre-commit.log
尝试查看目标路径时发现目录不存在:
ls /Users/redacted/.cache/pre-commit/repoljj12k4y/py_env-python3.10 "/Users/redacted/.cache/pre-commit/repoljj12k4y/py_env-python3.10": No such file or directory (os error 2)
环境说明
- Mac系统
- 使用pyenv管理Python版本
为什么pre-commit选择该路径创建虚拟环境?
pre-commit为了隔离各个钩子的依赖环境,会在用户目录的~/.cache/pre-commit/下为每个钩子仓库创建独立的缓存目录(比如repoljj12k4y是随机生成的仓库标识),并针对指定的Python版本创建专属虚拟环境。这种设计的目的是避免不同钩子的依赖包互相冲突,同时缓存环境后可以重复使用,减少后续运行的初始化时间。你看到目录不存在是因为虚拟环境创建失败,并非pre-commit没有尝试创建。
解决报错的步骤
1. 确认pyenv中已安装Python 3.10
运行以下命令查看已安装的Python版本:
pyenv versions
如果列表中没有3.10系列版本,执行安装命令:
pyenv install 3.10.13 # 可替换为最新的3.10.x版本
安装完成后,在项目目录下设置局部Python版本:
pyenv local 3.10.13
2. 确保pyenv的shim路径在系统PATH最前端
pre-commit需要找到pyenv管理的Python解释器,因此要保证~/.pyenv/shims在系统PATH的最前面。检查当前PATH:
echo $PATH
如果~/.pyenv/shims不在首位,编辑你的shell配置文件(.zshrc或.bashrc),添加以下内容:
export PATH="$HOME/.pyenv/shims:$PATH" eval "$(pyenv init -)"
保存后重启shell,或者执行以下命令使配置生效:
source ~/.zshrc # 对应你的shell配置文件
3. 清理pre-commit缓存并重新运行
删除已有的缓存目录,避免残留的错误环境影响:
pre-commit clean
然后重新运行pre-commit:
pre-commit run --all-files
4. 调整black钩子的Python版本配置(可选)
如果不需要强制指定Python 3.10,可以删除black钩子中的language_version: python3.10配置,让pre-commit使用当前环境的Python版本;或者改为pyenv中已安装的具体版本号,比如python3.10.13。
内容的提问来源于stack exchange,提问作者jamiet

