def __init__(self, input_mode=None): """Create a new InputSplitter instance. Parameters ---------- input_mode : str One of ['line', 'cell']; default is 'line'. The input_mode parameter controls how new inputs are used when fed via the :meth:`push` method: - 'line': meant for line-oriented clients, inputs are appended one at a time to the internal buffer and the whole buffer is compiled. - 'cell': meant for clients that can edit multi-line 'cells' of text at a time. A cell can contain one or more blocks that can be compile in 'single' mode by Python. In this mode, each new input new input completely replaces all prior inputs. Cell mode is thus equivalent to prepending a full reset() to every push() call. """ self._buffer = [] self._compile = codeop.CommandCompiler() self.encoding = get_input_encoding() self.input_mode = InputSplitter.input_mode if input_mode is None \ else input_mode
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, locals, *, run_callback=None): self.locals = {"__name__": "__console__", **locals} self.run_callback = run_callback self._buffer = [] self._compile = codeop.CommandCompiler() self._compile.compiler.flags |= PyCF_ALLOW_TOP_LEVEL_AWAIT if readline is not None: self._init_readline()
def parse_file(filename): compiler = codeop.CommandCompiler() source_lines = read_source_code(filename) source_lines, line_number = strip_encoding_declaration(source_lines) statements = [] statement = '' prompts = [] statement_started = False statement_first_line = statement_current_line = -1 statement_line_number = line_number for line in source_lines: line_number += 1 statement_current_line += 1 prompts.append('ps2' if statement_started else 'ps1') statement += line is_empty_line = line.strip() == '' statement_started = statement_started or not is_empty_line if statement_first_line == -1: if line.startswith('#'): continue elif is_empty_line: statement_started = False continue else: statement_first_line = statement_current_line statement_line_number = line_number code, compiled = compile_statement(compiler, statement) if compiled: statements.append( StatementInfo(statement_line_number, statement, prompts, statement_first_line, code)) statement_started = False statement_current_line = statement_first_line = -1 statement = '' prompts = [] if statement: if prompts[-1] == 'ps2': statement += '\n' prompts.append('ps2') code, compiled = compile_statement(compiler, statement) statements.append( StatementInfo(statement_line_number, statement, prompts, statement_first_line, code)) return statements
def __init__(self, ps1='>>> ', ps2='... ', startup_message='', parent=None): QPlainTextEdit.__init__(self, parent) self.ps1, self.ps2 = ps1, ps2 self.history = [] self.namespace = {} self.construct = [] self.compiler = codeop.CommandCompiler() self.stdout = StdoutProxy(self.appendPlainText) self.setWordWrapMode(QTextOption.WrapAnywhere) self.setUndoRedoEnabled(False) self.document().setDefaultFont(QFont('Monospace', 10, QFont.Normal)) self.showMessage(startup_message)
def icompile(src, filename='<input>', mode='single'): import sys if src.strip() == "": return compile("None", "", "eval") # {{{ compile ipython magic commands as Python code if src.startswith("__IP.magic"): import codeop return codeop.CommandCompiler()(src, filename, mode) # }}} # {{{ return None if src is unfinished multiline if src.count("\n") > 0: if not src.endswith("\n"): return None else: if src.strip().endswith(":"): return None # }}} import IPython AutoTB = IPython.ultraTB.AutoFormattedTB(mode='Context', color_scheme='Linux', call_pdb=1) try: ulang = _ipy.locals['__currentlang__'] if not isinstance(ulang, language.Language): raise SyntaxError("current language is not valid") elif not ulang.__impl__.name.endswith("~"): ulang = language.tmpLanguage(ulang, _ipy.locals['__name__']) _ipy.locals['__currentlang__'] = ulang lang = ulang.__impl__ expr = lang.parse(src, mode="interactive", execenv=_ipy.locals) return interactiveCompile(expr, _ipy.locals, filename, mode) # {{{ exception handling except SyntaxError: raise except macros.MacroExpandError, exc: macros.formatMacroError(exc) exc_info = exc.exc_info raise ValueError("macro expand error")
def __init__(self): self._compiler = codeop.CommandCompiler() # This is ugly, but it must be done this way to allow multiple # simultaneous ipython instances to coexist. Since Python itself # directly accesses the data structures in the linecache module, and # the cache therein is global, we must work with that data structure. # We must hold a reference to the original checkcache routine and call # that in our own check_cache() below, but the special IPython cache # must also be shared by all IPython instances. If we were to hold # separate caches (one in each CachingCompiler instance), any call made # by Python itself to linecache.checkcache() would obliterate the # cached data from the other IPython instances. if not hasattr(linecache, '_ipython_cache'): linecache._ipython_cache = {} if not hasattr(linecache, '_checkcache_ori'): linecache._checkcache_ori = linecache.checkcache # Now, we must monkeypatch the linecache directly so that parts of the # stdlib that call it outside our control go through our codepath # (otherwise we'd lose our tracebacks). linecache.checkcache = self.check_cache
def __init__(self, conn: socket_.socket, locals: ta.MutableMapping = None, filename: str = '<console>') -> None: super().__init__() if locals is None: locals = { '__name__': '__console__', '__doc__': None, '__console__': self, } self._conn = conn self._locals = locals self._filename = filename self._compiler = codeop.CommandCompiler() self._buffer: ta.List[str] = [] self._count = 0 self._write_count = -1
def __call__(self): global log, imap log = logging.getLogger('gmdb.cmd.shell') self.comp = codeop.CommandCompiler() sys.ps1 = getattr(sys, 'ps1', '>>> ') sys.ps2 = getattr(sys, 'ps2', '... ') if readline and conf.hist and os.path.isfile(conf.hist): readline.read_history_file(conf.hist) with IMAP4Control(False) as imap: print("\nYou may run now Python or IMAP commands:") print(">>> print('hello, world')") print(">>> SELECT INBOX\n") print("Run 'auth()' to perform normal authentication steps.") print("Press <Ctrl-C> once to cancel the current command.") print("Press <Ctrl-C> twice to exit (or type 'quit' or 'exit').\n") try: self._cmd_loop() finally: if readline and conf.hist: readline.write_history_file(conf.hist)
def __init__(self): """Create a new InputSplitter instance. """ self._buffer = [] self._compile = codeop.CommandCompiler() self.encoding = get_input_encoding()
def __init__(self, namespace=None, translator=None, magic=None, display_formatters=None, traceback_formatters=None, output_trap=None, history=None, message_cache=None, filename='<string>', config=None): # The namespace. if namespace is None: namespace = {} self.namespace = namespace # An object that will translate commands into executable Python. # The current translator does not work properly so for now we are going # without! # if translator is None: # from ipython1.core.translator import IPythonTranslator # translator = IPythonTranslator() self.translator = translator # An object that maintains magic commands. if magic is None: from ipython1.core.magic import Magic magic = Magic(self) self.magic = magic # A list of formatters for the displayhook. if display_formatters is None: display_formatters = default_display_formatters() self.display_formatters = display_formatters # A list of formatters for tracebacks. if traceback_formatters is None: traceback_formatters = default_traceback_formatters() self.traceback_formatters = traceback_formatters # The object trapping stdout/stderr. if output_trap is None: from ipython1.core.output_trap import OutputTrap output_trap = OutputTrap() self.output_trap = output_trap # An object that manages the history. if history is None: from ipython1.core.history import History history = History() self.history = history # An object that caches all of the return messages. if message_cache is None: from ipython1.core.message_cache import SimpleMessageCache message_cache = SimpleMessageCache() self.message_cache = message_cache # The "filename" of the code that is executed in this interpreter. self.filename = filename # An object that contains much configuration information. if config is None: # fixme: Move this constant elsewhere! config = Bunch(ESC_MAGIC='%') self.config = config # Hook managers. # fixme: make the display callbacks configurable. In the meantime, # enable macros. self.display_trap = DisplayTrap( formatters=self.display_formatters, callbacks=[self._possible_macro], ) self.traceback_trap = TracebackTrap( formatters=self.traceback_formatters) # This is used temporarily for reformating exceptions in certain # cases. It will go away once the ultraTB stuff is ported # to ipython1 self.tbHandler = ultraTB.FormattedTB(color_scheme='NoColor', mode='Context', tb_offset=2) # An object that can compile commands and remember __future__ # statements. self.command_compiler = codeop.CommandCompiler() # A replacement for the raw_input() and input() builtins. Change these # attributes later to configure them. self.raw_input_builtin = raw_input self.input_builtin = input # The number of the current cell. self.current_cell_number = 1 # This is the message dictionary assigned temporarily when running the # code. self.message = None self.setup_namespace()
def __init__(self, user_ns=None, global_ns=None, translator=None, magic=None, display_formatters=None, traceback_formatters=None, output_trap=None, history=None, message_cache=None, filename='<string>', config=None): # The local/global namespaces for code execution local_ns = user_ns # compatibility name if local_ns is None: local_ns = {} self.user_ns = local_ns # The local namespace if global_ns is None: global_ns = {} self.user_global_ns = global_ns # An object that will translate commands into executable Python. # The current translator does not work properly so for now we are going # without! # if translator is None: # from IPython.kernel.core.translator import IPythonTranslator # translator = IPythonTranslator() self.translator = translator # An object that maintains magic commands. if magic is None: from IPython.kernel.core.magic import Magic magic = Magic(self) self.magic = magic # A list of formatters for the displayhook. if display_formatters is None: display_formatters = default_display_formatters() self.display_formatters = display_formatters # A list of formatters for tracebacks. if traceback_formatters is None: traceback_formatters = default_traceback_formatters() self.traceback_formatters = traceback_formatters # The object trapping stdout/stderr. if output_trap is None: from IPython.kernel.core.output_trap import OutputTrap output_trap = OutputTrap() self.output_trap = output_trap # An object that manages the history. if history is None: from IPython.kernel.core.history import InterpreterHistory history = InterpreterHistory() self.history = history self.get_history_item = history.get_history_item self.get_history_input_cache = history.get_input_cache self.get_history_input_after = history.get_input_after # An object that caches all of the return messages. if message_cache is None: from IPython.kernel.core.message_cache import SimpleMessageCache message_cache = SimpleMessageCache() self.message_cache = message_cache # The "filename" of the code that is executed in this interpreter. self.filename = filename # An object that contains much configuration information. if config is None: # fixme: Move this constant elsewhere! config = Bunch(ESC_MAGIC='%') self.config = config # Hook managers. # fixme: make the display callbacks configurable. In the meantime, # enable macros. self.display_trap = DisplayTrap( formatters=self.display_formatters, callbacks=[self._possible_macro], ) self.traceback_trap = TracebackTrap( formatters=self.traceback_formatters) # This is used temporarily for reformating exceptions in certain # cases. It will go away once the ultraTB stuff is ported # to ipython1 self.tbHandler = ultraTB.FormattedTB(color_scheme='NoColor', mode='Context', tb_offset=2) # An object that can compile commands and remember __future__ # statements. self.command_compiler = codeop.CommandCompiler() # A replacement for the raw_input() and input() builtins. Change these # attributes later to configure them. self.raw_input_builtin = raw_input self.input_builtin = input # The number of the current cell. self.current_cell_number = 1 # Initialize cache, set in/out prompts and printing system self.outputcache = CachedOutput(self, rc.cache_size, rc.pprint, input_sep=rc.separate_in, output_sep=rc.separate_out, output_sep2=rc.separate_out2, ps1=rc.prompt_in1, ps2=rc.prompt_in2, ps_out=rc.prompt_out, pad_left=rc.prompts_pad_left) # Need to decide later if this is the right approach, but clients # commonly use sys.ps1/2, so it may be best to just set them here sys.ps1 = self.outputcache.prompt1.p_str sys.ps2 = self.outputcache.prompt2.p_str # This is the message dictionary assigned temporarily when running the # code. self.message = None self.setup_namespace()
def writelines(self, lines): for line in lines: self.write(line) def flush(self): pass def isatty(self): return True def read(self, *args): raise NotImplementedError def eval(code): try: exec(code, globals()) except SystemExit: metroui.exit() return compile = codeop.CommandCompiler() sys.stdout = PseudoFile(write=metroui.add_to_stdout) sys.stderr = PseudoFile(write=metroui.add_to_stderr) sys.stdin = PseudoFile(readline=metroui.readline) print("Python %s on %s" % (sys.version, sys.platform)) print('Type "help", "copyright", "credits" or "license" for more information.')