def push(self, line): if line.strip() == 'help': # Write some Cheshire3 help self.write("Cheshire3 Documentation can be found in the `docs` " "folder of the distribution\n" "or online at:\n" "http://cheshire3.org/docs/\n") self.write("Type help() for Python's interactive help, or " "help(object) for help about object.\n") return elif line.strip() == 'copyright': # Write Cheshire3 copyright info, before that of Python self.write('Cheshire3 is Copyright (c) 2005-2012, the University ' 'of Liverpool.\n') self.write('All rights reserved.\n\n') elif line.strip() == "license": self.write(cheshire3_license() + '\n\n') self.write("Type marc_utils_license() for marc_utils license\n") self.write("Type python_license() for Python license\n") elif line.strip() == "license()": self.write(cheshire3_license_text() + '\n') return elif line.strip() == "marc_utils_license()": self.write(marc_utils_license() + '\n') return elif line.strip() == "python_license()": return InteractiveConsole.push(self, "license()") return InteractiveConsole.push(self, line)
def push(self, line): if self.inQuery: if self.hasDeclEnd(line): self.inQuery= False more = InteractiveConsole.push(self, line) return more elif line.find("`") >= 0: exc = 'Traceback (most recent call last):\n' + \ ' File "<stdin>", line 1, in <module>\n' + \ ' Cannot have both Python code and SociaLite query in one line\n' print exc self.buffer = [] self.inQuery = False return False else: if line.strip(): self.buffer.append(line) return True else: if self.hasDeclBegin(line) and not self.hasDeclEnd(line): self.inQuery = True self.buffer.append(line) return True more = InteractiveConsole.push(self, line) return more
class PythonConsole(pudding.control.Console): """ an interactive python console for pudding """ def __init__(self, parent=None, lokals=None, **kwargs): pudding.control.Console.__init__(self, parent, initial='', **kwargs) self.interpreter = InteractiveConsole(lokals) self.interpreter.write = self.write self.stdout = sys.stdout sys.stdout = self def on_return(self): """ run the command if its complete """ self.input_buffer.append(self.input.value) self.write(">>> %s\n" % self.input.value) self.interpreter.push(self.input.value) self.input.clear() def write(self, string): """ write method to pretend to be a file like object """ self.output.label += "%s" % string print >>self.stdout, string
def push(self, input): self.redirectOutput(self.pipe, self.pipe) InteractiveConsole.push(self, input) self.redirectOutput(self.stdout, self.stderr) output = self.pipe.flush() return output
def push(self,line): self.get_output() InteractiveConsole.push(self,line) self.return_output() output = self.cache.flush() if len(output) > 0: return output return ""
def run(self, setup): if setup.cmd_list: console = InteractiveConsole(locals()) for command in setup.cmd_list.readlines(): command = command.strip() if command: console.push(command) if not setup.non_interactive: print("Dropping to interpreter; press ^D to resume") self.interpreters[setup.interpreter](self.core.get_locals())
def get_type(self, var): """Insert a command into the console.""" type_line = "'.'.join([type(%s).__module__, type(%s).__name__])" % \ (var[:-1], var[:-1]) self.get_output() InteractiveConsole.push(self, type_line) self.return_output() exec_line = self._cache.flush() + '.' exec_line = exec_line.replace("'", "") return exec_line
def push(self, line): self.get_output() # you can filter input here by doing something like # line = filter(line) InteractiveConsole.push(self, line) self.return_output() output = self.cache.flush() # you can filter the output here by doing something like # output = filter(output) return output # or do something else with it
def shell(): """Interactive Shell""" from code import InteractiveConsole console = InteractiveConsole() console.push("import infogami") console.push("from infogami.utils import delegate") console.push("from infogami.core import db") console.push("from infogami.utils.context import context as ctx") console.push("delegate.fakeload()") console.interact()
def push(self, line): self.get_output() InteractiveConsole.push(self, line) self.return_output() self.output = self.cache.flush() self.error = self.errcache.flush() if self.output: return self.output else: return self.error
def push(self,line): self.get_stdout() self.get_stderr() InteractiveConsole.push(self,line) self.return_stdout() self.return_stderr() stdout_output = self.stdout_cacher.flush() stderr_output = self.stderr_cacher.flush() return (stdout_output, stderr_output)
def push(self, line): 'Sends code to the console' self.get_output() InteractiveConsole.push(self, line) self.return_output() output = self.cache.flush() return output
def push(self, line): if not line: line = self.last_line self.last_line = line # Call the custom command if given. m = re.search(self.command_regex, line) if m: command = m.group('cmd') args = m.group('args') return self.command_map[m.group(1)](args) InteractiveConsole.push(self, line)
class Console: def __init__(self, statements): self.console = InteractiveConsole() self.run(statements) def run(self, statements): self.push('from Interpreter import *') self.push('interpreter = Interpreter()') for statement in statements.split('\n'): if statement != '': self.push("interpreter.push('" + statement.strip() + "')") def push(self, statement): self.console.push(statement)
def push(self,line): self.get_output() # you can filter input here by doing something like # line = filter(line) filtered_line = self.do_filters(line) self.irc.send("PRIVMSG %s :%s\r\n" % (self.channel, filtered_line)) InteractiveConsole.push(self, line) self.return_output() output = self.cache.flush() # you can filter the output here by doing something like # output = filter(output) if output != '': print output, # or do something else with it readline.write_history_file(self.histfile) return
def push( self, input ): output = list() output.append( ["%s" % input, '>>> ', self.inputColor] ) # execute on interactiveConsole console self.get_output() InteractiveConsole.push( self, input ) self.return_output() resultText = self.cache.flush() if len(resultText) > 0: output.append( ["%s" % resultText, '> ', self.outputColor] ) return output
def push(self, line): """Insert a command into the console.""" self.get_output() val = InteractiveConsole.push(self, line) self.return_output() self.output = self._cache.flush() return val
def push(self,line): self.get_output() more = InteractiveConsole.push(self,line) self.return_output() output = self.out_cache.flush() errors = self.err_cache.flush() return more,errors,output
def push(self, line): if(line == 'exit()'): return self.get_output() val = InteractiveConsole.push(self, line) self.return_output() self.output = self._cache.flush() return val
class Console: """Console tool.""" def __init__(self, globals): self.globals = globals self.console = InteractiveConsole(self.globals) self.prompt = ">>> " def launch(self): """Launch the tool.""" running = True while running: try: code = input(self.prompt) except (KeyboardInterrupt, EOFError): running = False break try: ret = self.console.push(code) except Exception: print(traceback.format_exc()) else: self.prompt = "... " if ret else ">>> " Model.data_connector.loop()
def handle(self, line): result = InteractiveConsole.push(self, line) if result: self.prompt_more() else: self.prompt_next() return result
def myshell(): shell = InteractiveConsole() try: while 1: line = shell.raw_input(ps1) while 1: result = shell.push(line) if not result: break line = shell.raw_input(ps2) except: pass return def get_output(self): sys.stdout = self.cache def return_output(self): sys.stdout = self.stdout def push(self,line): self.get_output() # you can filter input here by doing something like # line = filter(line) InteractiveConsole.push(self,line) self.return_output() output = self.cache.flush() # you can filter the output here by doing something like # output = filter(output) print output # or do something else with it return
def ic_push(self,line, mode='single', name='auto'): self.last_op = datetime.now() self.accept_output() signal.setitimer(signal.ITIMER_VIRTUAL,10) ret = InteractiveConsole.push(self,line) signal.setitimer(signal.ITIMER_VIRTUAL,0) self.return_output() return ret
def push(self, nickname, line): "Redirects stdout upon push." self.inc_tracker(nickname) sys.stdout = self self._ibuffer.append(line) if not InteractiveConsole.push(self, line): self.flush() sys.stdout = self._stdout
def push(self, line): if not line: if not self.last_line: return line = self.last_line self.last_line = line # Call the custom command if given. m = re.search(self.command_regex, line) if m: command_name = m.group('cmd') command = self.command_map[command_name] args = [] if m.group('args') is not None: argtext = str(m.group('args')) if command.lex_args: # Lex the args text. args += shlex.split(argtext) else: # Pass the raw text. args.append(argtext) if command_name in ('q', 'quit'): return command(*args) try: ret = command(*args) except: # The command encountered an error. traceback.print_exc(file=sys.stdout) return else: # Command succeeded; inject the result back into the shell. if ret: self.locals['ret'] = ret msg = 'Result of function has been assigned to name "ret"' self.logger.info(msg) return if xsel_enabled: p = subprocess.Popen(['xsel', '-bi'], stdin=subprocess.PIPE) p.communicate(input=line) InteractiveConsole.push(self, line)
def run_preamble(preamble, frame): """Displays the specified preamble.""" console = InteractiveConsole(frame) incomplete = False for line in process_input(preamble): if not incomplete and not line: incomplete = False continue prompt = PS2 if incomplete else PS1 print(display_prompt(line, prompt)) incomplete = console.push(line)
def push(self, line): try: more = InteractiveConsole.push(self, line) except KeyboardInterrupt: self.write('\nKeyboardInterrupt\n') self.resetbuffer() more = False if more: self.write(self.ps2) else: self.write(self.ps1)
def start(self, args): ic = InteractiveConsole() path = args["path"].value().path print "executing batch script " + path file = open(path) for line in file.xreadlines(): if line[0] == "#": continue elif line[0] == "!": cmds = self.lp.makeCommands(line[1:]) for cmd in cmds: exec_type = ["console"] config = self.cm.configByName(cmd[0]) args = config.generate(cmd[1]) proc = self.tm.add(cmd[0], args, exec_type) proc.event.wait() else: ic.push(line) ic.resetbuffer() file.close() return
class console(libs.threadmanager.Thread): def __init__(self): libs.threadmanager.Thread.__init__(self) self.console = InteractiveConsole(global_vars) initscript = [ "from libs.globals import global_vars", 'other = global_vars["friends"]["0"]', "other.send('test')" ] def run(self): while global_vars['running'] == True and not self._stop.isSet(): try: line = raw_input(">>>") if line == "runscript": for line in self.initscript: self.console.push(line) else: self.console.push(line) except KeyboardInterrupt: global_vars["running"] = False
def shell(*args): """Interactive Shell""" if not "--ipython" in args: from code import InteractiveConsole console = InteractiveConsole() console.push("import infogami") console.push("from infogami.utils import delegate") console.push("from infogami.core import db") console.push("from infogami.utils.context import context as ctx") console.push("delegate.fakeload()") console.interact() else: """IPython Interactive Shell - IPython must be installed to use.""" # remove an argument that confuses ipython sys.argv.pop(sys.argv.index("--ipython")) from IPython.Shell import IPShellEmbed import infogami from infogami.utils import delegate from infogami.core import db from infogami.utils.context import context as ctx delegate.fakeload() ipshell = IPShellEmbed() ipshell()
class TextConsole(ColorText): def __init__(self, master, **kw): kw.setdefault('width', 50) kw.setdefault('wrap', 'word') kw.setdefault('prompt1', '>>> ') kw.setdefault('prompt2', ' ') banner = kw.pop('banner', 'Python %s\n' % sys.version) self._prompt1 = kw.pop('prompt1') self._prompt2 = kw.pop('prompt2') ColorText.__init__(self, master, **kw) # --- history self.history = History() self._hist_item = 0 self._hist_match = '' # --- initialization self._console = InteractiveConsole( ) # python console to execute commands sys.stdin = Pipe() self.insert('end', banner, 'banner') self.prompt() self.mark_set('input', 'insert') self.mark_gravity('input', 'left') # --- bindings self.bind('<Control-Return>', self.on_ctrl_return) self.bind('<Shift-Return>', self.on_shift_return) self.bind('<KeyPress>', self.on_key_press) self.bind('<KeyRelease>', self.on_key_release) self.bind('<Tab>', self.on_tab) self.bind('<Down>', self.on_down) self.bind('<Up>', self.on_up) self.bind('<Return>', self.on_return) self.bind('<BackSpace>', self.on_backspace) self.bind('<Control-c>', self.on_ctrl_c) self.bind('<<Paste>>', self.on_paste) self.unbind('<Control-Shift-Home>') self.unbind('<Control-Shift-End>') def on_ctrl_c(self, event): """Copy selected code, removing prompts first""" sel = self.tag_ranges('sel') if sel: txt = self.get('sel.first', 'sel.last').splitlines() lines = [] for i, line in enumerate(txt): if line.startswith(self._prompt1): lines.append(line[len(self._prompt1):]) elif line.startswith(self._prompt2): lines.append(line[len(self._prompt2):]) else: lines.append(line) self.clipboard_clear() self.clipboard_append('\n'.join(lines)) return 'break' def on_paste(self, event): """Paste commands""" if self.compare('insert', '<', 'input'): return "break" sel = self.tag_ranges('sel') if sel: self.delete('sel.first', 'sel.last') txt = self.clipboard_get() self.insert("insert", txt) self.insert_cmd(self.get("input", "end")) return 'break' def prompt(self, result=False): """Insert a prompt""" if sys.stdin.reading: pass if result: self.insert('end', self._prompt2, 'prompt') else: self.insert('end', self._prompt1, 'prompt') self.mark_set('input', 'end-1c') def on_key_press(self, event): """Prevent text insertion in command history""" # self.trigger(event=event) if self.compare('insert', '<', 'input') and event.keysym not in ['Left', 'Right']: self._hist_item = len(self.history) self.mark_set('insert', 'input lineend') if not event.char.isalnum(): return 'break' def on_key_release(self, event): """Reset history scrolling""" # self.trigger(event=event) if self.compare('insert', '<', 'input') and event.keysym not in ['Left', 'Right']: self._hist_item = len(self.history) return 'break' def on_up(self, event): """Handle up arrow key press""" if self.compare('insert', '<', 'input'): self.mark_set('insert', 'end') return 'break' elif self.index('input linestart') == self.index('insert linestart'): # navigate history line = self.get('input', 'insert') self._hist_match = line hist_item = self._hist_item self._hist_item -= 1 item = self.history[self._hist_item] while self._hist_item >= 0 and not item[-1].startswith(line): self._hist_item -= 1 item = self.history[self._hist_item] if self._hist_item >= 0: index = self.index('insert') self.insert_cmd(item) self.mark_set('insert', index) else: self._hist_item = hist_item return 'break' def on_down(self, event): """Handle down arrow key press""" if self.compare('insert', '<', 'input'): self.mark_set('insert', 'end') return 'break' elif self.compare('insert lineend', '==', 'end-1c'): # navigate history line = self._hist_match self._hist_item += 1 item = self.history[self._hist_item] while item is not None and not item[-1].startswith(line): self._hist_item += 1 item = self.history[self._hist_item] if item is not None: self.insert_cmd(item) self.mark_set('insert', 'input+%ic' % len(self._hist_match)) else: self._hist_item = len(self.history) self.delete('input', 'end') self.insert('insert', line) return 'break' def on_tab(self, event): """Handle tab key press""" if self.compare('insert', '<', 'input'): self.mark_set('insert', 'input lineend') return "break" # indent code sel = self.tag_ranges('sel') if sel: start = str(self.index('sel.first')) end = str(self.index('sel.last')) start_line = int(start.split('.')[0]) end_line = int(end.split('.')[0]) + 1 for line in range(start_line, end_line): self.insert('%i.0' % line, ' ') else: txt = self.get('insert-1c') if not txt.isalnum() and txt != '.': self.insert('insert', ' ') return "break" def on_shift_return(self, event): """Handle Shift+Return key press""" if self.compare('insert', '<', 'input'): self.mark_set('insert', 'input lineend') return 'break' else: # execute commands self.mark_set('insert', 'end') self.insert('insert', '\n') self.insert('insert', self._prompt2, 'prompt') self.eval_current(True) def on_return(self, event=None): """Handle Return key press""" if self.compare('insert', '<', 'input'): self.mark_set('insert', 'input lineend') # self.inst_trigger() return 'break' else: self.eval_current(True) self.see('end') # self.inst_trigger() return 'break' def on_ctrl_return(self, event=None): """Handle Ctrl+Return key press""" self.insert('insert', '\n' + self._prompt2, 'prompt') return 'break' def on_backspace(self, event): """Handle delete key press""" if self.compare('insert', '<=', 'input'): self.mark_set('insert', 'input lineend') return 'break' sel = self.tag_ranges('sel') if sel: self.delete('sel.first', 'sel.last') else: linestart = self.get('insert linestart', 'insert') if re.search(r' ' * 4 + r'$', linestart): self.delete('insert-4c', 'insert') else: self.delete('insert-1c') return 'break' def insert_cmd(self, cmd): """Insert lines of code, adding prompts""" input_index = self.index('input') self.delete('input', 'end') _cmd = '' for i in range(len(cmd)): c = cmd[i].__add__('\n') _cmd += c lines = _cmd.splitlines() if lines: indent = len(re.search(r'^( )*', lines[0]).group()) self.insert('insert', lines[0][indent:]) for line in lines[1:]: line = line[indent:] self.insert('insert', '\n') self.prompt(True) self.insert('insert', line) self.mark_set('input', input_index) self.see('end') def eval_current(self, auto_indent=False): """Evaluate code""" index = self.index('input') lines = self.get('input', 'insert lineend').splitlines() # commands to execute self.mark_set('insert', 'insert lineend') if lines: # there is code to execute # remove prompts lines = [lines[0].rstrip()] + [ line[len(self._prompt2):].rstrip() for line in lines[1:] ] for i, l in enumerate(lines): if l.endswith('?'): lines[i] = 'help(%s)' % l[:-1] cmds = '\n'.join(lines) self.insert('insert', '\n') out = StringIO() # command output err = StringIO() # command error traceback with redirect_stderr(err): # redirect error traceback to err with redirect_stdout(out): # redirect command output # execute commands in interactive console res = self._console.push(cmds) # if res is True, this is a partial command, e.g. 'def test():' and we need to wait for the rest of # the code errors = err.getvalue() if errors: # there were errors during the execution self.insert('end', errors) # display the traceback self.mark_set('input', 'end') self.see('end') self.prompt() # insert new prompt else: output = out.getvalue() # get output if output: self.insert('end', output, 'output') self.mark_set('input', 'end') self.see('end') if not res and self.compare('insert linestart', '>', 'insert'): self.insert('insert', '\n') self.prompt(res) if auto_indent and lines: # insert indentation similar to previous lines indent = re.search(r'^( )*', lines[-1]).group() line = lines[-1].strip() if line and line[-1] == ':': indent = indent + ' ' self.insert('insert', indent) self.see('end') if res: self.mark_set('input', index) self._console.resetbuffer( ) # clear buffer since whole command will be retrieved from text widget elif lines: self.history.append(lines) # add commands to history self._hist_item = len(self.history) out.close() err.close() else: self.insert('insert', '\n') self.prompt()