Using annotations (python3) and decorators, pyopt aims to ease and simplify exposing python functions to the command line. It's easier than toying with sys.argv and works as though you wrote an entire optparse parser.
The following example auto-generates help with docstrings, usage, type casting for arguments and enforcing argument count:
import pyopt
import random
expose = pyopt.Exposer()
@expose.args
def roll_dice(number_of_faces:int, repetitions:int):
"""
Roll the dice to see if you are lucky or for general D&D pleasure.
number_of_faces - the max value of the die.
repititions - the amount of times to throw the dice.
"""
for i in range(repetitions):
print(random.randint(1, number_of_faces))
expose.run()Notice your code only needs 5 things:
- an import.
- an Exposer instance.
- a decorated function.
- type-annotations for casting (or not if you only need strings)
- a run().
c:\>dice.py -h
Usage: dice.py number_of_faces repetitions
Roll the dice to see if you are lucky or for general D&D pleasure.
number_of_faces - the max value of the die.
repititions - the amount of times to throw the dice.
c:\>dice.py 10
2 arguments required, got only 1. Run with ? or -h for more help.
c:\>dice.py 6 2
5
1
c:\>dice.py 6 2 100
Got 3 arguments and expected at most 2. Run with ? or -h for more help.
c:\>dice.py 6 asdf
Failed parsing 'repetitions', invalid literal for int() with base 10: 'asdf'. Run with ? or -h for more help.Even more Awesome than you think
Check out the Examples for options and exposing multiple functions.