我最近在 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 内部,提交失败
但是,如果我使用
$ git commit -m "testing commit"
从终端运行提交,则提交有效。它提供以下响应:
我是否设置不正确?我非常喜欢 PyCharm 的 VCS,并且不想从终端使用 git。
PyCharm 不会在虚拟环境下运行 git hooks。错误跟踪器中的相关票证:https://youtrack.jetbrains.com/issue/PY-12988
这对我有用。
我收到以下错误:
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
这解决了我的问题。
前面提到的 PyCharm 问题似乎不会很快得到修复(自 2014 年以来一直存在)。
下面的这个技巧对我有用; 我将其添加到 PyCharm 票证中:
这是一个对我来说有点烦人的解决方法:
- 关闭 PyCharm。
cd /your/project/dir
- 从命令行打开 PyCharm:
。 我用的是macOS,你用的是 应根据您的操作系统调整PYENV_VERSION="$(pyenv local | head -1)" open /Applications/PyCharm.app/
命令。open
我每次切换项目都必须这样做,否则
预提交挂钩不起作用。如果你有一个 为您的项目提供类似的配置(Python 版本并且不使用 PyLint),只需从 CLI 运行一次 PyCharm 即可。pylint
您可以手动编辑自动生成的预提交文件(位于项目目录中的
.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"]}'
以上解决方案都不适合我:
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 $@
发挥了魅力!
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 所遵循的步骤。
最后,确认您的 venv 中的 git hook 已启用。
在 PyCharm 的右下角,您应该看到 Python 解释器设置为 .venv 使用的 Python 版本,后跟保存 .venv 目录的目录名称。
现在 Python 解释器已设置为本地 venv,您将能够将 PyCharm Git 与您定义的 git 挂钩一起使用。