Skip to content

Instantly share code, notes, and snippets.

@alexvicegrab
Last active February 9, 2018 14:06
Show Gist options
  • Save alexvicegrab/19fa71baaee1d15812aa61974d0fee90 to your computer and use it in GitHub Desktop.
Save alexvicegrab/19fa71baaee1d15812aa61974d0fee90 to your computer and use it in GitHub Desktop.
Python argparse with either a template or options
#! /usr/bin/env python
"""
If template file "template.conf" contains:
["--foo", "sausage", "--bar", "egg"]
Calling:
$ python ./parser.py template template.conf
Will be equivalent to calling:
$ python ./parser.py options --foo sausage --bar egg
And the initial option we attach to the parser needs to appear before the command:
$ python -v ./parser.py template template.conf
"""
import argparse
import json
def arguments_from_template(arguments, parser):
if 'template_fn' in arguments:
if arguments.verbose:
print('Arguments with template action:')
print(json.dumps(vars(arguments)))
ind_args = []
with open(arguments.template_fn) as f:
template_dict = json.load(f)
for key, value in template_dict.items():
if value:
ind_args.extend(['--' + key, str(value)])
else:
ind_args.extend(['--' + key])
ind_args.insert(0, "options")
orig_args = arguments
arguments = parser.parse_args(ind_args)
arguments.__dict__.update(vars(orig_args))
if arguments.verbose:
print('Arguments with options action:')
print(json.dumps(vars(arguments)))
return arguments
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Template parser example')
# Add an argument that works for all parsers
parser.add_argument('-v', '--verbose', action='store_true',
help='Do we print the results we obtain after running the commands?')
subparsers = parser.add_subparsers(help='commands')
# Add a subparser for the template action
subparse_template = subparsers.add_parser('template', help='Use a template')
subparse_template.add_argument('template_fn', help='Template to use')
# Add a subparser for the individual option action
subparse_args = subparsers.add_parser('options', help='Use arguments')
subparse_args.add_argument('-f', '--foo', required=True, type=str,
help='Foo value')
subparse_args.add_argument('-b', '--bar', required=True, type=str,
help='Bar value')
arguments = parser.parse_args()
# If we are using the template command...
arguments = arguments_from_template(arguments, parser)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment