comparison cmd2.py @ 267:3333e61e7103

poutput, perror, pfeedback
author Catherine Devlin <catherine.devlin@gmail.com>
date Tue, 07 Apr 2009 18:26:41 -0400
parents ba45c2df855b
children 8f68e68033d4
comparison
equal deleted inserted replaced
265:ba45c2df855b 267:3333e61e7103
261 default_file_name = 'command.txt' 261 default_file_name = 'command.txt'
262 abbrev = True 262 abbrev = True
263 nonpythoncommand = 'cmd' 263 nonpythoncommand = 'cmd'
264 current_script_dir = None 264 current_script_dir = None
265 reserved_words = [] 265 reserved_words = []
266 feedback_to_output = False
267 quiet = False
266 settable = ['prompt', 'continuation_prompt', 'default_file_name', 'editor', 268 settable = ['prompt', 'continuation_prompt', 'default_file_name', 'editor',
267 'case_insensitive', 'echo', 'timing', 'abbrev'] 269 'case_insensitive', 'feedback_to_output', 'quiet', 'echo', 'timing',
270 'abbrev']
268 settable.sort() 271 settable.sort()
269 272
273 def poutput(self, msg):
274 self.stdout.write(msg)
275 if msg[-1] != '\n':
276 self.stdout('\n')
277 def perror(self, errmsg):
278 print str(errmsg)
279 def pfeedback(self, msg):
280 """For printing nonessential feedback. Can be silenced with `quiet`.
281 Inclusion in redirected output is controlled by `feedback_to_output`."""
282 if not self.quiet:
283 if self.feedback_to_output:
284 self.poutput(msg)
285 else:
286 print msg
270 editor = os.environ.get('EDITOR') 287 editor = os.environ.get('EDITOR')
271 _STOP_AND_EXIT = 2 288 _STOP_AND_EXIT = 2
272 if not editor: 289 if not editor:
273 if sys.platform[:3] == 'win': 290 if sys.platform[:3] == 'win':
274 editor = 'notepad' 291 editor = 'notepad'
591 while statement.parsed.multilineCommand and (statement.parsed.terminator == ''): 608 while statement.parsed.multilineCommand and (statement.parsed.terminator == ''):
592 statement = '%s\n%s' % (statement.parsed.raw, 609 statement = '%s\n%s' % (statement.parsed.raw,
593 self.pseudo_raw_input(self.continuation_prompt)) 610 self.pseudo_raw_input(self.continuation_prompt))
594 statement = self.parsed(statement) 611 statement = self.parsed(statement)
595 except Exception, e: 612 except Exception, e:
596 print e 613 self.perror(e)
597 return 0 614 return 0
598 if statement.parsed.command not in self.excludeFromHistory: 615 if statement.parsed.command not in self.excludeFromHistory:
599 self.history.append(statement.parsed.raw) 616 self.history.append(statement.parsed.raw)
600 try: 617 try:
601 (stop, statement) = self.postparsing_precmd(statement) 618 (stop, statement) = self.postparsing_precmd(statement)
602 except Exception, e: 619 except Exception, e:
603 print str(e) 620 self.perror(e)
604 return 0 621 return 0
605 if stop: 622 if stop:
606 return self.postparsing_postcmd(stop) 623 return self.postparsing_postcmd(stop)
607 624
608 if not statement.parsed.command: 625 if not statement.parsed.command:
621 if statement.parsed.output == '>>': 638 if statement.parsed.output == '>>':
622 mode = 'a' 639 mode = 'a'
623 try: 640 try:
624 self.stdout = open(os.path.expanduser(statement.parsed.outputTo), mode) 641 self.stdout = open(os.path.expanduser(statement.parsed.outputTo), mode)
625 except OSError, e: 642 except OSError, e:
626 print e 643 self.perror(e)
627 return self.postparsing_postcmd(stop=0) 644 return self.postparsing_postcmd(stop=0)
628 else: 645 else:
629 statekeeper = Statekeeper(self, ('stdout',)) 646 statekeeper = Statekeeper(self, ('stdout',))
630 self.stdout = tempfile.TemporaryFile() 647 self.stdout = tempfile.TemporaryFile()
631 if statement.parsed.output == '>>': 648 if statement.parsed.output == '>>':
641 except AttributeError: 658 except AttributeError:
642 return self.postparsing_postcmd(self.default(statement)) 659 return self.postparsing_postcmd(self.default(statement))
643 timestart = datetime.datetime.now() 660 timestart = datetime.datetime.now()
644 stop = func(statement) 661 stop = func(statement)
645 if self.timing: 662 if self.timing:
646 print 'Elapsed: %s' % str(datetime.datetime.now() - timestart) 663 self.pfeedback('Elapsed: %s' % str(datetime.datetime.now() - timestart))
647 except Exception, e: 664 except Exception, e:
648 print e 665 self.perror(e)
649 finally: 666 finally:
650 if statekeeper: 667 if statekeeper:
651 if statement.parsed.output and not statement.parsed.outputTo: 668 if statement.parsed.output and not statement.parsed.outputTo:
652 self.stdout.seek(0) 669 self.stdout.seek(0)
653 try: 670 try:
654 writeToPasteBuffer(self.stdout.read()) 671 writeToPasteBuffer(self.stdout.read())
655 except Exception, e: 672 except Exception, e:
656 print str(e) 673 self.perror(e)
657 elif statement.parsed.pipeTo: 674 elif statement.parsed.pipeTo:
658 for result in redirect.communicate(): 675 for result in redirect.communicate():
659 statekeeper.stdout.write(result or '') 676 statekeeper.stdout.write(result or '')
660 self.stdout.close() 677 self.stdout.close()
661 statekeeper.restore() 678 statekeeper.restore()
736 if p.startswith(param): 753 if p.startswith(param):
737 val = getattr(self, p) 754 val = getattr(self, p)
738 self.stdout.write('%s: %s\n' % (p, str(getattr(self, p)))) 755 self.stdout.write('%s: %s\n' % (p, str(getattr(self, p))))
739 any_shown = True 756 any_shown = True
740 if not any_shown: 757 if not any_shown:
741 print "Parameter '%s' not supported (type 'show' for list of parameters)." % param 758 self.perror("Parameter '%s' not supported (type 'show' for list of parameters)." % param)
742 759
743 def do_quit(self, arg): 760 def do_quit(self, arg):
744 return self._STOP_AND_EXIT 761 return self._STOP_AND_EXIT
745 do_exit = do_quit 762 do_exit = do_quit
746 do_q = do_quit 763 do_q = do_quit
785 raw_input(arg + '\n') 802 raw_input(arg + '\n')
786 803
787 def do_shell(self, arg): 804 def do_shell(self, arg):
788 'execute a command as if at the OS prompt.' 805 'execute a command as if at the OS prompt.'
789 os.system(arg) 806 os.system(arg)
790 807
791 def _attempt_py_command(self, arg):
792 try:
793 result = eval(arg, self.pystate)
794 print repr(result)
795 except SyntaxError:
796 exec(arg, self.pystate)
797 return
798
799 def do_py(self, arg): 808 def do_py(self, arg):
800 ''' 809 '''
801 py <command>: Executes a Python command. 810 py <command>: Executes a Python command.
802 py: Enters interactive Python mode. 811 py: Enters interactive Python mode.
803 End with `Ctrl-D` (Unix) / `Ctrl-Z` (Windows), `quit()`, 'exit()`. 812 End with `Ctrl-D` (Unix) / `Ctrl-Z` (Windows), `quit()`, 'exit()`.
872 881
873 commands are run after editor is closed. 882 commands are run after editor is closed.
874 "set edit (program-name)" or set EDITOR environment variable 883 "set edit (program-name)" or set EDITOR environment variable
875 to control which editing program is used.""" 884 to control which editing program is used."""
876 if not self.editor: 885 if not self.editor:
877 print "please use 'set editor' to specify your text editing program of choice." 886 self.perror("Please use 'set editor' to specify your text editing program of choice.")
878 return 887 return
879 filename = self.default_file_name 888 filename = self.default_file_name
880 if arg: 889 if arg:
881 try: 890 try:
882 buffer = self.last_matching(int(arg)) 891 buffer = self.last_matching(int(arg))
905 most recent command if omitted""" 914 most recent command if omitted"""
906 915
907 try: 916 try:
908 args = self.saveparser.parseString(arg) 917 args = self.saveparser.parseString(arg)
909 except pyparsing.ParseException: 918 except pyparsing.ParseException:
910 print self.do_save.__doc__ 919 self.perror(self.do_save.__doc__)
911 return 920 return
912 fname = args.fname or self.default_file_name 921 fname = args.fname or self.default_file_name
913 if args.idx == '*': 922 if args.idx == '*':
914 saveme = '\n\n'.join(self.history[:]) 923 saveme = '\n\n'.join(self.history[:])
915 elif args.idx: 924 elif args.idx:
918 saveme = self.history[-1] 927 saveme = self.history[-1]
919 try: 928 try:
920 f = open(os.path.expanduser(fname), 'w') 929 f = open(os.path.expanduser(fname), 'w')
921 f.write(saveme) 930 f.write(saveme)
922 f.close() 931 f.close()
923 print 'Saved to %s' % (fname) 932 self.pfeedback('Saved to %s' % (fname))
924 except Exception, e: 933 except Exception, e:
925 print 'Error saving %s: %s' % (fname, str(e)) 934 self.perror('Error saving %s: %s' % (fname, str(e)))
926 935
927 def read_file_or_url(self, fname): 936 def read_file_or_url(self, fname):
928 if isinstance(fname, file): 937 if isinstance(fname, file):
929 target = open(fname, 'r') 938 target = open(fname, 'r')
930 else: 939 else:
960 arg = arg.split(None, 1) 969 arg = arg.split(None, 1)
961 targetname, args = arg[0], (arg[1:] or [''])[0].strip() 970 targetname, args = arg[0], (arg[1:] or [''])[0].strip()
962 try: 971 try:
963 target = self.read_file_or_url(targetname) 972 target = self.read_file_or_url(targetname)
964 except IOError, e: 973 except IOError, e:
965 print 'Problem accessing script from %s: \n%s' % (targetname, e) 974 self.perror('Problem accessing script from %s: \n%s' % (targetname, e))
966 return 975 return
967 keepstate = Statekeeper(self, ('stdin','use_rawinput','prompt', 976 keepstate = Statekeeper(self, ('stdin','use_rawinput','prompt',
968 'continuation_prompt','current_script_dir')) 977 'continuation_prompt','current_script_dir'))
969 self.stdin = target 978 self.stdin = target
970 self.use_rawinput = False 979 self.use_rawinput = False
985 arg is string -> run most recent command by string search 994 arg is string -> run most recent command by string search
986 arg is /enclosed in forward-slashes/ -> run most recent by regex 995 arg is /enclosed in forward-slashes/ -> run most recent by regex
987 """ 996 """
988 'run [N]: runs the SQL that was run N commands ago' 997 'run [N]: runs the SQL that was run N commands ago'
989 runme = self.last_matching(arg) 998 runme = self.last_matching(arg)
990 print runme 999 self.pfeedback(runme)
991 if runme: 1000 if runme:
992 runme = self.precmd(runme) 1001 runme = self.precmd(runme)
993 stop = self.onecmd(runme) 1002 stop = self.onecmd(runme)
994 stop = self.postcmd(stop, runme) 1003 stop = self.postcmd(stop, runme)
995 do_r = do_run 1004 do_r = do_run