def restore_snapshot(object, snapshot, obj_name=None): ss = split(snapshot, '\n') ii = code.InteractiveInterpreter(locals()) gii = code.InteractiveInterpreter(sys.modules['__main__'].__dict__) for s in ss: if strip(s): pos = s.find('=') left = strip(s[0:pos]) right = strip(s[pos + 1:len(s)]) if left == '/*/' and obj_name: gii.runsource(obj_name + '=' + right) else: ii.runsource('object.' + left + '=' + right)
def __init__(self): self.translator = PySwahili() self.block_keywords = list( self.translator.sw_to_en["block_keywords"].values()) self.console = code.InteractiveConsole() self.intepreter = code.InteractiveInterpreter() self.newline = "\n"
def __init__(self, parent=None): super().__init__(parent) if not hasattr(sys, 'ps1'): sys.ps1 = '>>> ' if not hasattr(sys, 'ps2'): sys.ps2 = '... ' namespace = { '__name__': '__console__', '__doc__': None, 'q_app': QApplication.instance(), # We use parent as self here because the user "feels" the whole # console, not just the line edit. 'self': parent, 'objreg': objreg, } self._more = False self._buffer = [] self._lineedit = ConsoleLineEdit(namespace, self) self._lineedit.execute.connect(self.push) self._output = ConsoleTextEdit() self.write(self._curprompt()) self._vbox = QVBoxLayout() self._vbox.setSpacing(0) self._vbox.addWidget(self._output) self._vbox.addWidget(self._lineedit) self.setLayout(self._vbox) self._lineedit.setFocus() self._interpreter = code.InteractiveInterpreter(namespace)
def runsource(source): """ Execute python source in a separate interpreter, kinda like what 'Run Script' in the text editor does. This function only redirects errors. """ modules = code.sys.modules main_org = modules.get("__main__") main = ModuleType("__main__") namespace = main.__dict__ # namespace["__builtins__"] = modules["builtins"] namespace.update(__builtins__=modules.get("builtins")) console = code.InteractiveInterpreter(locals=namespace) stderr = StringIO() with redirect_stderr(stderr): try: modules["__main__"] = main console.runsource(source) except Exception: stderr.write(code.traceback.format_exc()) finally: modules["__main__"] = main_org return stderr.getvalue().strip()
def __init__(self, **kwargs): super(EvalConsole, self).__init__(**kwargs) self.namespace = {} self.interpreter = code.InteractiveInterpreter(self.namespace) layout = QVBoxLayout() self.setLayout(layout) self.display = PlainTextEdit(self) self.display.setReadOnly(True) clearAction = QAction(self.tr('Clear'), self.display) clearAction.triggered.connect(self.display.clear) self.display.addAction(clearAction) self.line = HistoryLine() self.line.submitted.connect(self.execCode) self.line.installEventFilter(self) self.line.completer().popup().installEventFilter(self) self.setFocusProxy(self.line) layout.addWidget(self.display) layout.addWidget(self.line) self.setWindowTitle(self.tr('Eval console')) self.addCategory('eval_console')
def __init__(self): self.interpreter = code.InteractiveInterpreter() self.equunit = "" self.equstr = "" self._block_dict = { "python": self.run_python_block, "latex": self.run_latex_block, "lathon": self.run_lathon_block, "py": self.run_python_block, "la": self.run_latex_block, "pl": self.run_lathon_block } self.units = {} self.latex_string = '' exec("from sympy.physics.units import *", self.units) self.prependtext = ( '\\documentclass[ngerman,fleqn,a4paper]{article}\n' '\\usepackage[utf8]{inputenc}\n' '\\usepackage{babel}\n' '\\usepackage{a4wide}\n' '\\usepackage{amsmath}\n' '\\setlength{\mathindent}{1cm} \n' '\\usepackage{graphicx}\n' '\\usepackage{titlesec}\n' '\\usepackage{gensymb}\n' '\\usepackage{float}\n' '\AtBeginDocument{%\n' ' \\abovedisplayskip=4pt plus 3pt minus 4pt\n' ' \\abovedisplayshortskip=0pt plus 3pt\n' ' \\belowdisplayskip=3pt plus 3pt minus 3pt\n' ' \\belowdisplayshortskip=0pt plus 3pt minus 3pt\n' '}')
def init(self, interpreter_locals): if interpreter_locals: self.interpreter = code.InteractiveInterpreter(interpreter_locals) self.interpreter.runsource('raw_input = self.raw_input') self.interpreter.runsource('input = self.input') self.interpreter.runsource('help = self.help') self.interpreterLocals = interpreter_locals
def create_link_table(links): ctx = SVMCORBA_RECORD.orb.resolve_initial_references("NameService") table = {} ii = code.InteractiveInterpreter(locals()) for lk in links.keys(): path = os.path.join(SVMCORBA_RECORD.stub_path, links[lk][0]) path = os.path.join(path, links[lk][1]) path = os.path.join(path, SVM_MODULE) sys.path = [path] + sys.path ii.runsource('import %s' % links[lk][0]) cpath = [ CosNaming.NameComponent('SVM', ''), CosNaming.NameComponent(SVM_MODULE, ''), CosNaming.NameComponent(links[lk][0], ''), CosNaming.NameComponent(links[lk][1], '') ] links[lk].append(ctx.resolve(cpath)) if table.has_key(lk): table[lk].append(eval('links[lk][4].%s' % links[lk][3])) else: table[lk] = [eval('links[lk][4].%s' % links[lk][3])] return table
class Runner: shell = code.InteractiveInterpreter(vars) def run(program): obj = compile('\n'.join(program.text()), 'program', mode='exec') run_vars = dict(vars) run_vars['__file__'] = program.path #def exit(): # prevent program from exiting the environment # raise KeyboardInterrupt #run_vars['exit'] = exit # BUGBUG: This does not work. #old_exit = sys.exit try: sys.exit = exit # this works, but also affects our REPL; and will not free the program's resources # TODO: __name__ exec(obj, run_vars, run_vars) except SystemExit: print('Program complete', file=sys.stderr) # @TODO: remove this finally: #sys.exit = old_exit #print('caught', file=sys.stderr) # break circular references for key, val in run_vars.items(): run_vars[key] = None # Also, to ensure all objects get destroyed, maybe see this: # http://lucumr.pocoo.org/2011/2/1/exec-in-python/ # indicating that Python explicitly delets vars before shutting down. def runsource(line): return Runner.shell.runsource(line)
def __init__(self, parent=None): super().__init__(parent) self._interpreter = code.InteractiveInterpreter() self._compiler = codeop.CommandCompiler() self._prompt = ">>> " self._promptLength = len(self._prompt) self._history = CodeHistory(self._prompt) self._currentLine = CodeLine() self._cursor = 0 self._historyLine = -1 # keys to ignore and allow something else to handle # currently, we don't have any, so this may be removed self._passKeys = {} self._keyFunctions = { Qt.Key_Home: self._keyHome, Qt.Key_End: self._keyEnd, Qt.Key_Left: self._keyArrowLeft, Qt.Key_Right: self._keyArrowRight, Qt.Key_Down: self._keyArrowDown, Qt.Key_Up: self._keyArrowUp, Qt.Key_Enter: self._runCode, Qt.Key_Return: self._runCode }
def __init__(self, parent, interpreterLocals=None): super(MyConsole, self).__init__(parent) self.parent = parent sys.stdout = self sys.stderr = self self.refreshMarker = False # to change back to >>> from ... self.multiLine = False # code spans more than one line self.command = '' # command to be run self.history = [] # list of commands entered self.historyIndex = -1 self.printBanner() # print sys info self.marker() # make the >>> or ... marker palette = QtGui.QPalette() palette.setColor(QtGui.QPalette.Base, Qt.black) palette.setColor(QtGui.QPalette.Text, QtGui.QColor(0, 255, 0)) self.setPalette(palette) self.setFont(QtGui.QFont('Courier', 8)) self.palette = palette self.interpreterLocals = interpreterLocals if interpreterLocals else {} self.interpreter = code.InteractiveInterpreter(self.interpreterLocals)
def __init__(self, parent, loc): tk.Frame.__init__(self, parent) self.input = InputEntry(self) self.input.grid(row=0, column=0) self.shell = code.InteractiveInterpreter(locals=loc)
def __init__(self, instance): super(PythonScriptingInstance.InterpreterThread, self).__init__() self.instance = instance self.locals = {"__name__": "__console__", "__doc__": None, "binaryninja": sys.modules[__name__]} self.interpreter = code.InteractiveInterpreter(self.locals) self.event = threading.Event() self.daemon = True # Latest selections from UI self.current_view = None self.current_func = None self.current_block = None self.current_addr = 0 self.current_selection_begin = 0 self.current_selection_end = 0 # Selections that were current as of last issued command self.active_view = None self.active_func = None self.active_block = None self.active_addr = 0 self.active_selection_begin = 0 self.active_selection_end = 0 self.locals["get_selected_data"] = self.get_selected_data self.locals["write_at_cursor"] = self.write_at_cursor self.exit = False self.code = None self.input = "" self.interpreter.runsource("from binaryninja import *\n")
def __init__(self, callback = None, locals = None, banner = ""): gtk.ScrolledWindow.__init__(self) self.interpreter = code.InteractiveInterpreter(locals) self.resetbuffer() self.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) self.textview = gtk.TextView() self.textview.connect("key_press_event", self.event_key_pressed) self.textview.modify_font(pango.FontDescription("monospace 9")) self.textview.modify_base(0, gtk.gdk.color_parse(offwhite)) self.textview.modify_text(0, gtk.gdk.color_parse(blue)) self.textview.set_wrap_mode(gtk.WRAP_WORD_CHAR) self.textview.set_left_margin(4) self.textview.connect("event-after", self.event_after) self.textbuffer = self.textview.get_buffer() self.errorWriter = ColorWriter(self.textbuffer, magenta) self.inputWriter = ColorWriter(self.textbuffer, blue) self.outputWriter = ColorWriter(self.textbuffer, gray) self.outputWriter.write(banner) self.inputWriter.write(">>> ") self.scroll_to_bottom() self.promptoffset = self.textbuffer.get_end_iter().get_offset() self.textbuffer.connect("mark-set", self.event_mark_set) self.textbuffer.connect("changed", lambda w: self.textview.queue_draw) self.add(self.textview) self.history = [""] self.history_index = 0 self.callback = callback
def __init__(self, robot): self.table = networktables.NetworkTables.getTable('Remote Shell') self.interpreter = code.InteractiveInterpreter(locals={ "robot": robot, "r": robot }) def ep(entry): # print("got", entry.value.getRaw()) stdout = io.StringIO() with redirect_stdout(stdout): stderr = io.StringIO() with redirect_stderr(stderr): self.interpreter.runsource(entry.value.getRaw()[:-22]) out = stdout.getvalue() if not out.strip(): out = "\n" out += stderr.getvalue() out += f" T{time.time_ns():<20}" self.table.putString("stdout", out) def do_repl2(*args, **kwaargs): import code code.interact(local={**locals(), **globals()}) self.table.getEntry("stdin").addListener( ep, networktables.NetworkTablesInstance.NotifyFlags.UPDATE | networktables.NetworkTablesInstance.NotifyFlags.NEW)
def start_service(): orb = SVMCORBA_RECORD.orb boa = BOA.BOA_init() ctx = orb.resolve_initial_references("NameService") path = [ CosNaming.NameComponent('SVM', ''), CosNaming.NameComponent(SVM_MODULE, ''), CosNaming.NameComponent(SVMCORBA_RECORD.module_name, '') ] for i in range(len(path)): try: ctx.bind_new_context(path[:i + 1]) except CosNaming.NamingContext.AlreadyBound: pass interface_name = SVMCORBA_RECORD.module_name + '_' + str( SVMCORBA_RECORD.module_num) stubpath = os.path.join( os.path.join(SVMCORBA_RECORD.work_path, 'serverif'), interface_name) sys.path = [stubpath] + sys.path impl = [] impl.append('from %s import %s' % (SVM_MODULE, SVMCORBA_RECORD.module_name)) impl.append('from %s_skel import %s_skel' % (SVM_MODULE, SVMCORBA_RECORD.module_name)) impl.append('from Fnorb.cos.naming import CosNaming') impl.append('import SVMCORBA') classdef = 'class inf_%dImpl(%s_skel.inf_%d_skel):\n' % ( SVMCORBA_RECORD.module_num, SVMCORBA_RECORD.module_name, SVMCORBA_RECORD.module_num) for p in SVMCORBA_RECORD.ports: pp = SVMCORBA_RECORD.ports[p] if pp[PORT_IN]: classdef = classdef + '\ def %s(self, event, params):\n\ SVMCORBA.receive_external_event(%s, event, params)\n' % (p, p) classdef = classdef + '\ def svm_module_add_connection(self, pserver, pclient, components):\n\ SVMCORBA.svm_module_add_connection(pserver, pclient, components)\n' impl.append(classdef) impl.append('ifimpl=inf_%dImpl()' % SVMCORBA_RECORD.module_num) impl.append('ref=boa.create("inf_%d", inf_%dImpl._FNORB_ID)' % (SVMCORBA_RECORD.module_num, SVMCORBA_RECORD.module_num)) impl.append('ctx.rebind([CosNaming.NameComponent("SVM", ""), CosNaming.NameComponent("%s", ""), CosNaming.NameComponent("%s", ""), CosNaming.NameComponent("inf_%d", "")], ref)'\ % (SVM_MODULE, SVMCORBA_RECORD.module_name, SVMCORBA_RECORD.module_num)) impl.append('boa.obj_is_ready(ref, ifimpl)') impl.append('SVMCORBA.SVMCORBA_RECORD.impl=ifimpl') ii = code.InteractiveInterpreter(locals()) for i in impl: ii.runsource(i) del sys.path[0] ThreadUtil.StartThread(boa._fnorb_mainloop, ())
def _run_script(self, script, locs): script_path = os.path.abspath(script) if not os.path.exists(script_path): raise IOError('Unable to open %s script' % script_path) import code i = code.InteractiveInterpreter(locals=locs) i.runsource(open(script_path).read(), script_path, 'exec')
def __init__(self, namespace): self.namespace = namespace self._interpreter = code.InteractiveInterpreter(namespace) # to satisfy webview infrastructure self.width, self.height = 0, 0 # name and link used when surfacing the REPL as an option in the webview dropdown self.display_name = None self.link_url = None
def __init__(self, x, y, w, h, callback=None): Console.__init__(self, x, y, w, h) self.interp = code.InteractiveInterpreter() self.buffer = "" self.tabature = 0 self.outputBox.addLine(">")
def __shell(app, response): import code, thread from gluon.shell import env (shell, lock) = (code.InteractiveInterpreter(), thread.allocate_lock()) shell.locals = env(app, True) response._custom_commit = lambda: None response._custom_rollback = lambda: None return (shell, lock)
def loop(self): try: ii = code.InteractiveInterpreter(globals()) s = raw_input(">>> ") while ii.runsource(s): s += "\n" + raw_input("... ") except SystemExit: Dosbox().exit()
def main(args=None, locals_=None, banner=None): translations.init() config, options, exec_args = bpargs.parse( args, ('curtsies options', None, [ Option('--log', '-L', action='count', help=_("log debug messages to bpython.log")), Option('--paste', '-p', action='store_true', help=_("start by pasting lines of a file into session")), ])) if options.log is None: options.log = 0 logging_levels = [logging.ERROR, logging.INFO, logging.DEBUG] level = logging_levels[min(len(logging_levels) - 1, options.log)] logging.getLogger('curtsies').setLevel(level) logging.getLogger('bpython').setLevel(level) if options.log: handler = logging.FileHandler(filename='bpython.log') logging.getLogger('curtsies').addHandler(handler) logging.getLogger('curtsies').propagate = False logging.getLogger('bpython').addHandler(handler) logging.getLogger('bpython').propagate = False interp = None paste = None if exec_args: if not options: raise ValueError("don't pass in exec_args without options") exit_value = 0 if options.paste: paste = curtsies.events.PasteEvent() encoding = inspection.get_encoding_file(exec_args[0]) with io.open(exec_args[0], encoding=encoding) as f: sourcecode = f.read() paste.events.extend(sourcecode) else: try: interp = code.InteractiveInterpreter(locals=locals_) bpargs.exec_code(interp, exec_args) except SystemExit as e: exit_value = e.args if not options.interactive: raise SystemExit(exit_value) else: # expected for interactive sessions (vanilla python does it) sys.path.insert(0, '') print(bpargs.version_banner()) mainloop(config, locals_, banner, interp, paste, interactive=(not exec_args))
def __init__(self, console): threading.Thread.__init__(self) self.console = console self.globals = {"__name__": "__console__", "__doc__": None} self.code = None self.event = threading.Event() self.done = threading.Event() self.exit = False self.interpreter = code.InteractiveInterpreter(self.globals) # There is no way to interrupt a thread that isn't the main thread, so # to avoid not being able to close the app, create the thread as # as daemon thread. self.daemon = True # Set up environment with useful variables and functions self.globals["data"] = Threads.GuiObjectProxy(self.console.view.data) self.globals["exe"] = Threads.GuiObjectProxy(self.console.view.exe) self.globals["view"] = Threads.GuiObjectProxy(self.console.view) self.globals["current_view"] = Threads.GuiObjectProxy( lambda: self.console.view.view) self.globals["change_view"] = Threads.GuiObjectProxy( lambda type: self.console.view.setViewType(type)) self.globals["navigate"] = Threads.GuiObjectProxy( lambda type, pos: self.console.view.navigate(type, pos)) self.globals["create_file"] = Threads.GuiObjectProxy( lambda data: Threads.create_file(data)) self.globals["cursor"] = Threads.GuiObjectProxy( lambda: self.console.view.view.get_cursor_pos()) self.globals["set_cursor"] = Threads.GuiObjectProxy( lambda pos: self.console.view.view.set_cursor_pos(pos)) self.globals["selection_range"] = Threads.GuiObjectProxy( lambda: self.console.view.view.get_selection_range()) self.globals["set_selection_range"] = Threads.GuiObjectProxy( lambda start, end: self.console.view.view.set_selection_range( start, end)) self.globals["selection"] = Threads.GuiObjectProxy( lambda: self.get_selection()) self.globals["replace_selection"] = Threads.GuiObjectProxy( lambda value: self.replace_selection(value)) self.globals["write_at_cursor"] = Threads.GuiObjectProxy( lambda value: self.write_at_cursor(value)) self.globals["undo"] = Threads.GuiObjectProxy( lambda: self.console.view.undo()) self.globals["redo"] = Threads.GuiObjectProxy( lambda: self.console.view.redo()) self.globals["commit"] = Threads.GuiObjectProxy( lambda: self.console.view.commit_undo()) self.globals["copy"] = Threads.GuiObjectProxy( lambda value: self.copy(value)) self.globals["paste"] = Threads.GuiObjectProxy( lambda: self.console.view.view.paste()) self.globals["clipboard"] = Threads.GuiObjectProxy( lambda: self.get_clipboard())
def init(self, interpreter_locals): # Mover este metodo dentro de __init__ ? if interpreter_locals: interpreter_locals.update(self.interpreterLocals) self.interpreterLocals = interpreter_locals if 'inspect' not in self.interpreterLocals: self.interpreterLocals['inspect'] = inspect self.interpreter = code.InteractiveInterpreter(self.interpreterLocals)
def __init__(self, scr, offset=0): # set up line editor # rl.history.read_file(CONSOLE_HISTORY) self.lastbuf = None # create interpreter object self.interp = code.InteractiveInterpreter() # set prompt self.update_prompt()
def test_flush_stdout_on_error(): runner = code.InteractiveInterpreter() old_stdout = sys.stdout try: mystdout = StringIO() sys.stdout = mystdout runner.runcode(compile("print(5);0/0", "<interactive>", "exec")) finally: sys.stdout = old_stdout assert mystdout.getvalue() == "5\n"
def getShellWidget(self): """Create an instance of shell widget. This can be either a QSciQScintialla widget or a PyCute widget (extends QTextArea) if the first is not available""" if not hasattr(self, 'shellWidget') or self.shellWidget is None: self.shellWidget = get_shell_class()( code.InteractiveInterpreter() , message='MOOSE version %s' % (moose._moose.__version__) ) self.shellWidget.interpreter.runsource('from moose import *') self.shellWidget.setVisible(False) return self.shellWidget
def setupInterp(self): self.line = qt.QString() self.lines = [] self.history = [] self.reading = self.more = self.pointer = 0 self.point = self.xlast = self.ylast = 0 self.interpreter = interp = code.InteractiveInterpreter() interplocals = interp.locals interplocals['shell'] = self interplocals['quit'] = interplocals['exit'] = self.eofPrompt
def python_entry_point(source_code: str): inperpreter = code.InteractiveInterpreter() inperpreter.runsource(source_code) inperpreter.runcode(code.compile_command(source_code)) console = code.InteractiveConsole() console.push(source_code) test.support.run_in_subinterp(source_code) _testcapi.run_in_subinterp(source_code) _xxsubinterpreters.run_string(source_code)
def _core_loadlib(self, request, response): data_tlv = packet_get_tlv(request, TLV_TYPE_DATA) if (data_tlv['type'] & TLV_META_TYPE_COMPRESSED) == TLV_META_TYPE_COMPRESSED: return ERROR_FAILURE preloadlib_methods = self.extension_functions.keys() i = code.InteractiveInterpreter({'meterpreter':self, 'packet_enum_tlvs':packet_enum_tlvs, 'packet_get_tlv':packet_get_tlv, 'tlv_pack':tlv_pack, 'STDProcess':STDProcess}) i.runcode(compile(data_tlv['value'], '', 'exec')) postloadlib_methods = self.extension_functions.keys() new_methods = filter(lambda x: x not in preloadlib_methods, postloadlib_methods) for method in new_methods: response += tlv_pack(TLV_TYPE_METHOD, method) return ERROR_SUCCESS, response