解析配置文件、环境和命令行参数,以获取单个选项集合
问题描述
Python 的标准库有用于配置文件解析的模块(configparser),环境变量读取(os.environ),以及命令行参数解析(argparse).我想编写一个程序来完成所有这些,并且:
Python's standard library has modules for configuration file parsing (configparser), environment variable reading (os.environ), and command-line argument parsing (argparse). I want to write a program that does all those, and also:
具有选项值的级联:
- 默认选项值,被覆盖
- 配置文件选项,被 覆盖
- 环境变量,被 覆盖
- 命令行选项.
允许在命令行中指定一个或多个配置文件位置,例如--config-file foo.conf
,并读取它(代替或附加到通常的配置文件).这仍然必须遵守上述级联.
Allows one or more configuration file locations specified on the command line with e.g. --config-file foo.conf
, and reads that (either instead of, or additional to, the usual configuration file). This must still obey the above cascade.
允许在一个地方定义选项来确定配置文件和命令行的解析行为.
Allows option definitions in a single place to determine the parsing behaviour for configuration files and the command line.
将已解析的选项统一为一个选项值的单一集合,以供程序的其余部分访问,而无需关心它们来自何处.
Unifies the parsed options into a single collection of option values for the rest of the program to access without caring where they came from.
我需要的一切显然都在 Python 标准库中,但它们不能顺利协同工作.
Everything I need is apparently in the Python standard library, but they don't work together smoothly.
如何在与 Python 标准库的偏差最小的情况下实现这一目标?
How can I achieve this with minimum deviation from the Python standard library?
解决方案
似乎标准库没有解决这个问题,让每个程序员都在拼凑 configparser
和 argparse
和 os.environ
以笨拙的方式组合在一起.
It seems the standard library doesn't address this, leaving each programmer to cobble configparser
and argparse
and os.environ
all together in clunky ways.
相关文章