reading a TOML config file from CLI with argparse

1.9k views Asked by At

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

1

There are 1 answers

0
Ryan On

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)}