def save_and_run(filename, cell): cell = cell.strip() with open(filename, 'w') as f: f.write(cell) shell = InteractiveShell() shell.run_cell(cell)
def ip(): """An instance of IPython.InteractiveShell. Will raise a skip if IPython is not installed. """ pytest.importorskip('IPython', minversion="6.0.0") from IPython.core.interactiveshell import InteractiveShell return InteractiveShell()
def _load_ipyhon(self): """Try loading IPython shell. The result is set in self._ipython (can be None if IPython not available). """ # Init self._ipython = None import __main__ # Try importing IPython try: import IPython except ImportError: return # Version ok? if IPython.version_info < (1, ): return # Create an IPython shell from IPython.core.interactiveshell import InteractiveShell self._ipython = InteractiveShell(user_module=__main__) # Set some hooks / event callbacks # Run hook (pre_run_code_hook is depreacted in 2.0) pre_run_cell_hook = self.ipython_pre_run_cell_hook if IPython.version_info < (2, ): self._ipython.set_hook("pre_run_code_hook", pre_run_cell_hook) else: self._ipython.events.register("pre_run_cell", pre_run_cell_hook) # Other hooks self._ipython.set_hook("editor", self.ipython_editor_hook) self._ipython.set_custom_exc((bdb.BdbQuit, ), self.dbstop_handler) # Some patching self._ipython.ask_exit = self.ipython_ask_exit # Make output be shown on Windows if sys.platform.startswith("win"): # IPython wraps std streams just like we do below, but # pyreadline adds *another* wrapper, which is where it # goes wrong. Here we set it back to bypass pyreadline. if IPython.version_info < ( 8, ): # corrects a problem with IOStream from IPython 8.x.x from IPython.utils import io io.stdin = io.IOStream(sys.stdin) io.stdout = io.IOStream(sys.stdout) io.stderr = io.IOStream(sys.stderr) # Ipython uses msvcrt e.g. for pausing between pages # but this does not work in pyzo import msvcrt msvcrt.getwch = msvcrt.getch = input # input is deffed above
def process(conn, stdout): shell = InteractiveShell() orig, sys.stdout = sys.stdout, stdout execRes = shell.run_cell(conn.recv()) sys.stdout = orig res = (execRes.result, execRes.error_before_exec or execRes.error_in_exec) conn.send(res)
def test_commit(session: Session, engine: Engine) -> None: session.execute("commit;") from IPython.core.interactiveshell import InteractiveShell shell = InteractiveShell() assert not shell.run_line_magic("load_ext", "sql") assert not shell.run_line_magic("sql", "duckdb:///:memory:") assert shell.run_line_magic("sql", "select 42;") == [(42,)]
def __init__(self, path=None): """ Constructor :path: If not None, create a new notebook. Else, load one from file """ self.path = path self.root_kernel = InteractiveShell() self.root_cell = Cell(self.root_kernel) self.current_cell = self.root_cell self.cells = {} self.cells[self.root_cell.cell_id] = self.root_cell
def __init__(self, path): self.path = path self.nb = nbformat.read(path, 4) self._code_answers = None self.mod = types.ModuleType(self.path) self.mod.__file__ = self.path self.mod.__loader__ = self self.mod.__dict__['get_ipython'] = get_ipython self.shell = InteractiveShell(user_module=self.mod).instance() self.shell.prepare_user_module(self.mod) # For saving the last line outputof iPython cells self.cell_outs = dict()
def ip(): """ Get an instance of IPython.InteractiveShell. Will raise a skip if IPython is not installed. """ pytest.importorskip("IPython", minversion="6.0.0") from IPython.core.interactiveshell import InteractiveShell # GH#35711 make sure sqlite history file handle is not leaked from traitlets.config import Config # isort:skip c = Config() c.HistoryManager.hist_file = ":memory:" return InteractiveShell(config=c)
def execute_cell(raw_cell, current_ns): """ Perform the execution of the async cell """ # Create a new InteractiveShell shell = InteractiveShell() # Disable Debugger shell.call_pdb = False shell.pdb = False # Process and Inject in the Namespace imported modules module_names = current_ns.pop('import_modules') modules = {} if module_names: for alias, mname in module_names: module = import_module(mname) modules[alias] = module shell.user_ns.update(current_ns) if modules: shell.user_ns.update(modules) output = '' with capture_output() as io: _ = shell.run_cell(raw_cell, silent=True, shell_futures=False) # Update Namespace updated_namespace = dict() updated_namespace.setdefault('import_modules', list()) for k, v in shell.user_ns.items(): try: if inspect_ismodule(v): updated_namespace['import_modules'].append((k, v.__name__)) else: _ = pickle.dumps({k: v}) updated_namespace[k] = v except TypeError: continue except pickle.PicklingError: continue except AttributeError: continue # if not output: output += io.stdout return output, updated_namespace
def __init__(self, kernel, parent_cell=None, branch_tag=None, cell_type="code"): self.cell_type = cell_type self.source = [] self.stdout = None self.parent = parent_cell self.children = [] self.generate_cell_id(branch_tag) if not branch_tag is None: new_kernel = InteractiveShell() new_kernel.push(kernel.user_ns) self.kernel = new_kernel else: self.kernel = kernel
def update(self): """ Evaluate the script to update the chart model with latest data sources. Changes to the chart model will trigger an update to the chart editor. """ self.updateStarted.emit() shell = InteractiveShell() script = self.document.scriptEditorModel.getScript() execRes = shell.run_cell(script) # error with syntax or execution if execRes.error_before_exec or execRes.error_in_exec: self.updateErrored.emit() return # update document which triggers a chart update self.document.chartEditorModel.setChartDataSources(execRes.result) self.updateFinished.emit()
def hello_world(): from IPython.core.interactiveshell import InteractiveShell # I replace \r\n with \n...this might cause problems for code that has legitimate \r characters in it # (like in a string) code = request.values.get('c', '').replace('\r\n', '\n') if len(code) > 0: s = "Code<br/><pre>%r</pre><hr/>" % code try: a = InteractiveShell() with capture() as out: a.run_cell(code) # c=compile(code,'<string>','exec') # with capture() as out: # exec c s += "Standard out<br/><pre>%s</pre><hr/>Standard Error<br/><pre>%s</pre>" % tuple( out) except Exception as e: s += "Error: %s" % e return s return "<form><textarea name='c' cols='100' rows='20'></textarea><br/><input type='submit'></form>"
def __init__(self, **kwargs): Kernel.__init__(self, **kwargs) self.ipy_shell = InteractiveShell() self.ipy_shell.extension_manager.load_extension('ipython_nose') InteractiveShell._instance = self.ipy_shell self._start_bash()
def __init__(self, **kwargs): self.shell = InteractiveShell(user_ns=kwargs)
import sys from IPython.core.interactiveshell import InteractiveShell import pandasjson as json import StringIO if __name__=="__main__": mode = "ipython" line = sys.stdin.readline() shell = InteractiveShell() while line: # explicitly write to stdout sys.stdout.write(line) sys.stdout.flush() # handle incoming data, parse it, and redirect # stdout so it doesn't interfere line = sys.stdin.readline() data = json.loads(line) codeOut = StringIO.StringIO() sys.stdout = codeOut try: code = data["code"] if data.get("autocomplete")==True: _, completions = shell.complete(code) print json.dumps(completions) elif code.startswith("print"): #exec(code) shell.ex(code) else: try: #print repr(eval(code)) print repr(shell.ev(code))
def ip(Compiler): """The current interactive shell""" from IPython import get_ipython from IPython.core.interactiveshell import InteractiveShell return get_ipython() or InteractiveShell()