🛠️ToolsShed

语义版本计算器

比较语义版本并检查版本是否满足范围(^、~、>=等)。

Compare Two Versions

Range Examples

^1.2.3>= 1.2.3 < 2.0.0
~1.2.3>= 1.2.3 < 1.3.0
>=1.0.0 <2.0.0>= 1.0.0 AND < 2.0.0
1.0.0 - 2.0.0>= 1.0.0 <= 2.0.0
1.x.x || 2.x.x1.x OR 2.x

常见问题

代码实现

# pip install packaging
from packaging.version import Version
from packaging.specifiers import SpecifierSet

v1 = Version("1.2.3")
v2 = Version("2.0.0")
v3 = Version("1.2.3-alpha.1")  # Note: packaging uses PEP 440 syntax

# Comparison
print(v1 < v2)    # True
print(v1 == Version("1.2.3"))  # True

# Check if a version satisfies a specifier
spec = SpecifierSet(">=1.0.0,<2.0.0")
print(Version("1.5.0") in spec)   # True
print(Version("2.0.0") in spec)   # False
print(Version("0.9.0") in spec)   # False

# PEP 440 pre-release (different from semver!)
v_pre = Version("1.0.0a1")    # alpha 1
v_rc  = Version("1.0.0rc2")   # release candidate 2
print(v_pre < v_rc < Version("1.0.0"))  # True

# Sorting versions
versions = [Version(v) for v in ["2.0.0", "1.0.0", "1.5.0", "1.5.1"]]
print(sorted(versions))
# [<Version('1.0.0')>, <Version('1.5.0')>, <Version('1.5.1')>, <Version('2.0.0')>]

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.