简体   繁体   English

python 中的 setup.py:如何安装子包?

[英]setup.py in python: how to install subpackages?

Consider the following package structure:考虑以下 package 结构:

src/
   /__init__.py
   bar.py
   /foo
       /__init__.py
       foobar.py

I want to write a setup.py such that if I do:我想写一个 setup.py 这样如果我这样做:

pip install -e .

from the root directory, all the following will work:从根目录开始,以下所有操作都将起作用:

import src
import src.foo
import foo

I am able to achieve the first two easily using eg find_namespace_packages, but I have tried various combos of find_namespace_packages(), find_packages(), package_dir, to also be able to import the subpackage foo without specifying the prefix (ie src.foo) without success.我可以使用例如 find_namespace_packages 轻松实现前两个,但是我尝试了 find_namespace_packages()、find_packages()、package_dir 的各种组合,也能够在不指定前缀(即 src.foo)的情况下导入子包 foo成功。 How do I do this?我该怎么做呢?

Perhaps I'm wrong, but I'm fairly sure you can't with the way you structure/package your repo.也许我错了,但我相当肯定你不能用你构建/打包你的回购的方式。 Python will look in src and each __init__.py allows for it to be indexed and thus it's consider part of the same package. Python 将在src中查找,并且每个__init__.py都允许对其进行索引,因此它被认为是同一个 package 的一部分。 Plus, there are potential namespace conflicts.此外,还有潜在的命名空间冲突。 What if instead of foo you had csv ?如果你有csv而不是foo怎么办? That would break the default csv library for python.这将破坏 python 的默认csv库。 By specifying src.foo it's explicit where foo is defined.通过指定src.foo可以明确定义foo的位置。

The only way I can think is to have your code in two separate repository with foo available on PyPI (ie, pip install foo ).我能想到的唯一方法是将您的代码放在两个单独的存储库中,并且foo在 PyPI 上可用(即pip install foo )。 After adding it to your requirements.txt Then you can do something like:将其添加到您的requirements.txt之后,您可以执行以下操作:

import foo

in src/__init__.py .src/__init__.py中。 This would allow for you to have: src.foo and foo .这将允许您拥有: src.foofoo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM