Mercurial > python-cmd2
comparison cmd2.py @ 207:a3bec7704e65
tweaking
author | catherine@dellzilla |
---|---|
date | Wed, 04 Mar 2009 17:44:57 -0500 |
parents | 00eaec841567 |
children | f10bd1f0c7e3 |
comparison
equal
deleted
inserted
replaced
206:00eaec841567 | 207:a3bec7704e65 |
---|---|
209 result = getPasteBuffer() | 209 result = getPasteBuffer() |
210 return result | 210 return result |
211 | 211 |
212 class Cmd(cmd.Cmd): | 212 class Cmd(cmd.Cmd): |
213 echo = False | 213 echo = False |
214 caseInsensitive = True | 214 case_insensitive = True |
215 continuationprompt = '> ' | 215 continuation_prompt = '> ' |
216 timing = False | 216 timing = False |
217 legalChars = '!#$%.:?@_' + pyparsing.alphanums + pyparsing.alphas8bit # make sure your terminators are not in here! | 217 legalChars = '!#$%.:?@_' + pyparsing.alphanums + pyparsing.alphas8bit # make sure your terminators are not in here! |
218 shortcuts = {'?': 'help', '!': 'shell', '@': 'load' } | 218 shortcuts = {'?': 'help', '!': 'shell', '@': 'load' } |
219 excludeFromHistory = '''run r list l history hi ed edit li eof'''.split() | 219 excludeFromHistory = '''run r list l history hi ed edit li eof'''.split() |
220 noSpecialParse = 'set ed edit exit'.split() | 220 noSpecialParse = 'set ed edit exit'.split() |
221 defaultExtension = 'txt' | 221 defaultExtension = 'txt' |
222 defaultFileName = 'command.txt' | 222 default_file_name = 'command.txt' |
223 settable = ['prompt', 'continuationprompt', 'defaultFileName', 'editor', 'caseInsensitive', | 223 settable = ['prompt', 'continuation_prompt', 'default_file_name', 'editor', 'case_insensitive', |
224 'echo', 'timing'] | 224 'echo', 'timing'] |
225 settable.sort() | 225 settable.sort() |
226 | 226 |
227 editor = os.environ.get('EDITOR') | 227 editor = os.environ.get('EDITOR') |
228 _STOP_AND_EXIT = 2 | 228 _STOP_AND_EXIT = 2 |
239 self.stdout.write(""" | 239 self.stdout.write(""" |
240 Commands are %(casesensitive)scase-sensitive. | 240 Commands are %(casesensitive)scase-sensitive. |
241 Commands may be terminated with: %(terminators)s | 241 Commands may be terminated with: %(terminators)s |
242 Settable parameters: %(settable)s | 242 Settable parameters: %(settable)s |
243 """ % | 243 """ % |
244 { 'casesensitive': (self.caseInsensitive and 'not ') or '', | 244 { 'casesensitive': (self.case_insensitive and 'not ') or '', |
245 'terminators': str(self.terminators), | 245 'terminators': str(self.terminators), |
246 'settable': ' '.join(self.settable) | 246 'settable': ' '.join(self.settable) |
247 }) | 247 }) |
248 | 248 |
249 def do_help(self, arg): | 249 def do_help(self, arg): |
274 | 274 |
275 def _init_parser(self): | 275 def _init_parser(self): |
276 r''' | 276 r''' |
277 >>> c = Cmd() | 277 >>> c = Cmd() |
278 >>> c.multilineCommands = ['multiline'] | 278 >>> c.multilineCommands = ['multiline'] |
279 >>> c.caseInsensitive = True | 279 >>> c.case_insensitive = True |
280 >>> c._init_parser() | 280 >>> c._init_parser() |
281 >>> print c.parser.parseString('').dump() | 281 >>> print c.parser.parseString('').dump() |
282 [] | 282 [] |
283 >>> print c.parser.parseString('/* empty command */').dump() | 283 >>> print c.parser.parseString('/* empty command */').dump() |
284 [] | 284 [] |
432 ''' | 432 ''' |
433 outputParser = (pyparsing.Literal('>>') | (pyparsing.WordStart() + '>') | pyparsing.Regex('[^=]>'))('output') | 433 outputParser = (pyparsing.Literal('>>') | (pyparsing.WordStart() + '>') | pyparsing.Regex('[^=]>'))('output') |
434 | 434 |
435 terminatorParser = pyparsing.Or([(hasattr(t, 'parseString') and t) or pyparsing.Literal(t) for t in self.terminators])('terminator') | 435 terminatorParser = pyparsing.Or([(hasattr(t, 'parseString') and t) or pyparsing.Literal(t) for t in self.terminators])('terminator') |
436 stringEnd = pyparsing.stringEnd ^ '\nEOF' | 436 stringEnd = pyparsing.stringEnd ^ '\nEOF' |
437 self.multilineCommand = pyparsing.Or([pyparsing.Keyword(c, caseless=self.caseInsensitive) for c in self.multilineCommands])('multilineCommand') | 437 self.multilineCommand = pyparsing.Or([pyparsing.Keyword(c, caseless=self.case_insensitive) for c in self.multilineCommands])('multilineCommand') |
438 oneLineCommand = (~self.multilineCommand + pyparsing.Word(self.legalChars))('command') | 438 oneLineCommand = (~self.multilineCommand + pyparsing.Word(self.legalChars))('command') |
439 pipe = pyparsing.Keyword('|', identChars='|') | 439 pipe = pyparsing.Keyword('|', identChars='|') |
440 self.commentGrammars.ignore(pyparsing.quotedString).setParseAction(lambda x: '') | 440 self.commentGrammars.ignore(pyparsing.quotedString).setParseAction(lambda x: '') |
441 self.commentInProgress.ignore(pyparsing.quotedString).ignore(pyparsing.cStyleComment) | 441 self.commentInProgress.ignore(pyparsing.quotedString).ignore(pyparsing.cStyleComment) |
442 afterElements = \ | 442 afterElements = \ |
443 pyparsing.Optional(pipe + pyparsing.SkipTo(outputParser ^ stringEnd)('pipeTo')) + \ | 443 pyparsing.Optional(pipe + pyparsing.SkipTo(outputParser ^ stringEnd)('pipeTo')) + \ |
444 pyparsing.Optional(outputParser + pyparsing.SkipTo(stringEnd).setParseAction(lambda x: x[0].strip())('outputTo')) | 444 pyparsing.Optional(outputParser + pyparsing.SkipTo(stringEnd).setParseAction(lambda x: x[0].strip())('outputTo')) |
445 if self.caseInsensitive: | 445 if self.case_insensitive: |
446 self.multilineCommand.setParseAction(lambda x: x[0].lower()) | 446 self.multilineCommand.setParseAction(lambda x: x[0].lower()) |
447 oneLineCommand.setParseAction(lambda x: x[0].lower()) | 447 oneLineCommand.setParseAction(lambda x: x[0].lower()) |
448 if self.blankLinesAllowed: | 448 if self.blankLinesAllowed: |
449 self.blankLineTerminationParser = pyparsing.NoMatch | 449 self.blankLineTerminationParser = pyparsing.NoMatch |
450 else: | 450 else: |
517 return 0 # command was empty except for comments | 517 return 0 # command was empty except for comments |
518 try: | 518 try: |
519 statement = self.parsed(line) | 519 statement = self.parsed(line) |
520 while statement.parsed.multilineCommand and (statement.parsed.terminator == ''): | 520 while statement.parsed.multilineCommand and (statement.parsed.terminator == ''): |
521 statement = '%s\n%s' % (statement.parsed.raw, | 521 statement = '%s\n%s' % (statement.parsed.raw, |
522 self.pseudo_raw_input(self.continuationprompt)) | 522 self.pseudo_raw_input(self.continuation_prompt)) |
523 statement = self.parsed(statement) | 523 statement = self.parsed(statement) |
524 except Exception, e: | 524 except Exception, e: |
525 print e | 525 print e |
526 return 0 | 526 return 0 |
527 | 527 |
751 "set edit (program-name)" or set EDITOR environment variable | 751 "set edit (program-name)" or set EDITOR environment variable |
752 to control which editing program is used.""" | 752 to control which editing program is used.""" |
753 if not self.editor: | 753 if not self.editor: |
754 print "please use 'set editor' to specify your text editing program of choice." | 754 print "please use 'set editor' to specify your text editing program of choice." |
755 return | 755 return |
756 filename = self.defaultFileName | 756 filename = self.default_file_name |
757 if arg: | 757 if arg: |
758 try: | 758 try: |
759 buffer = self.last_matching(int(arg)) | 759 buffer = self.last_matching(int(arg)) |
760 except ValueError: | 760 except ValueError: |
761 filename = arg | 761 filename = arg |
784 try: | 784 try: |
785 args = self.saveparser.parseString(arg) | 785 args = self.saveparser.parseString(arg) |
786 except pyparsing.ParseException: | 786 except pyparsing.ParseException: |
787 print self.do_save.__doc__ | 787 print self.do_save.__doc__ |
788 return | 788 return |
789 fname = args.fname or self.defaultFileName | 789 fname = args.fname or self.default_file_name |
790 if args.idx == '*': | 790 if args.idx == '*': |
791 saveme = '\n\n'.join(self.history[:]) | 791 saveme = '\n\n'.join(self.history[:]) |
792 elif args.idx: | 792 elif args.idx: |
793 saveme = self.history[int(args.idx)-1] | 793 saveme = self.history[int(args.idx)-1] |
794 else: | 794 else: |
802 print 'Error saving %s: %s' % (fname, str(e)) | 802 print 'Error saving %s: %s' % (fname, str(e)) |
803 | 803 |
804 def do_load(self, fname=None): | 804 def do_load(self, fname=None): |
805 """Runs command(s) from a file.""" | 805 """Runs command(s) from a file.""" |
806 if fname is None: | 806 if fname is None: |
807 fname = self.defaultFileName | 807 fname = self.default_file_name |
808 fname = os.path.expanduser(fname) | 808 fname = os.path.expanduser(fname) |
809 keepstate = Statekeeper(self, ('stdin','use_rawinput','prompt','continuationprompt')) | 809 keepstate = Statekeeper(self, ('stdin','use_rawinput','prompt','continuation_prompt')) |
810 if isinstance(fname, file): | 810 if isinstance(fname, file): |
811 self.stdin = fname | 811 self.stdin = fname |
812 else: | 812 else: |
813 try: | 813 try: |
814 self.stdin = open(os.path.expanduser(fname), 'r') | 814 self.stdin = open(os.path.expanduser(fname), 'r') |
818 except IOError: | 818 except IOError: |
819 print 'Problem opening file %s: \n%s' % (fname, e) | 819 print 'Problem opening file %s: \n%s' % (fname, e) |
820 keepstate.restore() | 820 keepstate.restore() |
821 return | 821 return |
822 self.use_rawinput = False | 822 self.use_rawinput = False |
823 self.prompt = self.continuationprompt = '' | 823 self.prompt = self.continuation_prompt = '' |
824 stop = self.cmdloop() | 824 stop = self.cmdloop() |
825 self.stdin.close() | 825 self.stdin.close() |
826 keepstate.restore() | 826 keepstate.restore() |
827 self.lastcmd = '' | 827 self.lastcmd = '' |
828 return (stop == self._STOP_AND_EXIT) and self._STOP_AND_EXIT | 828 return (stop == self._STOP_AND_EXIT) and self._STOP_AND_EXIT |
990 while True: | 990 while True: |
991 while not line.startswith(self.cmdapp.prompt): | 991 while not line.startswith(self.cmdapp.prompt): |
992 line = self.transcript.next() | 992 line = self.transcript.next() |
993 command = [line[len(self.cmdapp.prompt):]] | 993 command = [line[len(self.cmdapp.prompt):]] |
994 line = self.transcript.next() | 994 line = self.transcript.next() |
995 while line.startswith(self.cmdapp.continuationprompt): | 995 while line.startswith(self.cmdapp.continuation_prompt): |
996 command.append(line[len(self.cmdapp.continuationprompt):]) | 996 command.append(line[len(self.cmdapp.continuation_prompt):]) |
997 line = self.transcript.next() | 997 line = self.transcript.next() |
998 command = ''.join(command) | 998 command = ''.join(command) |
999 self.cmdapp.onecmd(command) | 999 self.cmdapp.onecmd(command) |
1000 result = self.outputTrap.read() | 1000 result = self.outputTrap.read() |
1001 if line.startswith(self.cmdapp.prompt): | 1001 if line.startswith(self.cmdapp.prompt): |