Ejemplo n.º 1
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
    """
    global km, kc, send, Empty
    from os.path import join as pjoin

    from IPython.config.loader import KeyValueConfigLoader

    if int(sys.version.split(" ")[0][0]) > 2:
        from queue import Empty
    else:
        from Queue import Empty

    try:
        from IPython.kernel import KernelManager, find_connection_file

    except ImportError:
        from IPython.zmq.blockingkernelmanager import BlockingKernelManager as KernelManager
        from IPython.zmq.kernelapp import kernel_aliases
        from IPython.lib.kernel import find_connection_file

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

        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())

        km = KernelManager(connection_file=fullpath)
        km.load_connection_file()
        km.start_channels()
        send = km.shell_channel.execute

        respond(None, "python.client.error.ipython-version", None)

        return

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

    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())

    km = KernelManager(connection_file=fullpath)
    km.load_connection_file()
    kc = km.client()
    kc.start_channels()
    send = kc.shell_channel.execute
    return km
Ejemplo n.º 2
0
    def init_connection_file(self):
        """find the connection file, and load the info if found.
        
        The current working directory and the current profile's security
        directory will be searched for the file if it is not given by
        absolute path.
        
        When attempting to connect to an existing kernel and the `--existing`
        argument does not match an existing file, it will be interpreted as a
        fileglob, and the matching file in the current profile's security dir
        with the latest access time will be used.
        
        After this method is called, self.connection_file contains the *full path*
        to the connection file, never just its name.
        """
        if self.existing:
            try:
                cf = find_connection_file(self.existing)
            except Exception:
                self.log.critical(
                    "Could not find existing kernel connection file %s",
                    self.existing)
                self.exit(1)
            self.log.debug("Connecting to existing kernel: %s" % cf)
            self.connection_file = cf
        else:
            # not existing, check if we are going to write the file
            # and ensure that self.connection_file is a full path, not just the shortname
            try:
                cf = find_connection_file(self.connection_file)
            except Exception:
                # file might not exist
                if self.connection_file == os.path.basename(
                        self.connection_file):
                    # just shortname, put it in security dir
                    cf = os.path.join(self.profile_dir.security_dir,
                                      self.connection_file)
                else:
                    cf = self.connection_file
                self.connection_file = cf
        try:
            self.connection_file = filefind(
                self.connection_file, ['.', self.profile_dir.security_dir])
        except IOError:
            self.log.debug("Connection File not found: %s",
                           self.connection_file)
            return

        # should load_connection_file only be used for existing?
        # as it is now, this allows reusing ports if an existing
        # file is requested
        try:
            self.load_connection_file()
        except Exception:
            self.log.error("Failed to load connection file: %r",
                           self.connection_file,
                           exc_info=True)
            self.exit(1)
Ejemplo n.º 3
0
    def init_connection_file(self):
        """find the connection file, and load the info if found.

        The current working directory and the current profile's security
        directory will be searched for the file if it is not given by
        absolute path.

        When attempting to connect to an existing kernel and the `--existing`
        argument does not match an existing file, it will be interpreted as a
        fileglob, and the matching file in the current profile's security dir
        with the latest access time will be used.

        After this method is called, self.connection_file contains the *full path*
        to the connection file, never just its name.
        """
        if self.existing:
            try:
                cf = find_connection_file(self.existing)
            except Exception:
                self.log.critical(
                    "Could not find existing kernel connection file %s", self.existing)
                self.exit(1)
            self.log.debug("Connecting to existing kernel: %s" % cf)
            self.connection_file = cf
        else:
            # not existing, check if we are going to write the file
            # and ensure that self.connection_file is a full path, not just the
            # shortname
            try:
                cf = find_connection_file(self.connection_file)
            except Exception:
                # file might not exist
                if self.connection_file == os.path.basename(self.connection_file):
                    # just shortname, put it in security dir
                    cf = os.path.join(
                        self.profile_dir.security_dir, self.connection_file)
                else:
                    cf = self.connection_file
                self.connection_file = cf
        try:
            self.connection_file = filefind(
                self.connection_file, ['.', self.profile_dir.security_dir])
        except IOError:
            self.log.debug(
                "Connection File not found: %s", self.connection_file)
            return

        # should load_connection_file only be used for existing?
        # as it is now, this allows reusing ports if an existing
        # file is requested
        try:
            self.load_connection_file()
        except Exception:
            self.log.error(
                "Failed to load connection file: %r", self.connection_file, exc_info=True)
            self.exit(1)
Ejemplo n.º 4
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
    """
    global km, kc, send

    from os.path import join as pjoin
    from IPython.config.loader import KeyValueConfigLoader

    try:
        from IPython.kernel import (
            KernelManager,
            find_connection_file,
        )
    except ImportError:
        from IPython.zmq.blockingkernelmanager import BlockingKernelManager as KernelManager
        from IPython.zmq.kernelapp import kernel_aliases
        from IPython.lib.kernel import find_connection_file

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

        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())

        km = KernelManager(connection_file = fullpath)
        km.load_connection_file()
        km.start_channels()
        send = km.shell_channel.execute # not sure if this should be changed as well

        respond(None, "python.client.error.ipython-version", None)
        return


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

    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())

    km = KernelManager(connection_file = fullpath)
    km.load_connection_file()
    kc = km.client()
    kc.start_channels()
    send = kc.execute
    return km
Ejemplo n.º 5
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
    """
    global km, kc, send

    from os.path import join as pjoin
    from IPython.config.loader import KeyValueConfigLoader

    try:
        from IPython.kernel import (
            KernelManager,
            find_connection_file,
        )
    except ImportError:
        from IPython.zmq.blockingkernelmanager import BlockingKernelManager as KernelManager
        from IPython.zmq.kernelapp import kernel_aliases
        from IPython.lib.kernel import find_connection_file

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

        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())

        km = KernelManager(connection_file=fullpath)
        km.load_connection_file()
        km.start_channels()
        send = km.shell_channel.execute

        respond(None, "python.client.error.ipython-version", None)
        return

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

    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())

    km = KernelManager(connection_file=fullpath)
    km.load_connection_file()
    kc = km.client()
    kc.start_channels()
    send = kc.shell_channel.execute
    return km
Ejemplo n.º 6
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)
    from IPython.config.loader import KeyValueConfigLoader
    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

    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()
    send = kc.shell_channel.execute

    #XXX: backwards compatibility for IPython < 0.13
    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)
    
    #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
Ejemplo n.º 7
0
from IPython.kernel import BlockingKernelClient, get_connection_file, find_connection_file

cf= find_connection_file("kernel-305.json")
client = BlockingKernelClient(connection_file=cf)
client.load_connection_file()
client.start_channels()
client.execute('ddd')
msg = client.get_shell_msg(block=True, timeout=3000)
print msg
Ejemplo n.º 8
0
#! /usr/bin/env python
import os
import sys
import signal
import re
from IPython.kernel import KernelManager, find_connection_file

# Connection file of most recently launched kernel instance
cf_name = ''
cf = find_connection_file(cf_name)

# FIXME: this gets the wrong pid (the connected client's)
# We want the pid of the kernel to send interrupts to.
# One hacky approach is to ask the kernel to os.getpid(),
# assuming it's responsive (see vim-ipython).
pid = int(re.findall(r'kernel-(\d+)\.json', cf)[0])

# Connect to kernel
km = KernelManager(connection_file=cf)
km.load_connection_file()
client = km.client()
client.start_channels()

# Propagate SIGTERM from sublime as SIGINT to kernel
def interrupt_handler(signum, frame):
    os.kill(pid, signal.SIGINT)
    sys.exit(130)
signal.signal(signal.SIGTERM, interrupt_handler)

# Code is sent over the shell channel.
# Execution runs asynchronously in the kernel process.