与setup.py和软件包共享软件包版本的正确方法是什么? [英] What is the correct way to share package version with setup.py and the package?

查看:69
本文介绍了与setup.py和软件包共享软件包版本的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 distutils setuptools 等,在 setup中指定了软件包版本。 py

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

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

I would like to be able to access the same version number from within the package:

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






我可以在包的__init__.py中添加 __ version__ ='1.0.0',但是我也想在包中包括其他导入,以创建简化的接口软件包:


I could add __version__ = '1.0.0' to my package's __init__.py, but I would also like to include additional imports in my package to create a simplified interface to the package:

# 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和软件包共享软件包版本的正确方法是什么?

However, these additional imports can cause the installation of foobar to fail if they import other packages that are not yet installed. What is the correct way to share package version with setup.py and the package?

推荐答案

在<$ c $中设置版本c> 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 和分发位置:

To make this work in all cases, where you could end up running this without having installed it, test for DistributionNotFound and the distribution location:

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

这篇关于与setup.py和软件包共享软件包版本的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆