In [1]:
from imp import reload
import autoargs; reload(autoargs);
In [2]:
# pass your function and args from your sys.argv, and you're off to the races!
def myprint(arg1, arg2):
print("arg1:", arg1)
print("arg2:", arg2)
autoargs.autocall(myprint, ["first", "second"])
In [3]:
# if you want your arguments to be types, use any function that expects a string
# and returns the type you want in your arg annotation
def str_repeat(s: str, n: int):
print((s * n).strip())
autoargs.autocall(str_repeat, ["args are easy!\n", "3"])
# if your args value is a string, it gets split using shlex
autoargs.autocall(str_repeat, "'still easy!\n' 3")
In [4]:
import functools
import operator
# varargs are supported too!
def product(*args: float):
return functools.reduce(operator.mul, args, 1.0)
print(autoargs.autocall(product, ["5", "10", "0.5"]))
def join(delimiter, *args):
return delimiter.join(args)
print(autoargs.autocall(join, [", ", "pretty easy", "right?"]))
In [5]:
def aggregate(*args: float, op: {'sum', 'mul'}):
if op == "sum":
return sum(args)
elif op == "mul":
return product(*args)
autoargs.autocall(aggregate, ["--help"])
In [6]:
# kwargs are supported using command-line syntax
def land_of_defaults(a="default-a", argb="b default"):
print(a, argb)
autoargs.autocall(land_of_defaults, []) # => "" (no args in call)
autoargs.autocall(land_of_defaults, ['-aOverride!']) # => "-aOverride!"
autoargs.autocall(land_of_defaults, ['-a', 'Override!']) # => "-a Override!"
autoargs.autocall(land_of_defaults, ['--argb', 'Override!']) # => "--argb Override!"
# warning! if an argument has a default, it can only be given via this kwarg syntax
In [7]:
# if you want to require a kwarg, use a kwonly-arg
def required_arg(normal, default="boring", *, required):
print(normal, default, required)
autoargs.autocall(required_arg, ["normal", "--required", "val"])
autoargs.autocall(required_arg, ["normal"])
In [7]:
def oops(arg: int):
return "%s is an integer!" % arg
autoargs.autocall(oops, [])
In [8]:
autoargs.autocall(oops, ["spam"])
In [9]:
autoargs.autocall(oops, ["20", "spam"])
In [10]:
# if you want access to the parser, go right ahead!
parser = autoargs.autoparser(myprint)
parser
Out[10]:
In [11]:
parsed = parser.parse_args(["first", "second"])
parsed
Out[11]:
In [12]:
vars(parsed)
Out[12]: