Last active
September 15, 2020 11:34
Parse command-line argument defaults from configuration file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def main(args): | |
# parse values from a configuration file if provided and use those as the | |
# default values for the argparse arguments | |
config_argparse = ArgumentParser(prog=__file__, add_help=False) | |
config_argparse.add_argument('-c', '--config-file', | |
help='path to configuration file') | |
config_args, _ = config_argparse.parse_known_args(args) | |
defaults = { | |
'option1': "default value", | |
'option2': "default value" | |
} | |
if config_args.config_file: | |
logger.info("Loading configuration: {}".format(config_args.config_file)) | |
try: | |
config_parser = ConfigParser() | |
with open(config_args.config_file) as f: | |
config_parser.read_file(f) | |
config_parser.read(config_args.config_file) | |
except OSError as err: | |
logger.error(str(err)) | |
sys.exit(1) | |
defaults.update(dict(config_parser.items('options'))) | |
# parse the program's main arguments using the dictionary of defaults and | |
# the previous parsers as "parent' parsers | |
parsers = [config_argparse] | |
main_parser = ArgumentParser(prog=__file__, parents=parsers) | |
main_parser.set_defaults(**defaults) | |
main_parser.add_argument('-1', '--option1') | |
main_parser.add_argument('-2', '--option2') | |
main_args = main_parser.parse_args(args) | |
if __name__ == "__main__": | |
main(sys.argv[1:]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment