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) # Load the calling scope (ida_module, ida_locals) = IPython.utils.frame.extract_module_locals(1) if 'idaapi' not in ida_locals: raise Exception("{0:s} must be called from idapythonrc.py or " "IDA's prompt.".format("IPythonKernel.start")) app.kernel.user_module = ida_module app.kernel.user_ns = ida_locals 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)
def _BlockOnRawInputReplyZMQ(): """Blocks until a message in the stdin channel is recieved. Returns: The value of the message, which is assumed to be of type raw_input_reply """ # pylint: disable=g-import-not-at-top from IPython.kernel.zmq.kernelapp import IPKernelApp app = IPKernelApp.instance() kernel = app.kernel stdin_socket = kernel.stdin_socket while True: try: _, reply = kernel.session.recv(stdin_socket, 0) except Exception: # Handle invalid message pass except KeyboardInterrupt: # re-raise KeyboardInterrupt, to truncate traceback raise KeyboardInterrupt else: break try: value = reply['content']['value'] except KeyError: # handle bad raw_input reply value = '' return value
def fork_kernel(self, config, pipe, resource_limits, logfile): """ A function to be set as the target for the new kernel processes forked in ForkingKernelManager.start_kernel. This method forks and initializes a new kernel, uses the update_function to update the kernel's namespace, sets resource limits for the kernel, and sends kernel connection information through the Pipe object. :arg IPython.config.loader config: kernel configuration :arg multiprocessing.Pipe pipe: a multiprocessing connection object which will send kernel ip, session, and port information to the other side :arg dict resource_limits: a dict with keys resource.RLIMIT_* (see config_default documentation for explanation of valid options) and values of the limit for the given resource to be set in the kernel process """ os.setpgrp() logging.basicConfig(filename=self.filename,format=str(uuid.uuid4()).split('-')[0]+': %(asctime)s %(message)s',level=logging.DEBUG) logging.debug("kernel forked; now starting and configuring") try: ka = IPKernelApp.instance(config=config, ip=config["ip"]) from namespace import InstrumentedNamespace ka.user_ns = InstrumentedNamespace() ka.initialize([]) except: logging.exception("Error initializing IPython kernel") try: if self.update_function is not None: self.update_function(ka) except: logging.exception("Error configuring up kernel") logging.debug("finished updating") for r, limit in resource_limits.iteritems(): resource.setrlimit(getattr(resource, r), (limit, limit)) pipe.send({"ip": ka.ip, "key": ka.session.key, "shell_port": ka.shell_port, "stdin_port": ka.stdin_port, "hb_port": ka.hb_port, "iopub_port": ka.iopub_port}) pipe.close() ka.start()
def fork_kernel(self, config, pipe, resource_limits, logfile): """ A function to be set as the target for the new kernel processes forked in ForkingKernelManager.start_kernel. This method forks and initializes a new kernel, uses the update_function to update the kernel's namespace, sets resource limits for the kernel, and sends kernel connection information through the Pipe object. :arg IPython.config.loader config: kernel configuration :arg multiprocessing.Pipe pipe: a multiprocessing connection object which will send kernel ip, session, and port information to the other side :arg dict resource_limits: a dict with keys resource.RLIMIT_* (see config_default documentation for explanation of valid options) and values of the limit for the given resource to be set in the kernel process """ os.setpgrp() logging.basicConfig(filename=self.filename,format=str(uuid.uuid4()).split('-')[0]+': %(asctime)s %(message)s',level=logging.DEBUG) logging.debug("kernel forked; now configuring") ka = IPKernelApp.instance(config=config, ip=config["ip"]) ka.initialize([]) logging.debug("now updating") try: if self.update_function is not None: self.update_function(ka) except: logging.exception("Error setting up kernel") logging.debug("finished updating") for r, limit in resource_limits.iteritems(): resource.setrlimit(getattr(resource, r), (limit, limit)) pipe.send({"ip": ka.ip, "key": ka.session.key, "shell_port": ka.shell_port, "stdin_port": ka.stdin_port, "hb_port": ka.hb_port, "iopub_port": ka.iopub_port}) pipe.close() ka.start()
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()
def mpl_kernel(gui): """Launch and return an IPython kernel with matplotlib support for the desired gui """ kernel = IPKernelApp.instance() kernel.initialize(['python', '--matplotlib=%s' % gui, #'--log-level=10' ]) return kernel
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()
def pylab_kernel(gui): """Launch and return an IPython kernel with pylab support for the desired gui """ kernel = IPKernelApp.instance() kernel.initialize(['python', '--pylab=%s' % gui, #'--log-level=10' ]) return kernel
def fork_kernel(self, config, pipe, resource_limits, logfile): """ A function to be set as the target for the new kernel processes forked in ForkingKernelManager.start_kernel. This method forks and initializes a new kernel, uses the update_function to update the kernel's namespace, sets resource limits for the kernel, and sends kernel connection information through the Pipe object. :arg IPython.config.loader config: kernel configuration :arg multiprocessing.Pipe pipe: a multiprocessing connection object which will send kernel ip, session, and port information to the other side :arg dict resource_limits: a dict with keys resource.RLIMIT_* (see config_default documentation for explanation of valid options) and values of the limit for the given resource to be set in the kernel process """ os.setpgrp() logging.basicConfig(filename=self.filename, format=str(uuid.uuid4()).split('-')[0] + ': %(asctime)s %(message)s', level=logging.DEBUG) logging.debug("kernel forked; now starting and configuring") try: ka = IPKernelApp.instance(config=config, ip=config["ip"]) from namespace import InstrumentedNamespace ka.user_ns = InstrumentedNamespace() # The following line on UNIX systems (and we are unlikely to run on # Windows) will lead to creation of a 1-second poller that will kill # this process as soon as its parent dies. More importanly, it will # prevent from execution the following if block: # https://github.com/ipython/ipython/blob/rel-2.1.0/IPython/kernel/zmq/kernelapp.py#L348 # which probably was filling some output buffer and used to severely # limit the number of computations possible without restarting the # server. TODO: figure out a better fix or confirm this is the one! ka.parent_handle = True ka.initialize([]) except: logging.exception("Error initializing IPython kernel") # FIXME: What's the point in proceeding after?! try: if self.update_function is not None: self.update_function(ka) except: logging.exception("Error configuring up kernel") logging.debug("finished updating") for r, limit in resource_limits.iteritems(): resource.setrlimit(getattr(resource, r), (limit, limit)) pipe.send({ "ip": ka.ip, "key": ka.session.key, "shell_port": ka.shell_port, "stdin_port": ka.stdin_port, "hb_port": ka.hb_port, "iopub_port": ka.iopub_port }) pipe.close() # The following line will erase JSON connection file with ports and # other numbers. Since we do not reuse the kernels, we don't really need # these files. And new kernels set atexit hook to delete the file, but # it does not get called, perhaps because kernels are stopped by system # signals. The result is accumulation of files leading to disk quota # issues AND attempts to use stale files to connect to non-existing # kernels that eventually crash the server. TODO: figure out a better # fix, perhaps kernels have to be stopped in a more gentle fashion? ka.cleanup_connection_file() ka.start()
def mpl_kernel(gui): """Launch and return an IPython kernel with pylab (matplotlib and numpy) support for the desired gui """ kernel = IPKernelApp.instance() kernel.initialize(['python', '--pylab=%s' % gui,#'--matplotlib=%s' % gui, #'--log-level=10' ]) IPKernelApp.pylab = 'inline' return kernel
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([]) # 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 = module app.kernel.user_ns = local_ns # START custom if hasattr(app, 'shell') and app.shell: app.shell.set_completer_frame() # END custom app.start()
def mpl_kernel(gui): """Launch and return an IPython kernel with pylab (matplotlib and numpy) support for the desired gui """ kernel = IPKernelApp.instance() kernel.initialize([ 'python', '--pylab=%s' % gui, #'--matplotlib=%s' % gui, #'--log-level=10' ]) IPKernelApp.pylab = 'inline' return kernel
def mpl_kernel(gui): """Launch and return an IPython kernel with matplotlib support for the desired gui """ kernel = IPKernelApp.instance() kernel.initialize( [ "python", "--matplotlib=%s" % gui, #'--log-level=10' ] ) return kernel
def main(unused_argv): sys.argv = ORIG_ARGV if not IS_KERNEL: # Drop all flags. sys.argv = [sys.argv[0]] # NOTE(sadovsky): For some reason, putting this import at the top level # breaks inline plotting. It's probably a bug in the stone-age version of # matplotlib. from IPython.html.notebookapp import NotebookApp # pylint: disable=g-import-not-at-top notebookapp = NotebookApp.instance() notebookapp.open_browser = True # password functionality adopted from quality/ranklab/main/tools/notebook.py # add options to run with "password" if FLAGS.password: from IPython.lib import passwd # pylint: disable=g-import-not-at-top notebookapp.ip = "0.0.0.0" notebookapp.password = passwd(FLAGS.password) else: print( "\nNo password specified; Notebook server will only be available" " on the local machine.\n") notebookapp.initialize(argv=["--notebook-dir", FLAGS.notebook_dir]) if notebookapp.ip == "0.0.0.0": proto = "https" if notebookapp.certfile else "http" url = "%s://%s:%d%s" % (proto, socket.gethostname(), notebookapp.port, notebookapp.base_project_url) print("\nNotebook server will be publicly available at: %s\n" % url) notebookapp.start() return # Drop the --flagfile flag so that notebook doesn't complain about an # "unrecognized alias" when parsing sys.argv. sys.argv = ([sys.argv[0]] + [z for z in sys.argv[1:] if not z.startswith("--flagfile")]) from IPython.kernel.zmq.kernelapp import IPKernelApp # pylint: disable=g-import-not-at-top kernelapp = IPKernelApp.instance() kernelapp.initialize() # Enable inline plotting. Equivalent to running "%matplotlib inline". ipshell = kernelapp.shell ipshell.enable_matplotlib("inline") kernelapp.start()
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 IPython.kernel.zmq.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.profile_dir.security_dir])
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 IPython.kernel.zmq.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.profile_dir.security_dir])
def fork_kernel(self, config, pipe, resource_limits, logfile): """ A function to be set as the target for the new kernel processes forked in ForkingKernelManager.start_kernel. This method forks and initializes a new kernel, uses the update_function to update the kernel's namespace, sets resource limits for the kernel, and sends kernel connection information through the Pipe object. :arg IPython.config.loader config: kernel configuration :arg multiprocessing.Pipe pipe: a multiprocessing connection object which will send kernel ip, session, and port information to the other side :arg dict resource_limits: a dict with keys resource.RLIMIT_* (see config_default documentation for explanation of valid options) and values of the limit for the given resource to be set in the kernel process """ os.setpgrp() logging.basicConfig(filename=self.filename,format=str(uuid.uuid4()).split('-')[0]+': %(asctime)s %(message)s',level=logging.DEBUG) logging.debug("kernel forked; now starting and configuring") try: ka = IPKernelApp.instance(config=config, ip=config["ip"]) from namespace import InstrumentedNamespace ka.user_ns = InstrumentedNamespace() # The following line on UNIX systems (and we are unlikely to run on # Windows) will lead to creation of a 1-second poller that will kill # this process as soon as its parent dies. More importanly, it will # prevent from execution the following if block: # https://github.com/ipython/ipython/blob/rel-2.1.0/IPython/kernel/zmq/kernelapp.py#L348 # which probably was filling some output buffer and used to severely # limit the number of computations possible without restarting the # server. TODO: figure out a better fix or confirm this is the one! ka.parent_handle = True ka.initialize([]) except: logging.exception("Error initializing IPython kernel") # FIXME: What's the point in proceeding after?! try: if self.update_function is not None: self.update_function(ka) except: logging.exception("Error configuring up kernel") logging.debug("finished updating") for r, limit in resource_limits.iteritems(): resource.setrlimit(getattr(resource, r), (limit, limit)) pipe.send({"ip": ka.ip, "key": ka.session.key, "shell_port": ka.shell_port, "stdin_port": ka.stdin_port, "hb_port": ka.hb_port, "iopub_port": ka.iopub_port}) pipe.close() # The following line will erase JSON connection file with ports and # other numbers. Since we do not reuse the kernels, we don't really need # these files. And new kernels set atexit hook to delete the file, but # it does not get called, perhaps because kernels are stopped by system # signals. The result is accumulation of files leading to disk quota # issues AND attempts to use stale files to connect to non-existing # kernels that eventually crash the server. TODO: figure out a better # fix, perhaps kernels have to be stopped in a more gentle fashion? ka.cleanup_connection_file() ka.start()
def _start_kernel(): """starts the ipython kernel and returns the ipython app""" import IPython from IPython.kernel.zmq.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() return _ipython_app
def main(unused_argv): sys.argv = ORIG_ARGV if not IS_KERNEL: # Drop all flags. sys.argv = [sys.argv[0]] # NOTE(sadovsky): For some reason, putting this import at the top level # breaks inline plotting. It's probably a bug in the stone-age version of # matplotlib. from IPython.html.notebookapp import NotebookApp # pylint: disable=g-import-not-at-top notebookapp = NotebookApp.instance() notebookapp.open_browser = True # password functionality adopted from quality/ranklab/main/tools/notebook.py # add options to run with "password" if FLAGS.password: from IPython.lib import passwd # pylint: disable=g-import-not-at-top notebookapp.ip = "0.0.0.0" notebookapp.password = passwd(FLAGS.password) else: print("\nNo password specified; Notebook server will only be available" " on the local machine.\n") notebookapp.initialize(argv=["--notebook-dir", FLAGS.notebook_dir]) if notebookapp.ip == "0.0.0.0": proto = "https" if notebookapp.certfile else "http" url = "%s://%s:%d%s" % (proto, socket.gethostname(), notebookapp.port, notebookapp.base_project_url) print("\nNotebook server will be publicly available at: %s\n" % url) notebookapp.start() return # Drop the --flagfile flag so that notebook doesn't complain about an # "unrecognized alias" when parsing sys.argv. sys.argv = ([sys.argv[0]] + [z for z in sys.argv[1:] if not z.startswith("--flagfile")]) from IPython.kernel.zmq.kernelapp import IPKernelApp # pylint: disable=g-import-not-at-top kernelapp = IPKernelApp.instance() kernelapp.initialize() # Enable inline plotting. Equivalent to running "%matplotlib inline". ipshell = kernelapp.shell ipshell.enable_matplotlib("inline") kernelapp.start()
def _start_kernel(): """starts the ipython kernel and returns the ipython app""" import IPython from IPython.kernel.zmq.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() return _ipython_app
def __init__(self, gui): # Start IPython kernel with GUI event loop support self.ipkernel = IPKernelApp.instance() self.ipkernel.initialize(['python', '--gui=%s' % gui, #'--log-level=10' # for debugging ]) # To create and track active qt consoles self.consoles = [] # This application will also act on the shell user namespace self.namespace = self.ipkernel.shell.user_ns # Keys present at startup so we don't print the entire pylab/numpy # namespace when the user clicks the 'namespace' button self._init_keys = set(self.namespace.keys()) # Example: a variable that will be seen by the user in the shell, and # that the GUI modifies (the 'Counter++' button increments it): self.namespace['app_counter'] = 0
def __init__(self, gui): # Start IPython kernel with GUI event loop support self.ipkernel = IPKernelApp.instance() self.ipkernel.initialize(['python', '--gui=%s' % gui, #'--log-level=10' # for debugging ]) # To create and track active qt consoles self.consoles = [] # This application will also act on the shell user namespace self.namespace = self.ipkernel.shell.user_ns # Keys present at startup so we don't print the entire pylab/numpy # namespace when the user clicks the 'namespace' button self._init_keys = set(self.namespace.keys()) # Example: a variable that will be seen by the user in the shell, and # that the GUI modifies (the 'Counter++' button increments it): self.namespace['app_counter'] = 0
def mpl_kernel(gui_backend): """ Launch and return an IPython kernel with matplotlib support. Parameters ---------- gui_backend -- string or None The GUI mode used to initialize the matplotlib mode. For options, see the `ipython --matplotlib` help pages. If None, the kernel is initialized without GUI support. """ kernel = IPKernelApp.instance() argv = ['python'] if gui_backend is not None: argv.append('--matplotlib={}'.format(gui_backend)) kernel.initialize(argv) return kernel
def main(unused_argv): sys.argv = ORIG_ARGV if not IS_KERNEL: sys.argv = [sys.argv[0]] from IPython.html.notebookapp import NotebookApp notebookapp = NotebookApp.instance() notebookapp.open_browser = True if FLAGS.password: from IPython.lib import passwd notebook.ip = "0.0.0.0" notebook.password = passwd(FLAGS.password) else: print( "\nNo password specified: Notebook server will only be available" " on the local machine.\n") notebookapp.initialize(argv=["--notebook-dir", FLAGS.notebook_dir]) if notebookapp.ip == "0.0.0.0": proto = "https" if notebookapp.certfile else "http" url = "%s://%s:%d%s" % (proto, socket.gethostname(), notebookapp.port, notebookapp.base_project_url) print("\nNotebook server will be publicly available at: %s\n" % url) notebookapp.start() return sys.argv = ([sys.argv[0]] + [z for z in sys.argv[1:] if not z.startswith("--flagfile")]) from IPython.kernel.zmq.kernelapp import IPKernelApp kernelapp = IPKernelApp.instance() kernelapp.initialize() ipshell = kernelapp.shell ipshell.enable_matplotlib("inline") kernelapp.start()
def execute(self, arbiter, props): shell = 'kernel-%d.json' % os.getpid() msg = None try: from IPython.kernel.zmq.kernelapp import IPKernelApp if not IPKernelApp.initialized(): app = IPKernelApp.instance() 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 app.kernel.user_module = sys.modules[__name__] app.kernel.user_ns = {'arbiter': arbiter} app.shell.set_completer_frame() app.kernel.start() except Exception as e: shell = False msg = str(e) return {'shell': shell, 'msg': msg}
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
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
def execute(self, arbiter, props): shell = 'kernel-%d.json' % os.getpid() msg = None try: from IPython.kernel.zmq.kernelapp import IPKernelApp if not IPKernelApp.initialized(): app = IPKernelApp.instance() 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 app.kernel.user_module = sys.modules[__name__] app.kernel.user_ns = {'arbiter': arbiter} app.shell.set_completer_frame() app.kernel.start() except Exception as e: shell = False msg = str(e) return {'shell': shell, 'msg': msg}
try: sys.path.remove(osp.dirname(__file__)) except ValueError: pass locals().pop('__file__') __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 IPython.kernel.zmq.kernelapp import IPKernelApp ipk_temp = IPKernelApp.instance() ipk_temp.config = kernel_config() ipk_temp.initialize() # Grabbing the kernel's shell to share its namespace with our # Variable Explorer __ipythonshell__ = ipk_temp.shell # Issue 977 : Since kernel.initialize() has completed execution, # we can now allow the monitor to communicate the availablility of # the kernel to accept front end connections. __ipythonkernel__ = ipk_temp del ipk_temp # Change %edit to open files inside Spyder # NOTE: Leave this and other magic modifications *after* setting
try: sys.path.remove(osp.dirname(__file__)) except ValueError: pass locals().pop('__file__') __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 IPython.kernel.zmq.kernelapp import IPKernelApp ipk_temp = IPKernelApp.instance() ipk_temp.config = kernel_config() ipk_temp.initialize() # Grabbing the kernel's shell to share its namespace with our # Variable Explorer __ipythonshell__ = ipk_temp.shell # Issue 977 : Since kernel.initialize() has completed execution, # we can now allow the monitor to communicate the availablility of # the kernel to accept front end connections. __ipythonkernel__ = ipk_temp del ipk_temp # Change %edit to open files inside Spyder # NOTE: Leave this and other magic modifications *after* setting
def start(): kernel = IPKernelApp.instance(kernel_class=MyKernel) kernel.initialize() kernel.kernel.eventloop = loop_slicer kernel.start()
def default_kernel_app(): from IPython.kernel.zmq.kernelapp import IPKernelApp app = IPKernelApp.instance() app.initialize(['python', '--pylab=qt']) app.kernel.eventloop = event_loop return app