是否有一种标准的方法将版本字符串与Python包相关联,以便我可以执行以下操作?

import foo
print(foo.version)

我认为有一些方法可以在没有任何额外硬编码的情况下检索数据,因为minor/major字符串已经在setup.py中指定了。我发现的替代解决方案是在我的foo/__init__.py中导入__version__,然后由setup.py生成__version__.py。


当前回答

与其他一些答案相比,还有一个稍微简单一点的选择:

__version_info__ = ('1', '2', '3')
__version__ = '.'.join(__version_info__)

(使用str()将版本号的自动递增部分转换为字符串相当简单。)

Of course, from what I've seen, people tend to use something like the previously-mentioned version when using __version_info__, and as such store it as a tuple of ints; however, I don't quite see the point in doing so, as I doubt there are situations where you would perform mathematical operations such as addition and subtraction on portions of version numbers for any purpose besides curiosity or auto-incrementation (and even then, int() and str() can be used fairly easily). (On the other hand, there is the possibility of someone else's code expecting a numerical tuple rather than a string tuple and thus failing.)

当然,这是我自己的观点,我很乐意听取其他人对使用数字元组的意见。


正如shezi提醒我的那样,(词汇)数字串的比较并不一定与直接的数字比较有相同的结果;需要前导零来提供这一点。因此,最后,将__version_info__(或任何它将被称为)存储为整数值的元组将允许更有效的版本比较。

其他回答

使用setuptools和pbr

没有管理版本的标准方法,但是管理包的标准方法是setuptools。

总的来说,我发现最好的版本管理解决方案是使用setuptools和pbr扩展。这是我现在管理版本的标准方式。

对于简单的项目来说,为完整的打包设置项目可能有些过分,但是如果您需要管理版本,那么您可能处于设置所有内容的正确级别。这样做还可以使您的包在PyPi上发布,以便每个人都可以下载并与Pip一起使用它。

PBR moves most metadata out of the setup.py tools and into a setup.cfg file that is then used as a source for most metadata, which can include version. This allows the metadata to be packaged into an executable using something like pyinstaller if needed (if so, you will probably need this info), and separates the metadata from the other package management/setup scripts. You can directly update the version string in setup.cfg manually, and it will be pulled into the *.egg-info folder when building your package releases. Your scripts can then access the version from the metadata using various methods (these processes are outlined in sections below).

当在VCS/SCM中使用Git时,这种设置甚至更好,因为它将从Git中引入大量元数据,这样你的回购就可以成为一些元数据的主要真实来源,包括版本、作者、更改日志等。对于version,它将基于repo中的git标记为当前提交创建一个版本字符串。

PyPA -用SetupTools打包Python包-教程 PBR最新的构建使用文档-如何用元数据设置一个8行的setup.py和setup.cfg文件。

由于PBR会直接从你的git repo中提取版本、作者、更新日志和其他信息,所以setup.cfg中的一些元数据可以被省略,并在为你的包创建发行版时自动生成(使用setup.py)。



实时获取当前版本

Setuptools将使用setup.py实时提取最新信息:

python setup.py --version

这将从setup.cfg文件或git repo中提取最新版本,基于最近的提交和repo中存在的标记。但是,该命令不会更新发行版中的版本。



更新版本元数据

当你使用setup.py(例如py setup.py sdist)创建发行版时,所有当前信息都会被提取并存储在发行版中。这实际上是运行setup.py——version命令,然后将版本信息存储到包中。Egg-info文件夹中的一组文件,用于存储分发元数据。

Note on process to update version meta-data: If you are not using pbr to pull version data from git, then just update your setup.cfg directly with new version info (easy enough, but make sure this is a standard part of your release process). If you are using git, and you don't need to create a source or binary distribution (using python setup.py sdist or one of the python setup.py bdist_xxx commands) the simplest way to update the git repo info into your <mypackage>.egg-info metadata folder is to just run the python setup.py install command. This will run all the PBR functions related to pulling metadata from the git repo and update your local .egg-info folder, install script executables for any entry-points you have defined, and other functions you can see from the output when you run this command. Note that the .egg-info folder is generally excluded from being stored in the git repo itself in standard Python .gitignore files (such as from Gitignore.IO), as it can be generated from your source. If it is excluded, make sure you have a standard "release process" to get the metadata updated locally before release, and any package you upload to PyPi.org or otherwise distribute must include this data to have the correct version. If you want the Git repo to contain this info, you can exclude specific files from being ignored (i.e. add !*.egg-info/PKG_INFO to .gitignore)



从脚本访问版本

您可以在包本身的Python脚本中从当前构建中访问元数据。以版本为例,到目前为止,我发现有几种方法可以做到这一点:

## This one is a new built-in as of Python 3.8.0 should become the standard
from importlib.metadata import version

v0 = version("mypackage")
print('v0 {}'.format(v0))

## I don't like this one because the version method is hidden
import pkg_resources  # part of setuptools

v1 = pkg_resources.require("mypackage")[0].version
print('v1 {}'.format(v1))

# Probably best for pre v3.8.0 - the output without .version is just a longer string with
# both the package name, a space, and the version string
import pkg_resources  # part of setuptools

v2 = pkg_resources.get_distribution('mypackage').version
print('v2 {}'.format(v2))

## This one seems to be slower, and with pyinstaller makes the exe a lot bigger
from pbr.version import VersionInfo

v3 = VersionInfo('mypackage').release_string()
print('v3 {}'.format(v3))

你可以把其中一个直接放在__init__.py中,让包提取版本信息,如下所示,类似于其他一些答案:

__all__ = (
    '__version__',
    'my_package_name'
)

import pkg_resources  # part of setuptools

__version__ = pkg_resources.get_distribution("mypackage").version

同样值得注意的是,__version__是一个半std。在python中,__version_info__也是一个元组,在简单的情况下,你可以这样做:

__version__ = '1.2.3'
__version_info__ = tuple([ int(num) for num in __version__.split('.')])

...你可以从文件或其他地方获取__version__字符串。

根据延迟的[STOP PRESS: rejected] PEP 396(模块版本号),有一种建议的方法来做到这一点。它描述了模块遵循的基本原理(当然是可选的)标准。下面是一个片段:

当模块(或包)包含版本号时,该版本应该在__version__属性中可用。

对于位于命名空间包中的模块,模块应该包含__version__属性。命名空间包本身不应该包含自己的__version__属性。

__version__属性的值应该是一个字符串。

自从第一次提出这个问题以来,已经完成了许多关于统一版本和支持约定的工作。可接受的选项现在在Python打包用户指南中详细介绍。同样值得注意的是,版本号方案在Python PEP 440中是相对严格的,因此如果您的包将被发布到Cheese Shop,那么保持正常是至关重要的。

以下是版本控制选项的简短分类:

Read the file in setup.py (setuptools) and get the version. Use an external build tool (to update both __init__.py as well as source control), e.g. bump2version, changes or zest.releaser. Set the value to a __version__ global variable in a specific module. Place the value in a simple VERSION text file for both setup.py and code to read. Set the value via a setup.py release, and use importlib.metadata to pick it up at runtime. (Warning, there are pre-3.8 and post-3.8 versions.) Set the value to __version__ in sample/__init__.py and import sample in setup.py. Use setuptools_scm to extract versioning from source control so that it's the canonical reference, not code.

注意(7)可能是最现代的方法(构建元数据独立于代码,由自动化发布)。还要注意,如果setup用于包发布,那么简单的python3 setup.py——version将直接报告版本。

重写2017 - 05

在写了13年以上的Python代码和管理各种包之后,我得出的结论是,DIY可能不是最好的方法。

我开始使用pbr包来处理包中的版本控制。如果您正在使用git作为您的SCM,这将像魔法一样适合您的工作流,节省您数周的工作时间(您将惊讶于问题的复杂程度)。

截至目前,pbr的月下载量为1200万次,达到这一水平并不需要任何肮脏的手段。这只是一件事——用非常简单的方法解决一个常见的包装问题。

PBR可以承担更多的包维护负担,而且不局限于版本控制,但它不会强迫您采用它的所有好处。

所以为了给你一个关于如何在一次提交中采用策略br的想法,看看切换包装到策略br

您可能会注意到版本根本没有存储在存储库中。PBR确实从Git分支和标记中检测到它。

不需要担心没有git存储库时会发生什么,因为在打包或安装应用程序时,pbr会“编译”并缓存版本,因此不依赖于git的运行时。

旧的解决方案

以下是我迄今为止见过的最好的解决方案,它也解释了为什么:

借“yourpackage / version.py:

# Store the version here so:
# 1) we don't load dependencies by storing it in __init__.py
# 2) we can import it in setup.py for the same reason
# 3) we can import it into your module module
__version__ = '0.12'

内部yourpackage / __init__ . py:

from .version import __version__

在setup . py:

exec(open('yourpackage/version.py').read())
setup(
    ...
    version=__version__,
    ...

如果你知道其他更好的方法,请告诉我。