Exemplo n.º 1
0
def connected_console(console_class=RichJupyterWidget, **kwargs):
    """
    Create a console widget, connected to another kernel running in the current
    process.

    This is used for instance if glue has been started from IPython.

    Keyword arguments will be added to the namespace of the shell.

    Parameters
    ----------
    console_class : `type`
        The class of the console widget to create
    """

    shell = get_ipython()

    if shell is None:
        raise RuntimeError("There is no IPython kernel in this process")

    client = QtKernelClient(connection_file=get_connection_file())
    client.load_connection_file()
    client.start_channels()

    control = console_class()
    control.kernel_client = client
    control.shell = shell
    control.shell.user_ns.update(**kwargs)

    return control
Exemplo n.º 2
0
def create_kernel_client(km):
    kid = km.start_kernel()
    kernel = km.get_kernel(kid)

    msg = 'Started new kernel {} (connection file {}, session key {})'
    logger.info(msg.format(kid, kernel.connection_file, kernel.session.key))

    # This is probably not the most optimal way to share connection data...
    with open(kernel.connection_file) as fp:
        connection = json.load(fp)
    logger.debug('Connection data:\n{}'.format(pprint.pformat(connection)))

    client = QtKernelClient(**connection)
    client.session.key = kernel.session.key
    client.start_channels()

    return client
Exemplo n.º 3
0
def connected_console(console_class=RichJupyterWidget, **kwargs):
    """
    Create a console widget, connected to another kernel running in the current
    process.

    This is used for instance if glue has been started from IPython.

    Keyword arguments will be added to the namespace of the shell.

    Parameters
    ----------
    console_class : `type`
        The class of the console widget to create
    """

    shell = get_ipython()

    if shell is None:
        raise RuntimeError("There is no IPython kernel in this process")

    client = QtKernelClient(connection_file=get_connection_file())
    client.load_connection_file()
    client.start_channels()

    control = console_class()
    control.kernel_client = client
    control.shell = shell
    control.shell.user_ns.update(**kwargs)

    return control
Exemplo n.º 4
0
    def __init__(self, customBanner=None, *args, **kwargs):
        super().__init__(*args, **kwargs)

        if customBanner is not None:
            self.banner = customBanner

        self.font_size = 6
        #        self.kernel_manager = kernel_manager = QtInProcessKernelManager()
        #        kernel_manager.start_kernel(show_banner=False)
        #        kernel_manager.kernel.gui = 'qt'
        #        self.kernel_client = kernel_client = self._kernel_manager.client()
        #        filename = "/tmp/connfile.json"
        filename = "/tmp/connfile"
        kernel_client = QtKernelClient(connection_file=filename)
        kernel_client.load_connection_file()
        kernel_client.start_channels()
        self.kernel_client = kernel_client

        def stop():
            kernel_client.shutdown()
            kernel_client.stop_channels()
#            kernel_manager.shutdown_kernel()
#QApplication.instance().exit()

        self.exit_requested.connect(stop)
Exemplo n.º 5
0
def connected_console(console_class=RichIPythonWidget, **kwargs):
    """Create a console widget, connected to another kernel running in
       the current process

    This only works on IPython v1.0 and above

    Parameters:
        console_class : The class of the console widget to create
        kwargs : Extra variables to put into the namespace
    """
    shell = get_ipython()
    if shell is None:
        raise RuntimeError("There is no IPython kernel in this process")

    client = QtKernelClient(connection_file=get_connection_file())
    client.load_connection_file()
    client.start_channels()

    control = console_class()
    control.kernel_client = client
    control.shell = shell
    control.shell.user_ns.update(**kwargs)
    return control
Exemplo n.º 6
0
    def _run_embedded_qtconsole(conn_filename):
        # This is launched as a new process.
        #
        # Wait max. ten seconds for the IPython kernel to be up and running,
        # which is done by checking for presence of the connection file
        # containing the kernels Zero Message Queue sockets and credentials.
        #
        # Then, start a new QApplication running the Jupyter Console client
        # widget connected to the kernel via the connection file.
        #
        for i in range(100):
            try:
                st = os.stat(conn_filename)
            except OSError as e:
                if e.errno != errno.ENOENT:
                    # No such file exception is ignored, all others re-raised
                    raise
            else:
                if st.st_size > 0:
                    # OK, connection file found, kernel seems to be running
                    break
            time.sleep(0.1)

        app = QtGui.QApplication(["Plot Workbench Console"])

        kernel_client = QtKernelClient(connection_file=conn_filename)
        kernel_client.load_connection_file()
        kernel_client.start_channels()

        def exit():
            kernel_client.shutdown()
            kernel_client.stop_channels()
            app.exit()

        ipython_widget = RichJupyterWidget()
        ipython_widget.kernel_client = kernel_client
        ipython_widget.exit_requested.connect(exit)
        ipython_widget.show()

        app.exec_()
Exemplo n.º 7
0
def connected_console(console_class=RichIPythonWidget, **kwargs):
    """Create a console widget, connected to another kernel running in
       the current process

    This only works on IPython v1.0 and above

    Parameters
    ----------
    console_class : The class of the console widget to create
    kwargs : Extra variables to put into the namespace
    """
    shell = get_ipython()
    if shell is None:
        raise RuntimeError("There is no IPython kernel in this process")

    client = QtKernelClient(connection_file=get_connection_file())
    client.load_connection_file()
    client.start_channels()

    control = console_class()
    control.kernel_client = client
    control.shell = shell
    control.shell.user_ns.update(**kwargs)
    return control
Exemplo n.º 8
0
    def _create_client_for_kernel(self, connection_file, hostname, sshkey,
                                  password):
        ipycon = self.ipyconsole

        # Verifying if the connection file exists
        try:
            cf_path = osp.dirname(connection_file)
            cf_filename = osp.basename(connection_file)
            # To change a possible empty string to None
            cf_path = cf_path if cf_path else None
            connection_file = find_connection_file(filename=cf_filename,
                                                   path=cf_path)
        except (IOError, UnboundLocalError):
            QMessageBox.critical(
                self, _('IPython'),
                _("Unable to connect to "
                  "<b>%s</b>") % connection_file)
            return

        # Getting the master id that corresponds to the client
        # (i.e. the i in i/A)
        master_id = None
        given_name = None
        external_kernel = False
        slave_ord = ord('A') - 1
        kernel_manager = None

        for cl in ipycon.get_clients():
            if connection_file in cl.connection_file:
                if cl.get_kernel() is not None:
                    kernel_manager = cl.get_kernel()
                connection_file = cl.connection_file
                if master_id is None:
                    master_id = cl.id_['int_id']
                given_name = cl.given_name
                new_slave_ord = ord(cl.id_['str_id'])
                if new_slave_ord > slave_ord:
                    slave_ord = new_slave_ord

        # If we couldn't find a client with the same connection file,
        # it means this is a new master client
        if master_id is None:
            ipycon.master_clients += 1
            master_id = to_text_string(ipycon.master_clients)
            external_kernel = True

        # Set full client name
        client_id = dict(int_id=master_id, str_id=chr(slave_ord + 1))

        # Creating the client
        show_elapsed_time = ipycon.get_option('show_elapsed_time')
        reset_warning = ipycon.get_option('show_reset_namespace_warning')
        ask_before_restart = ipycon.get_option('ask_before_restart')
        client = MxClientWidget(
            ipycon,
            id_=client_id,
            given_name=given_name,
            history_filename=get_conf_path('history.py'),
            config_options=ipycon.config_options(),
            additional_options=ipycon.additional_options(),
            interpreter_versions=ipycon.interpreter_versions(),
            connection_file=connection_file,
            menu_actions=self.menu_actions,
            hostname=hostname,
            external_kernel=external_kernel,
            slave=True,
            show_elapsed_time=show_elapsed_time,
            reset_warning=reset_warning,
            ask_before_restart=ask_before_restart,
            css_path=ipycon.css_path)

        # Change stderr_dir if requested
        if ipycon.test_dir is not None:
            client.stderr_dir = ipycon.test_dir

        # Create kernel client
        kernel_client = QtKernelClient(connection_file=connection_file)

        # This is needed for issue spyder-ide/spyder#9304.
        try:
            kernel_client.load_connection_file()
        except Exception as e:
            QMessageBox.critical(
                self, _('Connection error'),
                _("An error occurred while trying to load "
                  "the kernel connection file. The error "
                  "was:\n\n") + to_text_string(e))
            return

        if hostname is not None:
            try:
                connection_info = 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)
                newports = ipycon.tunnel_to_kernel(connection_info, hostname,
                                                   sshkey, password)
                (kernel_client.shell_port, kernel_client.iopub_port,
                 kernel_client.stdin_port, kernel_client.hb_port) = newports
                # Save parameters to connect comm later
                kernel_client.ssh_parameters = (hostname, sshkey, password)
            except Exception as e:
                QMessageBox.critical(
                    self, _('Connection error'),
                    _("Could not open ssh tunnel. The "
                      "error was:\n\n") + to_text_string(e))
                return

        # Assign kernel manager and client to shellwidget
        kernel_client.start_channels()
        shellwidget = client.shellwidget
        shellwidget.set_kernel_client_and_manager(kernel_client,
                                                  kernel_manager)
        shellwidget.sig_exception_occurred.connect(
            self.main.console.sig_exception_occurred)
        if external_kernel:
            shellwidget.sig_is_spykernel.connect(self.connect_external_kernel)
            shellwidget.check_spyder_kernel()

        # Set elapsed time, if possible
        if not external_kernel:
            ipycon.set_elapsed_time(client)

        # Adding a new tab for the client
        ipycon.add_tab(client, name=client.get_name())

        # Register client
        ipycon.register_client(client)
Exemplo n.º 9
0
    def __init__(self, user_variables=None):
        super().__init__()

        # get current running instance or create new instance
        shell = get_ipython()

        if shell is None:
            # If there is no currently running instance create an in-process
            # kernel.
            kernel_manager = QtInProcessKernelManager()
            kernel_manager.start_kernel(show_banner=False)
            kernel_manager.kernel.gui = 'qt'

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

            self.kernel_manager = kernel_manager
            self.kernel_client = kernel_client
            self.shell = kernel_manager.kernel.shell
            self.push = self.shell.push
        elif type(shell) == InProcessInteractiveShell:
            # If there is an existing running InProcessInteractiveShell
            # it is likely because multiple viewers have been launched from
            # the same process. In that case create a new kernel.
            # Connect existing kernel
            kernel_manager = QtInProcessKernelManager(kernel=shell.kernel)
            kernel_client = kernel_manager.client()

            self.kernel_manager = kernel_manager
            self.kernel_client = kernel_client
            self.shell = kernel_manager.kernel.shell
            self.push = self.shell.push
        elif isinstance(shell, TerminalInteractiveShell):
            # if launching from an ipython terminal then adding a console is
            # not supported. Instead users should use the ipython terminal for
            # the same functionality.
            self.kernel_client = None
            self.kernel_manager = None
            self.shell = None
            self.push = lambda var: None

        elif isinstance(shell, ZMQInteractiveShell):
            # if launching from jupyter notebook, connect to the existing
            # kernel
            kernel_client = QtKernelClient(
                connection_file=get_connection_file())
            kernel_client.load_connection_file()
            kernel_client.start_channels()

            self.kernel_manager = None
            self.kernel_client = kernel_client
            self.shell = shell
            self.push = self.shell.push
        else:
            raise ValueError('ipython shell not recognized; '
                             f'got {type(shell)}')
        # Add any user variables
        user_variables = user_variables or {}
        self.push(user_variables)

        self.enable_calltips = False
Exemplo n.º 10
0
    def _create_client_for_kernel(self, connection_file, hostname, sshkey,
                                  password):
        ipycon = self.ipyconsole

        # Verifying if the connection file exists
        try:
            cf_path = osp.dirname(connection_file)
            cf_filename = osp.basename(connection_file)
            # To change a possible empty string to None
            cf_path = cf_path if cf_path else None
            connection_file = find_connection_file(filename=cf_filename,
                                                   path=cf_path)
            if osp.splitext(connection_file)[1] != ".json":
                # There might be a file with the same id in the path.
                connection_file = find_connection_file(
                    filename=cf_filename + ".json", path=cf_path)
        except (IOError, UnboundLocalError):
            QMessageBox.critical(self, _('IPython'),
                                 _("Unable to connect to "
                                   "<b>%s</b>") % connection_file)
            return

        # Getting the master id that corresponds to the client
        # (i.e. the i in i/A)
        master_id = None
        given_name = None
        is_external_kernel = True
        known_spyder_kernel = False
        slave_ord = ord('A') - 1
        kernel_manager = None

        for cl in ipycon.clients:
            if connection_file in cl.connection_file:
                if cl.get_kernel() is not None:
                    kernel_manager = cl.get_kernel()
                connection_file = cl.connection_file
                if master_id is None:
                    master_id = cl.id_['int_id']
                    is_external_kernel = cl.shellwidget.is_external_kernel
                    known_spyder_kernel = cl.shellwidget.is_spyder_kernel
                given_name = cl.given_name
                new_slave_ord = ord(cl.id_['str_id'])
                if new_slave_ord > slave_ord:
                    slave_ord = new_slave_ord

        # If we couldn't find a client with the same connection file,
        # it means this is a new master client
        if master_id is None:
            ipycon.master_clients += 1
            master_id = str(ipycon.master_clients)

        # Set full client name
        client_id = dict(int_id=master_id,
                         str_id=chr(slave_ord + 1))

        # Creating the client
        show_elapsed_time = ipycon.get_conf('show_elapsed_time')
        reset_warning = ipycon.get_conf('show_reset_namespace_warning')
        ask_before_restart = ipycon.get_conf('ask_before_restart')
        client_args = {
            'ask_before_closing': ipycon.get_conf('ask_before_closing'),
            'std_dir': ipycon._test_dir if ipycon._test_dir else None,
            'is_external_kernel': is_external_kernel,
            'is_spyder_kernel': known_spyder_kernel,
            'handlers': ipycon.registered_spyder_kernel_handlers,
            'configuration': ipycon.CONFIGURATION
        }

        client = MxClientWidget(ipycon,
                              id_=client_id,
                              given_name=given_name,
                              history_filename=get_conf_path('history.py'),
                              config_options=ipycon.config_options(),
                              additional_options=ipycon.additional_options(),
                              interpreter_versions=ipycon.interpreter_versions(),
                              connection_file=connection_file,
                              # menu_actions=menu_actions,
                              hostname=hostname,
                              # slave=True,
                              show_elapsed_time=show_elapsed_time,
                              reset_warning=reset_warning,
                              ask_before_restart=ask_before_restart,
                              css_path=ipycon.css_path,
                              **client_args)

        # Create kernel client
        kernel_client = QtKernelClient(connection_file=connection_file)

        # This is needed for issue spyder-ide/spyder#9304.
        try:
            kernel_client.load_connection_file()
        except Exception as e:
            QMessageBox.critical(self, _('Connection error'),
                                 _("An error occurred while trying to load "
                                   "the kernel connection file. The error "
                                   "was:\n\n") + str(e))
            return

        if hostname is not None:
            try:
                connection_info = 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)
                newports = ipycon.tunnel_to_kernel(connection_info, hostname,
                                                 sshkey, password)
                (kernel_client.shell_port,
                 kernel_client.iopub_port,
                 kernel_client.stdin_port,
                 kernel_client.hb_port) = newports
                # Save parameters to connect comm later
                kernel_client.ssh_parameters = (hostname, sshkey, password)
            except Exception as e:
                QMessageBox.critical(self, _('Connection error'),
                                   _("Could not open ssh tunnel. The "
                                     "error was:\n\n") + str(e))
                return

        # Assign kernel manager and client to shellwidget
        kernel_client.start_channels()
        shellwidget = client.shellwidget
        shellwidget.set_kernel_client_and_manager(
            kernel_client, kernel_manager)
        shellwidget.sig_exception_occurred.connect(
            ipycon.sig_exception_occurred)

        if not known_spyder_kernel:
            shellwidget.sig_is_spykernel.connect(
                self.connect_external_spyder_kernel)
            shellwidget.check_spyder_kernel()

        ipycon.sig_shellwidget_created.emit(shellwidget)

        # Modified from IPython code to remove modelx widgets
        # kernel_client.stopped_channels.connect(
        #     lambda: ipycon.sig_shellwidget_deleted.emit(shellwidget))
        kernel_client.stopped_channels.connect(
            lambda c=client: self.process_finished(c)
        )

        # Set elapsed time, if possible
        if not is_external_kernel:
            ipycon.set_client_elapsed_time(client)

        # Adding a new tab for the client
        ipycon.add_tab(client, name=client.get_name())

        # Register client
        ipycon.register_client(client)
Exemplo n.º 11
0
    def __init__(self, main_window: "BaseMainWindow"):
        super().__init__()

        self.main_window = main_window
        self.syntax_style = "default"
        self.style_sheet = ""

        # Connect theme update
        user_variables = {
            "window": self.main_window,
            "settings": self.main_window.settings
        }

        # get current running instance or create new instance
        shell = get_ipython()

        if shell is None:
            # If there is no currently running instance create an in-process
            # kernel.
            kernel_manager = QtInProcessKernelManager()
            kernel_manager.start_kernel(show_banner=False)
            kernel_manager.kernel.gui = "qt"

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

            self.kernel_manager = kernel_manager
            self.kernel_client = kernel_client
            self.shell = kernel_manager.kernel.shell
            self.push = self.shell.push
        elif type(shell) is InProcessInteractiveShell:  # pylint: disable=C0123
            # If there is an existing running InProcessInteractiveShell
            # it is likely because multiple viewers have been launched from
            # the same process. In that case create a new kernel.
            # Connect existing kernel
            kernel_manager = QtInProcessKernelManager(kernel=shell.kernel)
            kernel_client = kernel_manager.client()

            self.kernel_manager = kernel_manager
            self.kernel_client = kernel_client
            self.shell = kernel_manager.kernel.shell
            self.push = self.shell.push
        elif isinstance(shell, TerminalInteractiveShell):
            # if launching from an ipython terminal then adding a console is
            # not supported. Instead users should use the ipython terminal for
            # the same functionality.
            self.kernel_client = None
            self.kernel_manager = None
            self.shell = None
            self.push = lambda var: None

        elif isinstance(shell, ZMQInteractiveShell):
            # if launching from jupyter notebook, connect to the existing
            # kernel
            kernel_client = QtKernelClient(
                connection_file=get_connection_file())
            kernel_client.load_connection_file()
            kernel_client.start_channels()

            self.kernel_manager = None
            self.kernel_client = kernel_client
            self.shell = shell
            self.push = self.shell.push
        else:
            raise ValueError("ipython shell not recognized; "
                             f"got {type(shell)}")
        # Add any user variables
        user_variables = user_variables or {}
        self.push(user_variables)

        self.enable_calltips = False