Skip to content

Instantly share code, notes, and snippets.

@turtlemonvh
Last active October 8, 2023 23:04
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save turtlemonvh/051e1034aa11cf2b3ae7fe30bf370dfe to your computer and use it in GitHub Desktop.
Save turtlemonvh/051e1034aa11cf2b3ae7fe30bf370dfe to your computer and use it in GitHub Desktop.
Multi-level arg parse

Multi-level arg parse

Shows how to structure a python app using arg parse that goes down many levels.

The "trick" is to

  • add a subparsers S1[]
  • add parsers P1[] to your subparser S1[x]
  • add a new set of subparsers S2[] to one of those parsers P1[x]

You can keep going from there.

Some other tips:

  • use lots of if statements
  • group parsers and add common arguments in loops
#!/usr/bin/env python
import argparse
"""Multi-level argparse example
# 2 commands down
python multilevel_argparse.py do thing
python multilevel_argparse.py do thing -f
# All levels get help text
python multilevel_argparse.py -h
python multilevel_argparse.py do -h
python multilevel_argparse.py do thing -h
"""
def do(options):
if options.method == "thing":
if options.force:
print("Doing it")
else:
print("Not doing it")
if __name__ == "__main__":
p = argparse.ArgumentParser(description="So deep!.")
action_sp = p.add_subparsers(help='commands', dest='action')
# Top level
do_action_p = action_sp.add_parser('do', help='Do something')
##
# Do parsers
##
do_action_sp = do_action_p.add_subparsers(help='Method to perform', dest='action')
do_action_thing_p = do_action_sp.add_parser('thing', help='Do the thing.')
do_force_parsers = [do_action_thing_p]
for p in do_force_parsers:
p.add_argument('-f', '--force',
default=False,
dest="force",
action='store_true',
help="Do with abandon."
)
##
# End argparse setup. Parse and start doing actions.
##
options = p.parse_args()
if options.action == 'do':
do(options)
@turtlemonvh
Copy link
Author

Because there is only 1 command on each level argparse compressed the help message a bit so calling help even on the top level shows this

$ python multilevel_argparse.py -h
usage: multilevel_argparse.py do thing [-h] [-f]

optional arguments:
  -h, --help   show this help message and exit
  -f, --force  Do with abandon.

If you add more commands on each level that changes.

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