【问题标题】:Any "fromfile_prefix_chars" equivalent for Python-Click任何 \"fromfile_prefix_chars\" 等效于 Python-Click
【发布时间】:2023-01-13 13:42:29
【问题描述】:

对于 argparse 库中可用的 fromfile_prefix_chars 选项,Click (https://click.palletsprojects.com/) 中是否有任何等效项?

有时我有很多论点要移交给基于 Click 的应用程序,并且 - 特别是在使用文件路径时 - 可能会达到某些 Windows 限制。因此,在使用 argparse 时,解决方案是使用 fromfile_prefix_chars 选项。但是,我们现在将转向 Click。

是否有可用的等效功能或是否可以在 Click 中复制此功能?

非常感谢您的帮助。

最好的祝福, gpx瑞奇

【问题讨论】:

  • 似乎没有,自己实现这个似乎微不足道

标签: python argparse python-click


【解决方案1】:

就在这里。你可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-28
    • 2017-05-24
    • 2012-08-17
    • 2018-12-26
    • 2017-03-07
    相关资源
    最近更新 更多