正确设置setuptools和pbr后,有以下几种方法:
import pkg_resources # part of setuptools
# I don't like this one because the version method is hidden
v1 = pkg_resources.require("my_package_name")[0].version
print('v1 {}'.format(v1))
# This is my favorite - the output without .version is just a longer string with
# both the package name, a space, and the version string
v2 = pkg_resources.get_distribution('my_package_name').version
print('v2 {}'.format(v2))
from pbr.version import VersionInfo
# This one seems to be slower, and with pyinstaller makes the exe a lot bigger
v3 = VersionInfo('my_package_name').release_string()
print('v3 {}'.format(v3))
# Update, new option as of Python 3.8 (credit: sinoroc)
# In Python 3.8, importlib.metadata is part of the stdlib,
# which removes run-time dependencies on `pbr` or `setuptools`
import importlib.metadata
__version__ = importlib.metadata.version('my_package_name')
如果你想从命令行获取它,你可以这样做:
py setup.py --version
如果软件包总是安装在本地,甚至可以从脚本中运行 setup.py 脚本:
from subprocess import Popen, PIPE
(output, err) = Popen('py setup.py --version'.split(' '),
stdout=PIPE, stderr=PIPE, text=True).communicate()
if err: print('ERROR: "{}"'.format(err))
else: print('setup.py --version = {}'.format(output))
注意:请参阅this answer,了解有关使用子进程启动和读取标准输出等的更多详细信息,尤其是在旧版本的 Python(3.7 之前)上。
然后您可以像这样将__version__ 添加到您的包__init__.py:
__all__ = (
'__version__',
'my_package_name'
)
# Or substitute a different method and assign the result to __version__
import pkg_resources # part of setuptools
__version__ = pkg_resources.get_distribution("my_package_name").version
其他一些可能有助于设置和有关如何更新版本和其他信息的详细信息的问答,尤其是从 Git 存储库获取信息(来自标签、作者和变更日志信息的版本)时: