Created
August 7, 2018 17:00
-
-
Save righthandabacus/c29ddbce3225b9f76265be6a2886ab87 to your computer and use it in GitHub Desktop.
python argparse sub command decorator
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
import argparse | |
# Expose argparser into global scope | |
_parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) | |
_subcmds = _parser.add_subparsers( | |
title="Commands", | |
description="Available actions", | |
dest="subcmd") | |
# Subcommand argparse decorator | |
def subcommand(args=[], subcmds=_subcmds): | |
"""Decorator to convert a function into a new argparse subcommand, by | |
calling subcmds.add_parser() with name and docstring from the decoratee as | |
name and description, and optionally call subparser.add_argument() if args | |
is provided. Example and recommanded usage: | |
``` | |
@subcommand() | |
def subscribe(*args): | |
"this is subscription" | |
pass | |
if __name__ == '__main__': | |
args = _parser.parse_args() | |
if args.subcmd: | |
args.subcmdfunc(args) | |
else: | |
_parser.print_help() | |
``` | |
Args: | |
args (list): list of lists, each will be arguments to parser.add_argument() | |
subcmds (argparse object): subparser object created by add_subparser(), | |
use _subcmds by default | |
""" | |
def _decorator(function): | |
parser = subcmds.add_parser(function.__name__, description=function.__doc__) | |
for arg in args: | |
parser.add_argument(*arg) | |
parser.set_defaults(subcmdfunc=function) | |
return function | |
return _decorator | |
@subcommand() | |
def alpha(*args): | |
"""job alpha | |
""" | |
print("alpha done") | |
@subcommand() | |
def beta(*args): | |
"""job beta | |
""" | |
print("beta done") | |
def main(): | |
"demonstration of subcommand in argparse" | |
args = _parser.parse_args() | |
if args.subcmd: | |
print("Calling %s()" % args.subcmd) | |
args.subcmdfunc(args) | |
else: | |
_parser.print_help() | |
print("Calling beta() directly") | |
beta() | |
_parser.description = main.__doc__ | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment