Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Create command line interface from function definition
"""
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()
Owner

fabrixxm commented May 19, 2017 edited

$ python3 climatik.py --help
usage: climatik.py [-h] [--is-pal] [--greeting GREETING] name

Greet the user

positional arguments:
  name

optional arguments:
  -h, --help           show this help message and exit
  --is-pal
  --greeting GREETING
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment