Structured programming with optionParser
michele.simionato at gmail.com
Tue Aug 31 06:19:08 CEST 2010
Perhaps, I should give an example of using plac.
For instance, here is how you could implement a SVN-like
tool with two commands ``checkout`` and ``commit``. The trick is to
write a class with two methods ``checkout`` and ``commit`` and an
attribute ``.commands`` listing them, and to call the class with
$ cat vcs.py
"A fictitious version control tool"
commands = ['checkout', 'commit']
def checkout(self, url):
if __name__ == '__main__':
import plac; plac.Interpreter.call(VCS)
The line ``plac.Interpreter.call`` instantiates the ``VCS`` class by
to it the arguments in the command line and then
calls the appropriate method.
You can use the script as follows::
$ python vcs.py -h
usage: vcs.py [-h] [args [args ...]]
-h, --help show this help message and exit
$ python vcs.py checkout url
$ python vcs.py commit
plac_ takes care of parsing the command line, giving the correct error
message if you pass wrong arguments or not enough arguments::
$ python vcs.py checkout
usage: checkout url
checkout: error: too few arguments
You should realize that there is no real difference between a
command-line argument parser featuring subcommands and an command
interpreter, therefore the previous script also works as an
$ python vcs.py -i
i> checkout url
There is full help support, i.e. you can ask for ``.help <command>``
for any command, including the special ones such as ``.help`` and
There is full support for autocompletion and command history too,
you have the readline library installed (on Unices) or the pyreadline
library (on Windows).
plac also support a batch mode: you can write a set of commands on
a file and have them executed by the plac runner.
$ echo vcs-commands.plac
# nontrivial commands here
$ plac_runner.py --batch vcs-commands.plac
skip #<lines with comments are skipped>
For more (including managing options, which I have not shown here) you
should check the full documentation of plac.
I have just uploaded release 0.7.2, which is required for this example
More information about the Python-list