Clipy is a microframework for creating simple and intuitive command line interfaces. It is uses optparse module to parse options, but also can be found useful with argparse.
Let’s try to build simple command line integer calculator. Now, open your favorite text editor and start editing. First we define main command:
from clipy import CompositeCommand
main = CompositeCommand()
Now we define four subcommands for addition, substraction, division and multiplication:
from clipy import Command
class Addition(Command):
summary = "add numbers"
def run(self, options, args, context=None):
a = int(self.challenge("a"))
b = int(self.challenge("b"))
result = a + b
print "a + b = %s" % result
class Substraction(Command):
summary = "substract numbers"
def run(self, options, args, context=None):
a = int(self.challenge("a"))
b = int(self.challenge("b"))
result = a - b
print "a - b = %s" % result
class Division(Command):
summary = "divide numbers"
def run(self, options, args, context=None):
a = int(self.challenge("a"))
b = int(self.challenge("b"))
result = a // b
print "a / b = %s" % result
class Multiplication(Command):
summary = "multiply numbers"
def run(self, options, args, context=None):
a = int(self.challenge("a"))
b = int(self.challenge("b"))
sum = a * b
print "a * b = %s" % result
Now we should add this subcommands to our main command:
main.add_command("add", Addition())
main.add_command("substract", Substraction())
main.add_command("divide", Division())
main.add_command("multiply", Multiplication())
And finnaly we add this lines at the end of the file:
if __name__ == "__main__":
main()
Now, save all this in file called calc.py and execute:
$ python calc.py -h
Usage: examples/calc.py [options]
Options:
-h, --help
Commands:
substract substract numbers
multiply multiply
add add numbers
help print help and exit
divide divide numbers
Ok, now let’s add 2 and 3:
$ python examples/calc.py add
a: 2
b: 3
a + b = 5
It works!