Skip to content

Instantly share code, notes, and snippets.

@tswicegood
Created April 21, 2012 15:44
Show Gist options
  • Save tswicegood/2437861 to your computer and use it in GitHub Desktop.
Save tswicegood/2437861 to your computer and use it in GitHub Desktop.
Fleshed out arg parser based on examples from python.org
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()
@tswicegood
Copy link
Author

Run the above code with args similar to this:

$ python invoke_args.py task1 1 2 3 5 --sum task2 2 3 4
{'MAIN': {'argv': [], 'end': 1, 'start': 0},
 'task1': {'args': Namespace(accumulate=<built-in function sum>, integers=[1, 2, 3, 5]),
           'argv': ['1', '2', '3', '5', '--sum'],
           'end': 7,
           'start': 1},
 'task2': {'args': Namespace(accumulate=<built-in function max>, integers=[2, 3, 4]),
           'argv': ['2', '3', '4'],
           'end': 11,
           'start': 7}}
11
4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment