comparison cmd2.py @ 133:31674148b13c

just beginning to make comments work
author catherine@Elli.myhome.westell.com
date Sat, 08 Nov 2008 17:10:20 -0500
parents 197a312f2656
children c28ae4f75c15
comparison
equal deleted inserted replaced
126:197a312f2656 133:31674148b13c
149 return result 149 return result
150 150
151 class Cmd(cmd.Cmd): 151 class Cmd(cmd.Cmd):
152 echo = False 152 echo = False
153 caseInsensitive = True 153 caseInsensitive = True
154 multilineCommands = [] 154 multilineCommands = ['_multiline_comment']
155 continuationPrompt = '> ' 155 continuationPrompt = '> '
156 shortcuts = {'?': 'help', '!': 'shell', '@': 'load'} 156 shortcuts = {'?': 'help', '!': 'shell', '@': 'load', '/*': '_multiline_comment', '#': '_comment'}
157 excludeFromHistory = '''run r list l history hi ed edit li eof'''.split() 157 excludeFromHistory = '''run r list l history hi ed edit li eof'''.split()
158 noSpecialParse = 'set ed edit exit'.split() 158 noSpecialParse = 'set ed edit exit'.split()
159 defaultExtension = 'txt' 159 defaultExtension = 'txt'
160 defaultFileName = 'command.txt' 160 defaultFileName = 'command.txt'
161 editor = os.environ.get('EDITOR') 161 editor = os.environ.get('EDITOR')
167 for editor in ['gedit', 'kate', 'vim', 'emacs', 'nano', 'pico']: 167 for editor in ['gedit', 'kate', 'vim', 'emacs', 'nano', 'pico']:
168 if not os.system('which %s' % (editor)): 168 if not os.system('which %s' % (editor)):
169 break 169 break
170 170
171 settable = ['prompt', 'continuationPrompt', 'defaultFileName', 'editor', 'caseInsensitive', 'echo'] 171 settable = ['prompt', 'continuationPrompt', 'defaultFileName', 'editor', 'caseInsensitive', 'echo']
172 _TO_PASTE_BUFFER = 1
173 def do_cmdenvironment(self, args): 172 def do_cmdenvironment(self, args):
174 self.stdout.write(""" 173 self.stdout.write("""
175 Commands are %(casesensitive)scase-sensitive. 174 Commands are %(casesensitive)scase-sensitive.
176 Commands may be terminated with: %(terminators)s 175 Commands may be terminated with: %(terminators)s
177 Settable parameters: %(settable)s 176 Settable parameters: %(settable)s
192 191
193 def __init__(self, *args, **kwargs): 192 def __init__(self, *args, **kwargs):
194 cmd.Cmd.__init__(self, *args, **kwargs) 193 cmd.Cmd.__init__(self, *args, **kwargs)
195 self.history = History() 194 self.history = History()
196 195
196 def do__comment(self, arg):
197 pass
198 def do__multiline_comment(self, arg):
199 pass
200
197 def do_shortcuts(self, args): 201 def do_shortcuts(self, args):
198 """Lists single-key shortcuts available.""" 202 """Lists single-key shortcuts available."""
199 result = "\n".join('%s: %s' % (sc[0], sc[1]) for sc in self.shortcuts.items()) 203 result = "\n".join('%s: %s' % (sc[0], sc[1]) for sc in self.shortcuts.items())
200 self.stdout.write("Single-key shortcuts for other commands:\n%s\n" % (result)) 204 self.stdout.write("Single-key shortcuts for other commands:\n%s\n" % (result))
201 205
206 specialTerminators = {'/*': pyparsing.Literal('*/')('terminator') }
202 terminatorPattern = ((pyparsing.Literal(';') ^ pyparsing.Literal('\n\n')) 207 terminatorPattern = ((pyparsing.Literal(';') ^ pyparsing.Literal('\n\n'))
203 ^ (pyparsing.Literal('\nEOF') + pyparsing.lineEnd))('terminator') 208 ^ (pyparsing.Literal('\nEOF') + pyparsing.lineEnd))('terminator')
204 argSeparatorPattern = pyparsing.Word(pyparsing.printables)('command') \ 209 argSeparatorPattern = pyparsing.Word(pyparsing.printables)('command') \
205 + pyparsing.SkipTo(pyparsing.StringEnd())('args') 210 + pyparsing.SkipTo(pyparsing.StringEnd())('args')
206 filenamePattern = pyparsing.Word(pyparsing.alphanums + '#$-_~{},.!:\\/') 211 filenamePattern = pyparsing.Word(pyparsing.alphanums + '#$-_~{},.!:\\/')
207 integerPattern = pyparsing.Word(pyparsing.nums).setParseAction( lambda s,l,t: [ int(t[0]) ] ) 212 integerPattern = pyparsing.Word(pyparsing.nums).setParseAction( lambda s,l,t: [ int(t[0]) ] )
208 pipePattern = pyparsing.Literal('|')('pipe') + pyparsing.restOfLine('pipeTo') 213 pipePattern = pyparsing.Literal('|')('pipe') + pyparsing.restOfLine('pipeTo')
209 redirectOutPattern = (pyparsing.Literal('>>') ^ '>')('output') \ 214 redirectOutPattern = (pyparsing.Literal('>>') ^ '>')('output') \
210 + pyparsing.Optional(filenamePattern)('outputTo') 215 + pyparsing.Optional(filenamePattern)('outputTo')
211 redirectInPattern = pyparsing.Literal('<')('input') \ 216 redirectInPattern = pyparsing.Literal('<')('input') \
212 + pyparsing.Optional(filenamePattern)('inputFrom') 217 + pyparsing.Optional(filenamePattern)('inputFrom')
213 punctuationPattern = pipePattern ^ redirectInPattern ^ redirectOutPattern 218 punctuationPattern = pipePattern ^ redirectInPattern ^ redirectOutPattern
214 for p in (terminatorPattern, pipePattern, redirectInPattern, redirectOutPattern, punctuationPattern): 219 for p in (terminatorPattern, pipePattern, redirectInPattern, redirectOutPattern, punctuationPattern):
215 p.ignore(pyparsing.sglQuotedString) 220 p.ignore(pyparsing.sglQuotedString)
216 p.ignore(pyparsing.dblQuotedString) 221 p.ignore(pyparsing.dblQuotedString)
217 222
245 '''if command in self.noSpecialParse: 250 '''if command in self.noSpecialParse:
246 result['statement'] = result['upToIncluding'] = result['unterminated'] = result.fullStatement 251 result['statement'] = result['upToIncluding'] = result['unterminated'] = result.fullStatement
247 result['command'] = command 252 result['command'] = command
248 result['args'] = ' '.join(result.fullStatement.split()[1:]) 253 result['args'] = ' '.join(result.fullStatement.split()[1:])
249 return result''' 254 return result'''
250 if s[0] in self.shortcuts: 255 for (shortcut, fullCommand) in self.shortcuts.items():
251 s = self.shortcuts[s[0]] + ' ' + s[1:] 256 if s.startswith(shortcut):
257 s = s.replace(shortcut, fullCommand + ' ', 1)
258 break
252 result['statement'] = s 259 result['statement'] = s
253 result['parseable'] = s 260 result['parseable'] = s
254 result += parseSearchResults(self.terminatorPattern, s) 261 terminator = self.specialTerminators.get(command) or self.terminatorPattern
262 result += parseSearchResults(terminator, s)
255 if result.terminator: 263 if result.terminator:
256 result['statement'] = result.upToIncluding 264 result['statement'] = result.upToIncluding
257 result['unterminated'] = result.before 265 result['unterminated'] = result.before
258 result['parseable'] = result.after 266 result['parseable'] = result.after
259 else: 267 else:
328 else: 336 else:
329 statekeeper = Statekeeper(self, ('stdout',)) 337 statekeeper = Statekeeper(self, ('stdout',))
330 self.stdout = tempfile.TemporaryFile() 338 self.stdout = tempfile.TemporaryFile()
331 if statement.output == '>>': 339 if statement.output == '>>':
332 self.stdout.write(getPasteBuffer()) 340 self.stdout.write(getPasteBuffer())
333 stop = cmd.Cmd.onecmd(self, statement.statement) 341 try:
342 stop = cmd.Cmd.onecmd(self, statement.statement)
343 except Exception, e:
344 print e
334 try: 345 try:
335 if statement.command not in self.excludeFromHistory: 346 if statement.command not in self.excludeFromHistory:
336 self.history.append(statement.fullStatement) 347 self.history.append(statement.fullStatement)
337 finally: 348 finally:
338 if statekeeper: 349 if statekeeper:
412 423
413 def do_EOF(self, arg): 424 def do_EOF(self, arg):
414 return True 425 return True
415 do_eof = do_EOF 426 do_eof = do_EOF
416 427
417 def clean(self, s):
418 """cleans up a string"""
419 if self.caseInsensitive:
420 return s.strip().lower()
421 return s.strip()
422
423 def showParam(self, param): 428 def showParam(self, param):
424 param = self.clean(param) 429 param = param.strip().lower()
425 if param in self.settable: 430 if param in self.settable:
426 val = getattr(self, param) 431 val = getattr(self, param)
427 self.stdout.write('%s: %s\n' % (param, str(getattr(self, param)))) 432 self.stdout.write('%s: %s\n' % (param, str(getattr(self, param))))
428 433
429 def do_quit(self, arg): 434 def do_quit(self, arg):
441 446
442 def do_set(self, arg): 447 def do_set(self, arg):
443 'Sets a parameter' 448 'Sets a parameter'
444 try: 449 try:
445 paramName, val = arg.split(None, 1) 450 paramName, val = arg.split(None, 1)
446 paramName = self.clean(paramName) 451 paramName = paramName.strip().lower()
447 if paramName not in self.settable: 452 if paramName not in self.settable:
448 raise NotSettableError 453 raise NotSettableError
449 currentVal = getattr(self, paramName) 454 currentVal = getattr(self, paramName)
450 if (val[0] == val[-1]) and val[0] in ("'", '"'): 455 if (val[0] == val[-1]) and val[0] in ("'", '"'):
451 val = val[1:-1] 456 val = val[1:-1]
478 try: 483 try:
479 if arg: 484 if arg:
480 return self.history.get(arg)[-1] 485 return self.history.get(arg)[-1]
481 else: 486 else:
482 return self.history[-1] 487 return self.history[-1]
483 except: 488 except IndexError:
484 return None 489 return None
485 def do_list(self, arg): 490 def do_list(self, arg):
486 """list [arg]: lists last command issued 491 """list [arg]: lists last command issued
487 492
488 no arg -> list absolute last 493 no arg -> list absolute last
509 to control which editing program is used.""" 514 to control which editing program is used."""
510 if not self.editor: 515 if not self.editor:
511 print "please use 'set editor' to specify your text editing program of choice." 516 print "please use 'set editor' to specify your text editing program of choice."
512 return 517 return
513 filename = self.defaultFileName 518 filename = self.defaultFileName
514 buffer = '' 519 if arg:
515 try: 520 try:
516 arg = int(arg) 521 buffer = self.last_matching(int(arg))
517 buffer = self.last_matching(arg) 522 except ValueError:
518 except:
519 if arg:
520 filename = arg 523 filename = arg
521 else: 524 buffer = ''
522 buffer = self.last_matching(arg) 525 else:
526 buffer = self.history[-1]
523 527
524 if buffer: 528 if buffer:
525 f = open(filename, 'w') 529 f = open(filename, 'w')
526 f.write(buffer or '') 530 f.write(buffer or '')
527 f.close() 531 f.close()