在setup.py中使用非默认包:pip install安装失败问题求助
解决pip install时setup.py依赖第三方库导致的ModuleNotFoundError问题
你遇到的问题是:python setup.py能正常运行,但pip install失败,因为pip在安装过程中(尤其是获取构建需求阶段)的环境不会自动识别非默认安装的依赖。你的setup.py依赖自定义库,而该库又依赖git这类第三方包,直接在setup.py中导入这些依赖会触发ModuleNotFoundError。
核心原因
pip在执行安装的构建准备阶段(比如报错中的Getting requirements to build editable)会创建隔离环境,不会自动继承当前环境的非默认依赖。如果setup.py的顶层代码直接导入未预先安装的包,就会出现找不到模块的错误。
解决方案
1. 正确声明依赖,移除setup.py顶层的直接导入
把所有依赖(包括你的自定义库和它依赖的第三方包)通过install_requires声明在setup函数中,不要在setup.py的模块级别直接导入这些包。
示例修改后的setup.py:
from setuptools import setup def get_version(): # 若需动态生成版本,参考方案2延迟导入依赖 return "1.0.0" setup( name="your-library", version=get_version(), install_requires=[ "gitpython", # 对应错误中的git模块,注意实际包名是gitpython "your-custom-library", # 你的自定义库,确保能被pip访问(如PyPI/git地址) # 其他运行时依赖 ], # 其他setup参数 )
2. 若需在构建阶段使用依赖(如动态获取版本),声明构建依赖
如果必须在setup过程中使用依赖(比如用git生成版本号),需要先声明构建阶段依赖,再延迟导入:
方式一:用setup.py的setup_requires
from setuptools import setup def get_version(): # 延迟导入,仅在函数调用时执行 import git repo = git.Repo(".") return repo.git.describe("--tags", "--abbrev=0") setup( name="your-library", version=get_version(), setup_requires=[ "gitpython", "your-custom-library" ], install_requires=[ # 运行时依赖 ], )
方式二:用pyproject.toml(推荐,符合PEP 517/518)
在项目根目录创建pyproject.toml,声明构建系统需要的依赖:
[build-system] requires = [ "setuptools", "wheel", "gitpython", "your-custom-library" ] build-backend = "setuptools.build_meta"
这种方式会让pip在执行任何setup代码前,先安装这些构建依赖,确保后续导入不会出错。
3. 确保自定义库可被pip访问
如果你的自定义库还没上传到PyPI,可以在install_requires中用git URL直接引用:
install_requires=[ "your-custom-library @ git+https://github.com/your-username/your-custom-library.git@main" ]
针对你错误的具体修复
你遇到的No module named 'git',实际需要安装的包是gitpython(import git语句来自这个包),只需在构建依赖或运行时依赖中添加gitpython即可解决。
内容的提问来源于stack exchange,提问作者Joshua M
相关产品推荐
相关产品推荐

