如何让pip仅将testpkg主包安装至site-packages而非子包?
问题:如何仅将testpkg目录安装到site-packages?
我的Python项目testpkg结构如下:
. ├── README.md ├── pyproject.toml ├── setup.py ├── testpkg/ | |-- __init__.py │ └── package1/ │ ├── __init__.py │ └── module.py └── tests/ ├── test1.py
执行python -m pip install .安装后,site-packages下同时出现testpkg和package1两个目录,我需要仅让testpkg目录被安装到site-packages。
我的尝试
按上述结构创建测试项目,执行本地pip安装,预期仅testpkg被加入site-packages。
我的setup.py文件内容:
from setuptools import setup, find_packages from pathlib import Path setup( name="testpkg", version="1.0.0", description="Description", download_url="https://github.com/path/to/repo", author="Me", python_requires=">=3.7", packages=find_packages(include=["testpkg", "testpkg.*"]), install_requires=[ "numpy", ], zip_safe=True, )
我的pyproject.toml文件内容:
[build-system] requires = ['setuptools>=42'] build-backend = 'setuptools.build_meta'
解决方案
问题根源在于find_packages的自动识别逻辑,即便指定了include=["testpkg", "testpkg.*"],仍可能因配置干扰或工具行为导致package1被识别为独立包安装。以下是两种可行的解决方法:
方法一:直接指定要安装的包列表
放弃自动查找,明确只安装testpkg根包,它会自动包含其下的子包testpkg.package1:
from setuptools import setup setup( name="testpkg", version="1.0.0", description="Description", download_url="https://github.com/path/to/repo", author="Me", python_requires=">=3.7", packages=["testpkg"], install_requires=[ "numpy", ], zip_safe=True, )
方法二:用exclude参数排除独立的package1
如果必须使用find_packages,添加exclude参数明确排除package1:
from setuptools import setup, find_packages setup( name="testpkg", version="1.0.0", description="Description", download_url="https://github.com/path/to/repo", author="Me", python_requires=">=3.7", packages=find_packages(include=["testpkg", "testpkg.*"], exclude=["package1"]), install_requires=[ "numpy", ], zip_safe=True, )
额外检查项
- 确认项目根目录没有
setup.cfg文件,若存在,其[options]中的packages配置可能会覆盖setup.py的设置 - 检查
package1目录的__init__.py,避免包含会让setuptools将其识别为独立包的元数据(如__version__)
内容的提问来源于stack exchange,提问作者interatomic
相关产品推荐
相关产品推荐

