Skip to content

Instantly share code, notes, and snippets.

@Puzer
Last active March 25, 2019 12:39
Show Gist options
  • Save Puzer/7b6f08ec832d0cd4bf540f6fa85ee4a2 to your computer and use it in GitHub Desktop.
Save Puzer/7b6f08ec832d0cd4bf540f6fa85ee4a2 to your computer and use it in GitHub Desktop.
Parse arguments with defaults
from run_something import main as run_something
run_something({'input':'a.txt',
'output':'b.txt'})
# Output: default 5
run_something({'input':'a.txt',
'default':10,
'output':'b.txt'})
# Output: default 10
from argparse import Namespace
def parse_args(argument_parser, prefetched_args=None):
if not prefetched_args:
# If prefetched arguments are empty - just use regular parsing
prefetched_args = argument_parser.parse_args()
else:
# if prefetched arguments are presented - use them and add default from argument_parser
if isinstance(prefetched_args, dict):
prefetched_args = Namespace(**prefetched_args)
for action in argument_parser._actions:
prefetched_args.__dict__[action.dest] = prefetched_args.__dict__.get(action.dest, action.default)
return prefetched_args
import argparse
from parsing_utils import parse_args
def main(args=None):
ap = argparse.ArgumentParser()
ap.add_argument('-i', '--input', required=True)
ap.add_argument('-d', '--default', default=5)
ap.add_argument('-o', '--output', required=True)
args = parse_args(ap, args)
print('default', args.default)
if __name__ == '__main__':
main()
# python run.py -i a.txt -o b.txt
# Output: default 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment