如何使用源代码中的 pbr 版本?

How can I use pbr version from source?

我的目标:

我想在我的 GIT 存储库中保持一致 版本,我在 pypi 存储库,并在我的源代码中使用 __version__ 变量。


详情:

我尝试使用 pbr, which generates the distro version from git tags, so these two versions will be coherent. However, I cannot find out how to keep the __version__ variable coherent with them in my source. (There are several ways 从源中获取版本,但如何连接到 git/distro?)

是否可以生成版本文件(解析表单源)或直接修改__version__变量?

最后,我在thispost中找到了解决方案。

import pkg_resources  # part of setuptools
version = pkg_resources.require("MyProject")[0].version

更新

post 显示了另一个更可靠的解决方案:

from pbr.version import VersionInfo

package_name='MyProject'
info = VersionInfo(package_name)

version = info.version_string()

Python3.8标准库中直接有解决方案:__version__ = importlib.metadata.version('Example')。参见 Using importlib.metadata