summaryrefslogtreecommitdiff
path: root/plac/doc/plac_adv.html
blob: 908445ae9aa9d08fc55493de9f3379fa79100f2a (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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.6: http://docutils.sourceforge.net/" />
<title>Testing and scripting your applications with plac</title>
<meta name="author" content="Michele Simionato" />
<meta name="date" content="June 2010" />
<style type="text/css">

.first {
  margin-top: 0 }

.last {
  margin-bottom: 0 }

a.toc-backref {
  text-decoration: none ;
  color: black }

dd {
  margin-bottom: 0.5em }

div.abstract {
  margin: 2em 5em }

div.abstract p.topic-title {
  font-weight: bold ;
  text-align: center }

div.attention, div.caution, div.danger, div.error, div.hint,
div.important, div.note, div.tip, div.warning {
  margin: 2em ;
  border: medium outset ;
  padding: 1em }

div.attention p.admonition-title, div.caution p.admonition-title,
div.danger p.admonition-title, div.error p.admonition-title,
div.warning p.admonition-title {
  color: red ;
  font-weight: bold ;
  font-family: sans-serif }

div.hint p.admonition-title, div.important p.admonition-title,
div.note p.admonition-title, div.tip p.admonition-title {
  font-weight: bold ;
  font-family: sans-serif }

div.dedication {
  margin: 2em 5em ;
  text-align: center ;
  font-style: italic }

div.dedication p.topic-title {
  font-weight: bold ;
  font-style: normal }

div.figure {
  margin-left: 2em }

div.footer, div.header {
  font-size: smaller }

div.system-messages {
  margin: 5em }

div.system-messages h1 {
  color: red }

div.system-message {
  border: medium outset ;
  padding: 1em }

div.system-message p.system-message-title {
  color: red ;
  font-weight: bold }

div.topic {
  margin: 2em }

hr {
  width: 75% }

ol.simple, ul.simple {
  margin-bottom: 1em }

ol.arabic {
  list-style: decimal }

ol.loweralpha {
  list-style: lower-alpha }

ol.upperalpha {
  list-style: upper-alpha }

ol.lowerroman {
  list-style: lower-roman }

ol.upperroman {
  list-style: upper-roman }

p.caption {
  font-style: italic }

p.credits {
  font-style: italic ;
  font-size: smaller }

p.label {
  white-space: nowrap }

p.topic-title {
  font-weight: bold }

pre.address {
  margin-bottom: 0 ;
  margin-top: 0 ;
  font-family: serif ;
  font-size: 100% }

pre.line-block {
  font-family: serif ;
  font-size: 100% }

pre.literal-block, pre.doctest-block {
  background-color: #eeeeee }

span.classifier {
  font-family: sans-serif ;
  font-style: oblique }

span.classifier-delimiter {
  font-family: sans-serif ;
  font-weight: bold }

span.interpreted {
  font-family: sans-serif }

span.option-argument {
  font-style: italic }

span.pre {
  white-space: pre }

span.problematic {
  color: red }

table {
  margin-top: 0.5em ;
  margin-bottom: 0.5em }

table.citation {
  border-left: solid thin gray ;
  padding-left: 0.5ex }

table.docinfo {
  margin: 2em 4em }

table.footnote {
  border-left: solid thin black ;
  padding-left: 0.5ex }

td, th {
  padding-left: 0.5em ;
  padding-right: 0.5em ;
  vertical-align: top }

th.docinfo-name, th.field-name {
  font-weight: bold ;
  text-align: left ;
  white-space: nowrap }

h1 tt, h2 tt, h3 tt, h4 tt, h5 tt, h6 tt {
  font-size: 100% }

tt {
  background-color: #eeeeee }

ul.auto-toc {
  list-style-type: none }


/*
Additional styles for "modern"-style of DocFactory.

:Author: Gunnar Schwant
:Contact: g.schwant@gmx.de
*/

.first {
  font-size: 10pt }

.last {
  font-size: 10pt }

a {
  text-decoration: none }

a.reference {
  color: #00009F }

a:hover {
  background-color: #00009F ;
  color: white }

body {
  font-family: arial,helvetica,univers ;
  font-size: 10pt ;
  padding-top: 0.6cm ;
  margin-left:0.5cm ;
  margin-right:0.5cm ;
  margin-bottom:0.5cm }

dd {
  font-size: 10pt ;
  padding-top: 0.1cm
}

dt {
  font-size: 10pt ;
  font-weight: bold ;
  background-color: #6FC7FB ;
  padding-left: 0.1cm ;
  padding-top: 0.1cm ;
  padding-bottom: 0.1cm }

div.abstract {
  font-size: 10pt }

div.abstract p.topic-title {
  font-size: 10pt }

div.attention, div.caution, div.danger, div.error, div.hint,
div.important, div.note, div.tip, div.warning {
  font-size: 10pt }

div.attention p.admonition-title, div.caution p.admonition-title,
div.danger p.admonition-title, div.error p.admonition-title,
div.warning p.admonition-title, div.hint p.admonition-title, 
div.important p.admonition-title, div.note p.admonition-title, 
div.tip p.admonition-title {
  margin-top: 0em ;
  font-size: 12pt ;
  font-family: arial,helvetica,univers }

div.dedication {
  font-size: 10pt }

div.dedication p.topic-title {
  font-size: 10pt }

div.figure {
  font-size: 10pt }

div.footer, div.header {
  font-size: 8pt }

div.system-messages {
  font-size: 10pt }

div.system-messages h1 {
  font-size: 12pt }

div.system-message {
  font-size: 10pt }

div.system-message p.system-message-title {
  font-size: 10pt }

div.topic {
  font-size: 10pt }

h1, h2, h3, h4, h5, h6 {
  padding-top: 0.5cm ;
  page-break-after: avoid ;
  font-family: arial,helvetica,univers }

h1 {
  font-size: 18pt }

h1.title {
  color: white ;
  background-color: #00009F ;
  padding-top: 0cm }

h2 {
  font-size: 16pt }

h2.subtitle {
  padding-top: 0cm }

h3 {
  font-size: 14pt }

h4 {
  font-size: 12pt }

h5, h6 {
  font-size: 10pt }

hr {
  width: 100%;
  page-break-after: always }

li {
  padding-top: 1mm ;
  padding-bottom: 1mm }

ol.simple, ul.simple {
  font-size: 10pt }

ol.arabic {
  font-size: 10pt }

ol.loweralpha {
  font-size: 10pt }

ol.upperalpha {
  font-size: 10pt }

ol.lowerroman {
  font-size: 10pt }

ol.upperroman {
  font-size: 10pt }

p.caption {
  font-size: 10pt }

p.credits {
  font-style: italic ;
  font-size: 8pt }

p.label {
  font-size: 10pt }

p.topic-title {
  font-size: 10pt }

pre.address {
  font-family: arial,helvetica,univers ;
  font-size: 10pt }

pre.line-block {
  font-size: 10pt }

pre.literal-block, pre.doctest-block {
  border-width: 1pt ;
  border-style: solid ;
  border-color: #999999 ;
  color: #0000C0 ;
  background-color: #ffffe0 ;
  font-size: 9pt }

span.classifier {
  font-size: 10pt ;
  font-family: arial,helvetica,univers }

span.classifier-delimiter {
  font-size: 10pt ;
  font-family: arial,helvetica,univers }

span.field-argument {
  font-size: 10pt }

span.interpreted {
  font-size: 10pt ;
  font-family: arial,helvetica,univers }

span.option-argument {
  font-size: 10pt }

span.problematic {
  font-size: 10pt }

table {
  font-size: 10pt ;
  border-collapse: collapse ;
  border-width: 1.5pt ;
  border-color: #003366 }

table.citation {
  font-size: 10pt }

table.docinfo {
  font-size: 10pt }

table.footnote {
  font-size: 8pt ;
  text-align: left }

table.table {
  width: 100% }

th {
  border-width: 1.5pt }

td {
  border-width: 1pt }

td, th {
  font-size: 10pt ;
  border-style: thin ;
  border-color: #003366 }

td.docinfo-name, th.field-name {
  font-size: 10pt }

h1 tt, h2 tt, h3 tt, h4 tt, h5 tt, h6 tt {
  font-size: 10pt }

</style>
</head>
<body>
<div class="document" id="testing-and-scripting-your-applications-with-plac">
<h1 class="title">Testing and scripting your applications with plac</h1>
<table class="docinfo" frame="void" rules="none">
<col class="docinfo-name" />
<col class="docinfo-content" />
<tbody valign="top">
<tr><th class="docinfo-name">Author:</th>
<td>Michele Simionato</td></tr>
<tr class="field"><th class="docinfo-name">E-mail:</th><td class="field-body"><a class="reference external" href="mailto:michele.simionato&#64;gmail.com">michele.simionato&#64;gmail.com</a></td>
</tr>
<tr><th class="docinfo-name">Date:</th>
<td>June 2010</td></tr>
<tr class="field"><th class="docinfo-name">Download page:</th><td class="field-body"><a class="reference external" href="http://pypi.python.org/pypi/plac">http://pypi.python.org/pypi/plac</a></td>
</tr>
<tr class="field"><th class="docinfo-name">Project page:</th><td class="field-body"><a class="reference external" href="http://micheles.googlecode.com/hg/plac/doc/plac.html">http://micheles.googlecode.com/hg/plac/doc/plac.html</a></td>
</tr>
<tr class="field"><th class="docinfo-name">Installation:</th><td class="field-body"><tt class="docutils literal">easy_install <span class="pre">-U</span> plac</tt></td>
</tr>
<tr class="field"><th class="docinfo-name">License:</th><td class="field-body">BSD license</td>
</tr>
<tr class="field"><th class="docinfo-name">Requires:</th><td class="field-body">Python 2.5+</td>
</tr>
</tbody>
</table>
<p><em>The present document discusses a few of the advanced use
cases for plac.  It assumes you have already read an understood the
basic documentation.</em></p>
<div class="contents topic" id="contents">
<p class="topic-title first">Contents</p>
<ul class="simple">
<li><a class="reference internal" href="#introduction" id="id1">Introduction</a></li>
<li><a class="reference internal" href="#from-scripts-to-interactive-applications" id="id2">From scripts to interactive applications</a></li>
<li><a class="reference internal" href="#testing-a-plac-application" id="id3">Testing a plac application</a></li>
<li><a class="reference internal" href="#plac-easy-tests" id="id4">Plac easy tests</a></li>
<li><a class="reference internal" href="#plac-batch-scripts" id="id5">Plac batch scripts</a></li>
<li><a class="reference internal" href="#containers-of-commands" id="id6">Containers of commands</a></li>
<li><a class="reference internal" href="#for-cmd-lovers" id="id7">For <tt class="docutils literal">cmd</tt> lovers</a></li>
<li><a class="reference internal" href="#the-plac-runner" id="id8">The plac runner</a></li>
<li><a class="reference internal" href="#a-non-class-based-example" id="id9">A non class-based example</a></li>
<li><a class="reference internal" href="#writing-your-own-plac-runner" id="id10">Writing your own plac runner</a></li>
<li><a class="reference internal" href="#summary" id="id11">Summary</a></li>
<li><a class="reference internal" href="#appendix-custom-annotation-objects" id="id12">Appendix: custom annotation objects</a></li>
</ul>
</div>
<div class="section" id="introduction">
<h1><a class="toc-backref" href="#id1">Introduction</a></h1>
<p>One of the design goals of <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> is to make it dead easy to write a
scriptable and testable interface for an application.  You can use
<a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> whenever you have an API with strings in input and strings in
output, and that includes a <em>huge</em> domain of applications.</p>
<p>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 <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> and can be run as batch scripts.</p>
<p>Actually, at the most general level, you can see <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> as a generic tool to
write domain specific languages (DSL). With <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> you
can test your application interactively as well as with batch
scripts, and even with the analogous of Python doctests for your
defined language.</p>
<p>You can easily replace the <tt class="docutils literal">cmd</tt> module of the standard library and
you could easily write an application like <a class="reference external" href="http://twill.idyll.org/">twill</a> with <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a>. Or you
could use it to script your building procedure. Or any other thing,
your imagination is the only limit!</p>
</div>
<div class="section" id="from-scripts-to-interactive-applications">
<h1><a class="toc-backref" href="#id2">From scripts to interactive applications</a></h1>
<p>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.  <tt class="docutils literal">plac</tt> provides an
<tt class="docutils literal">Interpreter</tt> class just for this purpose.</p>
<p>The <tt class="docutils literal">Interpreter</tt> class wraps the main function of a script and
provides an <tt class="docutils literal">.interact</tt> method to start an interactive interpreter
reading commands from the console.</p>
<p>For instance, you can define an interactive interpreter on top of the
<tt class="docutils literal">ishelve</tt> script introduced in the <a class="reference external" href="http://micheles.googlecode.com/hg/plac/doc/plac.html">basic documentation</a> as
follows:</p>
<pre class="literal-block">
# shelve_interpreter.py
import plac, ishelve

&#64;plac.annotations(
    interactive=('start interactive interface', 'flag'),
    subcommands='the commands of the underlying ishelve interpreter')
def main(interactive, *subcommands):
    &quot;&quot;&quot;
    This script works both interactively and non-interactively.
    Use .help to see the internal commands.
    &quot;&quot;&quot;
    if interactive:
        plac.Interpreter(ishelve.main).interact()
    else:
        for out in plac.call(ishelve.main, subcommands):
            print(out)

if __name__ == '__main__':
    plac.call(main)

</pre>
<p>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 <tt class="docutils literal"><span class="pre">-h/--help</span></tt> flag whereas the
internal interface only recognizes the <tt class="docutils literal">.help</tt> command:</p>
<pre class="literal-block">
$ python shelve_interpreter.py -h
</pre>
<pre class="literal-block">
usage: shelve_interpreter.py [-h] [-interactive]
                             [subcommands [subcommands ...]]

This script works both interactively and non-interactively. Use .help to see
the internal commands.

positional arguments:
  subcommands   the commands of the underlying ishelve interpreter

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

</pre>
<p>Thanks to this ingenuous trick, the script can be run both interactively
and non-interactively:</p>
<pre class="literal-block">
$ python shelve_interpreter.py .clear # non-interactive use
cleared the shelve
</pre>
<p>Here is an usage session, using <a class="reference external" href="http://freshmeat.net/projects/rlwrap/">rlwrap</a> to enable readline features
(<a class="reference external" href="http://freshmeat.net/projects/rlwrap/">rlwrap</a> is available in Unix-like systems):</p>
<pre class="literal-block">
$ 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&gt; a=1
setting a=1
i&gt; a
1
i&gt; b=2
setting b=2
i&gt; a b
1
2
i&gt; .del a
deleted a
i&gt; a
a: not found
i&gt; .show
b=2
i&gt; [CTRL-D]
</pre>
<p>The <tt class="docutils literal">.interact</tt> 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 <tt class="docutils literal"><span class="pre">prompt='i&gt;</span> '</tt> 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 <tt class="docutils literal">.intro</tt> attribute on the main function.</p>
<p>Notice that <tt class="docutils literal">plac.Interpreter</tt> is available only if you are using a recent
version of Python (&gt;= 2.5), because it is a context manager object
which uses extended generators internally.</p>
<p>You can conveniently test your application in interactive mode.
However manual testing is a poor substitute for automatic testing.</p>
</div>
<div class="section" id="testing-a-plac-application">
<h1><a class="toc-backref" href="#id3">Testing a plac application</a></h1>
<p>In principle, one could write automatic tests for the
<tt class="docutils literal">ishelve</tt> application by using <tt class="docutils literal">plac.call</tt> directly:</p>
<pre class="literal-block">
# test_ishelve.py
import plac, ishelve

def test():
    assert plac.call(ishelve.main, ['.clear']) == ['cleared the shelve']
    assert plac.call(ishelve.main, ['a=1']) == ['setting a=1']
    assert plac.call(ishelve.main, ['a']) == ['1']
    assert plac.call(ishelve.main, ['.delete=a']) == ['deleted a']
    assert plac.call(ishelve.main, ['a']) == ['a: not found']

if __name__ == '__main__':
    test()

</pre>
<p>However, using <tt class="docutils literal">plac.call</tt> is not especially nice. The big
issue is that <tt class="docutils literal">plac.call</tt> responds to invalid input by printing an
error message on stderr and by raising a <tt class="docutils literal">SystemExit</tt>: this is
certainly not a nice thing to do in a test.</p>
<p>As a consequence of this behavior it is impossible to test for invalid
commands, unless you wrap the <tt class="docutils literal">SystemExit</tt> exception by
hand each time (a possibly you do something with the error message in
stderr too). Luckily, <tt class="docutils literal">plac</tt> offers a better testing support through
the <tt class="docutils literal">check</tt> method of <tt class="docutils literal">Interpreter</tt> objects:</p>
<pre class="literal-block">
# test_ishelve2.py
from __future__ import with_statement
import plac, ishelve

def test():
    with plac.Interpreter(ishelve.main) as i:
        i.check('.clear', 'cleared the shelve')
        i.check('a=1', 'setting a=1')
        i.check('a', '1')
        i.check('.delete=a', 'deleted a')
        i.check('a', 'a: not found')

</pre>
<p>The method <tt class="docutils literal">.check(given_input, expected_output)</tt> works on strings
and raises an <tt class="docutils literal">AssertionError</tt> if the output produced by the
interpreter is different from the expected output for the given input.</p>
<p><tt class="docutils literal">AssertionError</tt> is catched by tools like <tt class="docutils literal">py.test</tt> and
<tt class="docutils literal">nosetests</tt> and actually <tt class="docutils literal">plac</tt> tests are intended to be run with
such tools.</p>
<p>Interpreters offer a minor syntactic advantage with respect to calling
<tt class="docutils literal">plac.call</tt> directly, but they offer a <em>major</em> semantic advantage when things
go wrong (read exceptions): an <tt class="docutils literal">Interpreter</tt> object internally invokes
something like <tt class="docutils literal">plac.call</tt>, but it wraps all exceptions, so that <tt class="docutils literal">i.check</tt>
is guaranteed not to raise any exception except <tt class="docutils literal">AssertionError</tt>.</p>
<p>Even the <tt class="docutils literal">SystemExit</tt> exception is captured and you can write your test as</p>
<blockquote>
<tt class="docutils literal"><span class="pre">i.check('-cler',</span> 'SystemExit: unrecognized arguments: <span class="pre">-cler')</span></tt></blockquote>
<p>without risk of exiting from the Python interpreter.</p>
<p>There is a second advantage of interpreters: if the main function contains some
initialization code and finalization code
(<tt class="docutils literal">__enter__</tt> and <tt class="docutils literal">__exit__</tt> functions) they will be run only
once at the beginning and at the end of the interpreter loop.
<tt class="docutils literal">plac.call</tt> instead ignores the initialization/finalization code.</p>
</div>
<div class="section" id="plac-easy-tests">
<h1><a class="toc-backref" href="#id4">Plac easy tests</a></h1>
<p>Writing your tests in terms of <tt class="docutils literal">Interpreter.check</tt> is certainly an
improvement over writing them in terms of <tt class="docutils literal">plac.call</tt>, but they
are still too low-level for my taste. The <tt class="docutils literal">Interpreter</tt> class provides
support for doctest-style tests, a.k.a. <em>plac easy tests</em>.</p>
<p>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 <tt class="docutils literal">ishelve.placet</tt> (the <tt class="docutils literal">.placet</tt>
extension is a mnemonic for plac easy tests):</p>
<pre class="literal-block">
#!ishelve.py
i&gt; .clear # start from a clean state
cleared the shelve
i&gt; a=1
setting a=1
i&gt; a
1
i&gt; .del a
deleted a
i&gt; a
a: not found
i&gt; .cler # spelling error
SystemExit: unrecognized arguments: .cler

</pre>
<p>Notice the precence of the shebang line containing the name of the
<a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> tool to test (a <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> tool is just a Python module with a
function called <tt class="docutils literal">main</tt>). 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.</p>
<p>You can test <tt class="docutils literal">ishelve.placet</tt> file by calling the
<tt class="docutils literal">.doctest</tt> method of the interpreter, as in this example:</p>
<pre class="literal-block">
$ python -c&quot;import plac, ishelve
plac.Interpreter(ishelve.main).doctest(open('ishelve.placet'), verbose=True)&quot;
</pre>
<p>Internally <tt class="docutils literal">Interpreter.doctests</tt> invokes <tt class="docutils literal">Interpreter.check</tt>
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 <tt class="docutils literal">plac</tt> are <em>not</em> unittests: they should be
used to model user interaction when the order of the operations
matters.  Since the single subtests in a <tt class="docutils literal">.placet</tt> file are not
independent, it makes sense to exit immediately at the first failure.</p>
<p>The support for doctests in <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> comes nearly for free, thanks to the <a class="reference external" href="http://docs.python.org/library/shlex.html">shlex</a>
module in the standard library, which is able to parse simple
languages as the ones you can implement with <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a>. In particular,
thanks to <a class="reference external" href="http://docs.python.org/library/shlex.html">shlex</a>, <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> is able to recognize comments (the default
comment character is <tt class="docutils literal">#</tt>), continuation lines, escape sequences and
more. Look at the <a class="reference external" href="http://docs.python.org/library/shlex.html">shlex</a> documentation if you need to customize how
the language is interpreted.</p>
<p>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 <tt class="docutils literal">.doctest</tt> method a list of
strings corresponding to the lines of the file).</p>
<p>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 <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> could reuse doctests directives like ELLIPSIS).</p>
<p>It is straighforward to integrate your <tt class="docutils literal">.placet</tt> tests with standard
testing tools. For instance, you can integrate your doctests with nose
or py.test as follow:</p>
<pre class="literal-block">
import os, shlex, plac

def test_doct():
   &quot;&quot;&quot;
   Find all the doctests in the current directory and run them with the
   corresponding plac interpreter (the shebang rules!)
   &quot;&quot;&quot;
   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:]
</pre>
<p>Here you should notice that usage of <tt class="docutils literal">plac.import_main</tt>, 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 <tt class="docutils literal">PLACPATH</tt> and it searches
the plac tool in the directories specified there (<tt class="docutils literal">PLACPATH</tt> is just
a string containing directory names separated by colons). If the variable
<tt class="docutils literal">PLACPATH</tt> is not defined, it just looks in the current directory.
If the plac tool is not found, an <tt class="docutils literal">ImportError</tt> is raised.</p>
</div>
<div class="section" id="plac-batch-scripts">
<h1><a class="toc-backref" href="#id5">Plac batch scripts</a></h1>
<p>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.
<a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> interpreters provide an <tt class="docutils literal">.execute</tt> method to perform just that.</p>
<p>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
<tt class="docutils literal">Interpreter.execute</tt> makes sure that any error raised by
<tt class="docutils literal">plac.call</tt> internally is re-raised.  In other words, <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a>
interpreters <em>wrap the errors, but does not eat them</em>: the errors are
always accessible and can be re-raised on demand.</p>
<p>In particular consider the following batch file, which contains a syntax
error (<tt class="docutils literal">.dl</tt> instead of <tt class="docutils literal">.del</tt>):</p>
<pre class="literal-block">
#!ishelve.py
.clear 
a=1 b=2
.show
.del a
.dl b
.show

</pre>
<p>If you execute the batch file, the interpreter will raise a <tt class="docutils literal">SystemExit</tt>
with an appropriated error message at the <tt class="docutils literal">.dl</tt> line and the last command
will <em>not</em> be executed:</p>
<pre class="literal-block">
$ python -c &quot;import plac, ishelve
plac.Interpreter(ishelve.main).execute(open('ishelve.plac'), verbose=True)&quot;
i&gt; .clear
cleared the shelve
i&gt; a=1 b=2
setting a=1
setting b=2
i&gt; .show
b=2
a=1
i&gt; .del a
deleted a
i&gt; .dl b
unrecognized arguments: .dl
</pre>
<p>The <tt class="docutils literal">verbose</tt> flag is there to show the lines which are being interpreted
(prefixed by <tt class="docutils literal">i&gt;</tt>). This is done on purpose, so that you can cut and paste
the output of the batch script and turn it into a <tt class="docutils literal">.placet</tt> test
(cool, isn't it?).</p>
</div>
<div class="section" id="containers-of-commands">
<h1><a class="toc-backref" href="#id6">Containers of commands</a></h1>
<p>When I discussed the <tt class="docutils literal">ishelve</tt> implementation in the <a class="reference external" href="http://micheles.googlecode.com/hg/plac/doc/plac.html">basic
documentation</a>, I said that it looked like a poor man implementation
of an object system as a chain of elifs; I also said that <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> was
able to do better.  Here I will substantiate my claim.</p>
<p><a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> is actually able to infer a set of subparsers from a
generic container of commands.  This is useful if you want to
implement <em>subcommands</em> (a familiar example of a command-line
application featuring subcommands is subversion).</p>
<p>Technically a container of commands is any object with a <tt class="docutils literal">.commands</tt> attribute
listing a set of functions or methods which are valid commands. A command
container may have initialization/finalization hooks (<tt class="docutils literal">__enter__/__exit__</tt>)
and dispatch hooks (<tt class="docutils literal">__missing__</tt>, invoked for invalid command names).</p>
<p>Using this feature the shelve interface can be rewritten in a more
object-oriented way as follows:</p>
<pre class="literal-block">
# ishelve2.py
import shelve, os, sys, plac

class ShelveInterface(object):
    &quot;A minimal interface over a shelve object&quot;
    commands = 'set', 'show', 'showall', 'delete'
    &#64;plac.annotations(
        configfile=('path name of the shelve', 'option'))
    def __init__(self, configfile='~/conf.shelve'):
        self.fname = os.path.expanduser(configfile)
        self.intro = 'Operating on %s. Available commands:\n%s' % (
            self.fname, '\n'.join(c for c in self.commands))
    def __enter__(self):
        self.sh = shelve.open(self.fname)
        return self
    def set(self, name, value):
        &quot;set name value&quot;
        yield 'setting %s=%s' % (name, value)
        self.sh[name] = value
    def show(self, *names):
        &quot;show given parameters&quot;
        for name in names:
            yield '%s = %s' % (name, self.sh[name]) # no error checking
    def showall(self):
        &quot;show all parameters&quot;
        for name in self.sh:
            yield '%s = %s' % (name, self.sh[name])
    def delete(self, name=None):
        &quot;delete given parameter (or everything)&quot;
        if name is None:
            yield 'deleting everything'
            self.sh.clear()
        else:
            yield 'deleting %s' % name
            del self.sh[name] # no error checking
    def __exit__(self, etype, exc, tb):
        self.sh.close()

main = ShelveInterface # the main 'function' can also be a class!

if __name__ == '__main__':
    i = plac.Interpreter(main())
    i.interact()

</pre>
<p><tt class="docutils literal">plac.Interpreter</tt> objects wrap context manager objects
consistently.  In other words, if you wrap an object with
<tt class="docutils literal">__enter__</tt> and <tt class="docutils literal">__exit__</tt> methods, they are invoked in the right
order (<tt class="docutils literal">__enter__</tt> before the interpreter loop starts and
<tt class="docutils literal">__exit__</tt> after the interpreter loop ends, both in the regular and
in the exceptional case). In our example, the methods <tt class="docutils literal">__enter__</tt>
and <tt class="docutils literal">__exit__</tt> 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 <tt class="docutils literal">show</tt> and <tt class="docutils literal">delete</tt> methods
on purpose, to verify that <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> works correctly in the presence of
exceptions.</p>
<p>Here is a session of usage on an Unix-like operating system:</p>
<pre class="literal-block">
$ rlwrap python ishelve2.py
Operating on /home/micheles/conf.shelve. Available commands:
set
show
showall
delete
i&gt; delete
deleting everything
i&gt; set a pippo
setting a=pippo
i&gt; set b lippo
setting b=lippo
i&gt; showall
b = lippo
a = pippo
i&gt; show a b
a = pippo
b = lippo
i&gt; del a
deleting a
i&gt; showall
b = lippo
i&gt; delete a
DBNotFoundError: (-30988, 'DB_NOTFOUND: No matching key/data pair found')
i&gt;
</pre>
<p>Notice that in interactive mode the traceback is hidden, unless
you pass the <tt class="docutils literal">verbose</tt> flag to the <tt class="docutils literal">Interpreter.interact</tt> method.</p>
<p>The interactive mode of <tt class="docutils literal">plac</tt> can be used as a replacement of the
<tt class="docutils literal">cmd</tt> module in the standard library. There are a few differences,
however. For instance you miss tab completion, even if use <a class="reference external" href="http://freshmeat.net/projects/rlwrap/">rlwrap</a>
(you get persistent command history for free, however). This is not
a big issue, since <tt class="docutils literal">plac</tt> understands command abbreviations.</p>
<p>If an abbreviation is ambiguous, <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> warns you:</p>
<pre class="literal-block">
$ rlwrap python ishelve2.py
usage: plac_runner.py ishelve2.py [-h] {delete,set,showall,show} ...
i&gt; sh
NameError: Ambiguous command 'sh': matching ['showall', 'show']
</pre>
</div>
<div class="section" id="for-cmd-lovers">
<h1><a class="toc-backref" href="#id7">For <tt class="docutils literal">cmd</tt> lovers</a></h1>
<p>I have been using the <a class="reference external" href="http://docs.python.org/library/cmd.html">cmd</a> module of the standard library for years.
I have also written a much enhanced <tt class="docutils literal">cmd2</tt> module which we are using
internally at work and from which I have taken some ideas used in <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a>.
In many ways <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> makes the <a class="reference external" href="http://docs.python.org/library/cmd.html">cmd</a> module obsolete,
but I realize why many nostalgic souls would still use <a class="reference external" href="http://docs.python.org/library/cmd.html">cmd</a>, especially
until <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> does not grow real auto-completion features, instead of
relying on <a class="reference external" href="http://freshmeat.net/projects/rlwrap/">rlwrap</a>. But there must not be competition between <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a>
and <a class="reference external" href="http://docs.python.org/library/cmd.html">cmd</a>: actually the two can happily work togethere. For this
reason I have put in the <tt class="docutils literal">plac_ext</tt> module a few lines of code
for gluing together <a class="reference external" href="http://docs.python.org/library/cmd.html">cmd</a> and <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a>, the <tt class="docutils literal">cmd_interface</tt>.
Using the <tt class="docutils literal">cmd_interface</tt> is quite trivial: give to it a plac
command container and you will get in exchange a <tt class="docutils literal">cmd.Cmd</tt> object:</p>
<pre class="literal-block">
# cmd_ext.py
from plac_ext import cmd_interface
import ishelve2

if __name__ == '__main__':
    cmd_interface(ishelve2.main()).cmdloop()

</pre>
<p>Here is an example of interactive session:</p>
<pre class="literal-block">
$ python cmd_ex.py
(Cmd) help

Documented commands (type help &lt;topic&gt;):
========================================
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]
</pre>
<p>Internally the <tt class="docutils literal">cmd_interface</tt> builds a <tt class="docutils literal">cmd.Cmd</tt> class and adds
to it the <tt class="docutils literal">do_</tt> methods corresponding to the commands in the container,
then it returns a <tt class="docutils literal">cmd.Cmd</tt> instance.</p>
<p>The <tt class="docutils literal">cmd_interface</tt> is just a proof of concept: it is there so that you
can study the source code and see an example of integration of <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a>
with a different framework. It may change and even go away in future
releases of <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a>.</p>
</div>
<div class="section" id="the-plac-runner">
<h1><a class="toc-backref" href="#id8">The plac runner</a></h1>
<p>The distribution of <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> includes a runner script named <tt class="docutils literal">plac_runner.py</tt>,
which will be installed in a suitable directory in your system by <a class="reference external" href="http://docs.python.org/distutils/">distutils</a>
(say in <tt class="docutils literal">\usr\local\bin\plac_runner.py</tt> in a Unix-like operative system).
The runner provides many facilities to run <tt class="docutils literal">.plac</tt> scripts and
<tt class="docutils literal">.placet</tt> files, as well as Python modules containg a <tt class="docutils literal">main</tt>
object, which can be a function, a command container object or
even a command container class.</p>
<p>For instance, suppose you want to execute a script containing commands
defined in the <tt class="docutils literal">ishelve2</tt> module like the following one:</p>
<pre class="literal-block">
#!ishelve2.py -c ~/conf.shelve
set a 1
del a
del a # intentional error

</pre>
<p>The first line of the <tt class="docutils literal">.plac</tt> 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:</p>
<pre class="literal-block">
$ 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')
</pre>
<p>The last command intentionally contained an error, to show that the
plac runner does not eat the traceback.</p>
<p>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</p>
<blockquote>
<tt class="docutils literal">alias <span class="pre">plac=&quot;rlwrap</span> plac_runner.py&quot;</tt></blockquote>
<p>(or you define a suitable <tt class="docutils literal">plac.bat</tt> script in Windows) you can
run the <tt class="docutils literal">ishelve2.py</tt> script in interactive mode as
follows:</p>
<pre class="literal-block">
$ plac -i ishelve2.py
Operating on /home/micheles/conf.shelve. Available commands:
set
show
showall
delete
i&gt; del
deleting everything
i&gt; set a 1
setting a=1
i&gt; set b 2
setting b=2
i&gt; show b
b = 2
</pre>
<p>Now you can cut and paste the interactive session an turns into into
a <tt class="docutils literal">.placet</tt> file like the following:</p>
<pre class="literal-block">
#!ishelve2.py -configfile=~/test.shelve
i&gt; del
deleting everything
i&gt; set a 1
setting a=1
i&gt; set b 2
setting b=2
i&gt; show b
b = 2

</pre>
<p>Notice that the first line specifies a test database
<tt class="docutils literal">~/test.shelve</tt>, to avoid clobbering your default shelve. If you
mispell the arguments in the first line plac will give you an
<a class="reference external" href="http://argparse.googlecode.com">argparse</a> error message (just try).</p>
<p>You can run placets following the shebang convention directly with
the plac runner:</p>
<pre class="literal-block">
$ plac --test ishelve2.placet
run 1 plac test(s)
</pre>
<p>If you want to see the output of the tests, pass the <tt class="docutils literal"><span class="pre">-v/--verbose</span></tt> flag.
Notice that he runner ignore the extension, so you can actually use any
extension your like, but <em>it relies on the first line of the file to invoke
the corresponding plac tool with the given arguments</em>.</p>
<p>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 <tt class="docutils literal">.placet</tt> files into a directory and its subdirectories
as follows:</p>
<pre class="literal-block">
$ find . -name \*.placet | xargs plac_runner.py -t
</pre>
<p>The plac runner expects the main function of your script to
return a plac tool, i.e. a function or an object with a <tt class="docutils literal">.commands</tt>
attribute. It this is not the case the runner gracefully exits.</p>
<p>It also works in non-interactive mode, if you call it as</p>
<blockquote>
<tt class="docutils literal">$ plac module.py args ...</tt></blockquote>
<p>Here is an example:</p>
<pre class="literal-block">
$ plac ishelve.py a=1
setting a=1
$ plac ishelve.py .show
a=1
</pre>
<p>Notice that it non-interactive mode the runner just invokes <tt class="docutils literal">plac.call</tt>
on the <tt class="docutils literal">main</tt> object of the Python module.</p>
</div>
<div class="section" id="a-non-class-based-example">
<h1><a class="toc-backref" href="#id9">A non class-based example</a></h1>
<p><a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> 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 <tt class="docutils literal">.commands</tt> attribute and possibly
<tt class="docutils literal">__enter__</tt> and/or <tt class="docutils literal">__exit__</tt> attributes.</p>
<p>In particular, a Python module is a perfect container of commands. As an
example, consider the following module implementing a fake Version
Control System:</p>
<pre class="literal-block">
&quot;A Fake Version Control System&quot;

import plac

commands = 'checkout', 'commit', 'status'

&#64;plac.annotations(url='url of the source code')
def checkout(url):
    &quot;A fake checkout command&quot;
    return ('checkout ', url)

&#64;plac.annotations(message=('commit message', 'option'))
def commit(message):
    &quot;A fake commit command&quot;
    return ('commit ', message)

&#64;plac.annotations(quiet=('summary information', 'flag', 'q'))
def status(quiet):
    &quot;A fake status command&quot;
    return ('status ', quiet)

def __missing__(name):
    return 'Command %r does not exist' % name

def __exit__(etype, exc, tb):
    &quot;Will be called automatically at the end of the call/cmdloop&quot;
    if etype in (None, GeneratorExit): # success
        print('ok')

main = __import__(__name__) # the module imports itself!

</pre>
<p>Notice that I have defined both an <tt class="docutils literal">__exit__</tt> hook and a <tt class="docutils literal">__missing__</tt>
hook, invoked for non-existing commands.
The real trick here is the line <tt class="docutils literal">main = __import__(__name__)</tt>, which
define <tt class="docutils literal">main</tt> to be an alias for the current module.</p>
<p>The <tt class="docutils literal">vcs</tt> module does not contain an <tt class="docutils literal">if __name__ == '__main__'</tt>
block, but you can still run it through the plac runner
(try <tt class="docutils literal">plac vcs.py <span class="pre">-h</span></tt>):</p>
<pre class="literal-block">
usage: plac_runner.py vcs.py [-h] {status,commit,checkout} ...

A Fake Version Control System

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

subcommands:
  {status,commit,checkout}
                        -h to get additional help

</pre>
<p>You can get help for the subcommands by postponing <tt class="docutils literal"><span class="pre">-h</span></tt> after the
name of the command:</p>
<pre class="literal-block">
$ 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
</pre>
<p>Notice how the docstring of the command is automatically shown in
usage message, as well as the documentation for the sub flag <tt class="docutils literal"><span class="pre">-q</span></tt>.</p>
<p>Here is an example of a non-interactive session:</p>
<pre class="literal-block">
$ plac vcs.py check url
checkout
url
$ plac vcs.py st -q
status
True
$ plac vcs.py co
commit
None
</pre>
<p>and here is an interactive session:</p>
<pre class="literal-block">
$ plac -i vcs.py
usage: plac_runner.py vcs.py [-h] {status,commit,checkout} ...
i&gt; check url
checkout
url
i&gt; st -q
status
True
i&gt; co
commit
None
i&gt; sto
Command 'sto' does not exist
i&gt; [CTRL-D]
ok
</pre>
<p>Notice the invocation of the <tt class="docutils literal">__missing__</tt> hook for non-existing commands.
Notice also that the <tt class="docutils literal">__exit__</tt> hook gets called only in interactive
mode.</p>
<p>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.</p>
</div>
<div class="section" id="writing-your-own-plac-runner">
<h1><a class="toc-backref" href="#id10">Writing your own plac runner</a></h1>
<p>The runner included in the <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> 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 <tt class="docutils literal">Interpreter</tt> class is the <tt class="docutils literal">.send</tt> method, which takes
strings in input and returns a four-tuple with attributes
<tt class="docutils literal">.str</tt>, <tt class="docutils literal">.etype</tt>, <tt class="docutils literal">.exc</tt> and <tt class="docutils literal">.tb</tt>:</p>
<ul class="simple">
<li><tt class="docutils literal">.str</tt> is the output of the command, if successful (a string);</li>
<li><tt class="docutils literal">.etype</tt> is the class of the exception, if the command fail;</li>
<li><tt class="docutils literal">.exc</tt> is the exception instance;</li>
<li><tt class="docutils literal">.tb</tt> is the traceback.</li>
</ul>
<p>Moreover the <tt class="docutils literal">__str__</tt> 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).</p>
<p>For instance, if you send a mispelled option to
the interpreter a <tt class="docutils literal">SystemExit</tt> will be trapped:</p>
<pre class="doctest-block">
&gt;&gt;&gt; import plac
&gt;&gt;&gt; from ishelve import ishelve
&gt;&gt;&gt; with plac.Interpreter(ishelve) as i:
...     print(i.send('.cler'))
...
SystemExit: unrecognized arguments: .cler
</pre>
<p>It is important to invoke the <tt class="docutils literal">.send</tt> method inside the context manager,
otherwise you will get a <tt class="docutils literal">RuntimeError</tt>.</p>
<p>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):</p>
<pre class="literal-block">
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()
</pre>
<p>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.</p>
<p>There is a final <em>caveat</em>: since the plac interpreter loop is
implemented via extended generators, plac interpreters are single threaded: you
will get an error if you <tt class="docutils literal">.send</tt> 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:</p>
<pre class="literal-block">
with interpreter:
    for input_value in iter(input_queue.get, EXIT):
        output_queue.put(interpreter.send(input_value))
</pre>
<p>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 <a class="reference external" href="http://docs.python.org/library/multiprocessing.html">multiprocessing</a> module.</p>
</div>
<div class="section" id="summary">
<h1><a class="toc-backref" href="#id11">Summary</a></h1>
<p>Once <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> 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:</p>
<ol class="arabic simple">
<li>if you want to implement a command-line script, use <tt class="docutils literal">plac.call</tt>;</li>
<li>if you want to implement a command interpreter, use <tt class="docutils literal">plac.Interpreter</tt>:<ul>
<li>for an interactive interpreter, call the <tt class="docutils literal">.interact</tt> method;</li>
<li>for an batch interpreter, call the <tt class="docutils literal">.execute</tt> method;</li>
</ul>
</li>
<li>for testing call the <tt class="docutils literal">Interpreter.check</tt> method in the appropriate context
or use the <tt class="docutils literal">Interpreter.doctest</tt> feature;</li>
<li>if you need to go at a lower level, you may need to call the
<tt class="docutils literal">Interpreter.send</tt> method.</li>
</ol>
<p>Moreover, remember that <tt class="docutils literal">plac_runner.py</tt> is your friend.</p>
</div>
<div class="section" id="appendix-custom-annotation-objects">
<h1><a class="toc-backref" href="#id12">Appendix: custom annotation objects</a></h1>
<p>Internally <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> uses an <tt class="docutils literal">Annotation</tt> class to convert the tuples
in the function signature into annotation objects, i.e. objects with
six attributes <tt class="docutils literal">help, kind, short, type, choices, metavar</tt>.</p>
<p>Advanced users can implement their own annotation objects.
For instance, here is an example of how you could implement annotations for
positional arguments:</p>
<pre class="literal-block">
# annotations.py
class Positional(object):
    def __init__(self, help='', type=None, choices=None, metavar=None):
        self.help = help
        self.kind = 'positional'
        self.abbrev = None
        self.type = type
        self.choices = choices
        self.metavar = metavar

</pre>
<p>You can use such annotations objects as follows:</p>
<pre class="literal-block">
# example11.py
import plac
from annotations import Positional

&#64;plac.annotations(
    i=Positional(&quot;This is an int&quot;, int),
    n=Positional(&quot;This is a float&quot;, float),
    rest=Positional(&quot;Other arguments&quot;))
def main(i, n, *rest):
    print(i, n, rest)

if __name__ == '__main__':
    import plac; plac.call(main)

</pre>
<p>Here is the usage message you get:</p>
<pre class="literal-block">
usage: example11.py [-h] i n [rest [rest ...]]

positional arguments:
  i           This is an int
  n           This is a float
  rest        Other arguments

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

</pre>
<p>You can go on and define <tt class="docutils literal">Option</tt> and <tt class="docutils literal">Flag</tt> 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.</p>
<!-- 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. -->
</div>
</div>
</body>
</html>