Example #1
0
def connect_kernel_from_file(kernel_type, connection_file):
    from jupyter_client import KernelManager
    # Create the kernel manager and connect a client
    # See: <http://jupyter-client.readthedocs.io/en/stable/api/client.html>
    km = KernelManager(connection_file=connection_file)
    km.load_connection_file()
    kc = km.client()
    kc.start_channels()

    # Alias execute function
    def _send(msg, **kwargs):
        """Send a message to the kernel client."""
        # Include dedent of msg so we don't get odd indentation errors.
        return kc.execute(textwrap.dedent(msg), **kwargs)

    send = _send

    # Ping the kernel
    kc.kernel_info()
    try:
        reply = kc.get_shell_msg(timeout=1)
    except Empty:
        return {"connected": False}
    else:
        # pid = get_pid(kernel_type)  # Ask kernel for its PID
        return {"connected": True, "kc": kc, "send": send}
Example #2
0
def km_from_string(s=''):
    """
    Create kernel manager.
    """

    global km, kc, send

    s = s.replace('--existing', '')

    try:
        if '--profile' in s:
            k, p = s.split('--profile')
            k = k.lstrip().rstrip()  # kernel part of the string
            p = p.lstrip().rstrip()  # profile part of the string
            fullpath = find_connection_file(k, p)
        elif s == '':
            fullpath = find_connection_file()
        else:
            fullpath = find_connection_file(s.lstrip().rstrip())
    except IOError:
        vim_echo(":IPython " + s + " failed", "Info")
        vim_echo("^-- failed '" + s + "' not found", "Error")
        return

    km = KernelManager(connection_file=fullpath)
    km.load_connection_file()
    kc = km.client()
    kc.start_channels()
    send = kc.execute
    vim_echo('Connected to {}'.format(fullpath))
Example #3
0
def temporary_connect_query(connection_file, code, retvar):
    # connect
    from jupyter_client import KernelManager
    _km = KernelManager(connection_file=connection_file)
    _km.load_connection_file()
    _kc = _km.client()
    _kc.start_channels()

    def _send(msg, **kwargs):
        """Send a message to the kernel client."""
        # Include dedent of msg so we don't get odd indentation errors.
        return _kc.execute(textwrap.dedent(msg), **kwargs)

    # send code
    msg_id = _send(code, silent=True, user_expressions={"_ret": retvar})

    try:
        reply = get_reply_msg(msg_id, _kc=_kc)
    except Empty:
        vim_echom("no reply from jupyter kernel", "WarningMsg")
        return -1

    # get result
    retval = None
    try:
        # Requires the fix for https://github.com/JuliaLang/IJulia.jl/issues/815
        retval = reply["content"]["user_expressions"]["_ret"]["data"][
            "text/plain"]
    except KeyError:
        vim_echom("Could not get return value, kernel not ready?")

    # disconnect
    _kc.stop_channels()

    return retval
Example #4
0
    def create_kernel_manager(self):
        """Create the kernel manager and connect a client.

        Returns
        -------
        bool
            True if client connects successfully, False on failure.
        """
        # Get client
        kernel_manager = KernelManager(connection_file=self.cfile)
        # The json may be badly encoding especially if autoconnecting
        try:
            kernel_manager.load_connection_file()
        # pylint: disable=broad-except
        except Exception:
            return False
        self.km_client = kernel_manager.client()

        # Open channel
        self.km_client.start_channels()

        # Ping the kernel
        self.km_client.kernel_info()
        try:
            self.km_client.get_shell_msg(timeout=1)
            return True
        except Empty:
            return False
Example #5
0
def kernel_client(config):
    try:
        if config.kernel != 'existing':
            cnx_file = find_connection_file(filename=config.kernel)
        else:
            cnx_file = find_connection_file()

        km = KernelManager(connection_file=cnx_file)
        km.load_connection_file()

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

        try:
            msg = kc.shell_channel.get_msg()
        except Empty:
            try:
                # try again :)
                sleep(1)
                msg = kc.shell_channel.get_msg()
            except Empty:
                raise RuntimeError(
                    'No message found in the channel. Is the kernel alive?')

    except Exception as e:
        print(format_text('PyExecError: ipython_exec was not able to connect to the desired jupyter kernel\n' + \
                          "Hint: execute 'ipython_start_kernel' or 'jupyter console' first\n" + \
                          format_exc(), config.to))
        exit(1)

    return kc
Example #6
0
    def connect_to_kernel(self):
        """Create kernel manager from existing connection file."""
        from jupyter_client import KernelManager, find_connection_file

        # Test if connection is alive
        connected = self.check_connection()
        attempt = 0
        max_attempts = 3
        while not connected and attempt < max_attempts:
            attempt += 1
            try:
                cfile = find_connection_file(
                )  # default filename='kernel-*.json'
            except IOError:
                self.vim_echom(
                    "kernel connection attempt {:d} failed - no kernel file".
                    format(attempt),
                    style="Error")
                continue

            # Create the kernel manager and connect a client
            # See: <http://jupyter-client.readthedocs.io/en/stable/api/client.html>
            km = KernelManager(connection_file=cfile)
            km.load_connection_file()
            self.kc = km.client()
            self.kc.start_channels()

            # Alias execute function
            def _send(msg, **kwargs):
                """Send a message to the kernel client."""
                # Include dedent of msg so we don't get odd indentation errors.
                return self.kc.execute(textwrap.dedent(msg), **kwargs)

            self.send = _send

            # Ping the kernel
            self.kc.kernel_info()
            try:
                self.reply = self.kc.get_shell_msg(timeout=1)
            except Empty:
                continue
            else:
                connected = True

        if connected:
            # Send command so that monitor knows vim is commected
            # send('"_vim_client"', store_history=False)
            self.pid = self.set_pid()  # Ask kernel for its PID
            self.vim_echom('kernel connection successful! pid = {}'.format(
                self.pid),
                           style='Question')
        else:
            self.kc.stop_channels()
            self.vim_echom('kernel connection attempt timed out',
                           style='Error')
Example #7
0
def connect_to_kernel():
    """Create kernel manager from existing connection file."""
    from jupyter_client import KernelManager, find_connection_file

    global kc, pid, send

    # Test if connection is alive
    connected = check_connection()
    attempt = 0
    max_attempts = 3
    while not connected and attempt < max_attempts:
        attempt += 1
        try:
            cfile = find_connection_file()  # default filename='kernel-*.json'
        except IOError:
            vim_echom("kernel connection attempt {:d} failed - no kernel file"\
                      .format(attempt), style="Error")
            continue

        # Create the kernel manager and connect a client
        # See: <http://jupyter-client.readthedocs.io/en/stable/api/client.html>
        km = KernelManager(connection_file=cfile)
        km.load_connection_file()
        kc = km.client()
        kc.start_channels()

        # Alias execute function
        def _send(msg, **kwargs):
            """Send a message to the kernel client."""
            # Include dedent of msg so we don't get odd indentation errors.
            return kc.execute(textwrap.dedent(msg), **kwargs)
        send = _send

        # Ping the kernel
        kc.kernel_info()
        try:
            reply = kc.get_shell_msg(timeout=1)
        except Empty:
            continue
        else:
            connected = True

    if connected:
        # Send command so that monitor knows vim is commected
        # send('"_vim_client"', store_history=False)
        pid = set_pid() # Ask kernel for its PID
        vim_echom('kernel connection successful! pid = {}'.format(pid),
                  style='Question')
    else:
        kc.stop_channels()
        vim_echom('kernel connection attempt timed out', style='Error')
Example #8
0
#------------------------------------------------------------------------------
#       Connect to the kernel
#------------------------------------------------------------------------------
# TODO move this loop to __init__ of IPythonMonitor??
connected = False
while not connected:
    try:
        # Default: filename='kernel-*.json'
        filename = find_connection_file()
    except IOError:
        continue

    # Create the kernel manager and connect a client
    km = KernelManager(connection_file=filename)
    km.load_connection_file()
    kc = km.client()
    kc.start_channels()

    # Ping the kernel
    msg_id = kc.kernel_info()
    try:
        reply = kc.get_shell_msg(timeout=1)
    except Empty:
        continue
    except Exception:
        traceback.print_exc()
    except KeyboardInterrupt:  # <C-c> or kill -SIGINT?
        sys.exit(0)
    else:
        connected = True
Example #9
0
class SimpleKernel(object):
    """
    ## Description
    **SimpleKernel**:
     A simplistic Jupyter kernel client wrapper.

    Additional information in [this GitHub issue]
    (

    )
    """
    def __init__(self, use_exist=False):
        """
        ## Description
        Initializes the `kernel_manager` and `client` objects
        and starts the kernel. Also initializes the pretty printer
        for displaying object properties and execution result
        payloads.

        ## Parameters
        None.
        """
        if not use_exist:
            # Initialize kernel and client
            self.kernel_manager, self.client = start_new_kernel()
            self.send = self.client.execute
        else:
            self.kernel_manager = KernelManager(
                connection_file=find_connection_file())
            self.kernel_manager.load_connection_file(find_connection_file())
            self.client = self.kernel_manager.client()
            self.client.start_channels()
            self.send = self.client.execute

        # Initialize pretty printer
        self.pp = PrettyPrinter(indent=2)

    # end __init__ ##

    def execute(self, code):
        """
        ## Description
        **execute**:
        Executes a code string in the kernel. Can return either
        the full execution response payload, or just `stdout`. Also,
        there is a verbose mode that displays the execution process.

        ## Parameters
        code : string
            The code string to get passed to `stdin`.
        verbose : bool (default=False)
            Whether to display processing information.
        get_type : bool (default=False) NOT IMPLEMENTED
            When implemented, will return a dict including the output
            and the type. E.g.

            1+1 ==> {stdout: 2, type: int}
            "hello" ==> {stdout: "hello", type: str}
            print("hello") ==> {stdout: "hello", type: NoneType}
            a=10 ==> {stdout: None, type: None}

        ## Returns
        `stdout` or the full response payload.
        """

        # Execute the code
        self.client.execute(code)

        # Continue polling for execution to complete
        list_io_msg = []
        while True:
            # Poll the message
            try:
                io_msg_content = self.client.get_iopub_msg(
                    timeout=0.2)['content']
                list_io_msg.append(io_msg_content)
            except queue.Empty:
                break

        if len(list_io_msg) < 3:
            temp = ''
        else:
            temp = list_io_msg[-2]

        # print(temp)
        # Check the message for various possibilities
        if 'data' in temp:  # Indicates completed operation
            out = temp['data']['text/plain']
        elif 'name' in temp and temp['name'] == "stdout":  # indicates output
            out = temp['text']
        elif 'traceback' in temp:  # Indicates error
            print("ERROR")
            out = '\n'.join(temp['traceback'])  # Put error into nice format
        else:
            out = ''

        return out

    def __del__(self):
        """
        ## Description
        Destructor. Shuts down kernel safely.
        """
        self.kernel_manager.shutdown_kernel()
Example #10
0
def connect_to_kernel(kernel_type, filename=''):
    """Create kernel manager from existing connection file."""
    from jupyter_client import KernelManager, find_connection_file

    global kc, pid, send, cfile

    # Test if connection is alive
    connected = check_connection()
    attempt = 0
    max_attempts = 3
    while not connected and attempt < max_attempts:
        attempt += 1
        try:
            cfile = find_connection_file(filename=filename)
        except IOError:
            vim_echom("kernel connection attempt {:d}/{:d} failed - no kernel file"\
                      .format(attempt, max_attempts), style="Error")
            continue

        # Create the kernel manager and connect a client
        # See: <http://jupyter-client.readthedocs.io/en/stable/api/client.html>
        km = KernelManager(connection_file=cfile)
        km.load_connection_file()
        kc = km.client()
        kc.start_channels()

        # Alias execute function
        def _send(msg, **kwargs):
            """Send a message to the kernel client."""
            # Include dedent of msg so we don't get odd indentation errors.
            return kc.execute(textwrap.dedent(msg), **kwargs)

        send = _send

        # Ping the kernel
        kc.kernel_info()
        try:
            reply = kc.get_shell_msg(timeout=1)
        except Empty:
            continue
        else:
            connected = True

    if connected:
        # Collect kernel info
        kernel_info = get_kernel_info(kernel_type)
        pid = kernel_info['pid']

        # Send command so that user knows vim is connected
        vim_echom('Connected: {}'.format(shorten_cfile()), style='Question')

        # More info by default
        is_short = int(vim.vars.get('jupyter_shortmess', 0))
        if not is_short:
            # Prettify output: appearance rules
            from pprint import PrettyPrinter
            pp = PrettyPrinter(indent=4, width=vim.eval('&columns'))
            kernel_string = pp.pformat(kernel_info)[4:-1]

            # Echo message
            vim_echom('To: ', style='Question')
            vim.command("echon \"{}\"".format(
                kernel_string.replace('\"', '\\\"')))

    else:
        if None is not kc: kc.stop_channels()
        vim_echom('kernel connection attempt timed out', style='Error')
Example #11
0
def km_from_string(s=''):
    """create kernel manager from IPKernelApp string
    such as '--shell=47378 --iopub=39859 --stdin=36778 --hb=52668' for IPython 0.11
    or just 'kernel-12345.json' for IPython 0.12
    """
    try:
        import IPython
    except ImportError:
        raise ImportError("Could not find IPython. " + _install_instructions)
    try:
        from traitlets.config.loader import KeyValueConfigLoader
    except ImportError:
        from IPython.config.loader import KeyValueConfigLoader
    try:
        from jupyter_client import KernelManager, find_connection_file
    except ImportError:
        try:
            from IPython.kernel import  KernelManager, find_connection_file
        except ImportError:
            #  IPython < 1.0
            from IPython.zmq.blockingkernelmanager import BlockingKernelManager as KernelManager
            from IPython.zmq.kernelapp import kernel_aliases
            try:
                from IPython.lib.kernel import find_connection_file
            except ImportError:
                # < 0.12, no find_connection_file
                pass

    global km, kc, send, history, complete, object_info

    # Test if connection is still alive
    connected = False
    starttime = time.time()
    attempt = 0
    s = s.replace('--existing', '')
    while not connected and (time.time() - starttime) < 5.0:
        if not attempt and os.path.isfile(s):
            fullpath = s
        else:
            try:
                s = fullpath = find_connection_file('kernel*')
            except IOError:
                echo("IPython connection attempt #%d failed - no kernel file" % attempt, "Warning")
                time.sleep(1)
                continue
        attempt += 1

        if 'connection_file' in KernelManager.class_trait_names():
            # 0.12 uses files instead of a collection of ports
            # include default IPython search path
            # filefind also allows for absolute paths, in which case the search
            # is ignored
            try:
                # XXX: the following approach will be brittle, depending on what
                # connection strings will end up looking like in the future, and
                # whether or not they are allowed to have spaces. I'll have to sync
                # up with the IPython team to address these issues -pi
                if '--profile' in s:
                    k,p = s.split('--profile')
                    k = k.lstrip().rstrip() # kernel part of the string
                    p = p.lstrip().rstrip() # profile part of the string
                    fullpath = find_connection_file(k,p)
                else:
                    fullpath = find_connection_file(s.lstrip().rstrip())
            except IOError as e:
                echo(":IPython " + s + " failed", "Info")
                echo("^-- failed '" + s + "' not found", "Error")
                return
            km = KernelManager(connection_file = fullpath)
            km.load_connection_file()
        else:
            if s == '':
                echo(":IPython 0.11 requires the full connection string")
                return
            loader = KeyValueConfigLoader(s.split(), aliases=kernel_aliases)
            cfg = loader.load_config()['KernelApp']
            try:
                km = KernelManager(
                    shell_address=(ip, cfg['shell_port']),
                    sub_address=(ip, cfg['iopub_port']),
                    stdin_address=(ip, cfg['stdin_port']),
                    hb_address=(ip, cfg['hb_port']))
            except KeyError as e:
                echo(":IPython " +s + " failed", "Info")
                echo("^-- failed --"+e.message.replace('_port','')+" not specified", "Error")
                return

        try:
            kc = km.client()
        except AttributeError:
            # 0.13
            kc = km
        kc.start_channels()

        execute = kc.execute if hasattr(kc, 'execute') else kc.shell_channel.execute
        history = kc.history if hasattr(kc, 'history') else kc.shell_channel.history
        complete = kc.complete if hasattr(kc, 'complete') else kc.shell_channel.complete
        object_info = kc.inspect if hasattr(kc, 'inspect') else kc.shell_channel.object_info

        def send(msg, **kwargs):
            kwds = dict(
                store_history=vim_vars.get('ipython_store_history', True),
                allow_stdin=allow_stdin,
            )
            kwds.update(kwargs)
            return execute(msg, **kwds)

        send('', silent=True)
        try:
            msg = kc.shell_channel.get_msg(timeout=1)
            connected = True
        except:
            echo("IPython connection attempt #%d failed - no messages" % attempt, "Warning")
            kc.stop_channels()
            continue

        #XXX: backwards compatibility for IPython < 1.0
        if not hasattr(kc, 'iopub_channel'):
            kc.iopub_channel = kc.sub_channel
        set_pid()

    if not connected:
        echo("IPython connection attempt timed out", "Error")
        return
    else:
        vim.command('redraw')
        echo("IPython connection successful")
        send('"_vim_client";_=_;__=__', store_history=False)

    #XXX: backwards compatibility for IPython < 0.13
    sc = kc.shell_channel
    if hasattr(sc, 'object_info'):
        import inspect
        num_oinfo_args = len(inspect.getargspec(sc.object_info).args)
        if num_oinfo_args == 2:
            # patch the object_info method which used to only take one argument
            klass = sc.__class__
            klass._oinfo_orig = klass.object_info
            klass.object_info = lambda s,x,y: s._oinfo_orig(x)

    #XXX: backwards compatibility for IPython < 1.0
    if not hasattr(kc, 'iopub_channel'):
        kc.iopub_channel = kc.sub_channel

    # now that we're connect to an ipython kernel, activate completion
    # machinery, but do so only for the local buffer if the user added the
    # following line the vimrc:
    #   let g:ipy_completefunc = 'local'
    vim.command("""
        if g:ipy_completefunc == 'global'
            set completefunc=CompleteIPython
        elseif g:ipy_completefunc == 'local'
            setl completefunc=CompleteIPython
        elseif g:ipy_completefunc == 'omni'
            setl omnifunc=CompleteIPython
        endif
        """)
    # also activate GUI doc balloons if in gvim
    vim.command("""
        if has('balloon_eval')
            set bexpr=IPythonBalloonExpr()
        endif
        """)
    return km
Example #12
0
def km_from_string(s=''):
    """create kernel manager from IPKernelApp string
    such as '--shell=47378 --iopub=39859 --stdin=36778 --hb=52668' for IPython 0.11
    or just 'kernel-12345.json' for IPython 0.12
    """
    try:
        import IPython
    except ImportError:
        raise ImportError("Could not find IPython. " + _install_instructions)
    try:
        from traitlets.config.loader import KeyValueConfigLoader
    except ImportError:
        from IPython.config.loader import KeyValueConfigLoader
    try:
        from jupyter_client import KernelManager, find_connection_file
    except ImportError:
        try:
            from IPython.kernel import  KernelManager, find_connection_file
        except ImportError:
            #  IPython < 1.0
            from IPython.zmq.blockingkernelmanager import BlockingKernelManager as KernelManager
            from IPython.zmq.kernelapp import kernel_aliases
            try:
                from IPython.lib.kernel import find_connection_file
            except ImportError:
                # < 0.12, no find_connection_file
                pass

    global km, kc, send, history, complete, object_info

    # Test if connection is still alive
    connected = False
    starttime = time.time()
    attempt = 0
    s = s.replace('--existing', '')
    while not connected and (time.time() - starttime) < 5.0:
        if not attempt and os.path.isfile(s):
            fullpath = s
        else:
            try:
                s = fullpath = find_connection_file('kernel*')
            except IOError:
                echo("IPython connection attempt #%d failed - no kernel file" % attempt, "Warning")
                time.sleep(1)
                continue
        attempt += 1

        km = KernelManager(connection_file=fullpath)
        km.load_connection_file()

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

        if 'connection_file' in KernelManager.class_trait_names():
            # 0.12 uses files instead of a collection of ports
            # include default IPython search path
            # filefind also allows for absolute paths, in which case the search
            # is ignored
            try:
                # XXX: the following approach will be brittle, depending on what
                # connection strings will end up looking like in the future, and
                # whether or not they are allowed to have spaces. I'll have to sync
                # up with the IPython team to address these issues -pi
                if '--profile' in s:
                    k,p = s.split('--profile')
                    k = k.lstrip().rstrip() # kernel part of the string
                    p = p.lstrip().rstrip() # profile part of the string
                    fullpath = find_connection_file(k,p)
                else:
                    fullpath = find_connection_file(s.lstrip().rstrip())
            except IOError as e:
                echo(":IPython " + s + " failed", "Info")
                echo("^-- failed '" + s + "' not found", "Error")
                return
            km = KernelManager(connection_file = fullpath)
            km.load_connection_file()
        else:
            if s == '':
                echo(":IPython 0.11 requires the full connection string")
                return
            loader = KeyValueConfigLoader(s.split(), aliases=kernel_aliases)
            cfg = loader.load_config()['KernelApp']
            try:
                km = KernelManager(
                    shell_address=(ip, cfg['shell_port']),
                    sub_address=(ip, cfg['iopub_port']),
                    stdin_address=(ip, cfg['stdin_port']),
                    hb_address=(ip, cfg['hb_port']))
            except KeyError as e:
                echo(":IPython " +s + " failed", "Info")
                echo("^-- failed --"+e.message.replace('_port','')+" not specified", "Error")
                return

        try:
            kc = km.client()
        except AttributeError:
            # 0.13
            kc = km
        kc.start_channels()

        execute = kc.execute if hasattr(kc, 'execute') else kc.shell_channel.execute
        history = kc.history if hasattr(kc, 'history') else kc.shell_channel.history
        complete = kc.complete if hasattr(kc, 'complete') else kc.shell_channel.complete
        object_info = kc.inspect if hasattr(kc, 'inspect') else kc.shell_channel.object_info

        def send(msg, **kwargs):
            kwds = dict(
                store_history=vim_vars.get('ipython_store_history', True),
            )
            kwds.update(kwargs)
            return execute(msg, **kwds)

        send('', silent=True)
        try:
            msg = kc.shell_channel.get_msg(timeout=1)
            connected = True
        except:
            echo("IPython connection attempt #%d failed - no messages" % attempt, "Warning")
            continue

        #XXX: backwards compatibility for IPython < 1.0
        if not hasattr(kc, 'iopub_channel'):
            kc.iopub_channel = kc.sub_channel
        set_pid()

    if not connected:
        echo("IPython connection attempt timed out", "Error")
        return
    else:
        vim.command('redraw')
        echo("IPython connection successful")
        send('"_vim_client";_=_;__=__', store_history=False)

    #XXX: backwards compatibility for IPython < 0.13
    sc = kc.shell_channel
    if hasattr(sc, 'object_info'):
        import inspect
        num_oinfo_args = len(inspect.getargspec(sc.object_info).args)
        if num_oinfo_args == 2:
            # patch the object_info method which used to only take one argument
            klass = sc.__class__
            klass._oinfo_orig = klass.object_info
            klass.object_info = lambda s,x,y: s._oinfo_orig(x)

    #XXX: backwards compatibility for IPython < 1.0
    if not hasattr(kc, 'iopub_channel'):
        kc.iopub_channel = kc.sub_channel

    # now that we're connect to an ipython kernel, activate completion
    # machinery, but do so only for the local buffer if the user added the
    # following line the vimrc:
    #   let g:ipy_completefunc = 'local'
    vim.command("""
        if g:ipy_completefunc == 'global'
            set completefunc=CompleteIPython
        elseif g:ipy_completefunc == 'local'
            setl completefunc=CompleteIPython
        elseif g:ipy_completefunc == 'omni'
            setl omnifunc=CompleteIPython
        endif
        """)
    # also activate GUI doc balloons if in gvim
    vim.command("""
        if has('balloon_eval')
            set bexpr=IPythonBalloonExpr()
        endif
        """)
    return km
Example #13
0
def km_from_string(s=''):
    """create kernel manager from IPKernelApp string
    such as '--shell=47378 --iopub=39859 --stdin=36778 --hb=52668' for IPython 0.11
    or just 'kernel-12345.json' for IPython 0.12
    """
    try:
        import IPython
    except ImportError:
        raise ImportError("Could not find IPython. " + _install_instructions)
    try:
        from traitlets.config.loader import KeyValueConfigLoader
    except ImportError:
        from traitl.config.loader import KeyValueConfigLoader
    try:
        from jupyter_client import (
            KernelManager,
            find_connection_file,
        )
    except ImportError:
        #  IPython < 1.0
        from IPython.zmq.blockingkernelmanager import BlockingKernelManager as KernelManager
        from IPython.zmq.kernelapp import kernel_aliases
        try:
            from IPython.lib.kernel import find_connection_file
        except ImportError:
            # < 0.12, no find_connection_file
            pass

    global km, kc, send

    s = s.replace('--existing', '')
    if 'connection_file' in KernelManager.class_trait_names():
        # 0.12 uses files instead of a collection of ports
        # include default IPython search path
        # filefind also allows for absolute paths, in which case the search
        # is ignored
        try:
            # XXX: the following approach will be brittle, depending on what
            # connection strings will end up looking like in the future, and
            # whether or not they are allowed to have spaces. I'll have to sync
            # up with the IPython team to address these issues -pi
            if '--profile' in s:
                k, p = s.split('--profile')
                k = k.lstrip().rstrip()  # kernel part of the string
                p = p.lstrip().rstrip()  # profile part of the string
                fullpath = find_connection_file(k, p)
            else:
                fullpath = find_connection_file(s.lstrip().rstrip())
        except IOError as e:
            echo(":IPython " + s + " failed", "Info")
            echo("^-- failed '" + s + "' not found", "Error")
            return
        km = KernelManager(connection_file=fullpath)
        km.load_connection_file()
    else:
        if s == '':
            echo(":IPython 0.11 requires the full connection string")
            return
        loader = KeyValueConfigLoader(s.split(), aliases=kernel_aliases)
        cfg = loader.load_config()['KernelApp']
        try:
            km = KernelManager(shell_address=(ip, cfg['shell_port']),
                               sub_address=(ip, cfg['iopub_port']),
                               stdin_address=(ip, cfg['stdin_port']),
                               hb_address=(ip, cfg['hb_port']))
        except KeyError as e:
            echo(":IPython " + s + " failed", "Info")
            echo(
                "^-- failed --" + e.message.replace('_port', '') +
                " not specified", "Error")
            return

    try:
        kc = km.client()
    except AttributeError:
        # 0.13
        kc = km
    kc.start_channels()

    try:
        send = kc.execute
    except AttributeError:
        # < 3.0
        send = kc.shell_channel.execute

    #XXX: backwards compatibility for IPython < 0.13
    try:
        import inspect
        sc = kc.shell_channel
        num_oinfo_args = len(inspect.getargspec(sc.object_info).args)
        if num_oinfo_args == 2:
            # patch the object_info method which used to only take one argument
            klass = sc.__class__
            klass._oinfo_orig = klass.object_info
            klass.object_info = lambda s, x, y: s._oinfo_orig(x)
    except:
        pass

    #XXX: backwards compatibility for IPython < 1.0
    if not hasattr(kc, 'iopub_channel'):
        kc.iopub_channel = kc.sub_channel

    # now that we're connect to an ipython kernel, activate completion
    # machinery, but do so only for the local buffer if the user added the
    # following line the vimrc:
    #   let g:ipy_completefunc = 'local'
    vim.command("""
        if g:ipy_completefunc == 'global'
            set completefunc=CompleteIPython
        elseif g:ipy_completefunc == 'local'
            setl completefunc=CompleteIPython
        endif
        """)
    # also activate GUI doc balloons if in gvim
    vim.command("""
        if has('balloon_eval')
            set bexpr=IPythonBalloonExpr()
        endif
        """)
    set_pid()
    return km
Example #14
0
    for fullpath in glob(os.path.join(os.path.dirname(filename), 'kernel*')):
        if not re.match('^(.*/)?kernel-[0-9]+.json', fullpath):
            continue
        yield fullpath


connected = False
while not connected:
    try:
        filename = find_connection_file('kernel*')
    except IOError:
        continue

    for fullpath in paths():
        km = KernelManager(connection_file=fullpath)
        km.load_connection_file()

        kc = km.client()
        kc.start_channels()
        try:
            send = kc.execute
        except AttributeError:
            send = kc.shell_channel.execute
        if not hasattr(kc, 'iopub_channel'):
            kc.iopub_channel = kc.sub_channel

        send('', silent=True)
        try:
            msg = kc.shell_channel.get_msg(timeout=1)
            connected = True
            socket = km.connect_iopub()