简体   繁体   中英

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. 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> -

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; 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.

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.

Thank you very much

Did you call 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. Also, not sure you need the second argument to loads (not 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)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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