PyCharm 内的 Git Hooks 在不正确的环境中运行

问题描述 投票:0回答:6

我最近在 PyCharm 中启动了一个新项目,最终利用了 anaconda 环境。然而,在尝试通过 PyCharm 进行第一次提交后,它似乎使用的是我的本机 python,而不是 PyCharm 中设置的环境。我尝试过多次重启PyCharm,重启电脑,并重新安装虚拟环境。

这是预提交挂钩的副本:

set -e

# Run linters and tests
source scripts/lint.sh

linter 如下:(已添加

which python
以突出显示该问题)

set -e
set -v

which python

flake8 ~project name~
mypy ~project name~
pytest -x
black --check --fast --quiet ~project name~

set +v

我正在通过 PyCharm -> VCS -> Commit 运行提交。在 PyCharm 内部,提交失败

enter image description here (下面这是大量的mypy错误,但要注意环境)

但是,如果我使用

$ git commit -m "testing commit"
从终端运行提交,则提交有效。它提供以下响应:

enter image description here

这是项目内部正确的虚拟环境,如下所示: enter image description here

我是否设置不正确?我非常喜欢 PyCharm 的 VCS,并且不想从终端使用 git。

python git pycharm anaconda
6个回答
7
投票

PyCharm 不会在虚拟环境下运行 git hooks。错误跟踪器中的相关票证:https://youtrack.jetbrains.com/issue/PY-12988


3
投票

这对我有用。

我收到以下错误:

18:37   Commit failed with error
            0 file committed, 1 file failed to commit: Update pre-commit hooks
            env: python3.7: No such file or directory

当我导航到项目仓库中的

.git/hooks/pre-commit
时,结果发现 shebang 行是
#!/usr/bin/env python3.7

这是一个问题,因为在我的 MacOS 上调用 python3.7 最终会得到以下结果:

zsh: command not found: python3.7

我可以添加全局 python3.7,或者更新 shebang。我选择了后一种并将 shebang 行更改为:

#!/usr/bin/env python3

这解决了我的问题。


1
投票

前面提到的 PyCharm 问题似乎不会很快得到修复(自 2014 年以来一直存在)。

下面的这个技巧对我有用; 我将其添加到 PyCharm 票证中

这是一个对我来说有点烦人的解决方法:

  1. 关闭 PyCharm。
  2. cd /your/project/dir
  3. 从命令行打开 PyCharm:
    PYENV_VERSION="$(pyenv local | head -1)" open /Applications/PyCharm.app/
    。 我用的是macOS,你用的是 应根据您的操作系统调整
    open
    命令。

我每次切换项目都必须这样做,否则

pylint
预提交挂钩不起作用。如果你有一个 为您的项目提供类似的配置(Python 版本并且不使用 PyLint),只需从 CLI 运行一次 PyCharm 即可。


0
投票

您可以手动编辑自动生成的预提交文件(位于项目目录中的

.git/hooks/pre-commit
)以添加虚拟环境的路径,替换:

# start templated
INSTALL_PYTHON = 'PATH/TO/YOUR/ENV/EXECUTABLE'

# start templated
INSTALL_PYTHON = 'PATH/TO/YOUR/ENV/EXECUTABLE'
os.environ['PATH'] = f'{os.path.dirname(INSTALL_PYTHON)}{os.pathsep}{os.environ["PATH"]}'

0
投票

以上解决方案都不适合我:

PyCharm 2020.3
on
Windows 10

我所做的是重命名

.git\hooks\pre-commit
->
.git\hooks\pre-commit.py

并创建了一个新的

.git\hooks\pre-commit
,其中包含以下内容:

#!/bin/bash

BASEDIR=$(dirname "$0")
/c/<PATH-to-YOUR-Python>/python.exe $BASEDIR/pre-commit.py $@

发挥了魅力!


0
投票

PyCharm 现在支持通过将 python 解释器指向您想要使用的任何本地 venv 来运行 git hook。请参阅此处的更新:https://youtrack.jetbrains.com/issue/PY-12988/Pycharm-does-not-use-virtualenv-pep8-for-git-hooks#focus=Comments-27-4796459.0-0

以下是我确认 PyCharm 使用正确的 venv 并启用 git hook 所遵循的步骤。

  • 转到“设置”>“项目”>“Python 解释器”>
  • 单击“添加口译员”链接,打开一个下拉列表。
  • 选择添加本地口译员
  • 选择现有单选按钮
  • 单击三点按钮打开文件对话框。
  • 选择您的 venv 文件夹,然后单击“确定”

最后,确认您的 venv 中的 git hook 已启用。

  • 转到设置 > 版本控制 > Git
  • 一直滚动到 Git 设置的底部(从 Pycharm v 2024.1 开始)
  • 确认选中“Activate virtualenv for hooks”。
  • 单击“确定”保存并关闭设置。

在 PyCharm 的右下角,您应该看到 Python 解释器设置为 .venv 使用的 Python 版本,后跟保存 .venv 目录的目录名称。

现在 Python 解释器已设置为本地 venv,您将能够将 PyCharm Git 与您定义的 git 挂钩一起使用。

© www.soinside.com 2019 - 2024. All rights reserved.