summaryrefslogtreecommitdiff
path: root/plac/doc/plac_adv.txt
blob: d8a421c97774993aaa1385865bcd074e3f049dd5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
Testing and scripting your applications with plac
=========================================================

:Author: Michele Simionato
:E-mail: michele.simionato@gmail.com
:Date: June 2010
:Download page: http://pypi.python.org/pypi/plac
:Project page: http://micheles.googlecode.com/hg/plac/doc/plac.html
:Installation: ``easy_install -U plac``
:License: BSD license
:Requires: Python 2.5+

*The present document discusses a few of the advanced use
cases for plac.  It assumes you have already read an understood the
basic documentation.*

.. contents::

Introduction
-----------------------------------------------------

One of the design goals of plac_ is to make it dead easy to write a
scriptable and testable interface for an application.  You can use
plac_ whenever you have an API with strings in input and strings in
output, and that includes a *huge* domain of applications.

A string-oriented interface is a scriptable interface by
construction. That means that you can define a command language for
your application and that it is possible to write scripts which are
interpretable by plac_ and can be run as batch scripts.

Actually, at the most general level, you can see plac_ as a generic tool to
write domain specific languages (DSL). With plac_ you
can test your application interactively as well as with batch
scripts, and even with the analogous of Python doctests for your
defined language.

You can easily replace the ``cmd`` module of the standard library and
you could easily write an application like twill_ with plac_. Or you
could use it to script your building procedure. Or any other thing,
your imagination is the only limit!

From scripts to interactive applications
------------------------------------------------------------

Command-line scripts have many advantages, but are no substitute
for interactive applications.
In particular, if you have a script with a large startup time which must be run
multiple times, it is best to turn it into an interactive application,
so that the startup is performed only once.  ``plac`` provides an
``Interpreter`` class just for this purpose. 

The ``Interpreter`` class wraps the main function of a script and
provides an ``.interact`` method to start an interactive interpreter
reading commands from the console.

For instance, you can define an interactive interpreter on top of the
``ishelve`` script introduced in the `basic documentation`_ as
follows:

.. include:: shelve_interpreter.py
   :literal:

A trick has been used here: the ishelve command-line interface has been
hidden inside an external interface. They are distinct: for instance
the external interface recognizes the ``-h/--help`` flag whereas the
internal interface only recognizes the ``.help`` command::

 $ python shelve_interpreter.py -h

.. include:: shelve_interpreter.help
   :literal:

Thanks to this ingenuous trick, the script can be run both interactively
and non-interactively::

 $ python shelve_interpreter.py .clear # non-interactive use
 cleared the shelve

Here is an usage session, using rlwrap_ to enable readline features
(rlwrap_ is available in Unix-like systems)::

 $ rlwrap python shelve_interpreter.py -i # interactive use
 usage: shelve_interpreter.py [.help] [.showall] [.clear] [.delete DELETE]
                              [.filename /home/micheles/conf.shelve]
                              [params [params ...]] [setters [setters ...]]
 i> a=1
 setting a=1
 i> a
 1
 i> b=2
 setting b=2
 i> a b
 1
 2
 i> .del a
 deleted a
 i> a
 a: not found
 i> .show
 b=2
 i> [CTRL-D]

The ``.interact`` method 
reads commands from the console and send them to the
underlying interpreter, until the user send a CTRL-D
command (CTRL-Z in Windows). There is a default
argument ``prompt='i> '`` which
can be used to change the prompt. The message displayed
by default is the argparse-provided usage message, but can be
customized by setting an ``.intro`` attribute on the main function.

Notice that ``plac.Interpreter`` is available only if you are using a recent
version of Python (>= 2.5), because it is a context manager object
which uses extended generators internally.

You can conveniently test your application in interactive mode.
However manual testing is a poor substitute for automatic testing.

Testing a plac application
-----------------------------------------------------------

In principle, one could write automatic tests for the
``ishelve`` application by using ``plac.call`` directly:

.. include:: test_ishelve.py
   :literal:

However, using ``plac.call`` is not especially nice. The big
issue is that ``plac.call`` responds to invalid input by printing an
error message on stderr and by raising a ``SystemExit``: this is
certainly not a nice thing to do in a test.

As a consequence of this behavior it is impossible to test for invalid
commands, unless you wrap the ``SystemExit`` exception by
hand each time (a possibly you do something with the error message in
stderr too). Luckily, ``plac`` offers a better testing support through
the ``check`` method of ``Interpreter`` objects:

.. include:: test_ishelve_more.py
   :literal:

The method ``.check(given_input, expected_output)`` works on strings
and raises an ``AssertionError`` if the output produced by the
interpreter is different from the expected output for the given input.

``AssertionError`` is catched by tools like ``py.test`` and
``nosetests`` and actually ``plac`` tests are intended to be run with
such tools.

Interpreters offer a minor syntactic advantage with respect to calling
``plac.call`` directly, but they offer a *major* semantic advantage when things
go wrong (read exceptions): an ``Interpreter`` object internally invokes
something like ``plac.call``, but it wraps all exceptions, so that ``i.check``
is guaranteed not to raise any exception except ``AssertionError``.

Even the ``SystemExit`` exception is captured and you can write your test as

    ``i.check('-cler', 'SystemExit: unrecognized arguments: -cler')``

without risk of exiting from the Python interpreter.

There is a second advantage of interpreters: if the main function contains some
initialization code and finalization code
(``__enter__`` and ``__exit__`` functions) they will be run only
once at the beginning and at the end of the interpreter loop.
``plac.call`` instead ignores the initialization/finalization code.

Plac easy tests
---------------------------------------------------------

Writing your tests in terms of ``Interpreter.check`` is certainly an
improvement over writing them in terms of ``plac.call``, but they
are still too low-level for my taste. The ``Interpreter`` class provides 
support for doctest-style tests, a.k.a. *plac easy tests*.

By using plac easy tests you can cut and paste your interactive session and
turn it into a runnable automatics test!
Consider for instance the following file ``ishelve.placet`` (the ``.placet``
extension is a mnemonic for plac easy tests):

.. include:: ishelve.placet
   :literal:

Notice the precence of the shebang line containing the name of the
plac_ tool to test (a plac_ tool is just a Python module with a
function called ``main``). The shebang is ignored by the interpreter
(it looks like a comment to it) but it is there so that external
tools (say a test runner) can infer the plac interpreter
to use to test the file.

You can test ``ishelve.placet`` file by calling the
``.doctest`` method of the interpreter, as in this example::

 $ python -c"import plac, ishelve
 plac.Interpreter(ishelve.main).doctest(open('ishelve.placet'), verbose=True)"

Internally ``Interpreter.doctests`` invokes something like ``Interpreter.check``
multiple times inside the same context and compare the output with the
expected output: if even a check fails, the whole test fail. The
easy tests supported by ``plac`` are *not* unittests: they should be
used to model user interaction when the order of the operations
matters.  Since the single subtests in a ``.placet`` file are not
independent, it makes sense to exit immediately at the first failure.

The support for doctests in plac_ comes nearly for free, thanks to the shlex_
module in the standard library, which is able to parse simple
languages as the ones you can implement with plac_. In particular,
thanks to shlex_, plac_ is able to recognize comments (the default
comment character is ``#``), continuation lines, escape sequences and
more. Look at the shlex_ documentation if you need to customize how
the language is interpreted.

In addition, I have implemented from scratch some support for line number
recognition, so that if a test fail you get the line number of the
failing command. This is especially useful if your tests are
stored in external files (plac easy tests does not need to be in
a file: you can just pass to the ``.doctest`` method a list of
strings corresponding to the lines of the file).

At the present plac easy tests do not use any code from the doctest
module, but the situation may change in the future (it would be nice
if plac_ could reuse doctests directives like ELLIPSIS).

It is straighforward to integrate your ``.placet`` tests with standard
testing tools. For instance, you can integrate your doctests with ``nose``
or ``py.test`` as follow::

 import os, shlex, plac
 
 def test_doct():
    """
    Find all the doctests in the current directory and run them with the
    corresponding plac interpreter (the shebang rules!)
    """
    placets = [f for f in os.listdir('.') if f.endswith('.placet')]
    for placet in placets:
        lines = list(open(placet))
        assert lines[0].startswith('#!'), 'Missing or incorrect shebang line!'
        firstline = lines[0][2:] # strip the shebang
        main = plac.import_main(*shlex.split(firstline))
        yield plac.Interpreter(main).doctest, lines[1:]

Here you should notice that usage of ``plac.import_main``, an utility
which is able to import the main function of the script specified in
the shabng line. You can use both the full path name of the
tool, or a relative path name. In this case the runner look at the
environment variable ``PLACPATH`` and it searches
the plac tool in the directories specified there (``PLACPATH`` is just
a string containing directory names separated by colons). If the variable
``PLACPATH`` is not defined, it just looks in the current directory.
If the plac tool is not found, an ``ImportError`` is raised.

Plac batch scripts
--------------------------------------------------

It is pretty easy to realize that an interactive interpreter can
also be used to run batch scripts: instead of reading the commands from
the console, it is enough to read the commands from a file.
plac_ interpreters provide an ``.execute`` method to perform just that.

There is just a subtle point to notice: whereas in an interactive loop
one wants to manage all exceptions, a batch script should not in the
background in case of unexpected errors. The implementation of
``Interpreter.execute`` makes sure that any error raised by
``plac.call`` internally is re-raised.  In other words, plac_
interpreters *wrap the errors, but does not eat them*: the errors are
always accessible and can be re-raised on demand.

In particular consider the following batch file, which contains a syntax
error (``.dl`` instead of ``.del``):

.. include:: ishelve.plac
   :literal:

If you execute the batch file, the interpreter will raise a ``SystemExit``
with an appropriated error message at the ``.dl`` line and the last command
will *not* be executed::

 $ python -c "import plac, ishelve
 plac.Interpreter(ishelve.main).execute(open('ishelve.plac'), verbose=True)" 
 i> .clear 
 cleared the shelve
 i> a=1 b=2
 setting a=1
 setting b=2
 i> .show
 b=2
 a=1
 i> .del a
 deleted a
 i> .dl b
 unrecognized arguments: .dl

The ``verbose`` flag is there to show the lines which are being interpreted
(prefixed by ``i>``). This is done on purpose, so that you can cut and paste
the output of the batch script and turn it into a ``.placet`` test
(cool, isn't it?).

Containers of commands 
----------------------------------------

When I discussed the ``ishelve`` implementation in the `basic
documentation`_, I said that it looked like a poor man implementation
of an object system as a chain of elifs; I also said that plac_ was
able to do better.  Here I will substantiate my claim.

plac_ is actually able to infer a set of subparsers from a
generic container of commands.  This is useful if you want to
implement *subcommands* (a familiar example of a command-line
application featuring subcommands is subversion).

Technically a container of commands is any object with a ``.commands`` attribute
listing a set of functions or methods which are valid commands. A command
container may have initialization/finalization hooks (``__enter__/__exit__``)
and dispatch hooks (``__missing__``, invoked for invalid command names).

Using this feature the shelve interface can be rewritten in a more
object-oriented way as follows:

.. include:: ishelve2.py
   :literal:

``plac.Interpreter`` objects wrap context manager objects
consistently.  In other words, if you wrap an object with
``__enter__`` and ``__exit__`` methods, they are invoked in the right
order (``__enter__`` before the interpreter loop starts and
``__exit__`` after the interpreter loop ends, both in the regular and
in the exceptional case). In our example, the methods ``__enter__``
and ``__exit__`` make sure the the shelve is opened and closed
correctly even in the case of exceptions. Notice that I have not
implemented any error checking in the ``show`` and ``delete`` methods
on purpose, to verify that plac_ works correctly in the presence of
exceptions.

Here is a session of usage on an Unix-like operating system::

 $ rlwrap python ishelve2.py
 Operating on /home/micheles/conf.shelve. Available commands:
 set
 show
 showall
 delete
 i> delete
 deleting everything
 i> set a pippo
 setting a=pippo
 i> set b lippo
 setting b=lippo
 i> showall
 b = lippo
 a = pippo
 i> show a b
 a = pippo
 b = lippo
 i> del a
 deleting a
 i> showall
 b = lippo
 i> delete a     
 DBNotFoundError: (-30988, 'DB_NOTFOUND: No matching key/data pair found')
 i> 

Notice that in interactive mode the traceback is hidden, unless
you pass the ``verbose`` flag to the ``Interpreter.interact`` method.

The interactive mode of ``plac`` can be used as a replacement of the 
``cmd`` module in the standard library. There are a few differences,
however. For instance you miss tab completion, even if use rlwrap_
(you get persistent command history for free, however). This is not
a big issue, since ``plac`` understands command abbreviations.

If an abbreviation is ambiguous, plac_ warns you::

 $ rlwrap python ishelve2.py
 usage: plac_runner.py ishelve2.py [-h] {delete,set,showall,show} ...
 i> sh
 NameError: Ambiguous command 'sh': matching ['showall', 'show']

For ``cmd`` lovers
--------------------------------------------------------

I have been using the cmd_ module of the standard library for years.
I have also written a much enhanced ``cmd2`` module which we are using
internally at work and from which I have taken some ideas used in plac_.
In many ways plac_ makes the cmd_ module obsolete,
but I realize why many nostalgic souls would still use cmd_, especially
until plac_ does not grow real auto-completion features, instead of
relying on rlwrap_. But there must not be competition between plac_
and cmd_: actually the two can happily work togethere. For this
reason I have put in the ``plac_ext`` module a few lines of code
for gluing together cmd_ and plac_, the ``cmd_interface``.
Using the ``cmd_interface`` is quite trivial: give to it a plac
command container and you will get in exchange a ``cmd.Cmd`` object:

.. include:: cmd_ex.py
 :literal:

Here is an example of interactive session::

 $ python cmd_ex.py 
 (Cmd) help 
 
 Documented commands (type help <topic>):
 ========================================
 delete  set  show  showall
 
 Undocumented commands:
 ======================
 EOF  help
 
 (Cmd) set a 1
 setting a=1
 (Cmd) show a
 a = 1
 (Cmd) showall 
 a = 1
 (Cmd) delete b
 KeyError: 'b'
 (Cmd) EOF [or CTRL-D]

Internally the ``cmd_interface`` builds a ``cmd.Cmd`` class and adds
to it the ``do_`` methods corresponding to the commands in the container,
then it returns a ``cmd.Cmd`` instance.

The ``cmd_interface`` is just a proof of concept: it is there so that you
can study the source code and see an example of integration of plac_
with a different framework. It may change and even go away in future
releases of plac_.

The plac runner
--------------------------------------------------------

The distribution of plac_ includes a runner script named ``plac_runner.py``,
which will be installed in a suitable directory in your system by distutils_
(say in ``\usr\local\bin\plac_runner.py`` in a Unix-like operative system).
The runner provides many facilities to run ``.plac`` scripts and
``.placet`` files, as well as Python modules containg a ``main``
object, which can be a function, a command container object or
even a command container class.

For instance, suppose you want to execute a script containing commands
defined in the ``ishelve2`` module like the following one:

.. include:: ishelve2.plac
   :literal:

The first line of the ``.plac`` script contains the name of the
python module containing the plac interpreter and the arguments
which must be passed to its main function in order to be able
to instantiate an interpreter object. The other lines contains
commands. Then you can run the script as follows::

 $ plac_runner.py --batch ishelve2.plac
 setting a=1
 deleting a
 Traceback (most recent call last):
   ...
 _bsddb.DBNotFoundError: (-30988, 'DB_NOTFOUND: No matching key/data pair found')

The last command intentionally contained an error, to show that the
plac runner does not eat the traceback.

The runner can also be used to run Python modules in interactive
mode and non-interactive mode. If you put this alias in your bashrc

  ``alias plac="rlwrap plac_runner.py"``

(or you define a suitable ``plac.bat`` script in Windows) you can
run the ``ishelve2.py`` script in interactive mode as
follows::

 $ plac -i ishelve2.py
 Operating on /home/micheles/conf.shelve. Available commands:
 set
 show
 showall
 delete
 i> del
 deleting everything
 i> set a 1
 setting a=1
 i> set b 2
 setting b=2
 i> show b
 b = 2

Now you can cut and paste the interactive session an turns into into
a ``.placet`` file like the following:

.. include:: ishelve2.placet
   :literal:

Notice that the first line specifies a test database
``~/test.shelve``, to avoid clobbering your default shelve. If you
mispell the arguments in the first line plac will give you an
argparse_ error message (just try).

You can run placets following the shebang convention directly with
the plac runner::

 $ plac --test ishelve2.placet
 run 1 plac test(s)

If you want to see the output of the tests, pass the ``-v/--verbose`` flag.
Notice that he runner ignore the extension, so you can actually use any
extension your like, but *it relies on the first line of the file to invoke
the corresponding plac tool with the given arguments*.

The plac runner does not provide any test discovery facility,
but you can use standard Unix tools to help. For instance, you can
run all the ``.placet`` files into a directory and its subdirectories
as follows::

 $ find . -name \*.placet | xargs plac_runner.py -t

The plac runner expects the main function of your script to
return a plac tool, i.e. a function or an object with a ``.commands``
attribute. It this is not the case the runner gracefully exits.

It also works in non-interactive mode, if you call it as

  ``$ plac module.py args ...``

Here is an example::

 $ plac ishelve.py a=1
 setting a=1
 $ plac ishelve.py .show
 a=1

Notice that it non-interactive mode the runner just invokes ``plac.call``
on the ``main`` object of the Python module.

A non class-based example
--------------------------------------------------------

plac_ does not force you to use classes to define command containers.
Even a simple function can be a valid command container, it is
enough to add to it a ``.commands`` attribute and possibly
``__enter__`` and/or ``__exit__`` attributes.

In particular, a Python module is a perfect container of commands. As an
example, consider the following module implementing a fake Version
Control System:

.. include:: vcs.py
   :literal:

Notice that I have defined both an ``__exit__`` hook and a ``__missing__``
hook, invoked for non-existing commands.
The real trick here is the line ``main = __import__(__name__)``, which
define ``main`` to be an alias for the current module.

The ``vcs`` module does not contain an ``if __name__ == '__main__'``
block, but you can still run it through the plac runner
(try ``plac vcs.py -h``):

.. include:: vcs.help
   :literal:

You can get help for the subcommands by postponing ``-h`` after the
name of the command::
 
 $ plac vcs.py status -h
 usage: vcs.py status [-h] [-q]
 
 A fake status command
 
 optional arguments:
   -h, --help   show this help message and exit
   -q, --quiet  summary information

Notice how the docstring of the command is automatically shown in
usage message, as well as the documentation for the sub flag ``-q``.

Here is an example of a non-interactive session::

 $ plac vcs.py check url
 checkout 
 url
 $ plac vcs.py st -q
 status 
 True
 $ plac vcs.py co
 commit 
 None

and here is an interactive session::

 $ plac -i vcs.py
 usage: plac_runner.py vcs.py [-h] {status,commit,checkout} ...
 i> check url
 checkout 
 url
 i> st -q
 status 
 True
 i> co
 commit 
 None
 i> sto
 Command 'sto' does not exist
 i> [CTRL-D]
 ok

Notice the invocation of the ``__missing__`` hook for non-existing commands.
Notice also that the ``__exit__`` hook gets called only in interactive
mode.

If the commands are completely independent, a module is a good fit for
a method container. In other situations, it is best to use a custom
class. 

Writing your own plac runner
----------------------------------------------------------

The runner included in the plac_ distribution is intentionally kept
small (around 50 lines of code) so that you can study it and write
your own runner if want to. If you need to go to such level
of detail, you should know that the most important method of
the ``Interpreter`` class is the ``.send`` method, which takes
strings in input and returns a four-tuple with attributes
``.str``, ``.etype``, ``.exc`` and ``.tb``:

- ``.str`` is the output of the command, if successful (a string);
- ``.etype`` is the class of the exception, if the command fail;
- ``.exc`` is the exception instance;
- ``.tb`` is the traceback.

Moreover the ``__str__`` representation of the output object is redefined
to return the output string if the command was successful or the error
message if the command failed (actually it returns the error message
preceded by the name of the exception class).

For instance, if you send a mispelled option to
the interpreter a ``SystemExit`` will be trapped:

>>> import plac
>>> from ishelve import ishelve
>>> with plac.Interpreter(ishelve) as i:
...     print(i.send('.cler'))
... 
SystemExit: unrecognized arguments: .cler

It is important to invoke the ``.send`` method inside the context manager,
otherwise you will get a ``RuntimeError``.

For instance, suppose you want to implement a graphical runner for a
plac-based interpreter with two text widgets: one to enter the commands
and one to display the results. Suppose you want to display the errors
with tracebacks in red. You will need to code something like that
(pseudocode follows)::

  input_widget = WidgetReadingInput()
  output_widget = WidgetDisplayingOutput()

  def send(interpreter, line):
      out = interpreter.send(line)
      if out.tb: # there was an error
          output_widget.display(out.tb, color='red')
      else:
          output_widget.display(out.str)

  main = plac.import_main(tool_path) # get the main object

  with plac.Interpreter(main) as i:
     def callback(event):
        if event.user_pressed_ENTER():
             send(i, input_widget.last_line)
     input_widget.addcallback(callback)
     gui_mainloop.start()

You can adapt the pseudocode to your GUI toolkit of choice and you can
also change the file associations in such a way that clicking on a
plac tool file the graphical user interface starts.

There is a final *caveat*: since the plac interpreter loop is
implemented via extended generators, plac interpreters are single threaded: you
will get an error if you ``.send`` commands from separated threads. 
You can circumvent the problem by using a queue. If EXIT is a sentinel
value to signal exiting from the interpreter look, you can write code
like this::

    with interpreter:
        for input_value in iter(input_queue.get, EXIT):
            output_queue.put(interpreter.send(input_value))

The same trick also work for processes; you could run the interpreter
loop in a separate process and send commands to it via the Queue
class provided by the multiprocessing_ module.

Summary
-------------------------------------------------------

Once plac_ claimed to be the easiest command-line arguments parser
in the world. Having read this document you may think that it is not
so easy after all. But it is a false impression. Actually the
rules are quite simple:

1. 
   if you want to implement a command-line script, use ``plac.call``;

2. 
   if you want to implement a command interpreter, use ``plac.Interpreter``:

   - for an interactive interpreter, call the ``.interact`` method;
   - for an batch interpreter, call the ``.execute`` method;

3. for testing call the ``Interpreter.check`` method in the appropriate context
   or use the ``Interpreter.doctest`` feature;

4. if you need to go at a lower level, you may need to call the
   ``Interpreter.send`` method.

Moreover, remember that ``plac_runner.py`` is your friend.

Appendix: custom annotation objects
--------------------------------------------------------

Internally plac_ uses an ``Annotation`` class to convert the tuples
in the function signature into annotation objects, i.e. objects with
six attributes ``help, kind, short, type, choices, metavar``.

Advanced users can implement their own annotation objects.
For instance, here is an example of how you could implement annotations for
positional arguments:

.. include:: annotations.py
   :literal:

You can use such annotations objects as follows:

.. include:: example11.py
   :literal:

Here is the usage message you get:

.. include:: example11.help
   :literal:

You can go on and define ``Option`` and ``Flag`` classes, if you like.
Using custom annotation objects you could do advanced things like extracting the
annotations from a configuration file or from a database, but I expect such
use cases to be quite rare: the default mechanism should work 
pretty well for most users.

.. _argparse: http://argparse.googlecode.com
.. _optparse: http://docs.python.org/library/optparse.html
.. _getopt: http://docs.python.org/library/getopt.html
.. _optionparse: http://code.activestate.com/recipes/278844-parsing-the-command-line/
.. _plac: http://pypi.python.org/pypi/plac
.. _scaling down: http://www.welton.it/articles/scalable_systems
.. _ArgumentParser: http://argparse.googlecode.com/svn/tags/r11/doc/ArgumentParser.html
.. _argparse.FileType: http://argparse.googlecode.com/svn/tags/r11/doc/other-utilities.html?highlight=filetype#FileType
.. _Clap: http://pypi.python.org/pypi/Clap/0.7
.. _OptionParser: http://docs.python.org/library/optparse.html?highlight=optionparser#optparse.OptionParser
.. _SQLAlchemy: http://www.sqlalchemy.org/
.. _SqlSoup: http://www.sqlalchemy.org/docs/reference/ext/sqlsoup.html
.. _CLIArgs: http://pypi.python.org/pypi/CLIArgs
.. _opterator: http://pypi.python.org/pypi/opterator
.. _advanced usage document: in-writing
.. _twill: http://twill.idyll.org/
.. _basic documentation: http://micheles.googlecode.com/hg/plac/doc/plac.html
.. _shlex: http://docs.python.org/library/shlex.html
.. _multiprocessing: http://docs.python.org/library/multiprocessing.html
.. _distutils: http://docs.python.org/distutils/
.. _cmd: http://docs.python.org/library/cmd.html
.. _rlwrap: http://freshmeat.net/projects/rlwrap/

.. If the script is invoked with no arguments, the default help is
    invoked: this is done by invoking the argparse_ low-level method
    ``.format_help``. In other words, the recognition of the couple
    ``-h/--help`` is disabled, but the original help feature is still there.