When generating CLI using ArgParse/OptParse we need to create a hierarchy of modules and submodules and link them together. This process is tedious and debugging the errors is cumbersome.
Instead, DocOpt parses the docstring (__doc__) of the file and generates a parser automatically. The docstring should be defined based on POSIX command description syntax.
An example:
$fincalc -h Usage: fincalc (si|simple-interest) -p <principal> -i <interest> -t <tenure> [--daily] [--plot-graph] fincalc (fd|fixed-deposit) -p <principal> -i <interest> -t <tenure> [--plot-graph] fincalc sip -p <principal> -i <interest> -t <tenure> [--plot-graph] fincalc emi -p <principal> -i <interest> -t <tenure> fincalc cagr -p <principal> -r <returns> -t <tenure> fincalc -h | --help Options: -h --help Show this screen. -p --principal Principal -i --interest Interest rate per annum -t --tenure Tenure in years -r --ret --returns Amount returned after investment import docopt opts = docopt.docopt(__doc__)
I have defined a financial calculator which can calculate Simple Interest, Compound Interest, SIP, EMI and CAGR. Lets evaluate the first line:
fincalc (si|simple-interest) -p <principal> -i <interest> -t <tenure> [--daily] [--plot-graph]
* fincalc -- name of the tool
* (si|simple-interest) -- we can use the commands si or simple-interest
* -p <principal> -- parameter p whose values are stored in <principal>
similarly -i <interest> and -t <tenure> define the interest and tenure parameters
* [--daily] -- indicates an optional flag called daily
* [--plot-graph] -- defines an optional flag called plot-graph
Lets do a few test runs:
I have included the Github gist with the code I have written to make this tool. Try it out and leave me your feedback.
Note: You need to have the following libraries installed to try out this script:
* docopt : pip install docopt
* matplotlib : pip install matplotlib [optional library if you want to generate a graph]
Comments