本文整理汇总了Python中IPython.kernel.zmq.kernelapp.IPKernelApp类的典型用法代码示例。如果您正苦于以下问题:Python IPKernelApp类的具体用法?Python IPKernelApp怎么用?Python IPKernelApp使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了IPKernelApp类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_connection_file
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])
示例2: start
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)
示例3: fork_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()
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()
示例4: bind_kernel
def bind_kernel(**kwargs):
"""Bind an Engine's Kernel to be used as a full IPython kernel.
This allows a running Engine to be used simultaneously as a full IPython kernel
with the QtConsole or other frontends.
This function returns immediately.
"""
from IPython.kernel.zmq.kernelapp import IPKernelApp
from IPython.parallel.apps.ipengineapp import IPEngineApp
# first check for IPKernelApp, in which case this should be a no-op
# because there is already a bound kernel
if IPKernelApp.initialized() and isinstance(IPKernelApp._instance, IPKernelApp):
return
if IPEngineApp.initialized():
try:
app = IPEngineApp.instance()
except MultipleInstanceError:
pass
else:
return app.bind_kernel(**kwargs)
raise RuntimeError("bind_kernel be called from an IPEngineApp instance")
示例5: _BlockOnRawInputReplyZMQ
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
示例6: 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()
示例7: pylab_kernel
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
示例8: mpl_kernel
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
示例9: embed_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()
示例10: mpl_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
示例11: execute
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}
示例12: fork_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()
示例13: _start_kernel
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
示例14: main
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()
示例15: __init__
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