Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get `setup.cfg` metadata at the command line (Python)

When you have a setup.py file, you can get the name of the package via the command:

C:\some\dir>python setup.py --name

And this would print the name of the package to the command line.

In an attempt to adhere to best practice, I'm trying to migrate away from setup.py by putting everything in setup.cfg since everything that was previously in setup.py was static content.

But our build pipeline depends on being able to call python setup.py --name. I'm looking to rewrite the pipeline in such a way that I don't need to create a setup.py file.

Is there way to get the name of the package when you have a setup.cfg but not a setup.py file?

like image 729
myoungberg Avatar asked Apr 24 '26 04:04

myoungberg


1 Answers

TL;DR, use the setuptools configuration API https://setuptools.pypa.io/en/latest/setuptools.html#configuration-api.

In your case, this line will give the name of the package:

python -c 'from setuptools.config import read_configuration as c; print(c("setup.cfg")["metadata"]["name"])'

Edit:

In setuptools v61.0.0 (24 Mar 2022) setuptools.config.read_configuration was deprecated . Using the new API, the command becomes:

python -c 'from setuptools.config.setupcfg import read_configuration as c; print(c("setup.cfg")["metadata"]["name"])'

Explanation:

Setuptools exposes a read_configuration() function for parsing metadata and options sections of the configuration. Internally, setuptools uses the configparser module to parse the configuration file setup.cfg. For simple str-type data such as the "name" key, configparser can be used to read the data. However, setuptools also allows dynamic configuration using directives that cannot be directly parsed with configparser.

Here is an example that shows the difference between the two approaches for replacing python setup.py --version:

$ tree .
.
├── my_package
│   └── __init__.py
├── pyproject.toml
└── setup.cfg

1 directory, 3 files

$ cat setup.cfg
[metadata]
name = my_package
version = attr:my_package.__version__

[options]
packages = find:

$ cat my_package/__init__.py 
__version__ = "1.0.0"

$ cat pyproject.toml

$ python -c 'from setuptools.config import read_configuration as c; print(c("setup.cfg")["metadata"]["version"])'
1.0.0

$ python -c 'from configparser import ConfigParser; c = ConfigParser(); c.read("setup.cfg"); print(c["metadata"]["version"])'
attr:my_package.__version__

like image 127
ali Avatar answered Apr 26 '26 17:04

ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!