# >>> # super(PyDevTerminalInteractiveShell, self).ask_exit() print( 'To exit the PyDev Console, terminate the console within Eclipse.') #------------------------------------------------------------------------- # Things related to magics #------------------------------------------------------------------------- def init_magics(self): super(PyDevTerminalInteractiveShell, self).init_magics() # TODO Any additional magics for PyDev? InteractiveShellABC.register( PyDevTerminalInteractiveShell) # @UndefinedVariable #======================================================================================================================= # _PyDevFrontEnd #======================================================================================================================= class _PyDevFrontEnd: version = release.__version__ def __init__(self, *args, **kwarg): # Create and initialize our IPython instance. self.ipython = PyDevTerminalInteractiveShell.instance() # Display the IPython banner, this has version info and
self.displayhook.set_parent(parent) self.display_pub.set_parent(parent) if hasattr(self, '_data_pub'): self.data_pub.set_parent(parent) try: sys.stdout.set_parent(parent) except AttributeError: pass try: sys.stderr.set_parent(parent) except AttributeError: pass def get_parent(self): return self.parent_header def init_magics(self): super(ZMQInteractiveShell, self).init_magics() self.register_magics(KernelMagics) self.magics_manager.register_alias('ed', 'edit') def init_virtualenv(self): # Overridden not to do virtualenv detection, because it's probably # not appropriate in a kernel. To use a kernel in a virtualenv, install # it inside the virtualenv. # https://ipython.readthedocs.io/en/latest/install/kernel_install.html pass InteractiveShellABC.register(ZMQInteractiveShell)
def auto_rewrite_input(self, cmd): """Overridden from the parent class to use fancy rewriting prompt""" if not self.show_rewritten_input: return tokens = self.prompts.rewrite_prompt_tokens() if self.pt_cli: self.pt_cli.print_tokens(tokens) print(cmd) else: prompt = ''.join(s for t, s in tokens) print(prompt, cmd, sep='') _prompts_before = None def switch_doctest_mode(self, mode): """Switch prompts to classic for %doctest_mode""" if mode: self._prompts_before = self.prompts self.prompts = ClassicPrompts(self) elif self._prompts_before: self.prompts = self._prompts_before self._prompts_before = None self._update_layout() InteractiveShellABC.register(TerminalInteractiveShell) if __name__ == '__main__': TerminalInteractiveShell.instance().interact()
class InProcessInteractiveShell(ZMQInteractiveShell): kernel = Instance('IPython.kernel.inprocess.ipkernel.InProcessKernel') #------------------------------------------------------------------------- # InteractiveShell interface #------------------------------------------------------------------------- def enable_gui(self, gui=None): """Enable GUI integration for the kernel.""" from IPython.kernel.zmq.eventloops import enable_gui if not gui: gui = self.kernel.gui return enable_gui(gui, kernel=self.kernel) def enable_matplotlib(self, gui=None): """Enable matplotlib integration for the kernel.""" if not gui: gui = self.kernel.gui return super(InProcessInteractiveShell, self).enable_matplotlib(gui) def enable_pylab(self, gui=None, import_all=True, welcome_message=False): """Activate pylab support at runtime.""" if not gui: gui = self.kernel.gui return super(InProcessInteractiveShell, self).enable_pylab(gui, import_all, welcome_message) InteractiveShellABC.register(InProcessInteractiveShell)
" $> ipython <app> --existing %s\n" "or even just:\n" " $> ipython <app> --existing\n" "if this is the most recent IPython session you have started." % os.path.basename(connection_file) ) def magic_qtconsole(self, arg_s): """Open a qtconsole connected to this kernel. Useful for connecting a qtconsole to running notebooks, for better debugging. """ try: p = connect_qtconsole(argv=arg_split(arg_s, os.name=='posix')) except Exception as e: error("Could not start qtconsole: %r" % e) return def set_next_input(self, text): """Send the specified text to the frontend to be presented at the next input cell.""" payload = dict( source='IPython.zmq.zmqshell.ZMQInteractiveShell.set_next_input', text=text ) self.payload_manager.write_payload(payload) InteractiveShellABC.register(ZMQInteractiveShell)
# >>> # <type 'exceptions.SystemExit'>:None # >>> # super(PyDevTerminalInteractiveShell, self).ask_exit() print('To exit the PyDev Console, terminate the console within Eclipse.') #------------------------------------------------------------------------- # Things related to magics #------------------------------------------------------------------------- def init_magics(self): super(PyDevTerminalInteractiveShell, self).init_magics() # TODO Any additional magics for PyDev? InteractiveShellABC.register(PyDevTerminalInteractiveShell) # @UndefinedVariable #======================================================================================================================= # _PyDevFrontEnd #======================================================================================================================= class _PyDevFrontEnd: version = release.__version__ def __init__(self, show_banner=True): # Create and initialize our IPython instance. self.ipython = PyDevTerminalInteractiveShell.instance() if show_banner: # Display the IPython banner, this has version info and
CreateMessage('clear_output', content=content, parent_header=self.parent_header)) class PepperInteractiveShell(InteractiveShell): """A subclass of InteractiveShell for the Pepper Messagin API.""" displayhook_class = Type(PepperShellDisplayHook) display_pub_class = Type(PepperDisplayPublisher) @staticmethod def enable_gui(gui): pass InteractiveShellABC.register(PepperInteractiveShell) class PepperKernel(Configurable): shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') shell_class = Type(PepperInteractiveShell) def __init__(self): self.shell = self.shell_class.instance(parent=self) self.shell.run_cell(""" import os matplotlib_config_dir = '/mplconfigdir' os.environ['XDG_CONFIG_HOME'] = matplotlib_config_dir os.environ['TMP'] = '' import matplotlib import matplotlib.cbook
from IPython.config.configurable import Configurable from IPython.core.interactiveshell import InteractiveShellABC from IPython.extensions import pretty as pretty_ext from IPython.external import pretty from IPython.testing import decorators as dec from IPython.testing import tools as tt from IPython.utils.traitlets import Bool #----------------------------------------------------------------------------- # Tests #----------------------------------------------------------------------------- class InteractiveShellStub(Configurable): pprint = Bool(True) InteractiveShellABC.register(InteractiveShellStub) class A(object): pass def a_pprinter(o, p, c): return p.text("<A>") class TestPrettyResultDisplay(TestCase): def setUp(self): self.ip = InteractiveShellStub() self.prd = pretty_ext.PrettyResultDisplay(shell=self.ip, config=None) @dec.skip_known_failure def test_for_type(self):
ast_transformers = List( [TransformDynamicVariablesToCalls(), Py5CodeValidation()]).tag(config=True) banner2 = Unicode("Activating py5 imported mode").tag(config=True) def run_cell(self, *args, **kwargs): # TODO: deprecated self.log.warning( "This kernel is deprecated. Uninstall it with `jupyter kernelspec uninstall py5`, install the new py5jupyter package, and then install the kernel with `python -m py5jupyter.kernels.py5.install --sys-prefix`." ) return super(Py5Shell, self).run_cell(*args, **kwargs) InteractiveShellABC.register(Py5Shell) class Py5Kernel(IPythonKernel): shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) shell_class = Type(Py5Shell) help_links = List([*IPythonKernel.help_links.default(), *_PY5_HELP_LINKS]).tag(config=True) implementation = 'py5' implementation_version = '0.8.2a1' class Py5App(IPKernelApp):
def __exit__(self, exc_type, exc_value, traceback): if exc_value is not None: print("exc_type", exc_type) print("exc_value", str(exc_value)) print("traceback", str(traceback)) sys.stdout = self.sys_stdout sys.stderr = self.sys_stderr class ProxyDisplayPublisher(DisplayPublisher): def publish(self, data, metadata=None, source=None): if not isinstance(data, dict): raise TypeError('data must be a dict, got: %r' % data) if metadata is not None and not isinstance(metadata, dict): raise TypeError('metadata must be a dict, got: %r' % data) content = {} content['data'] = encode_images(data) content['metadata'] = metadata print(json.dumps(json_clean(content))) class ProxyInteractiveShell(InteractiveShell): display_pub_class = Type(ProxyDisplayPublisher) def enable_gui(gui, kernel=None): pass InteractiveShellABC.register(ProxyInteractiveShell)
def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=None): """Version of run_cell that always uses shell_futures.""" return super(CoconutShell, self).run_cell(raw_cell, store_history, silent, shell_futures=True) def user_expressions(self, expressions): """Version of user_expressions that compiles Coconut code first.""" compiled_expressions = {} for key, expr in expressions.items(): try: compiled_expressions[key] = COMPILER.parse_eval(expr) except CoconutException: compiled_expressions[key] = expr return super(CoconutShell, self).user_expressions(compiled_expressions) InteractiveShellABC.register(CoconutShell) class CoconutKernel(IPythonKernel, object): """Jupyter kernel for Coconut.""" shell_class = CoconutShell implementation = "icoconut" implementation_version = VERSION language = "coconut" language_version = VERSION banner = version_banner language_info = { "name": "coconut", "mimetype": mimetype, "file_extension": code_exts[0], "codemirror_mode": {
received = json.loads(received.decode("utf-8")) if received["out"]: if received["out"].endswith("\n"): received["out"] = received["out"][:-1] print(received["out"]) if received["exc"]: lexer = get_lexer_by_name("ipython3") formatter = Terminal256Formatter(style="default") print(pygments.highlight(received["exc"], lexer, formatter)) result.error_in_exec = received["exc"] return True result.result = received["evl"] return False def init_magics(self): super(TransferInteractiveShell, self).init_magics() self.register_magics(TransferKernelMagics) class ITransferKernel(IPythonKernel): shell_class = Type(TransferInteractiveShell) implementation = "ITransfer" implementation_version = "0.1" InteractiveShellABC.register(TransferInteractiveShell) if __name__ == '__main__': from ipykernel.kernelapp import IPKernelApp IPKernelApp.launch_instance(kernel_class=ITransferKernel)
self._flush_streams() sendMessage('iopub', 'clear_output', content=content, parent_header=self.parent_header) class PepperInteractiveShell(InteractiveShell): """A subclass of InteractiveShell for the Pepper Messagin API.""" displayhook_class = Type(PepperShellDisplayHook) display_pub_class = Type(PepperDisplayPublisher) @staticmethod def enable_gui(gui): pass InteractiveShellABC.register(PepperInteractiveShell) class PepperKernel(Configurable): shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') shell_class = Type(PepperInteractiveShell) def __init__(self): self.shell = self.shell_class.instance(parent=self) self.shell.run_cell(""" import os matplotlib_config_dir = '/mplconfigdir' os.environ['XDG_CONFIG_HOME'] = matplotlib_config_dir os.environ['TMP'] = '' import matplotlib import matplotlib.cbook """)
store_history, silent, shell_futures=True) def user_expressions(self, expressions): """Version of user_expressions that compiles Coconut code first.""" compiled_expressions = {} for key, expr in expressions.items(): try: compiled_expressions[key] = COMPILER.parse_eval(expr) except CoconutException: compiled_expressions[key] = expr return super(CoconutShell, self).user_expressions(compiled_expressions) InteractiveShellABC.register(CoconutShell) class CoconutKernel(IPythonKernel, object): """Jupyter kernel for Coconut.""" shell_class = CoconutShell use_experimental_completions = True implementation = "icoconut" implementation_version = VERSION language = "coconut" language_version = VERSION banner = version_banner language_info = { "name": "coconut", "version": VERSION, "mimetype": mimetype, "codemirror_mode": {
kernel = Instance('ipykernel.inprocess.ipkernel.InProcessKernel', allow_none=True) #------------------------------------------------------------------------- # InteractiveShell interface #------------------------------------------------------------------------- def enable_gui(self, gui=None): """Enable GUI integration for the kernel.""" from ipykernel.eventloops import enable_gui if not gui: gui = self.kernel.gui enable_gui(gui, kernel=self.kernel) self.active_eventloop = gui def enable_matplotlib(self, gui=None): """Enable matplotlib integration for the kernel.""" if not gui: gui = self.kernel.gui return super(InProcessInteractiveShell, self).enable_matplotlib(gui) def enable_pylab(self, gui=None, import_all=True, welcome_message=False): """Activate pylab support at runtime.""" if not gui: gui = self.kernel.gui return super(InProcessInteractiveShell, self).enable_pylab(gui, import_all, welcome_message) InteractiveShellABC.register(InProcessInteractiveShell)
more = self.input_splitter.push_accepts_more() except SyntaxError: more = False if (self.SyntaxTB.last_syntax_error and self.autoedit_syntax): self.edit_syntax_error() source_raw = self.input_splitter.source_raw self.input_splitter.reset() ret = self.run_cell(source_raw, store_history=True) return ret InteractiveShellABC.register(XMPPInteractiveShell) class SimplePassphraseSecurity(object): def __init__(self,passphrase): self.passphrase = passphrase self.allowed_jabberids = {} def is_authorized(self, msg): sender = msg['from'] if self.passphrase == None: return True elif self.allowed_jabberids.has_key(sender): return True elif msg['body'] == self.passphrase: self.allowed_jabberids[sender] = 1