问题

在使用pip从源码安装python包时出现ModuleNotFoundError错误,细节如下:

$ pip install 'git+https://github.com/facebookresearch/pytorch3d.git@stable'

[stderr]
Traceback (most recent call last):
  File "<string>", line 14, in <module>
  File "/home/xx/.cache/uv/builds-v0/.tmpYL7BL9/lib/python3.9/site-packages/setuptools/build_meta.py", line 327, in get_requires_for_build_wheel
    return self._get_build_requires(config_settings, requirements=[])
  File "/home/xx/.cache/uv/builds-v0/.tmpYL7BL9/lib/python3.9/site-packages/setuptools/build_meta.py", line 297, in _get_build_requires
    self.run_setup()
  File "/home/xx/.cache/uv/builds-v0/.tmpYL7BL9/lib/python3.9/site-packages/setuptools/build_meta.py", line 497, in run_setup
    super().run_setup(setup_script=setup_script)
  File "/home/xx/.cache/uv/builds-v0/.tmpYL7BL9/lib/python3.9/site-packages/setuptools/build_meta.py", line 313, in run_setup
    exec(code, locals())
  File "<string>", line 15, in <module>
ModuleNotFoundError: No module named 'torch'

提示没有找到torch包,但是确实已经安装了torch依赖。

解决方案

问题的根本原因是:在构建过程中创建了一个干净的虚拟环境,该环境不会继承你当前环境中的已安装依赖(如 torch)。这是为了确保包安装过程的干净性,但也导致了缺失依赖的错误。如果构建过程依赖于 torch,但是临时环境中没有 torch,就会出现 ModuleNotFoundError 错误。

最直接的解决方案是使用 --no-build-isolation 参数,这将禁用构建过程中的虚拟环境隔离,使得构建过程能够访问当前环境中的依赖。

$ pip install 'git+https://github.com/facebookresearch/pytorch3d.git@stable' --no-build-isolation

转载时请包括本文地址:https://dw-dengwei.cn/posts/ModuleNotFoundError