comparison cmd2.py @ 280:38198b11f48c

adding .get() to opts
author catherine@DellZilla
date Wed, 07 Oct 2009 13:33:58 -0400
parents c6064bfd4d6c
children f4e8819a683a 7c6eb0fc75ef
comparison
equal deleted inserted replaced
279:c6064bfd4d6c 280:38198b11f48c
24 """ 24 """
25 import cmd, re, os, sys, optparse, subprocess, tempfile, pyparsing, doctest 25 import cmd, re, os, sys, optparse, subprocess, tempfile, pyparsing, doctest
26 import unittest, string, datetime, urllib, glob 26 import unittest, string, datetime, urllib, glob
27 from code import InteractiveConsole, InteractiveInterpreter, softspace 27 from code import InteractiveConsole, InteractiveInterpreter, softspace
28 from optparse import make_option 28 from optparse import make_option
29 __version__ = '0.5.5' 29 __version__ = '0.5.6'
30 30
31 class OptionParser(optparse.OptionParser): 31 class OptionParser(optparse.OptionParser):
32 def exit(self, status=0, msg=None): 32 def exit(self, status=0, msg=None):
33 self.values._exit = True 33 self.values._exit = True
34 if msg: 34 if msg:
57 'bar cow' 57 'bar cow'
58 ''' 58 '''
59 pattern = '\s+'.join(re.escape(a) for a in newArgList) + '\s*$' 59 pattern = '\s+'.join(re.escape(a) for a in newArgList) + '\s*$'
60 matchObj = re.search(pattern, oldArgs) 60 matchObj = re.search(pattern, oldArgs)
61 return oldArgs[matchObj.start():] 61 return oldArgs[matchObj.start():]
62
63 def _attr_get_(obj, attr):
64 '''Returns an attribute's value, or None (no error) if undefined.
65 Analagous to .get() for dictionaries.'''
66 try:
67 return getattr(obj, attr)
68 except AttributeError:
69 return None
62 70
63 def options(option_list): 71 def options(option_list):
64 def option_setup(func): 72 def option_setup(func):
65 optionParser = OptionParser() 73 optionParser = OptionParser()
66 for opt in option_list: 74 for opt in option_list:
68 optionParser.set_usage("%s [options] arg" % func.__name__.strip('do_')) 76 optionParser.set_usage("%s [options] arg" % func.__name__.strip('do_'))
69 optionParser._func = func 77 optionParser._func = func
70 def newFunc(instance, arg): 78 def newFunc(instance, arg):
71 try: 79 try:
72 opts, newArgList = optionParser.parse_args(arg.split()) # doesn't understand quoted strings shouldn't be dissected! 80 opts, newArgList = optionParser.parse_args(arg.split()) # doesn't understand quoted strings shouldn't be dissected!
81 opts.get = _attr_get_
73 newArgs = remainingArgs(arg, newArgList) # should it permit flags after args? 82 newArgs = remainingArgs(arg, newArgList) # should it permit flags after args?
74 except (optparse.OptionValueError, optparse.BadOptionError, 83 except (optparse.OptionValueError, optparse.BadOptionError,
75 optparse.OptionError, optparse.AmbiguousOptionError, 84 optparse.OptionError, optparse.AmbiguousOptionError,
76 optparse.OptionConflictError), e: 85 optparse.OptionConflictError), e:
77 print e 86 print e
561 s = s.replace(shortcut, expansion + ' ', 1) 570 s = s.replace(shortcut, expansion + ' ', 1)
562 break 571 break
563 result = self.parser.parseString(s) 572 result = self.parser.parseString(s)
564 result['command'] = result.multilineCommand or result.command 573 result['command'] = result.multilineCommand or result.command
565 result['raw'] = raw 574 result['raw'] = raw
566 result['clean'] = self.commentGrammars.transformString(result.args) 575 result['clean'] = self.commentGrammars.transformString(result.args) # oh no, strips ls box/*
567 result['expanded'] = s 576 result['expanded'] = s
568 p = ParsedString(result.clean) 577 p = ParsedString(result.clean)
569 p.parsed = result 578 p.parsed = result
570 p.parser = self.parsed 579 p.parser = self.parsed
571 for (key, val) in kwargs.items(): 580 for (key, val) in kwargs.items():
813 py <command>: Executes a Python command. 822 py <command>: Executes a Python command.
814 py: Enters interactive Python mode. 823 py: Enters interactive Python mode.
815 End with `Ctrl-D` (Unix) / `Ctrl-Z` (Windows), `quit()`, 'exit()`. 824 End with `Ctrl-D` (Unix) / `Ctrl-Z` (Windows), `quit()`, 'exit()`.
816 Non-python commands can be issued with `cmd("your command")`. 825 Non-python commands can be issued with `cmd("your command")`.
817 ''' 826 '''
827 self.pystate['self'] = self
818 arg = arg.parsed.raw[2:].strip() 828 arg = arg.parsed.raw[2:].strip()
819 if arg.strip(): 829 if arg.strip():
820 interp = InteractiveInterpreter(locals=self.pystate) 830 interp = InteractiveInterpreter(locals=self.pystate)
821 interp.runcode(arg) 831 interp.runcode(arg)
822 else: 832 else: