Exemplo n.º 1
0
class LpyShellWidget(RichJupyterWidget):  #, GraphicalStreamRedirection):
    def __init__(self, parent=None):
        """
        :param  parent: specifies the parent widget.
        If no parent widget has been specified, it is possible to
        exit the interpreter by Ctrl-D.
        """
        if sys.executable.endswith('pythonw.exe'):
            lpylog = open(tempfile.gettempdir() + '/lpylog.txt', 'w')
            sys.stdout = lpylog
            sys.stderr = lpylog

        RichJupyterWidget.__init__(self, parent)

        self.kernel_manager = QtInProcessKernelManager()
        self.kernel_manager.start_kernel(show_banner=False)

        self.kernel = self.kernel_manager.kernel
        self.kernel.gui = 'qt'

        self.shell = self.kernel.shell

        self.kernel_client = self.kernel_manager.client()
        self.kernel_client.start_channels()

        self.kernel.locals = self.kernel.shell.user_ns
Exemplo n.º 2
0
def in_process_console(console_class=RichIPythonWidget, **kwargs):
    """Create a console widget, connected to an in-process Kernel

    This only works on IPython v 0.13 and above

    Parameters
    ----------
    console_class : The class of the console widget to create
    kwargs : Extra variables to put into the namespace
    """

    km = QtInProcessKernelManager()
    km.start_kernel()

    kernel = km.kernel
    kernel.gui = 'qt4'

    client = km.client()
    client.start_channels()

    control = console_class()
    control.kernel_manager = km
    control.kernel_client = client
    control.shell = kernel.shell
    control.shell.user_ns.update(**kwargs)
    return control
Exemplo n.º 3
0
class JupyterWidget(RichJupyterWidget):
    def __init__(self):
        super(RichJupyterWidget, self).__init__()
        self.kernel_manager = QtInProcessKernelManager()
        self.kernel_manager.start_kernel()
        self.kernel = self.kernel_manager.kernel
        self.kernel.gui = 'qt4'
        self.kernel_client = self.kernel_manager.client()
        self.kernel_client.start_channels()

        def stop():
            kernel_client.stop_channels()
            kernel_manager.shutdown_kernel()
            guisupport.get_app_qt4().exit()

        self.exit_requested.connect(stop)

    def executeCmd(self, cmd):
        self.kernel.shell.ex(cmd)

    def evaluateCmd(self, cmd):
        self.kernel.shell.ev(cmd)

    def pushVar(self, **kwarg):
        self.kernel.shell.push(kwarg)

    def executeFile(self, file):
        """Execute a Python file in the interactive namespace."""
        self.shell.safe_execfile(file, self.shell.user_global_ns)

    def runCell(self, *args, **kwargs):
        """Execute a cell."""
        self.shell.run_cell(*args, **kwargs)
Exemplo n.º 4
0
def createConsole(parent):
    """
    disclaimer: this code is not mine. I copied it to get an embedded console
    It will be modified at some point to attempt interactability

    source: https://stackoverflow.com/a/26676570

    :param parent:
    :return:
    """
    kernel_manager = QtInProcessKernelManager()
    kernel_manager.start_kernel()
    kernel = kernel_manager.kernel
    kernel.gui = 'qt4'

    kernel_client = kernel_manager.client()
    kernel_client.start_channels()
    kernel_client.namespace = parent

    def stop():
        kernel_client.stop_channels()
        kernel_manager.shutdown_kernel()

    layout = QVBoxLayout(parent)
    widget = RichJupyterWidget(parent=parent)
    layout.addWidget(widget, Qt.AlignRight)
    widget.kernel_manager = kernel_manager
    widget.kernel_client = kernel_client
    widget.exit_requested.connect(stop)
    ipython_widget = widget
    ipython_widget.show()
    kernel.shell.push({'widget': widget, 'kernel': kernel, 'parent': parent})
    return {'widget': widget, 'kernel': kernel}
Exemplo n.º 5
0
def show():
    """
    An example of embedding a RichJupyterWidget with an in-process kernel.
    We recommend using a kernel in a separate process as the normal option - see
    embed_qtconsole.py for more information. In-process kernels are not well
    supported.
    To run this example:
        python3 inprocess_qtconsole.py
    """

    #global ipython_widget  # Prevent from being garbage collected

    # Create an in-process kernel
    kernel_manager = QtInProcessKernelManager()
    kernel_manager.start_kernel(show_banner=True)
    # kernel = kernel_manager.kernel
    # kernel.gui = 'qt5'

    kernel_client = kernel_manager.client()
    kernel_client.start_channels()

    ipython_widget = RichJupyterWidget()
    ipython_widget.kernel_manager = kernel_manager
    ipython_widget.kernel_client = kernel_client
    return ipython_widget
Exemplo n.º 6
0
def main():
    # Print the ID of the main process
    print_process_id()

    init_asyncio_patch()
    app = guisupport.get_app_qt4()

    # Create an in-process kernel
    # >>> print_process_id()
    # will print the same process ID as the main process
    kernel_manager = QtInProcessKernelManager()
    kernel_manager.start_kernel()
    kernel = kernel_manager.kernel
    kernel.gui = 'qt4'
    kernel.shell.push({'foo': 43, 'print_process_id': print_process_id})

    kernel_client = kernel_manager.client()
    kernel_client.start_channels()

    def stop():
        kernel_client.stop_channels()
        kernel_manager.shutdown_kernel()
        app.exit()

    control = RichIPythonWidget()
    control.kernel_manager = kernel_manager
    control.kernel_client = kernel_client
    control.exit_requested.connect(stop)
    control.show()

    guisupport.start_event_loop_qt4(app)
Exemplo n.º 7
0
def main():
    """Start kernel manager and client, create window, run app event loop,
    auto execute some code in user namespace. A minimalist example is shown in
    qt_ip_test.py.

    NOTE: Make sure that the Qt v2 API is being used by IPython by running `export
    QT_API=pyqt` at the command line before running neuropy, or by adding it to `.bashrc`"""
    app = guisupport.get_app_qt4()

    if INPROCESS:
        from qtconsole.inprocess import QtInProcessKernelManager
        km = QtInProcessKernelManager()
    else:
        from qtconsole.manager import QtKernelManager
        km = QtKernelManager()
    km.start_kernel()
    km.kernel.gui = 'qt4'
    kc = km.client()
    kc.start_channels()

    nw = NeuropyWindow()
    ipw = nw.ipw
    config_ipw(ipw)
    ipw.kernel_manager = km
    ipw.kernel_client = kc
    ipw.exit_requested.connect(nw.stop)
    nw.show()

    # execute some code through the frontend (once the event loop is running).
    # The output appears in the IPythonWidget (ipw).
    do_later(ipw.execute, 'run -i %s' % 'startup.py', hidden=True)
    do_later(ipw.execute, 'run -i %s' % 'globals.py', hidden=True)
    #guisupport.start_event_loop_qt4(app) # doesn't seem to work in IPy 5.3.0
    app.exec_()
Exemplo n.º 8
0
    def __init__(self, main_window):
        """
		desc:
			Constructor.

		arguments:
			main_window:	The main window object.
		"""

        super(ipython_console, self).__init__(main_window)
        kernel_manager = QtInProcessKernelManager()
        kernel_manager.start_kernel()
        self.kernel = kernel_manager.kernel
        self.kernel.gui = 'qt4'
        self.kernel.shell.banner1 = ''
        kernel_client = kernel_manager.client()
        kernel_client.start_channels()
        self.control = RichIPythonWidget()
        self.control.banner = self.banner()
        self.control.kernel_manager = kernel_manager
        self.control.kernel_client = kernel_client
        self.verticalLayout = QtWidgets.QVBoxLayout(self)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.verticalLayout)
        self.verticalLayout.addWidget(self.control)
Exemplo n.º 9
0
    def __init__(self, session, tool_name):
        ToolInstance.__init__(self, session, tool_name)
        # 'display_name' defaults to class name with spaces inserted
        # between lower-then-upper-case characters (therefore "Tool UI"
        # in this case), so only override if different name desired
        self.display_name = "ChimeraX Python Shell"
        from chimerax.ui import MainToolWindow
        self.tool_window = MainToolWindow(self)
        parent = self.tool_window.ui_area
        # UI content code
        from ipykernel.ipkernel import IPythonKernel
        save_ns = IPythonKernel.user_ns
        IPythonKernel.user_ns = {'session': session}
        from qtconsole.inprocess import QtInProcessKernelManager
        kernel_manager = QtInProcessKernelManager()
        kernel_manager.start_kernel()
        kernel_client = kernel_manager.client()
        kernel_client.start_channels()

        from qtconsole.rich_jupyter_widget import RichJupyterWidget
        self.shell = RichJupyterWidget(parent)
        def_banner = self.shell.banner
        self.shell.banner = "{}\nCurrent ChimeraX session available as 'session'.\n\n".format(
            def_banner)
        self.shell.kernel_manager = kernel_manager
        self.shell.kernel_client = kernel_client
        IPythonKernel.user_ns = save_ns

        from PyQt5.QtWidgets import QHBoxLayout
        layout = QHBoxLayout()
        layout.addWidget(self.shell)
        layout.setStretchFactor(self.shell, 1)
        parent.setLayout(layout)
        self.tool_window.manage(placement=None)
Exemplo n.º 10
0
    def __init__(self, *args, **kwargs):
        """
        A constructor matching that of RichJupyterWidget
        :param args: Positional arguments passed directly to RichJupyterWidget
        :param kwargs: Keyword arguments. The following keywords are understood by this widget:

          - startup_code: A code snippet to run on startup.

        the rest are passed to RichJupyterWidget
        """
        startup_code = kwargs.pop("startup_code", "")
        super(InProcessJupyterConsole, self).__init__(*args, **kwargs)

        # create an in-process kernel
        kernel_manager = QtInProcessKernelManager()
        kernel_manager.start_kernel()
        kernel = kernel_manager.kernel
        kernel.gui = 'qt'

        # use a separate thread for execution
        shell = kernel.shell
        shell.run_code = async_wrapper(shell.run_code, shell)

        # attach channels, start kernel and run any startup code
        kernel_client = kernel_manager.client()
        kernel_client.start_channels()
        if startup_code:
            shell.ex(startup_code)

        self.kernel_manager = kernel_manager
        self.kernel_client = kernel_client

        # Override python input to raise a QInputDialog.
        kernel.raw_input = QAppThreadCall(input_qinputdialog)
Exemplo n.º 11
0
def main():
    """Start kernel manager and client, create window, run app event loop"""
    app = guisupport.get_app_qt4()

    if INPROCESS:
        from qtconsole.inprocess import QtInProcessKernelManager
        km = QtInProcessKernelManager()
    else:
        from qtconsole.manager import QtKernelManager
        km = QtKernelManager()
    km.start_kernel()
    km.kernel.gui = 'qt4'
    kc = km.client()
    kc.start_channels()

    widget = RichJupyterWidget()
    widget.kernel_manager = km
    widget.kernel_client = kc
    if CLEANSHUTDOWN: # slow exit on CTRL+D
        def stop():
            kc.stop_channels()
            km.shutdown_kernel()
            app.exit()
        widget.exit_requested.connect(stop)
    else: # fast exit on CTRL+D
        widget.exit_requested.connect(app.quit)
    widget.show()
    guisupport.start_event_loop_qt4(app)
Exemplo n.º 12
0
def put_ipy(parent):
    kernel_manager = QtInProcessKernelManager()
    kernel_manager.start_kernel()
    kernel = kernel_manager.kernel
    kernel.gui = 'qt4'

    kernel_client = kernel_manager.client()
    kernel_client.start_channels()
    kernel_client.namespace = parent

    def stop():
        kernel_client.stop_channels()
        kernel_manager.shutdown_kernel()

    layout = QtWidgets.QVBoxLayout(parent)
    widget = RichJupyterWidget(parent=parent)
    layout.addWidget(widget)
    widget.kernel_manager = kernel_manager
    widget.kernel_client = kernel_client
    widget.exit_requested.connect(stop)
    ipython_widget = widget
    ipython_widget.show()
    kernel.shell.push({'widget': widget, 'kernel': kernel, 'parent': parent})

    return {'widget': widget, 'kernel': kernel}
Exemplo n.º 13
0
    class JupyterWidget(QWidget):

        _defaultWidth = 900
        _defaultHeight = 450

        def __init__(self):
            super(JupyterWidget, self).__init__()

            self._kernel_manager = QtInProcessKernelManager()
            self._kernel_manager.start_kernel(show_banner=True)

            self._kernel_client = self._kernel_manager.client()
            self._kernel_client.start_channels()

            self._kernel = self._kernel_manager.kernel
            self._kernel.gui = 'qt4'

            self._console = RichJupyterWidget()
            self._console.kernel_manager = self._kernel_manager
            self._console.kernel_client = self._kernel_client

            self._layout = QHBoxLayout()
            self._layout.addWidget(self._console)
            self._layout.setContentsMargins(QMargins(0, 0, 0, 0))

            self.setLayout(self._layout)

            self.resize(self._defaultWidth, self._defaultHeight)

        def push(self, name, value):
            self._kernel.shell.push({name: value})
Exemplo n.º 14
0
    def __init__(self, *args, **kw):
        super(MantidIPythonWidget, self).__init__(*args, **kw)

        # Create an in-process kernel
        kernel_manager = QtInProcessKernelManager()
        kernel_manager.start_kernel()
        kernel = kernel_manager.kernel
        kernel.gui = 'qt4'

        # Figure out the full path to the mantidplotrc.py file and then %run it
        mantidplotpath = path.split(
            path.dirname(__file__))[0]  # It's the directory above this one
        # print '[....]  mantid plot path: ', mantidplotpath
        mantidplotrc = path.join(mantidplotpath, 'mantidplotrc.py')
        shell = kernel.shell
        shell.run_line_magic('run', mantidplotrc)
        # print '[DB...BAUnderstand]: shell run: ', mantidplotrc

        # These 3 lines replace the run_code method of IPython's InteractiveShell class (of which the
        # shell variable is a derived instance) with our method defined above. The original method
        # is renamed so that we can call it from within the our_run_code method.
        f = shell.run_code
        shell.run_code = types.MethodType(our_run_code, shell)
        shell.ipython_run_code = f

        kernel_client = kernel_manager.client()
        kernel_client.start_channels()

        self.kernel_manager = kernel_manager
        self.kernel_client = kernel_client

        self._mainApplication = None

        return
Exemplo n.º 15
0
class LpyShellWidget(RichJupyterWidget, GraphicalStreamRedirection):
    def __init__(self, parent=None):
        """
        :param  parent: specifies the parent widget.
        If no parent widget has been specified, it is possible to
        exit the interpreter by Ctrl-D.
        """

        RichJupyterWidget.__init__(self, parent)

        self.kernel_manager = QtInProcessKernelManager()
        self.kernel_manager.start_kernel(show_banner=False)

        self.kernel = self.kernel_manager.kernel
        self.kernel.gui = 'qt4'
        self.shell = self.kernel.shell

        self.kernel_client = self.kernel_manager.client()
        self.kernel_client.start_channels()

        self.kernel.locals = self.kernel.shell.user_ns

        # Multiple Stream Redirection
        GraphicalStreamRedirection.__init__(self, self.kernel.stdout,
                                            self.kernel.stderr)
Exemplo n.º 16
0
class IPythonPlugin(GUIPlugin):
    name = 'IPython'

    def __init__(self):
        # # Enforce global style within the console
        # with open('xicam/gui/style.stylesheet', 'r') as f:
        #     style = f.read()
        # style = (qdarkstyle.load_stylesheet() + style)

        # Setup the kernel
        self.kernel_manager = QtInProcessKernelManager()
        self.kernel_manager.start_kernel()
        kernel = self.kernel_manager.kernel
        kernel.gui = 'qt'

        # Push Xi-cam variables into the kernel
        kernel.shell.push({
            plugin.name: plugin
            for plugin in pluginmanager.get_plugins_of_type("GUIPlugin") +
            pluginmanager.get_plugins_of_type("EZPlugin")
        })

        # Observe plugin changes
        pluginmanager.attach(self.pluginsChanged)

        # Continue kernel setuppluginmanager.getPluginsOfCategory("GUIPlugin")
        self.kernel_client = self.kernel_manager.client()
        threads.invoke_in_main_thread(self.kernel_client.start_channels)

        # Setup console widget
        def stop():
            self.kernel_client.stop_channels()
            self.kernel_manager.shutdown_kernel()

        control = RichJupyterWidget()
        control.kernel_manager = self.kernel_manager
        threads.invoke_in_main_thread(setattr, control, "kernel_client",
                                      self.kernel_client)
        control.exit_requested.connect(stop)
        # control.style_sheet = style
        control.syntax_style = u'monokai'
        control.set_default_style(colors='Linux')

        # Setup layout
        self.stages = {'Terminal': GUILayout(control)}

        # Save for later
        self.kernel = kernel

        super(IPythonPlugin, self).__init__()

    def pluginsChanged(self):
        self.kernel.shell.push({
            plugin.name: plugin
            for plugin in pluginmanager.get_plugins_of_type("GUIPlugin") +
            pluginmanager.get_plugins_of_type("EZPlugin")
        })
Exemplo n.º 17
0
def start_in_process_kernel():

    global kernel_manager, kernel_client

    kernel_manager = QtInProcessKernelManager()
    kernel_manager.start_kernel()

    kernel_client = kernel_manager.client()
    kernel_client.start_channels()
Exemplo n.º 18
0
    class JupyterWidget(RichJupyterWidget):
        def __init__(self):
            super().__init__()

            if 'asyncio' in sys.modules:
                self._init_asyncio_patch()

            self.kernel_manager = QtInProcessKernelManager()
            self.kernel_manager.start_kernel()

            self.kernel_client = self.kernel_manager.client()
            self.kernel_client.start_channels()

            # Fix issue with Jupyter 5.0+, see https://github.com/ipython/ipykernel/pull/376
            if hasattr(self.kernel_manager.kernel, '_abort_queue'):
                # noinspection PyProtectedMember
                self.kernel_manager.kernel._abort_queues = self.kernel_manager.kernel._abort_queue

            self.exit_requested.connect(self.stop)
            qApp.aboutToQuit.connect(self.stop)

        def _init_asyncio_patch(self):
            """set default asyncio policy to be compatible with tornado
            Tornado 6 (at least) is not compatible with the default
            asyncio implementation on Windows
            Pick the older SelectorEventLoopPolicy on Windows
            if the known-incompatible default policy is in use.
            do this as early as possible to make it a low priority and overrideable
            ref: https://github.com/tornadoweb/tornado/issues/2608
            FIXME: if/when tornado supports the defaults in asyncio,
                   remove and bump tornado requirement for py38
            """
            if sys.platform.startswith("win") and sys.version_info >= (
                    3, 8) and tornado.version_info < (6, 1):
                import asyncio
                try:
                    from asyncio import (
                        WindowsProactorEventLoopPolicy,
                        WindowsSelectorEventLoopPolicy,
                    )
                except ImportError:
                    pass
                    # not affected
                else:
                    if type(asyncio.get_event_loop_policy()
                            ) is WindowsProactorEventLoopPolicy:
                        # WindowsProactorEventLoopPolicy is not compatible with tornado 6
                        # fallback to the pre-3.8 default of Selector
                        asyncio.set_event_loop_policy(
                            WindowsSelectorEventLoopPolicy())

        def stop(self):
            self.kernel_client.stop_channels()
            self.kernel_manager.shutdown_kernel()

        def push(self, **kwargs):
            self.kernel_manager.kernel.shell.push(kwargs)
Exemplo n.º 19
0
class EmbedIPython(RichIPythonWidget):
    def __init__(self, **kwarg):
        super(RichIPythonWidget, self).__init__()
        self.kernel_manager = QtInProcessKernelManager()
        self.kernel_manager.start_kernel()
        self.kernel = self.kernel_manager.kernel
        self.kernel.gui = 'qt4'
        self.kernel.shell.push(kwarg)
        self.kernel_client = self.kernel_manager.client()
        self.kernel_client.start_channels()
Exemplo n.º 20
0
class EmbedIPython(RichIPythonWidget):
    def __init__(self, parent=None):
        super(RichIPythonWidget, self).__init__(parent)
        self.kernel_manager = QtInProcessKernelManager()
        self.kernel_manager.start_kernel()
        self.kernel = self.kernel_manager.kernel
        self.kernel.gui = 'qt4'
        # self.kernel.shell.push(kwarg)
        self.kernel_client = self.kernel_manager.client()
        self.kernel_client.start_channels()
        self.kernel.shell.run_cell('%pylab qt')
Exemplo n.º 21
0
    def init_jupyter_kernel(cls, widget):
        """Start a kernel, connect to it, and create a RichJupyterWidget to use it
        """
        kernel_manager = QtInProcessKernelManager(kernel_name="python3")
        kernel_manager.start_kernel()

        kernel_client = kernel_manager.client()
        kernel_client.start_channels()

        widget.kernel_manager = kernel_manager
        widget.kernel_client = kernel_client
Exemplo n.º 22
0
class IPythonView(RichJupyterWidget):
    """A view with an IPython console living in the same Python process as the GUI."""
    def __init__(self, *args, **kwargs):
        super(IPythonView, self).__init__(*args, **kwargs)

    def start_kernel(self):
        """Start the IPython kernel."""

        logger.debug("Starting the kernel.")

        self.kernel_manager = QtInProcessKernelManager()
        self.kernel_manager.start_kernel(show_banner=False)
        self.kernel_manager.kernel.gui = 'qt'
        self.kernel = self.kernel_manager.kernel
        self.shell = self.kernel.shell

        self.kernel_client = self.kernel_manager.client()
        self.kernel_client.start_channels()

        self.set_default_style('linux')
        self.exit_requested.connect(self.stop)

    def inject(self, **kwargs):
        """Inject variables into the IPython namespace."""
        logger.debug("Injecting variables into the kernel: %s.",
                     ', '.join(kwargs.keys()))
        self.kernel.shell.push(kwargs)

    def attach(self, gui, **kwargs):
        """Add the view to the GUI, start the kernel, and inject the specified variables."""
        gui.add_view(self)
        self.start_kernel()
        self.inject(gui=gui, **kwargs)
        try:
            import numpy
            self.inject(np=numpy)
        except ImportError:  # pragma: no cover
            pass
        try:
            import matplotlib.pyplot as plt
            self.inject(plt=plt)
        except ImportError:  # pragma: no cover
            pass

        @connect
        def on_close_view(sender, view):
            if view == self:
                self.stop()

    def stop(self):
        """Stop the kernel."""
        logger.debug("Stopping the kernel.")
        self.kernel_client.stop_channels()
        self.kernel_manager.shutdown_kernel()
Exemplo n.º 23
0
class Ipython(object):
    def __init__(self, scripts_path=''):
        self.kernel_manager = QtInProcessKernelManager()
        self.kernel_manager.start_kernel()
        self.kernel = self.kernel_manager.kernel
        sys.stdout = self.kernel.stdout
        sys.stderr = self.kernel.stderr

        self.scripts_path = scripts_path
        self.kernel.gui = 'qt4'

        self.kernel_client = self.kernel_manager.client()
        self.kernel_client.start_channels()

        self.control = RichJupyterWidget()
        self.control.kernel_manager = self.kernel_manager
        self.control.kernel_client = self.kernel_client
        self.control.exit_requested.connect(self.stop)

        self.control.setWindowTitle("IPython shell")

        self.execute('import numpy as np')
        self.execute('from matplotlib import pyplot as plt')
        self.execute('%matplotlib')
        self.execute('')

    def __del__(self):
        self.stop()
        self.close()

    def show(self):
        self.control.show()

        self.control.setWindowState(self.control.windowState()
                                    & ~QtCore.Qt.WindowMinimized
                                    | QtCore.Qt.WindowActive)
        self.control.activateWindow()

    def stop(self):
        self.kernel_client.stop_channels()
        self.kernel_manager.shutdown_kernel()

    def close(self):
        self.control.close()

    def push(self, vardic):
        self.kernel.shell.push(vardic)

    def execute(self, cmd):
        self.control.execute(cmd)

    def run_script(self, scriptname):
        scriptpath = os.path.join(self.scripts_path, scriptname)
        return self.control.execute('run -i %s' % scriptpath)
Exemplo n.º 24
0
class EmbedIPython(RichJupyterWidget):
    """ Some voodoo to get an ipython console in a Qt application. """
    def __init__(self, **kwarg):
        super(RichJupyterWidget, self).__init__()
        self.kernel_manager = QtInProcessKernelManager()
        self.kernel_manager.start_kernel()
        self.kernel = self.kernel_manager.kernel
        self.kernel.gui = 'qt4'
        self.kernel.shell.push(kwarg)
        self.kernel_client = self.kernel_manager.client()
        self.kernel_client.start_channels()
Exemplo n.º 25
0
class IPythonConsole:
    def __init__(self, layout, sim, gui):
        # Create an in-process kernel
        # >>> print_process_id()
        # will print the same process ID as the main process
        self.kernel_manager = QtInProcessKernelManager()
        self.kernel_manager.start_kernel()
        self.kernel = self.kernel_manager.kernel
        self.kernel.gui = 'qt4'

        self.kernel.shell.write("Welcome to AO Sim!")

        config = sim.config
        #Pass some useful objects to the user
        usefulObjects = {
            "sim": sim,
            "gui": gui,
            "config": config,
            "simConfig": sim.config.sim,
            "telConfig": sim.config.tel,
            "atmosConfig": sim.config.atmos
        }

        for i in range(sim.config.sim.nGS):
            usefulObjects["wfs{}Config".format(i)] = sim.config.wfss[i]
        for i in range(sim.config.sim.nDM):
            usefulObjects["dm{}Config".format(i)] = sim.config.dms[i]
        for i in range(sim.config.sim.nSci):
            usefulObjects["sci{}Config".format(i)] = sim.config.scis[i]

        self.kernel.shell.push(usefulObjects)
        #kernel.shell.push({'foo': 43, 'print_process_id': print_process_id})

        self.kernel_client = self.kernel_manager.client()
        self.kernel_client.start_channels()

        control = RichIPythonWidget()
        control.kernel_manager = self.kernel_manager
        control.kernel_client = self.kernel_client
        control.exit_requested.connect(self.stop)
        layout.addWidget(control)

        self.kernel.shell.ex("")
        #control.show()

        #self.kernel.show
    def stop(self):
        self.kernel_client.stop_channels()
        self.kernel_manager.shutdown_kernel()

    def write(self, message):
        self.kernel.shell.write(message)
        self.kernel.shell.ex("")
Exemplo n.º 26
0
class IPythonConsole:
    def __init__(self, layout, sim, gui):
        # Create an in-process kernel

        self.kernel_manager = QtInProcessKernelManager()
        # self.kernel_manager = QtKernelManager()
        self.kernel_manager.start_kernel()

        self.kernel = self.kernel_manager.kernel

        # self.kernel.shell.write("Welcome to AO Sim!\n")

        config = sim.config
        #Pass some useful objects to the user
        usefulObjects = {
            "sim": sim,
            "gui": gui,
            "config": config,
            "simConfig": sim.config.sim,
            "telConfig": sim.config.tel,
            "atmosConfig": sim.config.atmos,
            "np": numpy,
            "plt": pyplot
        }

        for i in range(sim.config.sim.nGS):
            usefulObjects["wfs{}Config".format(i)] = sim.config.wfss[i]
        for i in range(sim.config.sim.nDM):
            usefulObjects["dm{}Config".format(i)] = sim.config.dms[i]
        for i in range(sim.config.sim.nSci):
            usefulObjects["sci{}Config".format(i)] = sim.config.scis[i]

        self.kernel.shell.push(usefulObjects)

        self.kernel_client = self.kernel_manager.client()
        self.kernel_client.start_channels()

        control = RichIPythonWidget()
        control.kernel_manager = self.kernel_manager
        control.kernel_client = self.kernel_client
        control.exit_requested.connect(self.stop)
        layout.addWidget(control)

        # self.kernel.shell.ex("")

    def stop(self):
        self.kernel_client.stop_channels()
        self.kernel_manager.shutdown_kernel()

    def write(self, message):
        pass
Exemplo n.º 27
0
    def _setup_kernel(self):
        """ Setup the kernel for the widget.

        """
        kernel_manager = QtInProcessKernelManager()
        kernel_manager.start_kernel(show_banner=False)
        kernel = kernel_manager.kernel
        kernel.gui = 'qt'

        kernel_client = kernel_manager.client()
        kernel_client.start_channels()

        ipy_widget = self.ipy_widget
        ipy_widget.kernel_manager = kernel_manager
        ipy_widget.kernel_client = kernel_client
Exemplo n.º 28
0
def create(user_ns):
    """Create an in-process kernel."""
    manager = QtInProcessKernelManager()
    manager.start_kernel(show_banner=False)
    kernel = manager.kernel
    kernel.gui = 'qt4'
    kernel.user_ns = user_ns

    client = manager.client()
    client.start_channels()

    widget = RichJupyterWidget()
    widget.kernel_manager = manager
    widget.kernel_client = client
    return widget
Exemplo n.º 29
0
    def __init__(self, *args, **kwargs):
        """
        A constructor matching that of RichJupyterWidget
        :param args: Positional arguments passed directly to RichJupyterWidget
        :param kwargs: Keyword arguments. The following keywords are understood by this widget:

          - banner: Replace the default banner with this text
          - startup_code: A code snippet to run on startup. It is also added to the banner to inform the user.

        the rest are passed to RichJupyterWidget
        """
        banner = kwargs.pop("banner", "")
        startup_code = kwargs.pop("startup_code", "")
        super(InProcessJupyterConsole, self).__init__(*args, **kwargs)

        # adjust startup banner accordingly
        # newer ipython has banner1 & banner2 and not just banner
        two_ptr_banner = hasattr(self, 'banner1')
        if not banner:
            banner = self.banner1 if two_ptr_banner else self.banner
        if startup_code:
            banner += "\n" + \
                "The following code has been executed at startup:\n\n" + \
                startup_code
        if two_ptr_banner:
            self.banner1 = banner
            self.banner2 = ''
        else:
            self.banner = banner

        # create an in-process kernel
        kernel_manager = QtInProcessKernelManager()
        kernel_manager.start_kernel()
        kernel = kernel_manager.kernel
        kernel.gui = 'qt'

        # use a separate thread for execution
        shell = kernel.shell
        shell.run_code = async_wrapper(shell.run_code, shell)

        # attach channels, start kenel and run any startup code
        kernel_client = kernel_manager.client()
        kernel_client.start_channels()
        if startup_code:
            shell.ex(startup_code)

        self.kernel_manager = kernel_manager
        self.kernel_client = kernel_client
Exemplo n.º 30
0
def show():
    global ipython_widget  # Prevent from being garbage collected

    # Create an in-process kernel
    kernel_manager = QtInProcessKernelManager()
    kernel_manager.start_kernel(show_banner=False)
    kernel = kernel_manager.kernel
    kernel.gui = 'qt4'

    kernel_client = kernel_manager.client()
    kernel_client.start_channels()

    ipython_widget = RichJupyterWidget()
    ipython_widget.kernel_manager = kernel_manager
    ipython_widget.kernel_client = kernel_client
    ipython_widget.show()