使 Python 中的 distutils 自动查找包

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12966216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:17:24  来源:igfitidea点击:

make distutils in Python automatically find packages

pythondistutilssetup.py

提问by

When describing a python package in setup.pyin distutilsin Python, is there a way to make it so automatically get every directory that has a __init__.pyin it and include that as a subpackage?

当描述一个Python包setup.pydistutilsPython中,是有办法使它所以自动获得每一个有一个目录__init__.py中,并包含一个子包?

ie if the structure is:

即如果结构是:

mypackage/__init__.py
mypackage/a/__init__.py
mypackage/b/__init__.py

I want to avoid doing:

我想避免这样做:

packages = ['mypackage', 'mypackage.a', 'mypackage.b']

and instead just do:

而只是这样做:

packages = ['mypackage']

and have it automatically find things like aand bsince they have an init file. thanks.

并让它自动查找类似的东西ab因为它们有一个 init 文件。谢谢。

采纳答案by Sean Vieira

The easiest way (that I know of) is to use pkgutil.walk_packagesto yield the packages:

最简单的方法(我知道的)是pkgutil.walk_packages用来产生包:

from distutils.core import setup
from pkgutil import walk_packages

import mypackage

def find_packages(path=__path__, prefix=""):
    yield prefix
    prefix = prefix + "."
    for _, name, ispkg in walk_packages(path, prefix):
        if ispkg:
            yield name

setup(
    # ... snip ...
    packages = list(find_packages(mypackage.__path__, mypackage.__name__)),
    # ... snip ...
)

回答by dm76

I would recommend using the find_packages() function available with setuptoolssuch as:

我会建议使用find_packages()函数可用setuptools的,例如:

from setuptools import setup, find_packages

and then do

然后做

packages=find_packages()

回答by Brian Dilley

import re, os
def find_packages(path='.'):
    ret = []
    for root, dirs, files in os.walk(path):
        if '__init__.py' in files:
            ret.append(re.sub('^[^A-z0-9_]+', '', root.replace('/', '.')))
    return ret

setup(
...
packages = find_packages()
...
)

回答by Shubham Chaudhary

Same as dm76 answer, just that I also have tests in my repo, so I use:

与 dm76 答案相同,只是我的 repo 中也有测试,所以我使用:

from setuptools import find_packages

packages=find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]),