Last active
May 19, 2017 10:39
-
-
Save fabrixxm/826419ec32398ee9d285923c65afee3f to your computer and use it in GitHub Desktop.
Create command line interface from function definition
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
""" | |
climatik v0.0.1 | |
Create command line interface from function definition | |
""" | |
import inspect | |
import argparse | |
def command(fnc, *args, **kwargs): | |
"""Build command line from function | |
@command | |
def mycommand(positional, optional="default", switch:bool, switchoff=True): | |
... | |
""" | |
parser = argparse.ArgumentParser(description=fnc.__doc__) | |
sig = inspect.signature(fnc) | |
for k in sig.parameters: | |
param = sig.parameters[k] | |
name = param.name | |
arg = {} | |
# let's use annotation type for argument type | |
if not param.annotation is param.empty: | |
arg['type'] = param.annotation | |
# if param has default value, argument is optional | |
if not param.default is param.empty: | |
name = "--"+name | |
arg['default'] = param.default | |
arg['type'] = type(param.default) | |
# if argument type is bool, the argument become a switch | |
if 'type' in arg and arg['type'] is bool: | |
if not name.startswith('--'): | |
name = "--"+name | |
if not 'default' in arg: | |
arg['action']="store_true" | |
else: | |
arg['action']="store_" + str(not arg['default']).lower() | |
del arg['default'] | |
del arg['type'] | |
# "arg_name" to "arg-name" | |
name = name.replace("_", "-") | |
parser.add_argument(name, **arg) | |
def _main(): | |
nsargs = parser.parse_args() | |
args = vars(nsargs) | |
kwargs = { k.replace("-","_"): args[k] for k in args } | |
return fnc(**kwargs) | |
fnc.main = _main | |
return fnc | |
if __name__=="__main__": | |
@command | |
def mytest(name, is_pal:bool, greeting="Hi"): | |
"""Greet the user""" | |
theend = "!" if is_pal else "" | |
print("{} {}{}".format(greeting, name, theend)) | |
mytest.main() |
Author
fabrixxm
commented
May 19, 2017
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment