使用 distutils
、setuptools
等,在 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/