Structured programming with optionParser

Michele Simionato michele.simionato at
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
  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;

The line ```` 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 -h
 usage: [-h] [args [args ...]]

 positional arguments:

 optional arguments:
   -h, --help  show this help message and exit

 $ python checkout url
 $ python commit

plac_ takes care of parsing the command line, giving the correct error
message if you pass wrong arguments or not enough arguments::

 $ python 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 -i
 i> .help

 special commands
 .help  .last_tb

 custom commands
 checkout  commit

 i> checkout url
 i> commit

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
 checkout url
 # nontrivial commands here

 $ --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
to work.

More information about the Python-list mailing list