Created
April 21, 2012 15:44
-
-
Save tswicegood/2437861 to your computer and use it in GitHub Desktop.
Fleshed out arg parser based on examples from python.org
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 | |
import sys | |
from pprint import PrettyPrinter | |
pp = PrettyPrinter() | |
task1_parser = argparse.ArgumentParser() | |
task1_parser.add_argument('integers', metavar='N', type=int, nargs='+', | |
help='an integer for the accumulator') | |
task1_parser.add_argument('--sum', dest='accumulate', action='store_const', | |
const=sum, default=max, | |
help='sum the integers (default: find the max)') | |
task2_parser = argparse.ArgumentParser() | |
task2_parser.add_argument('integers', metavar='N', type=int, nargs='+', | |
help='an integer for the accumulator') | |
task2_parser.add_argument('--sum', dest='accumulate', action='store_const', | |
const=sum, default=max, | |
help='sum the integers (default: find the max)') | |
TASKS = { | |
"MAIN": {}, # Pseudo task | |
"task1": { | |
"task": object(), | |
"parser": task1_parser, | |
}, | |
"task2": { | |
"task": object(), | |
"parser": task2_parser, | |
} | |
} | |
TASK_ARGS_MAP = { | |
"MAIN": { | |
"start": 0, | |
"end": None, | |
} | |
} | |
def main(): | |
current_task = "MAIN" | |
for a in sys.argv[1:]: | |
if a in TASKS: | |
task_idx = sys.argv.index(a) | |
TASK_ARGS_MAP[current_task]["end"] = task_idx | |
TASK_ARGS_MAP[a] = { | |
"start": task_idx, | |
"end": None, | |
} | |
current_task = a | |
for task, opts in TASK_ARGS_MAP.items(): | |
if opts["end"] is None: | |
opts["end"] = len(sys.argv) | |
opts["argv"] = sys.argv[opts["start"] + 1:opts["end"]] | |
try: | |
opts["args"] = TASKS[task]["parser"].parse_args(opts["argv"]) | |
except KeyError: | |
pass | |
pp.pprint(TASK_ARGS_MAP) | |
print(TASK_ARGS_MAP["task1"]["args"].accumulate( | |
TASK_ARGS_MAP["task1"]["args"].integers)) | |
print(TASK_ARGS_MAP["task2"]["args"].accumulate( | |
TASK_ARGS_MAP["task2"]["args"].integers)) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Run the above code with args similar to this: