Created
May 11, 2022 03:22
-
-
Save shollingsworth/802321d9473bf70439aef72640a20e1a to your computer and use it in GitHub Desktop.
abstracted argparse subcommand example
This file contains hidden or 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
| #!/usr/bin/env python3 | |
| # -*- coding: utf-8 -*- | |
| """Argparse Subcommand Template.""" | |
| import argparse | |
| from pathlib import Path | |
| MAP = { | |
| "dev": { | |
| "arg1": "foo", | |
| }, | |
| "production": { | |
| "arg1": "bar", | |
| }, | |
| } | |
| def func1(args): | |
| print("func1", args) | |
| def func2(args): | |
| print("func2", args) | |
| ARG_MAP = { | |
| "func1": { | |
| "sub_args": [], | |
| "help": "Run func1", | |
| "func": func1, | |
| }, | |
| "func2": { | |
| "help": "Create a environment ciphertext blob", | |
| "func": func2, | |
| "sub_args": [ | |
| { | |
| "args": ["environment"], | |
| "kwargs": { | |
| "choices": MAP.keys(), | |
| "help": "Environment argument", | |
| }, | |
| }, | |
| { | |
| "args": ["json_file"], | |
| "kwargs": { | |
| "help": "JSON", | |
| "type": Path, | |
| }, | |
| }, | |
| ], | |
| }, | |
| } | |
| def main(): | |
| """Run main function.""" | |
| base_parser = argparse.ArgumentParser( | |
| description=__doc__, | |
| add_help=True, | |
| ) | |
| subparsers = base_parser.add_subparsers(dest="action") | |
| subparsers.required = True | |
| for target, item in ARG_MAP.items(): | |
| sub_p = subparsers.add_parser( | |
| target, | |
| help=item["help"], | |
| ) | |
| for arg in item["sub_args"]: | |
| sub_p.add_argument(*arg["args"], **arg["kwargs"]) | |
| args = base_parser.parse_args() | |
| try: | |
| ARG_MAP[args.action]["func"](args) # type: ignore | |
| except KeyboardInterrupt: | |
| raise SystemExit("Bye!") | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment