Skip to content

Instantly share code, notes, and snippets.

@drsm79
Created June 24, 2013 20:01
Show Gist options
  • Save drsm79/5853087 to your computer and use it in GitHub Desktop.
Save drsm79/5853087 to your computer and use it in GitHub Desktop.
I wanted a way to get my argparser to read args from a config file, so came up with this.
from argparse import Action, FileType, _ensure_value
class ConfigAction(Action):
"""
Given a json file ConfigAction will populate the parser with properties
defined in the json. This won't override settings from other actions or
allow settings not defined in the parser initialisation.
"""
def __init__(self,
option_strings,
dest,
default=None,
required=False,
help=None):
super(ConfigAction, self).__init__(
option_strings=option_strings,
dest=dest,
nargs=1,
default=default,
type=FileType('r'),
required=required,
help=help)
def __call__(self, parser, namespace, values, option_string=None):
cfg_values = {}
# get all
destinations = [getattr(x, 'dest') for x in parser._actions]
for i in values:
cfg_values.update(json.load(i))
for k, v in cfg_values.items():
if k in destinations:
if parser.get_default(k) == _ensure_value(namespace, k, v):
setattr(namespace, k, v)
def main():
parser = argparse.ArgumentParser(
description='Do some things'
)
parser.register('action', 'config', ConfigAction)
parser.add_argument('--config', action='config')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment