Created
September 8, 2017 14:05
-
-
Save kgaughan/b659d6c173b5a2203dfb3ae225135cce to your computer and use it in GitHub Desktop.
Providing default arguments to argparse.ArgumentParser with a config file.
This file contains hidden or 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
#!/usr/bin/env python | |
from __future__ import print_function | |
import argparse | |
import json | |
import sys | |
def process_args(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument( | |
'--conf', type=argparse.FileType('r'), | |
help='Configuration file' | |
) | |
args, remaining = parser.parse_known_args() | |
defaults = {} | |
if args.conf: | |
try: | |
defaults = json.load(args.conf) | |
except ValueError: | |
print('Error: Could not parse config file', file=sys.stderr) | |
sys.exit(1) | |
finally: | |
args.conf.close() | |
parser.add_argument( | |
'--method', type=str, required=('method' not in defaults), | |
choices=['GET', 'PUT', 'POST', 'DELETE'], | |
help='HTTP method' | |
) | |
parser.add_argument( | |
'--value', type=str, default='foo', | |
help="An argument with a default value" | |
) | |
parser.set_defaults(**defaults) | |
return parser.parse_args(remaining) | |
def main(): | |
print(process_args()) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment