Structured programming with optionParser
Michele Simionato
michele.simionato at gmail.com
Tue Aug 31 00:19:08 EDT 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
``plac.Interpreter.call``::
$ cat vcs.py
class VCS(object):
"A fictitious version control tool"
commands = ['checkout', 'commit']
def checkout(self, url):
return 'ok'
def commit(self):
return 'ok'
if __name__ == '__main__':
import plac; plac.Interpreter.call(VCS)
The line ``plac.Interpreter.call`` instantiates the ``VCS`` class by
passing
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 ...]]
positional arguments:
args
optional arguments:
-h, --help show this help message and exit
$ python vcs.py checkout url
ok
$ python vcs.py commit
ok
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
interactive interpreter::
$ python vcs.py -i
i> .help
special commands
================
.help .last_tb
custom commands
===============
checkout commit
i> checkout url
ok
i> commit
ok
There is full help support, i.e. you can ask for ``.help <command>``
for any command, including the special ones such as ``.help`` and
``.last_tb``.
There is full support for autocompletion and command history too,
provided
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
#!vcs.py:VCS
checkout url
# nontrivial commands here
commit
$ plac_runner.py --batch vcs-commands.plac
ok
skip #<lines with comments are skipped>
ok
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
to work.
More information about the Python-list
mailing list