summaryrefslogtreecommitdiff
path: root/plac/doc/plac_adv.html
blob: d9f73b9999a6bab87473684acd89e232b8ef26ec (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
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
<?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>
<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>

<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="#a-simple-example-a-shelve-interface" id="id2">A simple example: a shelve interface</a></li>
<li><a class="reference internal" href="#turning-a-script-into-an-interactive-application" id="id3">Turning a script into an interactive application</a></li>
<li><a class="reference internal" href="#testing-a-plac-application" id="id4">Testing a plac application</a></li>
<li><a class="reference internal" href="#plac-easytests" id="id5">Plac easytests</a></li>
<li><a class="reference internal" href="#plac-batch-scripts" id="id6">Plac batch scripts</a></li>
<li><a class="reference internal" href="#command-containers" id="id7">Command containers</a></li>
<li><a class="reference internal" href="#a-non-class-based-example" id="id8">A non class-based example</a></li>
<li><a class="reference internal" href="#writing-your-own-plac-runner" id="id9">Writing your own plac runner</a></li>
<li><a class="reference internal" href="#summary" id="id10">Summary</a></li>
<li><a class="reference internal" href="#appendix-custom-annotation-objects" id="id11">Appendix: custom annotation objects</a></li>
</ul>
</div>
<div class="section" id="introduction">
<h1><a class="toc-backref" href="#id1">Introduction</a></h1>
<p><a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> has been designed to be simple to use for simple stuff, but its
power should not be underestimated; it is actually a quite advanced
tool with a domain of applicability which far exceeds the realm of
command-line arguments parsers.</p>
<p>In this document I will discuss a few of the advanced use cases for <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a>.
I assume you have already read an understood the <a class="reference external" href="http://micheles.googlecode.com/hg/plac/doc/plac.html">basic documentation</a>.</p>
<p>One of the 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, even if originally
the application is not a command-line application.</p>
<p>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 this includes a <em>huge</em> domain
of applications. A string-oriented interface
is also a scriptable interface. That means that you can define
a command language for your application and that it is possible
to write scripts which are interpreted by <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> and can be run
as batch scripts to execute any kind of operations.</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). <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> makes it dead easy
to write interpreters for command-oriented languages, both
interactive interpreters and batch interpreters. 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="a-simple-example-a-shelve-interface">
<h1><a class="toc-backref" href="#id2">A simple example: a shelve interface</a></h1>
<p>Since I like to be concrete and to show examples, let me start by
considering the following use case: you want to store some
configuration parameters into a Python shelve and you need a
command-line tool to edit your configuration, i.e. you want a shelve
interface.
A possible implementation using <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> could be the following:</p>
<pre class="literal-block">
# ishelve.py
import os, shelve
import plac

DEFAULT_SHELVE = os.path.expanduser('~/conf.shelve')

&#64;plac.annotations(
    help=('show help', 'flag'),
    showall=('show all parameters in the shelve', 'flag'),
    clear=('clear the shelve', 'flag'),
    delete=('delete an element', 'option'),
    filename=('filename of the shelve', 'option'),
    params='names of the parameters in the shelve',
    setters='setters param=value')
def main(help, showall, clear, delete, filename=DEFAULT_SHELVE,
            *params, **setters):
    &quot;A simple interface to a shelve&quot;
    sh = shelve.open(filename)
    try:
        if not any([help, showall, clear, delete, params, setters]):
            yield 'no arguments passed, use .help to see the available commands'
        elif help: # custom help
            yield 'Commands: .help, .showall, .clear, .delete'
            yield '&lt;param&gt; ...'
            yield '&lt;param=value&gt; ...'
        elif showall:
            for param, name in sh.items():
                yield '%s=%s' % (param, name)
        elif clear:
            sh.clear()
            yield 'cleared the shelve'
        elif delete:
            try:
                del sh[delete]
            except KeyError:
                yield '%s: not found' % delete
            else:
                yield 'deleted %s' % delete
        for param in params:
            try:
                yield sh[param]
            except KeyError:
                yield '%s: not found' % param           
        for param, value in setters.items():
            sh[param] = value
            yield 'setting %s=%s' % (param, value)
    finally:
        sh.close()

main.add_help = False # there is a custom help, remove the default one
main.prefix_chars = '.' # use dot-prefixed commands

if __name__ == '__main__':
    for output in plac.call(main):
        print(output)

</pre>
<p>A few notes are in order:</p>
<ol class="arabic simple">
<li>I have disabled the ordinary help provided by <a class="reference external" href="http://argparse.googlecode.com">argparse</a> and I have
implemented a custom help command.</li>
<li>I have changed the prefix character used to recognize the options
to a dot: I like to change the prefix character when I disable the
default help.</li>
<li>A plac-specific feature, i.e. keyword arguments recognition is put
to good use to make it possible to store a value in the shelve with
the syntax <tt class="docutils literal">param_name=param_value</tt>.</li>
<li>varargs are used to retrieve parameters from the shelve and some
error checking is performed in the case of missing parameters</li>
<li>A command to clear the shelve is implemented as a flag (<tt class="docutils literal">.clear</tt>).</li>
<li>A command to delete a given parameter is implemented as an option
(<tt class="docutils literal">.delete</tt>).</li>
<li>There is an option with default (<tt class="docutils literal">.filename=conf.shelve</tt>) to store
the filename of the shelve.</li>
<li>All things considered, the code looks like a poor man object oriented
interface implemented with a chain of elifs instead of methods. Of course,
<a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> can do better than that, but I am starting from a low-level approach
first.</li>
</ol>
<!-- 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. -->
<p>If you run <tt class="docutils literal">ishelve.py</tt> without arguments you get the following
message:</p>
<pre class="literal-block">
$ python ishelve.py
no arguments passed, use .help to see the available commands
</pre>
<p>If you run <tt class="docutils literal">ishelve.py</tt> with the option <tt class="docutils literal">.h</tt> (or any abbreviation
of <tt class="docutils literal">.help</tt>) you get:</p>
<pre class="literal-block">
$ python ishelve.py .h
Commands: .help, .showall, .clear, .delete
&lt;param&gt; ...
&lt;param=value&gt; ...
</pre>
<p>You can check by hand that the tool work:</p>
<pre class="literal-block">
$ python ishelve.py .clear # start from an empty shelve
cleared the shelve
$ python ishelve.py a=1 b=2
setting a=1
setting b=2
$ python ishelve.py .showall
b=2
a=1
$ python ishelve.py .del b # abbreviation for .delete
deleted b
$ python ishelve.py a
1
$ python ishelve.py b
b: not found
$ python ishelve.py .cler # mispelled command
usage: ishelve.py [.help] [.showall] [.clear] [.delete DELETE]
                  [.filename /home/micheles/conf.shelve]
                  [params [params ...]] [setters [setters ...]]
ishelve.py: error: unrecognized arguments: .cler
</pre>
<p>Command-line scripts have many advantages, but are no substitute
for a real interactive application.</p>
</div>
<div class="section" id="turning-a-script-into-an-interactive-application">
<h1><a class="toc-backref" href="#id3">Turning a script into an interactive application</a></h1>
<p>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>You could define an interactive interpreter on top of <tt class="docutils literal">ishelve</tt> as
follows:</p>
<pre class="literal-block">
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 and 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">
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 <tt class="docutils literal">rlwrap</tt> to enable readline features
(<tt class="docutils literal">rlwrap</tt> 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 are two default
arguments <tt class="docutils literal"><span class="pre">prompt='i&gt;</span> '</tt>, and <tt class="docutils literal">intro=None</tt> which
can be used to change the prompt and the message displayed
at the beginning, which by default is the argparse-provided
usage message.</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>The distribution of <tt class="docutils literal">plac</tt> 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 distutils
(say in <tt class="docutils literal">\usr\local\bin\plac_runner.py</tt> in a Unix-like operative system).
The easiest way to turn a script into an interactive application is
to use the runner. 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 original <tt class="docutils literal">ishelve.py</tt> script in interactive mode as
follows:</p>
<pre class="literal-block">
$ plac -i ishelve.py
usage: plac_runner.py ishelve.py [.help] [.showall] [.clear]
                  [.delete DELETE] [.filename /home/micheles/conf.shelve]
                  [params [params ...]] [setters [setters ...]]
i&gt;
</pre>
<p>In other words, there is no need to write the interactive
wrapper (<tt class="docutils literal">shelve_interpreter.py</tt>) by hand, the plac runner
does the job for you.</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="#id4">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
from ishelve import ishelve

def test():
    assert plac.call(ishelve, []) == []
    assert plac.call(ishelve, ['.clear']) == ['cleared the shelve']
    assert plac.call(ishelve, ['a=1']) == ['setting a=1']
    assert plac.call(ishelve, ['a']) == ['1']
    assert plac.call(ishelve, ['.delete=a']) == ['deleted a']
    assert plac.call(ishelve, ['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.  If you want to use the <tt class="docutils literal">unittest</tt> module in the
standard library you can, but I am not going to support it directly
(reminder: <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> is opinionated and I dislike the unittest module).</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> also executes the initialization/finalization code,
but it runs it at each call, and that may be too expensive.</p>
</div>
<div class="section" id="plac-easytests">
<h1><a class="toc-backref" href="#id5">Plac easytests</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 easytests</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 easytests):</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>).  You can doctest it by calling the
<tt class="docutils literal">.doctest</tt> method of the interpreter</p>
<pre class="literal-block">
$ python -c&quot;import plac, ishelve
plac.Interpreter(ishelve.main).doctest(open('ishelve.placet'), verbose=True)&quot;
</pre>
<p>and you will get the following output:</p>
<pre class="literal-block">
i&gt; .clear # start from a clean state
-&gt; cleared the shelve
i&gt; a=1
-&gt; setting a=1
i&gt; a
-&gt; 1
i&gt; .del a
-&gt; deleted a
i&gt; a
-&gt; a: not found
i&gt; .cler # spelling error
-&gt; SystemExit: unrecognized arguments: .cler

</pre>
<p>You can also run placets following the shebang convention directly with
the plac runner:</p>
<pre class="literal-block">
$ plac --easytest ishelve.placet
run 1 plac easy test(s)
</pre>
<p>The 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 correspond
to an existing plac tool</em>, so you cannot skip it and you cannot write a
wrong shebang.</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 -e
</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>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:</p>
<pre class="literal-block">
import os, plac

def test_doct():
    &quot;&quot;&quot;
    Find all the doctests in the current directory and run them with the
    corresponding plac tool.
    &quot;&quot;&quot;
    transcripts = [f for f in os.listdir('.') if f.endswith('.placet')]
    for transcript in transcripts:
        lines = list(open(transcript))
        assert lines[0].startswith('#!'), 'Missing or incorrect shebang line!'
        tool_path = lines[0][2:].strip() # get the path to the tool to test
        main = plac.import_main(tool_path)
        yield plac.Interpreter(main).doctest, lines[1:]

</pre>
<p>Here you should notice that usage of <tt class="docutils literal">plac.import_main(path)</tt>, an utility
which is able to import the main function of the specified script.
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="#id6">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>
<pre class="literal-block">
plac.Interpreter(main).execute(line_iterator)
</pre>
<p>There is just a subtle point to notice: whereas in an interactive
loop one wants to manage all exceptions, in a batch script we want to
make sure that the script does not continue 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. The easiest way to execute the batch file is
to invoke the <tt class="docutils literal">plac</tt> runner:</p>
<pre class="literal-block">
$ plac --batch --verbose ishelve.batch
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"><span class="pre">--verbose</span></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="command-containers">
<h1><a class="toc-backref" href="#id7">Command containers</a></h1>
<p>When I discussed the <tt class="docutils literal">ishelve</tt> implementation, 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
import plac

# error checking is missing: this is left to the reader
class ShelveInterface(object):
    &quot;A minimal interface over a shelve object&quot;
    commands = 'set', 'show', 'showall', 'delete'
    def __init__(self, fname):
        self.fname = fname
    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])
    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]
    def __exit__(self, etype, exc, tb):
        self.sh.close()

main = ShelveInterface(os.path.expanduser('~/conf.shelve'))

if __name__ == '__main__':
    for output in plac.call(main):
        print(output)

</pre>
<p>You should notice that <tt class="docutils literal">plac.call</tt> understands the context manager
protocol: if you call 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 call and <tt class="docutils literal">__exit__</tt> after the call, both in the regular
and in the exceptional case). Since <tt class="docutils literal">plac.call</tt> does not use
the <tt class="docutils literal">with</tt> statement internally, such feature works even in old versions
of Python, before the introduction of the context manager
protocol (in Python 2.5). 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 (in particular I want to show
that <a class="reference external" href="http://pypi.python.org/pypi/plac">plac</a> does not &quot;eat&quot; the traceback).</p>
<p>Here is a session of usage on an Unix-like operating system:</p>
<pre class="literal-block">
$ alias conf=&quot;python ishelve2.py&quot;
$ conf set a pippo
setting a=pippo
$ conf set b lippo
setting b=lippo
$ conf showall
b = lippo
a = pippo
$ conf show a b
a = pippo
b = lippo
$ conf del a # an abbreviation
deleting a
$ conf showall
b = lippo
$ conf delete a # notice the full traceback
Traceback (most recent call last):
  ...
_bsddb.DBNotFoundError: (-30988, 'DB_NOTFOUND: No matching key/data pair found')
</pre>
<p>Notice that in script mode you get the full traceback, whereas in
interactive mode the traceback is hidden:</p>
<pre class="literal-block">
$ plac -i ishelve2.py
usage: plac_runner.py ishelve2.py [-h] {delete,set,showall,show} ...
i&gt; del a
DBNotFoundError: (-30988, 'DB_NOTFOUND: No matching key/data pair found')
i&gt;
</pre>
<p>You can see the traceback if you start the runner in verbose mode
(<tt class="docutils literal">plac <span class="pre">-vi</span> ishelve2.py</tt>).</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 <tt class="docutils literal">rlwrap</tt>
(you get persistent command history for free, however). This is not
a big issue, since <tt class="docutils literal">plac</tt> understands <em>command abbreviations</em>
(in all modes, not only in interactive mode).</p>
<p>If an abbreviation is ambiguous, plac warns you:</p>
<pre class="literal-block">
$ plac ishelve2.py -i
usage: plac_runner.py ishelve2.py [-h] {delete,set,showall,show} ...
i&gt; sh
NameError: Ambiguous command 'sh': matching ['showall', 'show']
</pre>
<p>Giving the same abbreviation in script mode gives the same error
but also shows the full traceback.</p>
</div>
<div class="section" id="a-non-class-based-example">
<h1><a class="toc-backref" href="#id8">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>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 and <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
ok
checkout
url
$ plac vcs.py st -q
ok
status
True
$ plac vcs.py co
ok
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 differently in interactive
mode and non-interactive mode: in the first case it is called at the end of the
interactive loop with a <tt class="docutils literal">GeneratorExit</tt> exception, whereas in
the second case there is no exception.</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>
<p>Technically a multi-parser is a parser object with an attribute <tt class="docutils literal">.subp</tt>
which is a dictionary of subparsers; each of the methods listed in
the attribute <tt class="docutils literal">.commands</tt> corresponds to a subparser inferred from
the method signature. The original object gets a <tt class="docutils literal">.p</tt> attribute
containing the main parser which is associated to an internal function
which dispatches on the right method depending on the method name.</p>
</div>
<div class="section" id="writing-your-own-plac-runner">
<h1><a class="toc-backref" href="#id9">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 40 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="#id10">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="#id11">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>
</div>
</div>
</body>
</html>