如何比较Python中的版本号? [英] How do I compare version numbers in Python?

查看:434
本文介绍了如何比较Python中的版本号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在走一个包含鸡蛋的目录,以将这些鸡蛋添加到sys.path.如果目录中有相同.egg的两个版本,我只想添加最新的版本.

I am walking a directory that contains eggs to add those eggs to the sys.path. If there are two versions of the same .egg in the directory, I want to add only the latest one.

我有一个正则表达式r"^(?P<eggName>\w+)-(?P<eggVersion>[\d\.]+)-.+\.egg$,用于从文件名中提取名称和版本.问题是比较版本号,它是一个像2.3.1这样的字符串.

I have a regular expression r"^(?P<eggName>\w+)-(?P<eggVersion>[\d\.]+)-.+\.egg$ to extract the name and version from the filename. The problem is comparing the version number, which is a string like 2.3.1.

由于我正在比较字符串,所以10之上有2种排序方式,但这对于版本来说是不正确的.

Since I'm comparing strings, 2 sorts above 10, but that's not correct for versions.

>>> "2.3.1" > "10.1.1"
True

我可以进行一些拆分,解析,转换为int等操作,最终我将得到一种解决方法.但这是Python,不是Java .有一种比较优雅的方式来比较版本字符串吗?

I could do some splitting, parsing, casting to int, etc., and I would eventually get a workaround. But this is Python, not Java. Is there an elegant way to compare version strings?

推荐答案

使用

packaging.version.parse是第三方实用程序,但被 setuptools 使用(因此,您可能已经安装),并且符合当前的 PEP 440 ;如果版本兼容,它将返回packaging.version.Version,否则返回packaging.version.LegacyVersion.后者将始终在有效版本之前排序.

packaging.version.parse is a third-party utility but is used by setuptools (so you probably already have it installed) and is conformant to the current PEP 440; it will return a packaging.version.Version if the version is compliant and a packaging.version.LegacyVersion if not. The latter will always sort before valid versions.

注意:包装最近已供应商进入setuptools .

许多软件仍在使用的古老替代方法是 distutils.version ,内置但未记录且仅符合被取代的 PEP 386 ;

An ancient alternative still used by a lot of software is distutils.version, built in but undocumented and conformant only to the superseded PEP 386;

>>> from distutils.version import LooseVersion, StrictVersion
>>> LooseVersion("2.3.1") < LooseVersion("10.1.2")
True
>>> StrictVersion("2.3.1") < StrictVersion("10.1.2")
True
>>> StrictVersion("1.3.a4")
Traceback (most recent call last):
...
ValueError: invalid version number '1.3.a4'

如您所见,它将有效的PEP 440版本视为不严格",因此与现代Python的有效版本概念不符.

As you can see it sees valid PEP 440 versions as "not strict" and therefore doesn’t match modern Python’s notion of what a valid version is.

由于未记录distutils.version,因此此处是相关的文档字符串.

As distutils.version is undocumented, here's the relevant docstrings.

这篇关于如何比较Python中的版本号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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