-
-
Save nad2000/6520056 to your computer and use it in GitHub Desktop.
Back ported to 2.7 (it should work with earlier versions with added 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
import argparse | |
import inspect | |
class Argumentor: | |
def __init__(self, description=None): | |
self._parser = argparse.ArgumentParser(description=description) | |
self._subparsers = self._parser.add_subparsers() | |
def add(self, description={}): | |
""" | |
@description - argument description dictionary | |
""" | |
def add_decorator(func): | |
subparser = self._subparsers.add_parser(func.__name__, help=func.__doc__) | |
subparser.set_defaults(_func=func) | |
# | |
sig = inspect.getargspec(func) | |
defaults = dict(zip(sig.args[-len(sig.defaults):],sig.defaults)) | |
for idx,name in enumerate(sig.args): | |
arg_help = description.get(name) if description else "Argument #{0}".format(idx+1) | |
if not name in defaults: | |
# a positional argument | |
subparser.add_argument(name, help=arg_help) | |
else: | |
# an optional argument | |
arg_default = defaults.get(name) | |
subparser.add_argument("-" + name[0], "--" + name, | |
help=arg_help, | |
action="store" if arg_default is None else "store_const", | |
const=arg_default) | |
return func | |
return add_decorator | |
def parse(self): | |
args = vars(self._parser.parse_args()) | |
func = args.pop("func", self._parser.print_usage) | |
func(**args) | |
if __name__ == "__main__": | |
""" | |
Usage example: | |
""" | |
parser = Argumentor("An Argumentor Example") | |
@parser.add(dict(some_command="some kind of command", option="an option")) | |
def show(some_command, option = None): | |
"show something" | |
print("some_command:", some_command) | |
print("option:", option) | |
@parser.add(dict(whatever="something completely different", const_option="eat spam")) | |
def do(whatever, const_option = "spam"): | |
"do something" | |
print("whatever:", whatever) | |
print("const_option:", const_option) | |
parser.parse() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment