python - 与 setup.py 和包共享包版本的正确方法是什么?

标签 python setuptools distutils

使用 distutilssetuptools 等,在 setup.py 中指定包版本:

# file: setup.py
...
setup(
name='foobar',
version='1.0.0',
# other attributes
)

我希望能够从包中访问相同的版本号:

>>> import foobar
>>> foobar.__version__
'1.0.0'

我可以将 __version__ = '1.0.0' 添加到我的包的 __init__.py 中,但我还想在我的包中包含其他导入以创建包的简化接口(interface):

# file: __init__.py

from foobar import foo
from foobar.bar import Bar

__version__ = '1.0.0'

# file: setup.py

from foobar import __version__
...
setup(
name='foobar',
version=__version__,
# other attributes
)

但是,如果这些额外的导入导入其他尚未安装的包,可能会导致 foobar 的安装失败。与 setup.py 和包共享包版本的正确方法是什么?

最佳答案

仅在 setup.py 中设置版本,并使用 pkg_resources 读取您自己的版本,有效地查询 setuptools 元数据:

文件:setup.py

setup(
    name='foobar',
    version='1.0.0',
    # other attributes
)

文件:__init__.py

from pkg_resources import get_distribution

__version__ = get_distribution('foobar').version

为了在所有情况下都能正常工作,在没有安装它的情况下最终运行它,测试 DistributionNotFound 和分发位置:

from pkg_resources import get_distribution, DistributionNotFound
import os.path

try:
    _dist = get_distribution('foobar')
    # Normalize case for Windows systems
    dist_loc = os.path.normcase(_dist.location)
    here = os.path.normcase(__file__)
    if not here.startswith(os.path.join(dist_loc, 'foobar')):
        # not installed, but there is another version that *is*
        raise DistributionNotFound
except DistributionNotFound:
    __version__ = 'Please install this project with setup.py'
else:
    __version__ = _dist.version

关于python - 与 setup.py 和包共享包版本的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17583443/

相关文章:

python - 分发支持 Python 的大型应用程序 : best practices

python - 无法使用 distutils 构建 Cython 模块

Python打包分发安装后步骤

python - 使用pyculib进行3D FFT结果错误

python - 如何在pygame中控制单个子弹

python - setuptools python setup.py 安装不复制所有子模块

python - 使用 setup.py bdist_wininst 构建的 Windows 安装程序在安装时触发 RuntimeError。我该如何解决?

python - 无法从文件中逐行列出?

python - 在 Pandas 数据框中查找元素

python - 使用 distutils/setuptools 配置扩展模块