我想在 python 3.9 中解析 TOML 文件,我想知道是否可以在不安装另一个包的情况下这样做。
既然
pip
知道如何使用 pyproject.toml
文件,并且我已经安装了 pip
,那么 pip
是否提供了一个可以在我自己的代码中导入和使用的解析器?
。就在pip github repo中搜索“pyproject.toml”后,我在源代码中找到了以下函数::
def load_pyproject_toml(
use_pep517: Optional[bool], pyproject_toml: str, setup_py: str, req_name: str
) -> Optional[BuildSystemDetails]:
"""Load the pyproject.toml file.
Parameters:
use_pep517 - Has the user requested PEP 517 processing? None
means the user hasn't explicitly specified.
pyproject_toml - Location of the project's pyproject.toml file
setup_py - Location of the project's setup.py file
req_name - The name of the requirement we're processing (for
error reporting)
Returns:
None if we should use the legacy code path, otherwise a tuple
(
requirements from pyproject.toml,
name of PEP 517 backend,
requirements we should check are installed after setting
up the build environment
directory paths to import the backend from (backend-path),
relative to the project root.
)
"""
has_pyproject = os.path.isfile(pyproject_toml)
has_setup = os.path.isfile(setup_py)
if not has_pyproject and not has_setup:
raise InstallationError(
f"{req_name} does not appear to be a Python project: "
f"neither 'setup.py' nor 'pyproject.toml' found."
)
if has_pyproject:
with open(pyproject_toml, encoding="utf-8") as f:
pp_toml = tomli.loads(f.read())
...
tomli
在
顶部导入:
from pip._vendor import tomli
检查 REPL
>>> from pip._vendor import tomli
>>> tomli.loads('[foo]\nbar = "baz"')
{'foo': {'bar': 'baz'}}
当然,这不是公共 API 的一部分,您应该真的
不要依赖它。
tomllib
,如果失败,请导入 wim 提到的供应版本:
try: import tomllib
except ModuleNotFoundError: import pip._vendor.tomli as tomllib
由于 API 是相同的(或者足够接近我需要的),因此无需进一步更改代码即可运行良好。我还确认了上面提到 Python 3.8 中的
pip._vendor.toml
的评论是不正确的;这是
tomli
,就像所有其他人一样。但是,这适用于“现代”版本的 pip,它只能在 3.7 及更高版本上使用。 Python 3.6 及更低版本有 自己独立的 版本,并且 3.6 中似乎没有供应商的 TOML 库。由于在我的特定情况下,我只是在安装这些软件包及其依赖项之前使用它对
pyproject.toml
文件进行一点解析,并且无论如何我总是使用虚拟环境,所以我决定最好的选择是保持简单:直接从 PyPI 安装
tomli
包并仅使用它,省去了多次不同检查的麻烦。但是,如果您仅支持 Python 3.7 及更高版本,则上述可能是最简单的解决方案之一。