简体   繁体   English

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

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

I have a bit of trouble writing an add argument that supports reading a file path that consists a configuration file of toml package.我在编写支持读取由 toml 包的配置文件组成的文件路径的 add 参数时遇到了一些麻烦。 What I need to write, is a simple command to a CLI where The configuration file can be specified as an option to the CLI: m2mtest --config <file_path> -我需要写的是一个简单的 CLI 命令,其中配置文件可以指定为 CLI 的一个选项: m2mtest --config <file_path> -

this part I think is:这部分我认为是:

    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)

I'm not sure if I wrote it correctly .. What I need to do is:我不确定我是否写对了..我需要做的是:

If the --config option is not specified, look for a file named m2mtest_config.toml in the current directory;如果没有指定--config选项,则在当前目录中查找名为m2mtest_config.toml的文件; if such a file exists, use it.如果存在这样的文件,请使用它。

If no such file exists, then config file is not used for that CLI run---the options to be used are the ones specified in the command line.如果不存在这样的文件,则该 CLI 运行不使用配置文件——要使用的选项是在命令行中指定的选项。

If an option is specified in both the command line and config file, then the command-line value overrides the config-file value如果在命令行和配置文件中都指定了一个选项,则命令行值会覆盖配置文件值

I would really like to get some help implementing that line.我真的很想得到一些帮助来实现这条线。 I know that I do not need to parse the file of the toml config file, since toml.load(f,_dict=dict) does it and saves it into a dict.我知道我不需要解析 toml 配置文件的文件,因为 toml.load(f,_dict=dict) 会这样做并将其保存到字典中。

Thank you very much非常感谢

Did you call parser.parse_args() ?你有没有打电话给parser.parse_args() Also, not sure about the last line in your example.另外,不确定您示例中的最后一行。 I think dict is a reserved word and not a valid variable.认为dict是一个保留字,而不是一个有效的变量。 Also, not sure you need the second argument to loads (not load ).另外,不确定您是否需要loads的第二个参数(不是load )。 Anyway, this works for me:无论如何,这对我有用:

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