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

问题描述

编写一个支持读取包含toml软件包的配置文件文件路径的add参数时,我有些麻烦。 我需要编写的是对CLI的简单命令,其中 可以将配置文件指定为CLI的一个选项:m2mtest --config -

我认为这部分是:

    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)会执行该操作并将其保存到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)}