Last active
April 10, 2021 10:30
-
-
Save Exifers/91623c3886dc49fd2446be5d9d8ba7c3 to your computer and use it in GitHub Desktop.
A nested subparsers CLI in python
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
#! /usr/bin/python3 | |
import argparse | |
def bake_bread(): | |
print('baking bread') | |
def bake_cookies(): | |
print('baking cookies') | |
if __name__ == '__main__': | |
parser = argparse.ArgumentParser() | |
subparsers = parser.add_subparsers(dest='namespace', required=True) | |
parser_bake_subparsers = subparsers \ | |
.add_parser('bake', help='Baking related commands') \ | |
.add_subparsers(dest='command', required=True) | |
parser_bake_subparsers \ | |
.add_parser('bread') \ | |
.set_defaults(func=bake_bread) | |
parser_bake_subparsers \ | |
.add_parser('cookies') \ | |
.set_defaults(func=bake_cookies) | |
namespace = parser.parse_args() | |
if hasattr(namespace, 'func'): | |
namespace.func() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment