Skip to content

Instantly share code, notes, and snippets.

@Pk13055
Created August 10, 2020 16:40
Show Gist options
  • Save Pk13055/408045d199c778aaa920f52445ee4f2f to your computer and use it in GitHub Desktop.
Save Pk13055/408045d199c778aaa920f52445ee4f2f to your computer and use it in GitHub Desktop.
Pass config file(s) and load default vals in `argparse`
#!/usr/bin/env python3
# coding: utf-8
"""
:author: pk13055
:brief: wrapper script for pars initiation
"""
import argparse
import configparser
from multiprocessing import set_start_method
import sys
def collect_configs(argv=None):
"""Collect arguments
"""
# Do argv default this way, as doing it in the functional
# declaration sets it at compile time.
if argv is None:
argv = sys.argv
# Parse any conf_file specification
# We make this parser with add_help=False so that
# it doesn't parse -h and print help.
conf_parser = argparse.ArgumentParser(
description=__doc__, # printed with -h/--help
# Don't mess with format of description
formatter_class=argparse.RawDescriptionHelpFormatter,
# Turn off help, so we print all options in response to -h
add_help=False
)
conf_parser.add_argument('-c', '--config', dest='configs', action='append',
default=['configs/default.cfg'],
help="configuration file paths")
args, remaining_argv = conf_parser.parse_known_args()
config = configparser.ConfigParser()
success = config.read(args.configs)
failed = list(set(args.configs) - set(success))
def map_value(section: str, k: str):
if config.get(section, k) in ['yes', 'on', 'no', 'off', 'true', 'false', '1', '0']:
return config.getboolean(section, k)
else:
try:
return config.getint(section, k)
except ValueError:
return config.getfloat(section, k)
sections = {
'default': {
k: map_value('DEFAULT', k) for k, v in config.defaults().items()
}
}
[
sections.update({
section: {
k: map_value(section, k) for k in config[section].keys()
}
}) for section in config.sections()
]
# add high level cli options here
parser = argparse.ArgumentParser(parents=[conf_parser])
parser.add_argument('--verbose', '-v', action='count', default=3)
parser.set_defaults(**sections.get('default', dict()))
args = parser.parse_args(remaining_argv)
sections.pop('default') # since args will contain the default values
return sections, args
def main():
section, args = collect_configs()
print(section, args)
# TODO: add code here
if __name__ == "__main__":
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment