繁体   English   中英

使用 argparse 从 CLI 读取 TOML 配置文件

[英]reading a TOML config file from CLI with argparse

我在编写支持读取由 toml 包的配置文件组成的文件路径的 add 参数时遇到了一些麻烦。 我需要写的是一个简单的 CLI 命令,其中配置文件可以指定为 CLI 的一个选项: m2mtest --config <file_path> -

这部分我认为是:

    parser.add_argument('--config', type=argparse.FileType('r'), help='A configuration file for the CLI', default = [ f for f in os.listdir( '.' )
                            if os.path.isfile( f ) and f == "m2mtest_config.toml"],
                dest = 'config' )
    if parser.config is not None:
        dict = toml.load(parser.config, _dict=dict)

我不确定我是否写对了..我需要做的是:

如果没有指定--config选项,则在当前目录中查找名为m2mtest_config.toml的文件; 如果存在这样的文件,请使用它。

如果不存在这样的文件,则该 CLI 运行不使用配置文件——要使用的选项是在命令行中指定的选项。

如果在命令行和配置文件中都指定了一个选项,则命令行值会覆盖配置文件值

我真的很想得到一些帮助来实现这条线。 我知道我不需要解析 toml 配置文件的文件,因为 toml.load(f,_dict=dict) 会这样做并将其保存到字典中。

非常感谢

你有没有打电话给parser.parse_args() 另外,不确定您示例中的最后一行。 认为dict是一个保留字,而不是一个有效的变量。 另外,不确定您是否需要loads的第二个参数(不是load )。 无论如何,这对我有用:

import argparse
import os
import toml

parser = argparse.ArgumentParser()

parser.add_argument(
    '--config', 
    type=argparse.FileType('r'), 
    help='A configuration file for the CLI', 
    default = [ 
        f for f in os.listdir( '.' ) 
        if os.path.isfile( f ) and f == "m2mtest_config.toml"
    ], 
    dest = 'config' 
)

args = parser.parse_args()
toml_config = toml.loads(parser.config) if args.config else {}

# merge command line config over config file
config = {**toml_config, **vars(args)}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM