如何从根目录将指定子目录的本地Python模块安装为types下的独立包?
问题背景
我的仓库结构如下:
root_dir/ ├── python/ │ └── libraries/ │ └──types/ │ ├── type1/ │ │ └── math/ │ │ └── math.py │ └── type2/ │ └── categories/ │ └── category1/ │ ├── module1/ │ │ └── module1.py │ ├── module2/ │ │ ├──module2.py │ │ └── test/ │ │ └── test_module2.py │ └── module3/ │ ├── module3.py │ └── test/ │ └── test_module3.py └── notebooks/ └── type1/ └── categories/ └── category1/ └── notebook.ipynb
我需要从根目录root_dir出发,把root_dir\python\libraries\types\type1安装为types.type1,把root_dir\python\libraries\types\type2\categories安装为types.type2.categories这两个独立包,并且希望能在notebook.ipynb中使用以下语句导入模块:
from types.type1.math.math import Vector from types.type2.categories.category1.module1.module1 import Calculator from types.type2.categories.category1.module2.module2 import Processor
解决方案
1. 补全包结构文件
给每个需要被识别为Python包的目录添加__init__.py文件(Python 3.3+可省略,但显式添加能避免兼容性问题),调整后的结构如下:
root_dir/ ├── python/ │ └── libraries/ │ └── types/ │ ├── __init__.py # 根types包的初始化文件 │ ├── type1/ │ │ ├── __init__.py │ │ └── math/ │ │ ├── __init__.py │ │ └── math.py │ └── type2/ │ ├── __init__.py │ └── categories/ │ ├── __init__.py │ └── category1/ │ ├── __init__.py │ ├── module1/ │ │ ├── __init__.py │ │ └── module1.py │ ├── module2/ │ │ ├── __init__.py │ │ ├── module2.py │ │ └── test/ │ │ └── test_module2.py │ └── module3/ │ ├── __init__.py │ ├── module3.py │ └── test/ │ └── test_module3.py └── notebooks/ └── type1/ └── categories/ └── category1/ └── notebook.ipynb
2. 添加包配置文件
在root_dir/python/libraries/types目录下创建pyproject.toml文件,内容如下:
[build-system] requires = ["setuptools>=61.0"] build-backend = "setuptools.build_meta" [project] name = "types" version = "0.1.0" packages = [ "types.type1", "types.type2.categories", "types.type1.math", "types.type2.categories.category1", "types.type2.categories.category1.module1", "types.type2.categories.category1.module2", "types.type2.categories.category1.module3" ]
这个文件告诉setuptools要打包哪些子包,确保层级结构符合你的导入需求。
3. 安装包
打开终端,切换到root_dir/python/libraries/types目录,执行以下命令进行可编辑安装(开发阶段推荐,修改代码后无需重新安装):
pip install -e .
如果是Windows系统,命令完全一致,只要确保终端路径正确即可。若不需要实时同步代码修改,直接执行pip install .完成永久安装。
4. 验证导入
打开notebook.ipynb,直接使用你需要的导入语句即可,比如:
from types.type1.math.math import Vector from types.type2.categories.category1.module1.module1 import Calculator from types.type2.categories.category1.module2.module2 import Processor
内容的提问来源于stack exchange,提问作者user146268
相关产品推荐
相关产品推荐

