예제 #1
0
    def createConsoleTab(self):
        """ Initialize a python console and return its widget """
        from qtconsole.rich_jupyter_widget import RichJupyterWidget
        from qtconsole.manager import QtKernelManager

        kernel_manager = QtKernelManager(kernel_name='python3')
        kernel_manager.start_kernel()
        kernel = kernel_manager.kernel
        kernel.gui = 'qt'

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

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

        widget = RichJupyterWidget(parent=self)
        widget.kernel_manager = kernel_manager
        widget.kernel_client = kernel_client
        widget.exit_requested.connect(stop)
        ipython_widget = widget
        ipython_widget.show()
        self.kernel_client = kernel_client
        #kernel_client.execute("import devices.demo.demo")
        return widget
예제 #2
0
 def start_python_kernel(self):
     """Starts kernel manager and client and attaches
     the client to the Python Console."""
     self._kernel_starting = True
     km = QtKernelManager(kernel_name=self.kernel_name)
     try:
         blackhole = open(os.devnull, 'w')
         km.start_kernel(stdout=blackhole, stderr=blackhole)
         kc = km.client()
         kc.start_channels()
         self.kernel_manager = km
         self.kernel_client = kc
         self.connect_signals()
         return True
     except FileNotFoundError:
         self._toolbox.msg_error.emit(
             "\tCouldn't find the Python executable specified by the Jupyter kernel"
         )
         self._kernel_starting = False
         return False
     except NoSuchKernel:  # kernelspecs for the selected kernel_name not available
         self._toolbox.msg_error.emit(
             "\tCouldn't find the specified IPython kernel specs [{0}]".
             format(self.kernel_name))
         self._kernel_starting = False
         return False
예제 #3
0
def launch_qtconsole(connection_file):
    wait_for_connection_file(connection_file)

    app = QtWidgets.QApplication([])
    app._kernel_has_shutdown = False

    kernel_manager = QtKernelManager()
    kernel_manager.load_connection_file(connection_file)

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

    jupyter_widget = JupyterWidget()
    jupyter_widget.kernel_manager = kernel_manager
    jupyter_widget.kernel_client = kernel_client

    window = MainWindow(jupyter_widget)
    window.show()

    def shutdown_kernel():
        if app._kernel_has_shutdown:
            return

        jupyter_widget.kernel_client.stop_channels()
        jupyter_widget.kernel_manager.shutdown_kernel()
        app._kernel_has_shutdown = True
        app.exit()

    jupyter_widget.exit_requested.connect(shutdown_kernel)
    app.aboutToQuit.connect(shutdown_kernel)

    return app.exec_()
예제 #4
0
파일: python3.py 프로젝트: skerr92/mu
class KernelRunner(QObject):
    """
    Used to control the iPython kernel in a non-blocking manner so the UI
    remains responsive.
    """

    kernel_started = pyqtSignal(QtKernelManager, QtKernelClient)
    kernel_finished = pyqtSignal()
    # Used to build context with user defined envars when running the REPL.
    default_envars = os.environ.copy()

    def __init__(self, cwd, envars):
        """
        Initialise the kernel runner with a target current working directory.
        """
        super().__init__()
        self.cwd = cwd
        self.envars = dict(envars)

    def start_kernel(self):
        """
        Create the expected context, start the kernel, obtain a client and
        emit a signal when both are started.
        """
        logger.info(sys.path)
        os.chdir(self.cwd)  # Ensure the kernel runs with the expected CWD.
        # Add user defined envars to os.environ so they can be picked up by
        # the child process running the kernel.
        logger.info("Starting iPython kernel with user defined envars: "
                    "{}".format(self.envars))
        for k, v in self.envars.items():
            os.environ[k] = v
        # Ensure the expected paths are in PYTHONPATH of the subprocess so the
        # kernel and Mu-installed third party applications can be found.
        if "PYTHONPATH" not in os.environ:
            paths = sys.path + [MODULE_DIR]
            os.environ["PYTHONPATH"] = os.pathsep.join(paths)
        if MODULE_DIR not in os.environ["PYTHONPATH"]:
            # This is needed on Windows to ensure user installed third party
            # packages are available in the REPL.
            new_path = os.pathsep.join([os.environ["PYTHONPATH"], MODULE_DIR])
            os.environ["PYTHONPATH"] = new_path
        logger.info("REPL PYTHONPATH: {}".format(os.environ["PYTHONPATH"]))
        self.repl_kernel_manager = QtKernelManager()
        self.repl_kernel_manager.start_kernel()
        self.repl_kernel_client = self.repl_kernel_manager.client()
        self.kernel_started.emit(self.repl_kernel_manager,
                                 self.repl_kernel_client)

    def stop_kernel(self):
        """
        Clean up the context, stop the client connections to the kernel, affect
        an immediate shutdown of the kernel and emit a "finished" signal.
        """
        os.environ.clear()
        for k, v in self.default_envars.items():
            os.environ[k] = v
        self.repl_kernel_client.stop_channels()
        self.repl_kernel_manager.shutdown_kernel(now=True)
        self.kernel_finished.emit()
예제 #5
0
    def __init__(self, kernel, *args, **kwargs):
        bg_color = get_emacs_var("eaf-emacs-theme-background-color")
        fg_color = get_emacs_var("eaf-emacs-theme-foreground-color")
        dark_mode = (get_emacs_var("eaf-jupyter-dark-mode") == "force" or \
                     get_emacs_var("eaf-jupyter-dark-mode") == True or \
                     (get_emacs_var("eaf-jupyter-dark-mode") == "follow" and get_emacs_var("eaf-emacs-theme-mode") == "dark"))
        self._init_style(bg_color, fg_color, dark_mode)

        self.scrollbar_visibility = False

        super(EafJupyterWidget, self).__init__(*args, **kwargs)

        kernel_manager = QtKernelManager(kernel_name=kernel)
        kernel_manager.start_kernel()

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

        self.kernel_manager = kernel_manager
        self.kernel_client = kernel_client

        self._control.setStyleSheet("border: none;")
        self._page_control.setStyleSheet("border: none;")

        self._kill_ring = EafKillRing(self._control)
예제 #6
0
파일: repl.py 프로젝트: mrsuman2002/enki-1
    def __init__(self, title, icon):
        DockWidget.__init__(self, core.mainWindow(), title, icon, "Alt+I")
        self.setObjectName(title)

        self.setAllowedAreas(Qt.BottomDockWidgetArea | Qt.LeftDockWidgetArea
                             | Qt.RightDockWidgetArea)

        # Copied from https://github.com/jupyter/qtconsole/blob/master/examples/inprocess_qtconsole.py, then modified based on https://github.com/jupyter/qtconsole/blob/master/qtconsole/qtconsoleapp.py -- the QtInProcessKernelManager is blocking, so infinite loops crash Enki!
        kernel_manager = QtKernelManager()
        kernel_manager.start_kernel()
        kernel_manager.client_factory = QtKernelClient
        kernel_manager.kernel.gui = 'qt'

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

        self.ipython_widget = RichJupyterWidget()
        self.ipython_widget.kernel_manager = kernel_manager
        self.ipython_widget.kernel_client = kernel_client
        # By default, iPython adds a blank line between inputs. Per Monika's request, this eliminates the extra line. See https://qtconsole.readthedocs.io/en/latest/config_options.html#options; this fix was based on info from https://stackoverflow.com/questions/38652671/ipython-5-0-remove-spaces-between-input-lines.
        self.ipython_widget.input_sep = ''
        self.ipython_widget.show()

        self.setWidget(self.ipython_widget)
        self.setFocusProxy(self.ipython_widget)
예제 #7
0
class KernelRunner(QObject):
    """
    Used to control the iPython kernel in a non-blocking manner so the UI
    remains responsive.
    """
    kernel_started = pyqtSignal(QtKernelManager, QtKernelClient)
    kernel_finished = pyqtSignal()

    def __init__(self, cwd):
        """
        Initialise the kernel runner with a target current working directory.
        """
        super().__init__()
        self.cwd = cwd

    def start_kernel(self):
        """
        Start the kernel, obtain a client and emit a signal when both are
        started.
        """
        os.chdir(self.cwd)  # Ensure the kernel runs with the expected CWD.
        self.repl_kernel_manager = QtKernelManager()
        self.repl_kernel_manager.start_kernel()
        self.repl_kernel_client = self.repl_kernel_manager.client()
        self.kernel_started.emit(self.repl_kernel_manager,
                                 self.repl_kernel_client)

    def stop_kernel(self):
        """
        Stop the client connections to the kernel, affect an immediate
        shutdown of the kernel and emit a "finished" signal.
        """
        self.repl_kernel_client.stop_channels()
        self.repl_kernel_manager.shutdown_kernel(now=True)
        self.kernel_finished.emit()
예제 #8
0
 def create_kernel_manager_and_client(self, connection_file=None,
                                      hostname=None, sshkey=None,
                                      password=None):
     """Create kernel manager and client"""
     cf = find_connection_file(connection_file, profile='default')
     kernel_manager = QtKernelManager(connection_file=cf, config=None)
     kernel_client = kernel_manager.client()
     kernel_client.load_connection_file()
     if hostname is not None:
         try:
             newports = self.tunnel_to_kernel(dict(ip=kernel_client.ip,
                                   shell_port=kernel_client.shell_port,
                                   iopub_port=kernel_client.iopub_port,
                                   stdin_port=kernel_client.stdin_port,
                                   hb_port=kernel_client.hb_port),
                                   hostname, sshkey, password)
             (kernel_client.shell_port, kernel_client.iopub_port,
              kernel_client.stdin_port, kernel_client.hb_port) = newports
         except Exception as e:
             print(("Could not open ssh tunnel. The error was:\n\n" + e.message))
             return None, None
     kernel_client.start_channels()
     # To rely on kernel's heartbeat to know when a kernel has died
     kernel_client.hb_channel.unpause()
     return kernel_manager, kernel_client
예제 #9
0
 def _start_kernel():
     km = QtKernelManager(autorestart=False)
     km.start_kernel()
     kc = km.client()
     kc.start_channels()
     kc.execute("%gui qt", silent=True)
     time.sleep(1.5)
     return km, kc
예제 #10
0
class IPythonConsole(idaapi.PluginForm):
    def __init__(self, connection_file, *args):
        super(IPythonConsole, self).__init__(*args)
        self.connection_file = connection_file

    def OnCreate(self, form):
        try:
            if is_using_pyqt5():
                self.parent = self.FormToPyQtWidget(form,
                                                    ctx=sys.modules[__name__])
            else:
                self.parent = self.FormToPySideWidget(
                    form, ctx=sys.modules[__name__])
            layout = self._createConsoleWidget()
            self.parent.setLayout(layout)
        except:
            import traceback
            print(traceback.format_exc())

    def _createConsoleWidget(self):
        if is_using_pyqt5():
            layout = QtWidgets.QVBoxLayout()
        else:
            layout = QtGui.QVBoxLayout()
        connection_file = find_connection_file(self.connection_file)
        self.kernel_manager = QtKernelManager(connection_file=connection_file)
        self.kernel_manager.load_connection_file()
        self.kernel_manager.client_factory = QtKernelClient
        self.kernel_client = self.kernel_manager.client()
        self.kernel_client.start_channels()

        widget_options = {}
        if sys.platform.startswith('linux'):
            # Some upstream bug crashes IDA when the ncurses completion is
            # used. I'm not sure where the bug is exactly (IDA's Qt5 bindings?)
            # but using the "droplist" instead works around the crash. The
            # problem is present only on Linux.
            # See: https://github.com/eset/ipyida/issues/8
            widget_options["gui_completion"] = 'droplist'
        self.ipython_widget = IdaRichJupyterWidget(self.parent,
                                                   **widget_options)
        self.ipython_widget.kernel_manager = self.kernel_manager
        self.ipython_widget.kernel_client = self.kernel_client
        layout.addWidget(self.ipython_widget)

        return layout

    def Show(self, name="IPython Console"):
        return idaapi.PluginForm.Show(self, name)

    def OnClose(self, form):
        try:
            pass
        except:
            import traceback
            print(traceback.format_exc())
예제 #11
0
파일: python3.py 프로젝트: wu6692776/mu
class KernelRunner(QObject):
    """
    Used to control the iPython kernel in a non-blocking manner so the UI
    remains responsive.
    """
    kernel_started = pyqtSignal(QtKernelManager, QtKernelClient)
    kernel_finished = pyqtSignal()
    # Used to build context with user defined envars when running the REPL.
    default_envars = os.environ.copy()

    def __init__(self, cwd, envars):
        """
        Initialise the kernel runner with a target current working directory.
        """
        super().__init__()
        self.cwd = cwd
        self.envars = dict(envars)

    def start_kernel(self):
        """
        Create the expected context, start the kernel, obtain a client and
        emit a signal when both are started.
        """
        logger.info(sys.path)
        os.chdir(self.cwd)  # Ensure the kernel runs with the expected CWD.
        # Add user defined envars to os.environ so they can be picked up by
        # the child process running the kernel.
        logger.info('Starting iPython kernel with user defined envars: '
                    '{}'.format(self.envars))
        for k, v in self.envars.items():
            os.environ[k] = v
        if sys.platform == 'darwin':
            parent_dir = os.path.dirname(__file__)
            if '.app/Contents/Resources/app/mu' in parent_dir:
                # Mu is running as a macOS app bundle. Ensure the expected
                # paths are in PYTHONPATH of the subprocess so the kernel can
                # be found.
                os.environ['PYTHONPATH'] = ':'.join(sys.path)
        self.repl_kernel_manager = QtKernelManager()
        self.repl_kernel_manager.start_kernel()
        self.repl_kernel_client = self.repl_kernel_manager.client()
        self.kernel_started.emit(self.repl_kernel_manager,
                                 self.repl_kernel_client)

    def stop_kernel(self):
        """
        Clean up the context, stop the client connections to the kernel, affect
        an immediate shutdown of the kernel and emit a "finished" signal.
        """
        os.environ.clear()
        for k, v in self.default_envars.items():
            os.environ[k] = v
        self.repl_kernel_client.stop_channels()
        self.repl_kernel_manager.shutdown_kernel(now=True)
        self.kernel_finished.emit()
예제 #12
0
class IPythonConsole(idaapi.PluginForm):
    
    def __init__(self, connection_file, *args):
        super(IPythonConsole, self).__init__(*args)
        self.connection_file = connection_file
    
    def OnCreate(self, form):
        try:
            if is_using_pyqt5():
                self.parent = self.FormToPyQtWidget(form, ctx=sys.modules[__name__])
            else:
                self.parent = self.FormToPySideWidget(form, ctx=sys.modules[__name__])
            layout = self._createConsoleWidget()
            self.parent.setLayout(layout)
        except:
            import traceback
            print(traceback.format_exc())

    def _createConsoleWidget(self):
        if is_using_pyqt5():
            layout = QtWidgets.QVBoxLayout()
        else:
            layout = QtGui.QVBoxLayout()
        connection_file = find_connection_file(self.connection_file)
        self.kernel_manager = QtKernelManager(connection_file=connection_file)
        self.kernel_manager.load_connection_file()
        self.kernel_manager.client_factory = QtKernelClient
        self.kernel_client = self.kernel_manager.client()
        self.kernel_client.start_channels()

        widget_options = {}
        if sys.platform.startswith('linux'):
            # Some upstream bug crashes IDA when the ncurses completion is
            # used. I'm not sure where the bug is exactly (IDA's Qt5 bindings?)
            # but using the "droplist" instead works around the crash. The
            # problem is present only on Linux.
            # See: https://github.com/eset/ipyida/issues/8
            widget_options["gui_completion"] = 'droplist'
        self.ipython_widget = IdaRichJupyterWidget(self.parent, **widget_options)
        self.ipython_widget.kernel_manager = self.kernel_manager
        self.ipython_widget.kernel_client = self.kernel_client
        layout.addWidget(self.ipython_widget)

        return layout

    def Show(self, name="IPython Console"):
        return idaapi.PluginForm.Show(self, name)

    def OnClose(self, form):
        try:
            pass
        except:
            import traceback
            print(traceback.format_exc())
예제 #13
0
def make_jupyter_widget_with_kernel():
    """Start a kernel, connect to it, and create a RichJupyterWidget to use it
    """
    kernel_manager = QtKernelManager(kernel_name=USE_KERNEL)
    kernel_manager.start_kernel()

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

    jupyter_widget = RichJupyterWidget()
    jupyter_widget.kernel_manager = kernel_manager
    jupyter_widget.kernel_client = kernel_client
    return jupyter_widget
예제 #14
0
파일: main.py 프로젝트: LiorL090/BambaCharm
    def make_jupyter_widget_with_kernel(self):
        """Start a kernel, connect to it, and create a RichJupyterWidget to use it
        """
        USE_KERNEL = 'python3'
        kernel_manager = QtKernelManager(kernel_name=USE_KERNEL)
        kernel_manager.start_kernel()

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

        jupyter_widget = RichJupyterWidget()
        jupyter_widget.kernel_manager = kernel_manager
        jupyter_widget.kernel_client = kernel_client
        jupyter_widget._display_banner = False
        return jupyter_widget
예제 #15
0
파일: jupyter.py 프로젝트: GliaHQ/Glia
    def start_kernel(self, kernel: str):
        kernel_manager = QtKernelManager(kernel_name=kernel)
        kernel_manager.start_kernel()

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

        jupyter_widget = RichJupyterWidget()

        jupyter_widget.style_sheet = get_theme_contents(
            "dracula", "jupyter.css")
        jupyter_widget.syntax_style = "dracula"
        jupyter_widget.kernel_manager = kernel_manager
        jupyter_widget.kernel_client = kernel_client
        return jupyter_widget  # Binding this to a variable won't work.
예제 #16
0
def independent_qtconsole():

    kernel_manager = QtKernelManager()
    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()

    return ipython_widget
예제 #17
0
파일: pyomo_viewer.py 프로젝트: Pyomo/pyomo
 def __init__(self):
     super().__init__()
     km = QtKernelManager(autorestart=False)
     km.start_kernel()
     kc = km.client()
     kc.start_channels()
     self.jupyter_widget = RichJupyterWidget()
     self.jupyter_widget.kernel_manager = km
     self.jupyter_widget.kernel_client = kc
     self.setCentralWidget(self.jupyter_widget)
     kc.execute("%gui qt", silent=True)
     time.sleep(3) # I need something better here, but I need to make sure
                   # the QApplication in the kernel has started before
                   # attempting to start the UI or it won't start
     kc.execute(
         "from pyomo.contrib.viewer.ui import get_mainwindow", silent=True)
     kc.execute("import pyomo.environ as pyo", silent=True)
     kc.execute("ui, model = get_mainwindow()", silent=True)
예제 #18
0
    def run(self):
        self.mutex.lock()
        kernel_manager = QtKernelManager(kernel_name="""python3""")
        kernel_manager.start_kernel()

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

        # notify to update ui
        self.initialized.emit(kernel_manager, kernel_client)

        # wait for exit
        self.wait_condition.wait(self.mutex)
        self.mutex.unlock()

        # stop channels and kernel
        kernel_client.stop_channels()
        kernel_manager.shutdown_kernel()
예제 #19
0
 def __init__(self):
     super().__init__()
     km = QtKernelManager(autorestart=False)
     km.start_kernel()
     kc = km.client()
     kc.start_channels()
     self.jupyter_widget = RichJupyterWidget()
     self.jupyter_widget.kernel_manager = km
     self.jupyter_widget.kernel_client = kc
     self.setCentralWidget(self.jupyter_widget)
     kc.execute("%gui qt", silent=True)
     time.sleep(3)  # I need something better here, but I need to make sure
     # the QApplication in the kernel has started before
     # attempting to start the UI or it won't start
     kc.execute("from pyomo.contrib.viewer.ui import get_mainwindow",
                silent=True)
     kc.execute("import pyomo.environ as pyo", silent=True)
     kc.execute("ui, model = get_mainwindow()", silent=True)
예제 #20
0
    def _start_kernel():
        km = QtKernelManager(autorestart=False)
        km.start_kernel()
        kc = km.client()
        kc.start_channels()
        kc.execute("%gui qt", silent=True)
        # make sure there is no possible way the user can start the model
        # viewer before the Qt Application in the kernel finishes starting
        time.sleep(1.0)
        # Now just do the standard imports of things you want to be available
        # and whatever we may want to do to set up the environment just create
        # an empty model, so you can start the model viewer right away.  You
        # can add to the model if you want to use it, or create a new one.
        kc.execute("""
from pyomo.contrib.viewer.ui import get_mainwindow
import pyomo.environ as pyo
model = pyo.ConcreteModel("Default Model")""", silent=True)
        return km, kc
예제 #21
0
파일: python3.py 프로젝트: procount/mu
class KernelRunner(QObject):
    """
    Used to control the iPython kernel in a non-blocking manner so the UI
    remains responsive.
    """
    kernel_started = pyqtSignal(QtKernelManager, QtKernelClient)
    kernel_finished = pyqtSignal()

    def start_kernel(self):
        self.repl_kernel_manager = QtKernelManager()
        self.repl_kernel_manager.start_kernel()
        self.repl_kernel_client = self.repl_kernel_manager.client()
        self.kernel_started.emit(self.repl_kernel_manager,
                                 self.repl_kernel_client)

    def stop_kernel(self):
        self.repl_kernel_client.stop_channels()
        self.repl_kernel_manager.shutdown_kernel(now=True)
        self.kernel_finished.emit()
예제 #22
0
def _make_jupyter_widget_with_kernel(kernel_name):
    """
    Start a kernel, connect to it, and create a RichJupyterWidget to use it.

    Parameters
    ----------
    kernel_name : str
        Kernel name to use.
    """
    kernel_manager = QtKernelManager(kernel_name=kernel_name)
    kernel_manager.start_kernel()

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

    jupyter_widget = RichJupyterWidget()
    jupyter_widget.kernel_manager = kernel_manager
    jupyter_widget.kernel_client = kernel_client
    return jupyter_widget
예제 #23
0
    def run(self):
        self.mutex.lock()
        kernel_manager = QtKernelManager(kernel_name='python3')
        kernel_manager.start_kernel()

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

        # notify to update ui
        self.initialized.emit(kernel_manager, kernel_client)

        # wait for exit
        self.wait_condition.wait(self.mutex)
        self.mutex.unlock()

        # stop channels and kernel
        kernel_client.stop_channels()
        kernel_manager.shutdown_kernel(
            now=True)  # add now=True; Fix exit error;  200924 liugang
예제 #24
0
    def __init__(self, parent=None, custom_banner=None, **kwargs):
        super(QIPythonWidget_embed, self).__init__(parent=parent, **kwargs)

        self.plugin = parent

        kernel_manager = QtKernelManager(kernel_name=USE_KERNEL)
        kernel_manager.start_kernel()

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

        self.jupyter_widget = RichJupyterWidget()
        self.jupyter_widget.kernel_manager = kernel_manager
        self.jupyter_widget.kernel_client = kernel_client

        if custom_banner is not None:
            self.jupyter_widget.banner = custom_banner

        layout = QHBoxLayout()
        layout.addWidget(self.jupyter_widget)
    def start_kernel(self, k_name, k_path):
        """Starts a kernel manager and kernel client and attaches the client to Julia or Python Console.

        Args:
            k_name (str): Kernel name
            k_path (str): Directory where the the kernel specs are located
        """
        if self.kernel_manager and self.kernel_name != k_name:
            old_k_name_anchor = "<a style='color:#99CCFF;' title='{0}' href='#'>{1}</a>".format(
                k_path, self.kernel_name)
            self._toolbox.msg.emit(
                f"Kernel changed in Settings. Shutting down current kernel {old_k_name_anchor}."
            )
            self.shutdown_kernel()
        self.kernel_name = k_name
        new_k_name_anchor = "<a style='color:#99CCFF;' title='{0}' href='#'>{1}</a>".format(
            k_path, self.kernel_name)
        self._toolbox.msg.emit(
            f"*** Starting {self._name} (kernel {new_k_name_anchor}) ***")
        self._kernel_starting = True  # This flag is unset when a correct msg is received from iopub_channel
        km = QtKernelManager(kernel_name=self.kernel_name)
        try:
            blackhole = open(os.devnull, 'w')
            km.start_kernel(stdout=blackhole, stderr=blackhole)
            kc = km.client()
            kc.hb_channel.time_to_dead = JUPYTER_KERNEL_TIME_TO_DEAD
            kc.start_channels()
            self.kernel_manager = km
            self.kernel_client = kc
            return
        except FileNotFoundError:
            self._toolbox.msg_error.emit(
                f"Couldn't find the executable specified by kernel {self.kernel_name}"
            )
            self._kernel_starting = False
            return
        except NoSuchKernel:  # kernelspecs missing (probably happens when kernel.json file does not exist
            self._toolbox.msg_error.emit(
                f"Couldn't find kernel specs for kernel {self.kernel_name}")
            self._kernel_starting = False
            return
예제 #26
0
    def __init__(self, parent, customBanner=None, *args, **kwargs):
        super(QIPythonWidget, self).__init__(parent)

        self.plugin = parent

        if customBanner is not None:
            self.banner = customBanner

        kernel_manager = QtKernelManager(kernel_name=USE_KERNEL)
        kernel_manager.start_kernel()

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

        jupyter_widget = RichJupyterWidget()
        jupyter_widget.kernel_manager = kernel_manager
        jupyter_widget.kernel_client = kernel_client

        layout = QVBoxLayout()
        layout.addWidget(jupyter_widget)

        self.setLayout(layout)
예제 #27
0
파일: python3.py 프로젝트: lordmauve/mu
class KernelRunner(QObject):
    """
    Used to control the iPython kernel in a non-blocking manner so the UI
    remains responsive.
    """
    kernel_started = pyqtSignal(QtKernelManager, QtKernelClient)
    kernel_finished = pyqtSignal()

    def __init__(self, cwd):
        """
        Initialise the kernel runner with a target current working directory.
        """
        super().__init__()
        self.cwd = cwd

    def start_kernel(self):
        """
        Start the kernel, obtain a client and emit a signal when both are
        started.
        """
        logger.info(sys.path)
        os.chdir(self.cwd)  # Ensure the kernel runs with the expected CWD.
        self.repl_kernel_manager = QtKernelManager()
        self.repl_kernel_manager.start_kernel()
        self.repl_kernel_client = self.repl_kernel_manager.client()
        self.kernel_started.emit(self.repl_kernel_manager,
                                 self.repl_kernel_client)

    def stop_kernel(self):
        """
        Stop the client connections to the kernel, affect an immediate
        shutdown of the kernel and emit a "finished" signal.
        """
        self.repl_kernel_client.stop_channels()
        self.repl_kernel_manager.shutdown_kernel(now=True)
        self.kernel_finished.emit()
예제 #28
0
 def __init__(self, parent=None):
     super().__init__(parent=parent)
     # Setup widget
     self.kernel = RichJupyterWidget()
     self.setLayout(QHBoxLayout())
     self.layout().setContentsMargins(0, 0, 0, 0)
     self.layout().addWidget(self.kernel)
     # Create a Kernel
     logger.debug("Starting Jupyter Kernel ...")
     kernel_manager = QtKernelManager(kernel_name='python3')
     kernel_manager.start_kernel()
     kernel_client = kernel_manager.client()
     kernel_client.start_channels()
     self.kernel.kernel_manager = kernel_manager
     self.kernel.kernel_client = kernel_client
     # Ensure we shutdown the kernel
     app = QApplication.instance()
     app.aboutToQuit.connect(self.shutdown)
     # Styling
     self.kernel.syntax_style = 'monokai'
     self.kernel.set_default_style(colors='Linux')
     # Ensure cleanup
     app = QApplication.instance()
     app.aboutToQuit.connect(self.shutdown)
예제 #29
0
파일: repl.py 프로젝트: bjones1/enki
    def __init__(self, title, icon):
        DockWidget.__init__(self, core.mainWindow(), title, icon, "Alt+I")
        self.setObjectName(title)

        self.setAllowedAreas(Qt.BottomDockWidgetArea | Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea)

        # Copied from https://github.com/jupyter/qtconsole/blob/master/examples/inprocess_qtconsole.py, then modified based on https://github.com/jupyter/qtconsole/blob/master/qtconsole/qtconsoleapp.py -- the QtInProcessKernelManager is blocking, so infinite loops crash Enki!
        kernel_manager = QtKernelManager()
        kernel_manager.start_kernel()
        kernel_manager.client_factory = QtKernelClient
        kernel_manager.kernel.gui = 'qt'

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

        self.ipython_widget = RichJupyterWidget()
        self.ipython_widget.kernel_manager = kernel_manager
        self.ipython_widget.kernel_client = kernel_client
        # By default, iPython adds a blank line between inputs. Per Monika's request, this eliminates the extra line. See https://qtconsole.readthedocs.io/en/latest/config_options.html#options; this fix was based on info from https://stackoverflow.com/questions/38652671/ipython-5-0-remove-spaces-between-input-lines.
        self.ipython_widget.input_sep = ''
        self.ipython_widget.show()

        self.setWidget(self.ipython_widget)
        self.setFocusProxy(self.ipython_widget)
class Tests(unittest.TestCase):

    def setUp(self):
        """Open a kernel."""
        self.kernel_manager = QtKernelManager()
        self.kernel_manager.start_kernel()
        self.kernel_client = self.kernel_manager.client()
        self.kernel_client.start_channels(shell=True, iopub=True)
        self.blocking_client = self.kernel_client.blocking_client()
        self.blocking_client.start_channels(shell=True, iopub=True)
        self.comm_manager = self.kernel_client.comm_manager

        # Check if client is working
        self.blocking_client.execute('print(0)')
        try:
            self._get_next_msg()
            self._get_next_msg()
        except TimeoutError:
            # Maybe it works now?
            self.blocking_client.execute('print(0)')
            self._get_next_msg()
            self._get_next_msg()


    def tearDown(self):
        """Close the kernel."""
        if self.kernel_manager:
            self.kernel_manager.shutdown_kernel(now=True)
        if self.kernel_client:
            self.kernel_client.shutdown()

    def _get_next_msg(self, timeout=10):
        # Get status messages
        timeout_time = time.time() + timeout
        msg_type = 'status'
        while msg_type == 'status':
            if timeout_time < time.time():
                raise TimeoutError
            try:
                msg = self.blocking_client.get_iopub_msg(timeout=3)
                msg_type = msg['header']['msg_type']
            except Empty:
                pass
        return msg
    
    def test_kernel_to_frontend(self):
        """Communicate from the kernel to the frontend."""
        comm_manager = self.comm_manager
        blocking_client = self.blocking_client

        class DummyCommHandler():
            def __init__(self):
                comm_manager.register_target('test_api', self.comm_open)
                self.last_msg = None
        
            def comm_open(self, comm, msg):
                comm.on_msg(self.comm_message)
                comm.on_close(self.comm_message)
                self.last_msg = msg['content']['data']
                self.comm = comm
        
            def comm_message(self, msg):
                self.last_msg = msg['content']['data']
        
        handler = DummyCommHandler()
        blocking_client.execute(
        "from ipykernel.comm import Comm\n"
        "comm = Comm(target_name='test_api', data='open')\n"
        "comm.send('message')\n"
        "comm.close('close')\n"
        "del comm\n"
        "print('Done')\n"
        )
        # Get input
        msg = self._get_next_msg()
        assert msg['header']['msg_type'] == 'execute_input'
        # Open comm
        msg = self._get_next_msg()
        assert msg['header']['msg_type'] == 'comm_open'
        comm_manager._dispatch(msg)
        assert handler.last_msg == 'open'
        assert handler.comm.comm_id == msg['content']['comm_id']
        # Get message
        msg = self._get_next_msg()
        assert msg['header']['msg_type'] == 'comm_msg'
        comm_manager._dispatch(msg)
        assert handler.last_msg == 'message'
        assert handler.comm.comm_id == msg['content']['comm_id']
        # Get close
        msg = self._get_next_msg()
        assert msg['header']['msg_type'] == 'comm_close'
        comm_manager._dispatch(msg)
        assert handler.last_msg == 'close'
        assert handler.comm.comm_id == msg['content']['comm_id']
        # Get close
        msg = self._get_next_msg()
        assert msg['header']['msg_type'] == 'stream'

    def test_frontend_to_kernel(self):
        """Communicate from the frontend to the kernel."""
        comm_manager = self.comm_manager
        blocking_client = self.blocking_client
        blocking_client.execute(
            "class DummyCommHandler():\n"
            "    def __init__(self):\n"
            "        get_ipython().kernel.comm_manager.register_target(\n"
            "            'test_api', self.comm_open)\n"
            "    def comm_open(self, comm, msg):\n"
            "        comm.on_msg(self.comm_message)\n"
            "        comm.on_close(self.comm_message)\n"
            "        print(msg['content']['data'])\n"
            "    def comm_message(self, msg):\n"
            "        print(msg['content']['data'])\n"
            "dummy = DummyCommHandler()\n"
        )
        # Get input
        msg = self._get_next_msg()
        assert msg['header']['msg_type'] == 'execute_input'
        # Open comm
        comm = comm_manager.new_comm('test_api', data='open')
        msg = self._get_next_msg()
        assert msg['header']['msg_type'] == 'stream'
        assert msg['content']['text'] == 'open\n'
        # Get message
        comm.send('message')
        msg = self._get_next_msg()
        assert msg['header']['msg_type'] == 'stream'
        assert msg['content']['text'] == 'message\n'
        # Get close
        comm.close('close')
        msg = self._get_next_msg()

        # Received message has a header and parent header. The parent header has
        # the info about the close message type in Python 3
        assert msg['parent_header']['msg_type'] == 'comm_close'
        assert msg['msg_type'] == 'stream'
        assert msg['content']['text'] == 'close\n'
예제 #31
0
class IPythonConsole(cutter.CutterDockWidget):
    def __init__(self, connection_file, *args):
        print("[10] inside IPythonConsole init")
        super(IPythonConsole, self).__init__(*args)
        self.connection_file = connection_file

    def create(self):
        print("[11] inside IPythonConsole create")
        try:
            layout = self._createConsoleWidget()
            self.parent().setLayout(layout)
        except:
            import traceback
            print(traceback.format_exc())

    def _createConsoleWidget(self):
        print("[12] inside IPythonConsole _createConsoleWidget")
        layout = QtWidgets.QVBoxLayout()

        connection_file = find_connection_file(self.connection_file)
        self.kernel_manager = QtKernelManager(connection_file=connection_file)
        self.kernel_manager.load_connection_file()
        self.kernel_manager.client_factory = QtKernelClient
        self.kernel_client = self.kernel_manager.client()
        self.kernel_client.start_channels()

        widget_options = {}
        if sys.platform.startswith('linux'):
            # Some upstream bug crashes IDA when the ncurses completion is
            # used. I'm not sure where the bug is exactly (IDA's Qt5 bindings?)
            # but using the "droplist" instead works around the crash. The
            # problem is present only on Linux.
            # See: https://github.com/eset/ipyida/issues/8
            widget_options["gui_completion"] = 'droplist'
        widget_options.update(_user_widget_options)
        print(
            "[13] inside IPythonConsole before creating CutterRichJupyterWidget"
        )

        class fake_font():
            def pointSize(self):
                return 16

        QtWidgets.QApplication.instance().font = fake_font

        self.ipython_widget = CutterRichJupyterWidget(self.parent,
                                                      **widget_options)
        print(
            "[15] inside IPythonConsole after creating CutterRichJupyterWidget"
        )

        self.ipython_widget.kernel_manager = self.kernel_manager
        self.ipython_widget.kernel_client = self.kernel_client
        self.ipython_widget.setWindowTitle("iPython Widget")
        layout.addWidget(self.ipython_widget)

        return layout

    def setFocusToPrompt(self):
        # This relies on the internal _control widget but it's the most reliable
        # way I found so far.
        if hasattr(self.ipython_widget, "_control"):
            self.ipython_widget._control.setFocus()
        else:
            print(
                "[IPyIDA] setFocusToPrompt: Widget has no _control attribute.")

    def close(self, form):
        try:
            pass
        except:
            import traceback
            print(traceback.format_exc())