With a simple setup.py
file:
from setuptools import setup
setup(
name='foo',
version='1.2.3',
)
I can do
$> python setup.py --version
1.2.3
without installing the package.
Is there similar functionality for the equivalent pyproject.toml
file:
[project]
name = "foo"
version = "1.2.3"
With Python 3.11+, something like this should work:
python3.11 -c "import tomllib; print(tomllib.load(open('pyproject.toml', 'rb'))['project']['version'])"
This parses the TOML file directly, and assumes that version is not dynamic.
In some cases, version is declared dynamic in pyproject.toml
, so it can not be parsed directly from this file and a solution (the only one?) is to actually build the project, or at least its metadata.
For this purpose, we can use the build.util.project_wheel_metadata()
function from the build
project, for example with a small script like this:
#!/usr/bin/env python
import argparse
import pathlib
import build.util
def _main():
args_parser = argparse.ArgumentParser()
args_parser.add_argument('path')
args = args_parser.parse_args()
path_name = getattr(args, 'path')
path = pathlib.Path(path_name)
#
metadata = build.util.project_wheel_metadata(path)
version = metadata.get('Version')
print(version)
if __name__ == '__main__':
_main()
Or as a one-liner:
python -c "import build.util; print(build.util.project_wheel_metadata('.').get('Version'))"