如何在命令行 (Python) 获取 `setup.cfg` 元数据

myo*_*erg 8 python setuptools setup.py python-packaging

当你有一个setup.py文件时,你可以通过以下命令获取包的名称:

C:\some\dir>python setup.py --name
Run Code Online (Sandbox Code Playgroud)

这会将包的名称打印到命令行。

为了遵循最佳实践,我试图setup.py通过将所有内容放入其中来迁移setup.cfg,因为以前的所有内容setup.py都是静态内容。

但我们的构建管道依赖于能够调用python setup.py --name. 我希望以不需要创建setup.py文件的方式重写管道。

setup.cfg当您有文件但没有文件时,有没有办法获取包的名称setup.py

ali*_*ali 5

TL;DR,使用 setuptools 配置 API https://setuptools.pypa.io/en/latest/setuptools.html#configuration-api

\n

在您的情况下,这一行将给出包的名称:

\n
python -c \'from setuptools.config import read_configuration as c; print(c("setup.cfg")["metadata"]["name"])\'\n
Run Code Online (Sandbox Code Playgroud)\n
\n

编辑:

\n

在 setuptools v61.0.0(2022 年 3 月 24 日)中setuptools.config.read_configuration已弃用。使用新的 API,命令变为:

\n
python -c \'from setuptools.config.setupcfg import read_configuration as c; print(c("setup.cfg")["metadata"]["name"])\'\n
Run Code Online (Sandbox Code Playgroud)\n
\n

解释:

\n

setuptools 公开了一个read_configuration()用于解析配置的元数据和选项部分的函数。在内部,setuptools 使用该configparser模块来解析配置文件setup.cfg。对于简单str类型的数据,例如“name”键,可以使用configparser来读取数据。但是,setuptools 还允许使用无法使用 configparser 直接解析的指令进行动态配置。

\n

下面的示例显示了两种替换方法之间的差异python setup.py --version

\n
$ tree .\n.\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 my_package\n\xe2\x94\x82\xc2\xa0\xc2\xa0 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 __init__.py\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 pyproject.toml\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 setup.cfg\n\n1 directory, 3 files\n\n$ cat setup.cfg\n[metadata]\nname = my_package\nversion = attr:my_package.__version__\n\n[options]\npackages = find:\n\n$ cat my_package/__init__.py \n__version__ = "1.0.0"\n\n$ cat pyproject.toml\n\n$ python -c \'from setuptools.config import read_configuration as c; print(c("setup.cfg")["metadata"]["version"])\'\n1.0.0\n\n$ python -c \'from configparser import ConfigParser; c = ConfigParser(); c.read("setup.cfg"); print(c["metadata"]["version"])\'\nattr:my_package.__version__\n\n
Run Code Online (Sandbox Code Playgroud)\n

  • _注意:_ 如果您使用 `pyproject.toml` (带有 `setuptools.build_meta` 后端),那么您根本不需要解析 `setup.cfg` 文件,项目名称和版本将在 TOML 中指定([PEP621](https://peps.python.org/pep-0621/))。那么这种方法就失败了,但是更简单的 `python -c ' from setuptools import setup; setup()' --name` 和 `python3 -c ' from setuptools import setup; setup()' --version` 在任何情况下都应该继续工作。 (2认同)

Cub*_*x48 4

也许使用ConfigParser Python 模块?

python -c "from configparser import ConfigParser; cf = ConfigParser(); cf.read('setup.cfg'); print(cf['metadata']['name'])"
Run Code Online (Sandbox Code Playgroud)

  • 如果所需的元数据是版本,但您遇到声明 `version=attr: my_package.__version__` 的项目,这将导致相当大的问题 https://setuptools.pypa.io/en/latest/userguide/declarative_config.html#specifying -values 这将是做到这一点的方法,现在我滚动得足够多了:/sf/answers/4989348311/ (3认同)