Last active
March 25, 2019 12:39
-
-
Save Puzer/7b6f08ec832d0cd4bf540f6fa85ee4a2 to your computer and use it in GitHub Desktop.
Parse arguments with defaults
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 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 |
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 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 |
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
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