Created
June 24, 2013 20:01
-
-
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.
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
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) |
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(): | |
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