comparison cmd2.py @ 244:e0c60ea7ad5d

midway through py script change
author catherine@Elli.myhome.westell.com
date Wed, 25 Mar 2009 14:08:01 -0400
parents de3e2a040279
children 2cda5a817e5a
comparison
equal deleted inserted replaced
243:de3e2a040279 244:e0c60ea7ad5d
255 echo = False 255 echo = False
256 case_insensitive = True 256 case_insensitive = True
257 continuation_prompt = '> ' 257 continuation_prompt = '> '
258 timing = False 258 timing = False
259 legalChars = '!#$%.:?@_' + pyparsing.alphanums + pyparsing.alphas8bit # make sure your terminators are not in here! 259 legalChars = '!#$%.:?@_' + pyparsing.alphanums + pyparsing.alphas8bit # make sure your terminators are not in here!
260 shortcuts = {'?': 'help', '!': 'shell', '@': 'load' } 260 shortcuts = {'?': 'help', '!': 'shell', '@': 'load', '@@': '_relative_load'}
261 excludeFromHistory = '''run r list l history hi ed edit li eof'''.split() 261 excludeFromHistory = '''run r list l history hi ed edit li eof'''.split()
262 noSpecialParse = 'set ed edit exit'.split() 262 noSpecialParse = 'set ed edit exit'.split()
263 defaultExtension = 'txt' 263 defaultExtension = 'txt'
264 default_file_name = 'command.txt' 264 default_file_name = 'command.txt'
265 abbrev = True 265 abbrev = True
266 nonpythoncommand = 'cmd' 266 nonpythoncommand = 'cmd'
267 current_script_dir = None
267 settable = ['prompt', 'continuation_prompt', 'default_file_name', 'editor', 268 settable = ['prompt', 'continuation_prompt', 'default_file_name', 'editor',
268 'case_insensitive', 'echo', 'timing', 'abbrev'] 269 'case_insensitive', 'echo', 'timing', 'abbrev']
269 settable.sort() 270 settable.sort()
270 271
271 editor = os.environ.get('EDITOR') 272 editor = os.environ.get('EDITOR')
302 def __init__(self, *args, **kwargs): 303 def __init__(self, *args, **kwargs):
303 cmd.Cmd.__init__(self, *args, **kwargs) 304 cmd.Cmd.__init__(self, *args, **kwargs)
304 self.history = History() 305 self.history = History()
305 self._init_parser() 306 self._init_parser()
306 self.pystate = {} 307 self.pystate = {}
308 self.shortcuts = sorted(self.shortcuts.items(), reverse=True)
307 309
308 def do_shortcuts(self, args): 310 def do_shortcuts(self, args):
309 """Lists single-key shortcuts available.""" 311 """Lists single-key shortcuts available."""
310 result = "\n".join('%s: %s' % (sc[0], sc[1]) for sc in self.shortcuts.items()) 312 result = "\n".join('%s: %s' % (sc[0], sc[1]) for sc in sorted(self.shortcuts))
311 self.stdout.write("Single-key shortcuts for other commands:\n%s\n" % (result)) 313 self.stdout.write("Single-key shortcuts for other commands:\n%s\n" % (result))
312 314
313 prefixParser = pyparsing.Empty() 315 prefixParser = pyparsing.Empty()
314 commentGrammars = pyparsing.Or([pyparsing.pythonStyleComment, pyparsing.cStyleComment]) 316 commentGrammars = pyparsing.Or([pyparsing.pythonStyleComment, pyparsing.cStyleComment])
315 commentGrammars.addParseAction(lambda x: '') 317 commentGrammars.addParseAction(lambda x: '')
533 if isinstance(raw, ParsedString): 535 if isinstance(raw, ParsedString):
534 p = raw 536 p = raw
535 else: 537 else:
536 raw = self.preparse(raw, **kwargs) 538 raw = self.preparse(raw, **kwargs)
537 s = self.inputParser.transformString(raw.lstrip()) 539 s = self.inputParser.transformString(raw.lstrip())
538 for (shortcut, expansion) in self.shortcuts.items(): 540 for (shortcut, expansion) in self.shortcuts:
539 if s.lower().startswith(shortcut): 541 if s.lower().startswith(shortcut):
540 s = s.replace(shortcut, expansion + ' ', 1) 542 s = s.replace(shortcut, expansion + ' ', 1)
541 break 543 break
542 result = self.parser.parseString(s) 544 result = self.parser.parseString(s)
543 result['command'] = result.multilineCommand or result.command 545 result['command'] = result.multilineCommand or result.command
807 self.pystate['quit'] = quit 809 self.pystate['quit'] = quit
808 self.pystate['exit'] = quit 810 self.pystate['exit'] = quit
809 self.pystate[self.nonpythoncommand] = onecmd 811 self.pystate[self.nonpythoncommand] = onecmd
810 try: 812 try:
811 cprt = 'Type "help", "copyright", "credits" or "license" for more information.' 813 cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
814 keepstate = Statekeeper(sys, ('stdin','stdout'))
815 sys.stdout = self.stdout
816 sys.stdin = self.stdin
812 interp.interact(banner= "Python %s on %s\n%s\n(%s)\n%s" % 817 interp.interact(banner= "Python %s on %s\n%s\n(%s)\n%s" %
813 (sys.version, sys.platform, cprt, self.__class__.__name__, self.do_py.__doc__)) 818 (sys.version, sys.platform, cprt, self.__class__.__name__, self.do_py.__doc__))
819 keepstate.restore()
814 except EmbeddedConsoleExit: 820 except EmbeddedConsoleExit:
815 return 821 return
816 822
817 def do_history(self, arg): 823 def do_history(self, arg):
818 """history [arg]: lists past commands issued 824 """history [arg]: lists past commands issued
910 f.close() 916 f.close()
911 print 'Saved to %s' % (fname) 917 print 'Saved to %s' % (fname)
912 except Exception, e: 918 except Exception, e:
913 print 'Error saving %s: %s' % (fname, str(e)) 919 print 'Error saving %s: %s' % (fname, str(e))
914 920
921 def read_file_or_url(self, fname):
922 if isinstance(fname, file):
923 target = open(fname, 'r')
924 else:
925 match = self.urlre.match(fname)
926 if match:
927 target = urllib.urlopen(match.group(1))
928 else:
929 fname = os.path.expanduser(fname)
930 try:
931 result = open(os.path.expanduser(fname), 'r')
932 except IOError, e:
933 result = open('%s.%s' % (os.path.expanduser(fname),
934 self.defaultExtension), 'r')
935 return result
936
937 def do__relative_load(self, arg=None):
938 '''
939 Runs commands in script at file or URL; if this is called from within an
940 already-running script, the filename will be interpreted relative to the
941 already-running script's directory.'''
942 if arg:
943 arg = arg.split(None, 1)
944 targetname, args = arg[0], (arg[1:] or [''])[0]
945 targetname = os.path.join(self.current_script_dir or '', targetname)
946 self.do__load('%s %s' % (targetname, args))
947
915 urlre = re.compile('(https?://[-\\w\\./]+)') 948 urlre = re.compile('(https?://[-\\w\\./]+)')
916 def do_load(self, fname=None): 949 def do_load(self, arg=None):
917 """Runs script of command(s) from a file or URL.""" 950 """Runs script of command(s) from a file or URL."""
918 if fname is None: 951 if arg is None:
919 fname = self.default_file_name 952 targetname = self.default_file_name
920 keepstate = Statekeeper(self, ('stdin','use_rawinput','prompt','continuation_prompt')) 953 else:
921 try: 954 arg = arg.split(None, 1)
922 if isinstance(fname, file): 955 targetname, args = arg[0], (arg[1:] or [''])[0].strip()
923 target = open(fname, 'r') 956 try:
924 else: 957 target = self.read_file_or_url(targetname)
925 match = self.urlre.match(fname)
926 if match:
927 target = urllib.urlopen(match.group(1))
928 else:
929 fname = os.path.expanduser(fname)
930 try:
931 target = open(os.path.expanduser(fname), 'r')
932 except IOError, e:
933 target = open('%s.%s' % (os.path.expanduser(fname),
934 self.defaultExtension), 'r')
935 except IOError, e: 958 except IOError, e:
936 print 'Problem accessing script from %s: \n%s' % (fname, e) 959 print 'Problem accessing script from %s: \n%s' % (targetname, e)
937 keepstate.restore()
938 return 960 return
961 keepstate = Statekeeper(self, ('stdin','use_rawinput','prompt',
962 'continuation_prompt','current_script_dir'))
939 self.stdin = target 963 self.stdin = target
940 self.use_rawinput = False 964 self.use_rawinput = False
941 self.prompt = self.continuation_prompt = '' 965 self.prompt = self.continuation_prompt = ''
966 self.current_script_dir = os.path.split(targetname)[0]
942 stop = self.cmdloop() 967 stop = self.cmdloop()
943 self.stdin.close() 968 self.stdin.close()
944 keepstate.restore() 969 keepstate.restore()
945 self.lastcmd = '' 970 self.lastcmd = ''
946 return (stop == self._STOP_AND_EXIT) and self._STOP_AND_EXIT 971 return (stop == self._STOP_AND_EXIT) and self._STOP_AND_EXIT