就在这里。你可以使用default_map to override defaults
您可以通过多种方式做到这一点:
使用 python 字典传递文件
您可以使用 ast.literal_eval 解析 python 字典:
import ast
import click
import os
@click.group()
@click.pass_context
def main(ctx):
config = os.getenv('CLICK_CONFIG_FILE', './click_config')
if os.path.exists(config):
with open(config) as f:
ctx.default_map = ast.literal_eval(f.read())
@main.command()
@click.option("--param", default=2)
def test(param):
print(param)
if __name__ == '__main__':
main()
假设我们有两个配置文件:
# click_config
{
'test': {'param': 3}
}
# config_click
{
'test': {'param': 4}
}
现在,这是您调用命令时发生的情况:
# Highest precedence, overrides any config file
$ python main.py test --param 1
1
# No config file exists. Takes the default, defined in the command
$ python main.py test
2
# Default config file exists, overrides default to 3
$ python main.py test
3
# Custom config file provided, overrides default to 4
$ CLICK_CONFIG_FILE=./config_click python main.py test
4
# Again. The command line has the highest precedence:
$ CLICK_CONFIG_FILE=./config_click python main.py test --param 1
1
传递 yaml 配置文件
你可以关注this answer here 用 yaml 做同样的事情。
传递ini文件
Here可以找到一篇解释如何采用ini文件的文章。
使用扩展(配置格式又是ini)
查看this。