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

2024-09-29 23:17:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我在编写一个add参数时遇到了一些问题,该参数支持读取由toml包的配置文件组成的文件路径。 我需要编写的是一个简单的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中

多谢各位


Tags: 文件命令行路径addconfigparserfor参数
1条回答
网友
1楼 · 发布于 2024-09-29 23:17:17

你打电话给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)}

相关问题 更多 >

    热门问题