如何从根目录安装子目录中的本地Python模块作为独立包?

0 投票
1 回答
36 浏览
提问于 2025-04-14 16:33

我有一个这样的项目结构:

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\type1types.type1,以及 root_dir\python\libraries\types\type2\categoriestypes.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 个回答

0

在根目录下的 python\libraries 文件夹里添加一个 setup.py 文件,像这样:

from setuptools import setup, find_namespace_packages

setup(
    name='types.type1',
    version='0.1',
    packages=find_namespace_packages(where='types', include=['type1.math']),
    package_dir={'': 'types'},
)

然后在 python\libraries\types 文件夹里再添加一个 setup.py 文件,像这样:

from setuptools import setup, find_namespace_packages

setup(
    name='types.type2.categories',
    version='0.1',
    packages=find_namespace_packages(where='type2'),
    package_dir={'': 'type2'},
    install_requires=[
        'types.type1',
    ]
)

这样就解决了问题。我现在可以使用这些导入语句:

from type1.math.math import Vector
from categories.category1.module1.module1 import Calculator
from categories.category1.module2.module2 import Processor

这对我的项目来说运行得很好。

撰写回答