summaryrefslogtreecommitdiff
path: root/doxygen/man/man3/cmd2.3
blob: 099fd47da24c065fc92c3465ae61cc7db46e346d (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
.TH "cmd2" 3 "Fri Sep 9 2011" "Cmd2" \" -*- nroff -*-
.ad l
.nh
.SH NAME
cmd2 \- 
.SH SYNOPSIS
.br
.PP
.SS "Classes"

.in +1c
.ti -1c
.RI "class \fBBorg\fP"
.br
.ti -1c
.RI "class \fBCmd\fP"
.br
.ti -1c
.RI "class \fBCmd2TestCase\fP"
.br
.ti -1c
.RI "class \fBEmbeddedConsoleExit\fP"
.br
.ti -1c
.RI "class \fBEmptyStatement\fP"
.br
.ti -1c
.RI "class \fBHistory\fP"
.br
.ti -1c
.RI "class \fBHistoryItem\fP"
.br
.ti -1c
.RI "class \fBNotSettableError\fP"
.br
.ti -1c
.RI "class \fBOptionParser\fP"
.br
.ti -1c
.RI "class \fBOutputTrap\fP"
.br
.ti -1c
.RI "class \fBParsedString\fP"
.br
.ti -1c
.RI "class \fBPasteBufferError\fP"
.br
.ti -1c
.RI "class \fBStatekeeper\fP"
.br
.ti -1c
.RI "class \fBStubbornDict\fP"
.br
.in -1c
.SS "Functions"

.in +1c
.ti -1c
.RI "def \fB_attr_get_\fP"
.br
.ti -1c
.RI "def \fBcast\fP"
.br
.ti -1c
.RI "def \fBget_paste_buffer\fP"
.br
.ti -1c
.RI "def \fBget_paste_buffer\fP"
.br
.ti -1c
.RI "def \fBljust\fP"
.br
.ti -1c
.RI "def \fBoptions\fP"
.br
.ti -1c
.RI "def \fBremaining_args\fP"
.br
.ti -1c
.RI "def \fBreplace_with_file_contents\fP"
.br
.ti -1c
.RI "def \fBstubbornDict\fP"
.br
.ti -1c
.RI "def \fBwrite_to_paste_buffer\fP"
.br
.in -1c
.SS "Variables"

.in +1c
.ti -1c
.RI "string \fB__version__\fP = '0\&.6\&.4'"
.br
.ti -1c
.RI "\fBcan_clip\fP = False"
.br
.ti -1c
.RI "list \fBoptions_defined\fP = []"
.br
.ti -1c
.RI "string \fBpastebufferr\fP"
.br
.ti -1c
.RI "string \fBteststring\fP = 'Testing for presence of xclip\&.'"
.br
.ti -1c
.RI "\fBwrite_to_paste_buffer\fP = get_paste_buffer"
.br
.ti -1c
.RI "tuple \fBxclipproc\fP = subprocess\&.Popen('xclip -sel clip', shell=True, stdout=subprocess\&.PIPE, stdin=subprocess\&.PIPE)"
.br
.in -1c
.SH "Detailed Description"
.PP 
.PP
.nf
Variant on standard library's cmd with extra features.

To use, simply import cmd2.Cmd instead of cmd.Cmd; use precisely as though you
were using the standard library's cmd, while enjoying the extra features.

Searchable command history (commands: "hi", "li", "run")
Load commands from file, save to file, edit commands in file
Multi-line commands
Case-insensitive commands
Special-character shortcut commands (beyond cmd's "@" and "!")
Settable environment parameters
Optional _onchange_{paramname} called when environment parameter changes
Parsing commands with `optparse` options (flags)
Redirection to file with >, >>; input from file with <
Easy transcript-based testing of applications (see example/example.py)
Bash-style ``select`` available

Note that redirection with > and | will only work if `self.stdout.write()`
is used in place of `print`.  The standard library's `cmd` module is 
written to use `self.stdout.write()`, 

- Catherine Devlin, Jan 03 2008 - catherinedevlin.blogspot.com

mercurial repository at http://www.assembla.com/wiki/show/python-cmd2
.fi
.PP
 
.SH "Function Documentation"
.PP 
.SS "def cmd2::_attr_get_ (obj, attr)\fC [private]\fP".PP
.nf
Returns an attribute's value, or None (no error) if undefined.
   Analagous to .get() for dictionaries.  Useful when checking for
   value of options that may not have been defined on a given
   method..fi
.PP
 
.PP
Definition at line 98 of file cmd2\&.py'\&.
.PP
.nf
98 
99 def _attr_get_(obj, attr):
100     '''Returns an attribute's value, or None (no error) if undefined\&.
101        Analagous to \&.get() for dictionaries\&.  Useful when checking for
102        value of options that may not have been defined on a given
103        method\&.'''
104     try:
105         return getattr(obj, attr)
106     except AttributeError:
107         return None
108     
109 optparse\&.Values\&.get = _attr_get_
    
.fi
.SS "def cmd2::cast (current, new)".PP
.nf
Tries to force a new value into the same type as the current..fi
.PP
 
.PP
Definition at line 1412 of file cmd2\&.py'\&.
.PP
Referenced by cmd2::Cmd::do_set()\&.
.PP
.nf
1412 
1413 def cast(current, new):
1414     '''Tries to force a new value into the same type as the current\&.'''
1415     typ = type(current)
1416     if typ == bool:
1417         try:
1418             return bool(int(new))
1419         except (ValueError, TypeError):
1420             pass
1421         try:
1422             new = new\&.lower()    
1423         except:
1424             pass
1425         if (new=='on') or (new[0] in ('y','t')):
1426             return True
1427         if (new=='off') or (new[0] in ('n','f')):
1428             return False
1429     else:
1430         try:
1431             return typ(new)
1432         except:
1433             pass
1434     print ('Problem setting parameter (now %s) to %s; incorrect type?' % (current, new))
1435     return current
        
.fi
.SS "def cmd2::get_paste_buffer ()"
.PP
Definition at line 184 of file cmd2\&.py'\&.
.PP
Referenced by get_paste_buffer(), cmd2::Cmd::redirect_output(), and replace_with_file_contents()\&.
.PP
.nf
184 
185         def get_paste_buffer():
186             win32clipboard\&.OpenClipboard(0)
187             try:
188                 result = win32clipboard\&.GetClipboardData()
189             except TypeError:
190                 result = ''  #non-text
191             win32clipboard\&.CloseClipboard()
            return result            
.fi
.SS "def cmd2::get_paste_buffer (args)"
.PP
Definition at line 198 of file cmd2\&.py'\&.
.PP
References get_paste_buffer()\&.
.PP
.nf
198 
199         def get_paste_buffer(*args):
            raise OSError, pastebufferr % ('pywin32', 'Download from http://sourceforge\&.net/projects/pywin32/')
.fi
.SS "def cmd2::ljust (x, width, fillchar = \fC' '\fP)"
.PP
Definition at line 352 of file cmd2\&.py'\&.
.PP
Referenced by cmd2::Cmd::do_show()\&.
.PP
.nf
352 
353 def ljust(x, width, fillchar=' '):
354     'analogous to str\&.ljust, but works for lists'
355     if hasattr(x, 'ljust'):
356         return x\&.ljust(width, fillchar)
357     else:
358         if len(x) < width:
359             x = (x + [fillchar] * width)[:width]
360         return x
    
.fi
.SS "def cmd2::options (option_list, arg_desc = \fC'arg'\fP)".PP
.nf
Used as a decorator and passed a list of optparse-style options,
   alters a cmd2 method to populate its ``opts`` argument from its
   raw text argument.

   Example: transform
   def do_something(self, arg):

   into
   @options([make_option('-q', '--quick', action="store_true",
             help="Makes things fast")],
             "source dest")
   def do_something(self, arg, opts):
       if opts.quick:
           self.fast_button = True
   .fi
.PP
 
.PP
Definition at line 112 of file cmd2\&.py'\&.
.PP
References remaining_args()\&.
.PP
Referenced by cmd2::Cmd::do_py(), pirate8::Pirate::do_sing(), and cmd2::Cmd::select()\&.
.PP
.nf
112 
113 def options(option_list, arg_desc='arg'):
114     '''Used as a decorator and passed a list of optparse-style options,
115        alters a cmd2 method to populate its ``opts`` argument from its
116        raw text argument\&.
117 
118        Example: transform
119        def do_something(self, arg):
120 
121        into
122        @options([make_option('-q', '--quick', action='store_true',
123                  help='Makes things fast')],
124                  'source dest')
125        def do_something(self, arg, opts):
126            if opts\&.quick:
127                self\&.fast_button = True
128        '''
129     if not isinstance(option_list, list):
130         option_list = [option_list]
131     for opt in option_list:
132         options_defined\&.append(pyparsing\&.Literal(opt\&.get_opt_string()))
133     def option_setup(func):
134         optionParser = OptionParser()
135         for opt in option_list:
136             optionParser\&.add_option(opt)
137         optionParser\&.set_usage('%s [options] %s' % (func\&.__name__[3:], arg_desc))
138         optionParser\&._func = func
139         def new_func(instance, arg):
140             try:
141                 opts, newArgList = optionParser\&.parse_args(arg\&.split())
142                 # Must find the remaining args in the original argument list, but 
143                 # mustn't include the command itself
144                 #if hasattr(arg, 'parsed') and newArgList[0] == arg\&.parsed\&.command:
145                 #    newArgList = newArgList[1:]
146                 newArgs = remaining_args(arg, newArgList)
147                 if isinstance(arg, ParsedString):
148                     arg = arg\&.with_args_replaced(newArgs)
149                 else:
150                     arg = newArgs
151             except optparse\&.OptParseError, e:
152                 print (e)
153                 optionParser\&.print_help()
154                 return
155             if hasattr(opts, '_exit'):
156                 return None
157             result = func(instance, arg, opts)                            
158             return result        
159         new_func\&.__doc__ = '%s\n%s' % (func\&.__doc__, optionParser\&.format_help())
160         return new_func
161     return option_setup

.fi
.SS "def cmd2::remaining_args (oldArgs, newArgList)".PP
.nf

Preserves the spacing originally in the argument after
the removal of options.

>>> remaining_args('-f bar   bar   cow', ['bar', 'cow'])
'bar   cow'
.fi
.PP
 
.PP
Definition at line 86 of file cmd2\&.py'\&.
.PP
Referenced by options()\&.
.PP
.nf
86 
87 def remaining_args(oldArgs, newArgList):
88     '''
89     Preserves the spacing originally in the argument after
90     the removal of options\&.
91     
92     >>> remaining_args('-f bar   bar   cow', ['bar', 'cow'])
93     'bar   cow'
94     '''
95     pattern = '\s+'\&.join(re\&.escape(a) for a in newArgList) + '\s*$'
96     matchObj = re\&.search(pattern, oldArgs)
97     return oldArgs[matchObj\&.start():]
   
.fi
.SS "def cmd2::replace_with_file_contents (fname)"
.PP
Definition at line 336 of file cmd2\&.py'\&.
.PP
References get_paste_buffer()\&.
.PP
.nf
336 
337 def replace_with_file_contents(fname):
338     if fname:
339         try:
340             result = open(os\&.path\&.expanduser(fname[0]))\&.read()
341         except IOError:
342             result = '< %s' % fname[0]  # wasn't a file after all
343     else:
344         result = get_paste_buffer()
345     return result      

.fi
.SS "def cmd2::stubbornDict (arg, kwarg)".PP
.nf

>>> sorted(stubbornDict('cow a bovine\\nhorse an equine').items())
[('cow', 'a bovine'), ('horse', 'an equine')]
>>> sorted(stubbornDict(['badger', 'porcupine a poky creature']).items())
[('badger', ''), ('porcupine', 'a poky creature')]
>>> sorted(stubbornDict(turtle='has shell', frog='jumpy').items())
[('frog', 'jumpy'), ('turtle', 'has shell')]
.fi
.PP
 
.PP
Definition at line 321 of file cmd2\&.py'\&.
.PP
Referenced by cmd2::StubbornDict::__add__(), and cmd2::StubbornDict::__radd__()\&.
.PP
.nf
321 
322 def stubbornDict(*arg, **kwarg):
323     '''
324     >>> sorted(stubbornDict('cow a bovine\\nhorse an equine')\&.items())
325     [('cow', 'a bovine'), ('horse', 'an equine')]
326     >>> sorted(stubbornDict(['badger', 'porcupine a poky creature'])\&.items())
327     [('badger', ''), ('porcupine', 'a poky creature')]
328     >>> sorted(stubbornDict(turtle='has shell', frog='jumpy')\&.items())
329     [('frog', 'jumpy'), ('turtle', 'has shell')]
330     '''
331     result = {}
332     for a in arg:
333         result\&.update(StubbornDict\&.to_dict(a))
334     result\&.update(kwarg)                      
335     return StubbornDict(result)
        
.fi
.SS "def \fBcmd2::write_to_paste_buffer\fP (txt)"
.PP
Definition at line 192 of file cmd2\&.py'\&.
.PP
References write_to_paste_buffer\&.
.PP
.nf
192 
193         def write_to_paste_buffer(txt):
194             win32clipboard\&.OpenClipboard(0)
195             win32clipboard\&.EmptyClipboard()
196             win32clipboard\&.SetClipboardText(txt)
            win32clipboard\&.CloseClipboard()        
.fi
.SH "Variable Documentation"
.PP 
.SS "string \fBcmd2::__version__\fP = '0\&.6\&.4'"
.PP
Definition at line 45 of file cmd2\&.py'\&.
.SS "\fBcmd2::can_clip\fP = False"
.PP
Definition at line 202 of file cmd2\&.py'\&.
.SS "list \fBcmd2::options_defined\fP = []"
.PP
Definition at line 110 of file cmd2\&.py'\&.
.SS "string \fBcmd2::pastebufferr\fP"\fBInitial value:\fP
.PP
.nf
1 '''Redirecting to or from paste buffer requires %s
2 to be installed on operating system\&.
3 %s'''
.fi
.PP
Definition at line 177 of file cmd2\&.py'\&.
.SS "string \fBcmd2::teststring\fP = 'Testing for presence of xclip\&.'"
.PP
Definition at line 227 of file cmd2\&.py'\&.
.SS "def \fBcmd2::write_to_paste_buffer\fP = get_paste_buffer"
.PP
Definition at line 200 of file cmd2\&.py'\&.
.PP
Referenced by cmd2::Cmd::restore_output(), and write_to_paste_buffer()\&.
.SS "tuple \fBcmd2::xclipproc\fP = subprocess\&.Popen('xclip -sel clip', shell=True, stdout=subprocess\&.PIPE, stdin=subprocess\&.PIPE)"
.PP
Definition at line 228 of file cmd2\&.py'\&.
.SH "Author"
.PP 
Generated automatically by Doxygen for Cmd2 from the source code'\&.