当前位置: 首页>>代码示例>>Python>>正文


Python IPKernelApp.instance方法代码示例

本文整理汇总了Python中ipykernel.kernelapp.IPKernelApp.instance方法的典型用法代码示例。如果您正苦于以下问题:Python IPKernelApp.instance方法的具体用法?Python IPKernelApp.instance怎么用?Python IPKernelApp.instance使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ipykernel.kernelapp.IPKernelApp的用法示例。


在下文中一共展示了IPKernelApp.instance方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: pylab_kernel

# 需要导入模块: from ipykernel.kernelapp import IPKernelApp [as 别名]
# 或者: from ipykernel.kernelapp.IPKernelApp import instance [as 别名]
 def pylab_kernel(self, gui):
     '''Launch an IPython kernel with pylab support for the gui.'''
     trace = False
         # Forces Leo's --debug option.
     self.kernelApp = kernelApp = IPKernelApp.instance()
         # IPKernalApp is a singleton class.
         # Return the singleton instance, creating it if necessary.
     if kernelApp:
         # pylab is needed for Qt event loop integration.
         args = ['python', '--pylab=%s' % (gui)]
         if trace or g.app.debug:
             args.append('--log-level=20')
                 # Higher is *quieter*
             # args.append('--debug')
             # Produces a verbose IPython log.
             #'--log-level=10'
             # '--pdb', # User-level debugging
         try:
             kernelApp.initialize(args)
         except Exception:
             sys.stdout = sys.__stdout__
             print('kernelApp.initialize failed!')
             raise
     else:
         g.trace('IPKernelApp.instance failed!')
     return kernelApp
开发者ID:Darriall,项目名称:leo-editor,代码行数:28,代码来源:leoIPython.py

示例2: do_one_iteration

# 需要导入模块: from ipykernel.kernelapp import IPKernelApp [as 别名]
# 或者: from ipykernel.kernelapp.IPKernelApp import instance [as 别名]
def do_one_iteration():
    """Perform an iteration on IPython kernel runloop"""
    if IPKernelApp.initialized():
        app = IPKernelApp.instance()
        app.kernel.do_one_iteration()
    else:
        raise Exception("Kernel is not initialized")
开发者ID:eset,项目名称:ipyida,代码行数:9,代码来源:kernel.py

示例3: server_factory

# 需要导入模块: from ipykernel.kernelapp import IPKernelApp [as 别名]
# 或者: from ipykernel.kernelapp.IPKernelApp import instance [as 别名]
def server_factory(network_manager_factory, verbosity, **kwargs):
    init_qt_app(verbose=verbosity >= 5)
    SplashKernel.network_manager_factory = network_manager_factory
    kernel = IPKernelApp.instance(kernel_class=SplashKernel)
    kernel.initialize()
    kernel.kernel.eventloop = loop_qt5
    kernel.start()
开发者ID:pawelmhm,项目名称:splash,代码行数:9,代码来源:kernel.py

示例4: start

# 需要导入模块: from ipykernel.kernelapp import IPKernelApp [as 别名]
# 或者: from ipykernel.kernelapp.IPKernelApp import instance [as 别名]
def start():
    with xvfb.autostart():
        # FIXME: logs go to nowhere
        init_qt_app(verbose=False)
        kernel = IPKernelApp.instance(kernel_class=SplashKernel)
        kernel.initialize()
        kernel.kernel.eventloop = loop_qt4
        kernel.start()
开发者ID:SimonWan,项目名称:splash,代码行数:10,代码来源:kernel.py

示例5: embed_kernel

# 需要导入模块: from ipykernel.kernelapp import IPKernelApp [as 别名]
# 或者: from ipykernel.kernelapp.IPKernelApp import instance [as 别名]
    def embed_kernel(module=None, local_ns=None, **kwargs):
        """Embed and start an IPython kernel in a given scope.

        Parameters
        ----------
        module : ModuleType, optional
            The module to load into IPython globals (default: caller)
        local_ns : dict, optional
            The namespace to load into IPython user namespace (default: caller)

        kwargs : various, optional
            Further keyword args are relayed to the IPKernelApp constructor,
            allowing configuration of the Kernel.  Will only have an effect
            on the first embed_kernel call for a given process.

        """
        # get the app if it exists, or set it up if it doesn't
        if IPKernelApp.initialized():
            app = IPKernelApp.instance()
        else:
            app = IPKernelApp.instance(**kwargs)
            app.initialize(sys.argv)
            # Undo unnecessary sys module mangling from init_sys_modules.
            # This would not be necessary if we could prevent it
            # in the first place by using a different InteractiveShell
            # subclass, as in the regular embed case.
            main = app.kernel.shell._orig_sys_modules_main_mod
            if main is not None:
                sys.modules[app.kernel.shell._orig_sys_modules_main_name] = main

        # load the calling scope if not given
        (caller_module, caller_locals) = extract_module_locals(1)
        if module is None:
            module = caller_module
        if local_ns is None:
            local_ns = caller_locals

        app.kernel.user_module = None
        app.kernel.user_ns = None
        app.shell.set_completer_frame()

        if app.poller is not None:
            app.poller.start()

        app.kernel.start()
        return app
开发者ID:tmr232,项目名称:ida_ipython,代码行数:48,代码来源:ipythonEmbed.py

示例6: _start_kernel

# 需要导入模块: from ipykernel.kernelapp import IPKernelApp [as 别名]
# 或者: from ipykernel.kernelapp.IPKernelApp import instance [as 别名]
def _start_kernel():
    """starts the ipython kernel and returns the ipython app"""
    global _ipython_app, _kernel_running

    if _ipython_app and _kernel_running:
        return _ipython_app

    import IPython
    from ipykernel.kernelapp import IPKernelApp
    from zmq.eventloop import ioloop

    # patch IPKernelApp.start so that it doesn't block
    def _IPKernelApp_start(self):
        if self.poller is not None:
            self.poller.start()
        self.kernel.start()

        # set up a timer to periodically poll the zmq ioloop
        loop = ioloop.IOLoop.instance()

        def poll_ioloop(timer_id, time):
            global _kernel_running

            # if the kernel has been closed then run the event loop until it gets to the
            # stop event added by IPKernelApp.shutdown_request
            if self.kernel.shell.exit_now:
                _log.debug("IPython kernel stopping (%s)" % self.connection_file)
                timer.kill_timer(timer_id)
                loop.start()
                _kernel_running = False
                return

            # otherwise call the event loop but stop immediately if there are no pending events
            loop.add_timeout(0, lambda: loop.add_callback(loop.stop))
            loop.start()

        global _kernel_running
        _kernel_running = True
        timer.set_timer(100, poll_ioloop)

    IPKernelApp.start = _IPKernelApp_start

    # IPython expects sys.__stdout__ to be set
    sys.__stdout__ = sys.stdout
    sys.__stderr__ = sys.stderr

    # call the API embed function, which will use the monkey-patched method above
    IPython.embed_kernel()

    _ipython_app = IPKernelApp.instance()

    # patch ipapp so anything else trying to get a terminal app (e.g. ipdb)
    # gets our IPKernalApp.
    from IPython.terminal.ipapp import TerminalIPythonApp
    TerminalIPythonApp.instance = lambda: _ipython_app
    __builtins__["get_ipython"] = lambda: _ipython_app.shell

    return _ipython_app
开发者ID:AJP4,项目名称:pyxll-examples,代码行数:60,代码来源:ipython.py

示例7: launch

# 需要导入模块: from ipykernel.kernelapp import IPKernelApp [as 别名]
# 或者: from ipykernel.kernelapp.IPKernelApp import instance [as 别名]
def launch(app, MW = None):
    if MW is None:
        from manuskript.functions import mainWindow
        MW = mainWindow()

    MW.show()

    # Support for IPython Jupyter QT Console as a debugging aid.
    # Last argument must be --console to enable it
    # Code reference : 
    # https://github.com/ipython/ipykernel/blob/master/examples/embedding/ipkernel_qtapp.py
    # https://github.com/ipython/ipykernel/blob/master/examples/embedding/internal_ipkernel.py
    if len(sys.argv) > 1 and sys.argv[-1] == "--console":
        try:
            from IPython.lib.kernel import connect_qtconsole
            from ipykernel.kernelapp import IPKernelApp
            # Only to ensure matplotlib QT mainloop integration is available
            import matplotlib

            # Create IPython kernel within our application
            kernel = IPKernelApp.instance()
            
            # Initialize it and use matplotlib for main event loop integration with QT
            kernel.initialize(['python', '--matplotlib=qt'])

            # Create the console in a new process and connect
            console = connect_qtconsole(kernel.abs_connection_file, profile=kernel.profile)

            # Export MW and app variable to the console's namespace
            kernel.shell.user_ns['MW'] = MW
            kernel.shell.user_ns['app'] = app
            kernel.shell.user_ns['kernel'] = kernel
            kernel.shell.user_ns['console'] = console

            # When we close manuskript, make sure we close the console process and stop the
            # IPython kernel's mainloop, otherwise the app will never finish.
            def console_cleanup():
                app.quit()
                console.kill()
                kernel.io_loop.stop()
            app.lastWindowClosed.connect(console_cleanup)

            # Very important, IPython-specific step: this gets GUI event loop
            # integration going, and it replaces calling app.exec_()
            kernel.start()
        except Exception as e:
            print("Console mode requested but error initializing IPython : %s" % str(e))
            print("To make use of the Interactive IPython QT Console, make sure you install : ")
            print("$ pip3 install ipython qtconsole matplotlib")
            qApp.exec_()
    else:
        qApp.exec_()
    qApp.deleteLater()
开发者ID:olivierkes,项目名称:manuskript,代码行数:55,代码来源:main.py

示例8: run

# 需要导入模块: from ipykernel.kernelapp import IPKernelApp [as 别名]
# 或者: from ipykernel.kernelapp.IPKernelApp import instance [as 别名]
    def run(self):
        global logger
        logger = log.kernel_logger.getChild(str(os.getpid()))
        logger.debug("forked kernel is running")
        log.std_redirect(logger)
        # Become a group leader for cleaner exit.
        os.setpgrp()
        dir = os.path.join(self.dir, self.id)
        try:
            os.mkdir(dir)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
        os.chdir(dir)
        #config = traitlets.config.loader.Config({"ip": self.ip})
        #config.HistoryManager.enabled = False
        app = IPKernelApp.instance(log=logger)
        from namespace import InstrumentedNamespace
        app.user_ns = InstrumentedNamespace()
        app.initialize([])  # Redirects stdout/stderr
        #log.std_redirect(logger)   # Uncomment for debugging
        # This function should be called via atexit, but it isn't, perhaps due
        # to forking. Stale connection files do cause problems.
        app.cleanup_connection_file()
        kernel_init.initialize(app.kernel)
        for r, limit in self.rlimits.iteritems():
            resource.setrlimit(getattr(resource, r), (limit, limit))
        logger.debug("kernel ready")
        context = zmq.Context.instance()
        socket = context.socket(zmq.PUSH)
        socket.connect("tcp://localhost:{}".format(self.waiter_port))
        socket.send_json({
            "id": self.id,
            "connection": {
                "key": app.session.key,                
                "ip": app.ip,
                "hb": app.hb_port,
                "iopub": app.iopub_port,
                "shell": app.shell_port,
                },
            "rlimits": self.rlimits,
            })
            
        def signal_handler(signum, frame):
            logger.info("received %s, shutting down", signum)
            # TODO: this may not be the best way to do it.
            app.kernel.do_shutdown(False)

        signal.signal(signal.SIGTERM, signal_handler)
        app.start()
        logger.debug("Kernel.run finished")
开发者ID:kwankyu,项目名称:sagecell,代码行数:53,代码来源:kernel_provider.py

示例9: start

# 需要导入模块: from ipykernel.kernelapp import IPKernelApp [as 别名]
# 或者: from ipykernel.kernelapp.IPKernelApp import instance [as 别名]
    def start(self):
        if self._timer is not None:
            raise Exception("IPython kernel is already running.")

        # The IPKernelApp initialization is based on the IPython source for
        # IPython.embed_kernel available here:
        # https://github.com/ipython/ipython/blob/rel-3.2.1/IPython/kernel/zmq/embed.py

        if IPKernelApp.initialized():
            app = IPKernelApp.instance()
        else:
            app = IPKernelApp.instance(
                outstream_class='ipyida.kernel.IDATeeOutStream'
            )
            app.initialize()

            main = app.kernel.shell._orig_sys_modules_main_mod
            if main is not None:
                sys.modules[app.kernel.shell._orig_sys_modules_main_name] = main
        
            # IPython <= 3.2.x will send exception to sys.__stderr__ instead of
            # sys.stderr. IDA's console will not be able to display exceptions if we
            # don't send it to IDA's sys.stderr. To fix this, we call both the
            # ipython's and IDA's excepthook (IDA's excepthook is actually Python's
            # default).
            sys.excepthook = wrap_excepthook(sys.excepthook)

        app.shell.set_completer_frame()

        app.kernel.start()
        app.kernel.do_one_iteration()
    
        self.connection_file = app.connection_file

        def ipython_kernel_iteration():
            app.kernel.do_one_iteration()
            return int(1000 * app.kernel._poll_interval)
        self._timer = idaapi.register_timer(int(1000 * app.kernel._poll_interval), ipython_kernel_iteration)
开发者ID:eset,项目名称:ipyida,代码行数:40,代码来源:kernel.py

示例10: get_connection_file

# 需要导入模块: from ipykernel.kernelapp import IPKernelApp [as 别名]
# 或者: from ipykernel.kernelapp.IPKernelApp import instance [as 别名]
def get_connection_file(app=None):
    """Return the path to the connection file of an app

    Parameters
    ----------
    app : IPKernelApp instance [optional]
        If unspecified, the currently running app will be used
    """
    if app is None:
        from ipykernel.kernelapp import IPKernelApp
        if not IPKernelApp.initialized():
            raise RuntimeError("app not specified, and not in a running Kernel")

        app = IPKernelApp.instance()
    return filefind(app.connection_file, ['.', app.connection_dir])
开发者ID:DataScience2016,项目名称:ipykernel,代码行数:17,代码来源:connect.py

示例11: main

# 需要导入模块: from ipykernel.kernelapp import IPKernelApp [as 别名]
# 或者: from ipykernel.kernelapp.IPKernelApp import instance [as 别名]
def main():
    # Remove this module's path from sys.path:
    try:
        sys.path.remove(osp.dirname(__file__))
    except ValueError:
        pass

    try:
        locals().pop('__file__')
    except KeyError:
        pass
    __doc__ = ''
    __name__ = '__main__'

    # Add current directory to sys.path (like for any standard Python interpreter
    # executed in interactive mode):
    sys.path.insert(0, '')

    # Fire up the kernel instance.
    from ipykernel.kernelapp import IPKernelApp

    if not IS_EXT_INTERPRETER:
        from spyder.utils.ipython.spyder_kernel import SpyderKernel
    else:
        # We add "spyder" to sys.path for external interpreters,
        # so this works!
        # See create_kernel_spec of plugins/ipythonconsole
        from utils.ipython.spyder_kernel import SpyderKernel

    kernel = IPKernelApp.instance()
    kernel.kernel_class = SpyderKernel
    try:
        kernel.config = kernel_config()
    except:
        pass
    kernel.initialize()

    # Set our own magics
    kernel.shell.register_magic_function(varexp)

    # Set Pdb class to be used by %debug and %pdb.
    # This makes IPython consoles to use the class defined in our
    # sitecustomize instead of their default one.
    import pdb
    kernel.shell.InteractiveTB.debugger_cls = pdb.Pdb

    # Start the (infinite) kernel event loop.
    kernel.start()
开发者ID:rlaverde,项目名称:spyder,代码行数:50,代码来源:start_kernel.py

示例12: gui_kernel

# 需要导入模块: from ipykernel.kernelapp import IPKernelApp [as 别名]
# 或者: from ipykernel.kernelapp.IPKernelApp import instance [as 别名]
def gui_kernel(gui_backend):
    """ Launch and return an IPython kernel GUI with support.

    Parameters
    ----------
    gui_backend -- string or None
      The GUI mode used to initialize the GUI mode. For options, see
      the `ipython --gui` help pages. If None, the kernel is initialized
      without GUI support.
    """

    kernel = IPKernelApp.instance()

    argv = ['python']
    if gui_backend is not None:
        argv.append('--gui={}'.format(gui_backend))
    kernel.initialize(argv)

    return kernel
开发者ID:enthought,项目名称:envisage,代码行数:21,代码来源:internal_ipkernel.py

示例13: main

# 需要导入模块: from ipykernel.kernelapp import IPKernelApp [as 别名]
# 或者: from ipykernel.kernelapp.IPKernelApp import instance [as 别名]
def main():
    # Remove this module's path from sys.path:
    try:
        sys.path.remove(osp.dirname(__file__))
    except ValueError:
        pass

    try:
        locals().pop('__file__')
    except KeyError:
        pass
    __doc__ = ''
    __name__ = '__main__'

    # Add current directory to sys.path (like for any standard Python interpreter
    # executed in interactive mode):
    sys.path.insert(0, '')

    # Fire up the kernel instance.
    from ipykernel.kernelapp import IPKernelApp

    if not IS_EXT_INTERPRETER:
        from spyder.utils.ipython.spyder_kernel import SpyderKernel
    else:
        # We add "spyder" to sys.path for external interpreters,
        # so this works!
        # See create_kernel_spec of plugins/ipythonconsole
        from utils.ipython.spyder_kernel import SpyderKernel

    kernel = IPKernelApp.instance()
    kernel.kernel_class = SpyderKernel
    try:
        kernel.config = kernel_config()
    except:
        pass
    kernel.initialize()

    # NOTE: Leave this and other magic modifications *after* setting
    # __ipythonkernel__ to not have problems while starting kernels
    kernel.shell.register_magic_function(varexp)

    # Start the (infinite) kernel event loop.
    kernel.start()
开发者ID:jitseniesen,项目名称:spyder,代码行数:45,代码来源:start_kernel.py

示例14: setup_ipython

# 需要导入模块: from ipykernel.kernelapp import IPKernelApp [as 别名]
# 或者: from ipykernel.kernelapp.IPKernelApp import instance [as 别名]
    def setup_ipython():
        try:
            ipy = IPKernelApp.instance()

            # Keep a reference to the kernel even if this module is reloaded
            sys._ipython_app = ipy
            sys._ipython_kernel_running = True

            # patch user_global_ns so that it always references the user_ns dict
            setattr(ipy.shell.__class__, 'user_global_ns', property(lambda self: self.user_ns))

            # patch ipapp so anything else trying to get a terminal app (e.g. ipdb) gets our IPKernalApp.
            TerminalIPythonApp.instance = lambda: ipy
            __builtins__["get_ipython"] = lambda: ipy.shell.__class__

            # Use the inline matplotlib backend
            mpl = ipy.shell.find_magic("matplotlib")
            if mpl:
                mpl("inline")
        finally:
            event.set()
开发者ID:pyxll,项目名称:pyxll-examples,代码行数:23,代码来源:ipython.py

示例15: default_kernel_app

# 需要导入模块: from ipykernel.kernelapp import IPKernelApp [as 别名]
# 或者: from ipykernel.kernelapp.IPKernelApp import instance [as 别名]
def default_kernel_app():
    """ Return a configured IPKernelApp """

    def event_loop(kernel):
        """ Non-blocking qt event loop."""
        kernel.timer = QtCore.QTimer()
        kernel.timer.timeout.connect(kernel.do_one_iteration)
        kernel.timer.start(1000 * kernel._poll_interval)

    app = IPKernelApp.instance()
    try:
        app.initialize(['python', '--pylab=qt'])
    except ZMQError:
        pass  # already set up

    app.kernel.eventloop = event_loop

    try:
        app.start()
    except RuntimeError:  # already started
        pass

    return app
开发者ID:feldman4,项目名称:glue,代码行数:25,代码来源:terminal.py


注:本文中的ipykernel.kernelapp.IPKernelApp.instance方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。