Makefile - 我应该如何提取“pyproject.toml”中嵌入的版本号?
我有一个带有 pyproject.toml 文件的 python 项目。通常,我将项目的版本号存储在 pyproject.toml
中,如下所示:
% grep version pyproject.toml
version = "0.0.2"
%
我希望将该版本号放入 Makefile
变量中,无论版本术语周围有多少空格。
我应该如何将 pyproject.toml
版本字符串提取到名为 VERSION
的 Makefile
环境变量中?
I have a python project with a pyproject.toml
file. Typically I store the project's version number in pyproject.toml
like this:
% grep version pyproject.toml
version = "0.0.2"
%
I want to get that version number into a Makefile
variable regardless of how many spaces wind up around the version terms.
What should I do to extract the pyproject.toml
version string into a Makefile
environment variable called VERSION
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这似乎是最好的...我把它放在我的
Makefile
特别感谢 @charl-botha 对于
-m 1
grep 参数...gnu 和 bsd grep 支持-m
在这种情况下。额外信息:从 2024 年开始,我停止在 pyproject.toml 中查找版本号...现在我将版本嵌入到我的
__about__.py
中并进行管理所有带有hatch
的版本,这对于构建 Python 项目来说非常棒(它取代类似的工具诗)。This seemed to work out the best... I put this in my
Makefile
Special thanks to @charl-botha for the
-m 1
grep argument... both gnu and bsd grep support-m
in this context.Extra info: As of 2024, I stopped grepping through my pyproject.toml for version numbers... now I embed the version in my
__about__.py
and manage all versions withhatch
, which is just awesome for building Python projects (it replaces tools like poetry).如果您有安装了 tomli 软件包的 Python,或者您使用的是内置 toml 的 Python 3.11(在这种情况下,您将
import tomllib
而不是tomli
) ,并且您的 pyproject.toml 遵循诗歌约定,类似以下内容会很好用:在命令行上进行简单测试:
显然您可以轻松调整所需版本的位置> 其他情况下的条目
pyproject.toml
约定。顺便说一句,
tomllib
实际上是tomli
,请参阅 https://peps.python.org/pep-0680/#rationaleIf you have a Python available with the tomli package installed, or you're on Python 3.11 with toml built-in (in which case you would
import tomllib
instead oftomli
), and yourpyproject.toml
follows poetry convention, something like the following would work well:Test on command-line with simply:
Obviously you can easily adapt the location of the desired
version
entry in the case of otherpyproject.toml
conventions.BTW,
tomllib
is in facttomli
, see https://peps.python.org/pep-0680/#rationale解析major.minor.patch的替代解决方案,基于@Mike Pennington'答案:
An alternative solution to parse
major.minor.patch
, based on @Mike Pennington's answer:如果这就是该文件真正包含的全部内容,那么它与 makefile 语法非常接近,您可以将其作为 makefile 包含在内:
如果您不想或不能这样做,我会使用 sed 为它:
If that's all that file really contains, that's sufficiently close to makefile syntax that you can just include it as a makefile:
If you don't want to, or can't, do that, I'd use
sed
for it:您可能需要先
poetry install
。You many need to
poetry install
first.