Update: this answer still has problems; for example, it cannot handle required arguments and requires a clumsy configuration syntax. Instead, ConfigArgParse seems to be exactly what this question asks for, and is a transparent replacement.
One problem with the current one is that it will not throw an error if the arguments in the configuration file are invalid. Here is a version with another drawback: you need to include the -- or - prefix in the keys.
Here is the Python code ( Gist link with MIT license):
# Filename: main.py import argparse import configparser if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--config_file', help='config file') args, left_argv = parser.parse_known_args() if args.config_file: with open(args.config_file, 'r') as f: config = configparser.SafeConfigParser() config.read([args.config_file]) parser.add_argument('--arg1', help='argument 1') parser.add_argument('--arg2', type=int, help='argument 2') for k, v in config.items("Defaults"): parser.parse_args([str(k), str(v)], args) parser.parse_args(left_argv, args) print(args)
Here is an example configuration file:
Now works
> python main.py --config_file config_correct.conf --arg1 override Namespace(arg1='override', arg2=3, config_file='test_argparse.conf')
However, if our configuration file has an error:
Running the script will result in an error if desired:
> python main.py --config_file config_invalid.conf --arg1 override usage: test_argparse_conf.py [-h] [--config_file CONFIG_FILE] [--arg1 ARG1] [--arg2 ARG2] main.py: error: argument --arg2: invalid int value: 'not an integer!'
The main disadvantage is that it uses parser.parse_args somewhat parser.parse_args to get error checking from ArgumentParser, but I don’t know of any alternatives to this.
Achal Dave Feb 13 '18 at 1:55 2018-02-13 01:55
source share