Python 项目的版本通过 pyproject.toml 文件指定:
[project]
name = "markdown-img-icexmoon"
version = "2.0.3"
description = "A program for find and upload images in markdown file and will replace them."
readme = "README.md"
requires-python = ">=3.13"
但这样做有一个问题,这个用于描述项目信息的 toml 文件通常只在打包时生效,用户通过 pypi 下载和安装后,模块目录下是没有toml文件的。因此你也无法通过解析 toml 文件的方式获取版本号。即使在开发时这样做有效,但在用户安装后相应的程序就会报错。
所以如果你需要在程序中获取当前程序的版本号就变成了一个很艰难的任务。
很常见的是,为 Python 程序提供一个命令行参数
-v以显示当前版本。
可以借助一个编译工具 实现这一点。
首先需要修改项目说明文件pyproject.toml:
[project]
name = "markdown-img-icexmoon"
dynamic = ["version"] # 在这里通过 scm 动态获取版本号
# version = "xxx" 不再需要固定版本号
# ...
# 设置打包工具
[build-system]
requires = ["setuptools>=80", "setuptools-scm>=8"]
build-backend = "setuptools.build_meta"
[tool.setuptools_scm]
version_file = "src/markdown_img/_version.py" # 指定生成的版本号文件
[tool.setuptools.packages.find]
where = ["src"] # 需要打包的模块所在的目录
include = ["markdown_img"] # 模块名称
打包工具使用 git 的 tag 标签作为版本号,因此你需要先使用 Git 进行版本控制,并添加标签:
git tag 2.0.3
如果当前修改还未提交,或者已经提交但没有 tag,打包工具会使用一个带分支名称和包含离最后一个 tag 提交数目的版本号。因此正式打包时最好保证代码已提交,以便生成一个干净的版本号。
打包项目:
python -m build
如果没有安装,先安装:
pip install build。
项目打包后会在模块下生成一个_version.py文件:
# ...
__version__ = version = '2.0.3'
__version_tuple__ = version_tuple = (2, 0, 3)
__commit_id__ = commit_id = 'g2644fda4f'
我们可以很容易使用这个文件获取到项目版本号:
from ._version import __version__
print(__version__)
我的项目 就是通过这种方式获取版本号的,可以参考源码。
The End.

文章评论