My favorites | Sign in
Project Home Downloads Wiki Issues Source
Project Information
Members
Featured
Wiki pages
Links

What is pyopt

Using annotations (python3) and decorators, pyopt simplifies exposing python functions to the command line. It's easier than toying with sys.argv and works as though you wrote an entire argparse/optparse parser.

You expose functions to the command line as opposed to the usual mode of parsing arguments and calling things manually.

A simple example

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().
And voila! The following functionality is exposed:

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.

Options and exposing multiple functions

Check out the Examples for even more awesome.

Contact

For bugs, ideas etc: ubershmekel at gmail

Powered by Google Project Hosting