【问题标题】:pre-commit isort no module named 'setuptools'预提交没有名为“setuptools”的模块
【发布时间】:2022-01-10 09:19:08
【问题描述】:

我正在尝试运行 pre-commit 钩子,但是当它们遇到抛出以下错误的 isort 钩子时它们会失败:

  File "/home/el/.cache/pre-commit/repoffrjhcx0/py_env-python3/lib/python3.10/site-packages/_distutils_hack/__init__.py", line 92, in create_module
    return importlib.import_module('setuptools._distutils')
  File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named 'setuptools'

我正在使用 docker,并且我已经检查了 setuptools 是否已安装在我的全局机器上和我的 docker 上。我不明白为什么会发生此错误。我认为 isort 设置了它自己的环境,但是为什么不安装它,因为它是在他们的配置文件 pyproject.toml 中定义的。

以下是我的 pre-commit 和 isort 配置:

.pre-commit-config.yaml

repos:
- repo: https://github.com/pycqa/isort
  rev: 5.8.0
  hooks:
    - id: isort
      args: ["--multi-line=5", "--line-length=120", "--use-parentheses", "--filter-files"]
      exclude: "migrations"
      stages: [commit]

tox.ini

[isort]
line_length=120
skip_glob=*migrations*
multi_line_output=5
sections=FUTURE,STDLIB,THIRDPARTY,FIRSTPARTY,LOCALFOLDER
use_parentheses=true
include_trailing_comma=true
lines_between_types=1
lines_after_imports=2
[testenv:isort]
deps =
    isort
commands =
    isort . --check-only --diff

系统上的 Python 版本:3.10.1

docker 上的 Python 版本:3.8

感谢您的帮助!

【问题讨论】:

  • pypi.org/project/setuptools这对你有帮助吗?
  • @VincentBénet 感谢您的回复。 setuptools 安装在系统范围和 docker 上,但 precommit isort 由于某种原因无法看到。

标签: python pre-commit-hook pre-commit pre-commit.com isort


【解决方案1】:

这是a bug in setuptools,已修复(另见the pinned issue on isort

您可以通过设置以下环境变量来解决此错误:SETUPTOOLS_USE_DISTUTILS=stdlib

setuptools 的版本来自您正在使用的virtualenv 的版本,因此您可能需要升级以获得正确的版本

这里有一个更长的summary of what went wrong with setuptools

以下是需要跟进的相关事项:

为什么我们会突然看到这个:

  • 最新的 virtualenv 版本将 setuptools 升级到 60.1.0(尽管 changelog saysupgraded to 60.1.0 here)
  • setuptools 60.* 将默认设置更改为使用 setuptools-embedded distutils 而不是 stdlib distutils
  • setuptools 通过一个.pth 文件来执行此操作,该文件将distutils 的导入重定向到setuptools._distutils
  • 在 pip 的隔离构建期间(由pyproject.toml 触发,例如通过poetry 安装isort)pip 尝试清除 当前sys.path 的封闭环境并隔离到 pyproject.toml-installed 构建依赖,但是有点晚了 因为应用了封闭环境中的.pth 文件。所以在 这个环境setuptools没有安装,但是它的导入钩子 是

免责声明:我创建了预提交

【讨论】:

  • 这是一个如此详细的答案。我真的很感谢你的帮助!预提交也很棒!谢谢
猜你喜欢
  • 2020-02-24
  • 2014-04-27
  • 2017-11-12
  • 2022-11-10
  • 1970-01-01
  • 2013-01-03
  • 1970-01-01
  • 2018-07-12
  • 2018-07-13
相关资源
最近更新 更多