-
-
Save major0/cd76e886a3c0b2ab4c1b6e69370f503b to your computer and use it in GitHub Desktop.
Using a decorator to simplify subcommand creation with argparse
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
"""This is free and unencumbered software released into the public domain. | |
Anyone is free to copy, modify, publish, use, compile, sell, or | |
distribute this software, either in source code form or as a compiled | |
binary, for any purpose, commercial or non-commercial, and by any | |
means. | |
In jurisdictions that recognize copyright laws, the author or authors | |
of this software dedicate any and all copyright interest in the | |
software to the public domain. We make this dedication for the benefit | |
of the public at large and to the detriment of our heirs and | |
successors. We intend this dedication to be an overt act of | |
relinquishment in perpetuity of all present and future rights to this | |
software under copyright law. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | |
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. | |
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR | |
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, | |
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR | |
OTHER DEALINGS IN THE SOFTWARE. | |
For more information, please refer to <http://unlicense.org/> | |
""" | |
from argparse import ArgumentParser | |
cli = ArgumentParser() | |
subcommands = { "root": { "parser": cli, "subparser": cli.add_subparsers(dest='subcommand')}} | |
def argument(*name_or_flags, **kwargs): | |
"""Convenience function to properly format arguments to pass to the | |
subcommand decorator. | |
""" | |
return (list(name_or_flags), kwargs) | |
def subcommand(args=[], parent=root, command=None, aliaes=[], subparser=False): | |
"""Decorator to define a new subcommand in a sanity-preserving way. | |
The function will be stored in the ``func`` variable when the parser | |
parses arguments so that it can be called directly like so:: | |
args = cli.parse_args() | |
args.func(args) | |
Usage example:: | |
@subcommand([argument("-d", help="Enable debug mode", action="store_true")]) | |
def subcommand(args): | |
print(args) | |
Then on the command line:: | |
$ python cli.py subcommand -d | |
""" | |
def decorator(func): | |
if name is None: | |
entry = func.__name__ | |
else: | |
entry = name | |
parser = subcommands[parent]["subparser"].add_parser(entry, description=func.__doc__, help=func.__doc__, aliases=aliases) | |
parser.set_defaults(func=func) | |
subcommands[func.__name__] = { "parser": parser } | |
if subparser: | |
# Use `func.__name__` since it is globally unique | |
subcommands[func.__name__]["subparser"] = parser.add_subparsers(dest='subcommand') | |
for arg in args: | |
parser.add_argument(*arg[0], **arg[1]) | |
return decorator | |
@subcommand() | |
def nothing(args): | |
print("Nothing special!") | |
@subcommand([argument("-d", help="Debug mode", action="store_true")]) | |
def test(args): | |
print(args) | |
@subcommand([argument("-f", "--filename", help="A thing with a filename")]) | |
def filename(args): | |
print(args.filename) | |
@subcommand([argument("name", help="Name")]) | |
def name(args): | |
print(args.name) | |
if __name__ == "__main__": | |
args = cli.parse_args() | |
if 'func' not in args: | |
cli.print_help() | |
else: | |
args.func(args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment