##// END OF EJS Templates
move IPKernelApp from zmq.ipkernel to zmq.kernelapp...
MinRK -
Show More
@@ -0,0 +1,57 b''
1 """Simple function for embedding an IPython kernel
2 """
3 #-----------------------------------------------------------------------------
4 # Imports
5 #-----------------------------------------------------------------------------
6
7 import sys
8
9 from IPython.utils.frame import extract_module_locals
10
11 from kernelapp import IPKernelApp
12
13 #-----------------------------------------------------------------------------
14 # Code
15 #-----------------------------------------------------------------------------
16
17 def embed_kernel(module=None, local_ns=None, **kwargs):
18 """Embed and start an IPython kernel in a given scope.
19
20 Parameters
21 ----------
22 module : ModuleType, optional
23 The module to load into IPython globals (default: caller)
24 local_ns : dict, optional
25 The namespace to load into IPython user namespace (default: caller)
26
27 kwargs : various, optional
28 Further keyword args are relayed to the KernelApp constructor,
29 allowing configuration of the Kernel. Will only have an effect
30 on the first embed_kernel call for a given process.
31
32 """
33 # get the app if it exists, or set it up if it doesn't
34 if IPKernelApp.initialized():
35 app = IPKernelApp.instance()
36 else:
37 app = IPKernelApp.instance(**kwargs)
38 app.initialize([])
39 # Undo unnecessary sys module mangling from init_sys_modules.
40 # This would not be necessary if we could prevent it
41 # in the first place by using a different InteractiveShell
42 # subclass, as in the regular embed case.
43 main = app.kernel.shell._orig_sys_modules_main_mod
44 if main is not None:
45 sys.modules[app.kernel.shell._orig_sys_modules_main_name] = main
46
47 # load the calling scope if not given
48 (caller_module, caller_locals) = extract_module_locals(1)
49 if module is None:
50 module = caller_module
51 if local_ns is None:
52 local_ns = caller_locals
53
54 app.kernel.user_module = module
55 app.kernel.user_ns = local_ns
56 app.shell.set_completer_frame()
57 app.start()
@@ -81,5 +81,5 b' def embed_kernel(module=None, local_ns=None, **kwargs):'
81 81 local_ns = caller_locals
82 82
83 83 # Only import .zmq when we really need it
84 from .zmq.ipkernel import embed_kernel as real_embed_kernel
84 from .zmq.embed import embed_kernel as real_embed_kernel
85 85 real_embed_kernel(module=module, local_ns=local_ns, **kwargs)
@@ -42,9 +42,9 b' from IPython.utils.py3compat import str_to_bytes'
42 42 from IPython.utils.traitlets import (
43 43 Dict, List, Unicode, CUnicode, Int, CBool, Any, CaselessStrEnum
44 44 )
45 from IPython.zmq.ipkernel import (
46 flags as ipkernel_flags,
47 aliases as ipkernel_aliases,
45 from IPython.zmq.kernelapp import (
46 kernel_flags,
47 kernel_aliases,
48 48 IPKernelApp
49 49 )
50 50 from IPython.zmq.session import Session, default_secure
@@ -65,7 +65,7 b' from IPython.utils.localinterfaces import LOCALHOST, LOCAL_IPS'
65 65 # Aliases and Flags
66 66 #-----------------------------------------------------------------------------
67 67
68 flags = dict(ipkernel_flags)
68 flags = dict(kernel_flags)
69 69
70 70 # the flags that are specific to the frontend
71 71 # these must be scrubbed before being passed to the kernel,
@@ -85,7 +85,7 b' app_flags.update(boolean_flag('
85 85 ))
86 86 flags.update(app_flags)
87 87
88 aliases = dict(ipkernel_aliases)
88 aliases = dict(kernel_aliases)
89 89
90 90 # also scrub aliases from the frontend
91 91 app_aliases = dict(
@@ -63,9 +63,9 b' from IPython.core.profiledir import ProfileDir'
63 63 from IPython.frontend.consoleapp import IPythonConsoleApp
64 64 from IPython.zmq.session import Session, default_secure
65 65 from IPython.zmq.zmqshell import ZMQInteractiveShell
66 from IPython.zmq.ipkernel import (
67 flags as ipkernel_flags,
68 aliases as ipkernel_aliases,
66 from IPython.zmq.kernelapp import (
67 kernel_flags,
68 kernel_aliases,
69 69 IPKernelApp
70 70 )
71 71 from IPython.utils.importstring import import_item
@@ -195,7 +195,7 b' class NotebookWebApplication(web.Application):'
195 195 # Aliases and Flags
196 196 #-----------------------------------------------------------------------------
197 197
198 flags = dict(ipkernel_flags)
198 flags = dict(kernel_flags)
199 199 flags['no-browser']=(
200 200 {'NotebookApp' : {'open_browser' : False}},
201 201 "Don't open the notebook in a browser after startup."
@@ -234,7 +234,7 b" flags.update(boolean_flag('script', 'FileNotebookManager.save_script',"
234 234 # or it will raise an error on unrecognized flags
235 235 notebook_flags = ['no-browser', 'no-mathjax', 'read-only', 'script', 'no-script']
236 236
237 aliases = dict(ipkernel_aliases)
237 aliases = dict(kernel_aliases)
238 238
239 239 aliases.update({
240 240 'ip': 'NotebookApp.ip',
@@ -71,7 +71,7 b' from IPython.utils.py3compat import str_to_bytes'
71 71 from IPython.utils.traitlets import (
72 72 Dict, List, Unicode, Integer, CaselessStrEnum, CBool, Any
73 73 )
74 from IPython.zmq.ipkernel import IPKernelApp
74 from IPython.zmq.kernelapp import IPKernelApp
75 75 from IPython.zmq.session import Session, default_secure
76 76 from IPython.zmq.zmqshell import ZMQInteractiveShell
77 77
@@ -24,7 +24,7 b' from IPython.utils.traitlets import ('
24 24 )
25 25 from IPython.utils.warn import warn,error
26 26
27 from IPython.zmq.ipkernel import IPKernelApp
27 from IPython.zmq.kernelapp import IPKernelApp
28 28 from IPython.zmq.session import Session, default_secure
29 29 from IPython.zmq.zmqshell import ZMQInteractiveShell
30 30 from IPython.frontend.consoleapp import (
@@ -233,7 +233,7 b' class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):'
233 233 profile = ("IPython.core.profileapp.ProfileApp",
234 234 "Create and manage IPython profiles."
235 235 ),
236 kernel = ("IPython.zmq.ipkernel.IPKernelApp",
236 kernel = ("IPython.zmq.kernelapp.IPKernelApp",
237 237 "Start a kernel without an attached frontend."
238 238 ),
239 239 console=('IPython.frontend.terminal.console.app.ZMQTerminalIPythonApp',
@@ -127,7 +127,7 b' def get_connection_file(app=None):'
127 127 If unspecified, the currently running app will be used
128 128 """
129 129 if app is None:
130 from IPython.zmq.ipkernel import IPKernelApp
130 from IPython.zmq.kernelapp import IPKernelApp
131 131 if not IPKernelApp.initialized():
132 132 raise RuntimeError("app not specified, and not in a running Kernel")
133 133
@@ -50,7 +50,7 b' def bind_kernel(**kwargs):'
50 50
51 51 This function returns immediately.
52 52 """
53 from IPython.zmq.ipkernel import IPKernelApp
53 from IPython.zmq.kernelapp import IPKernelApp
54 54 from IPython.parallel.apps.ipengineapp import IPEngineApp
55 55
56 56 # first check for IPKernelApp, in which case this should be a no-op
@@ -37,7 +37,8 b' from IPython.parallel.apps.baseapp import ('
37 37 catch_config_error,
38 38 )
39 39 from IPython.zmq.log import EnginePUBHandler
40 from IPython.zmq.ipkernel import Kernel, IPKernelApp
40 from IPython.zmq.ipkernel import Kernel
41 from IPython.zmq.kernelapp import IPKernelApp
41 42 from IPython.zmq.session import (
42 43 Session, session_aliases, session_flags
43 44 )
@@ -35,7 +35,8 b' from IPython.parallel.factory import RegistrationFactory'
35 35 from IPython.parallel.util import disambiguate_url
36 36
37 37 from IPython.zmq.session import Message
38 from IPython.zmq.ipkernel import Kernel, IPKernelApp
38 from IPython.zmq.ipkernel import Kernel
39 from IPython.zmq.kernelapp import IPKernelApp
39 40
40 41 class EngineFactory(RegistrationFactory):
41 42 """IPython engine"""
@@ -17,7 +17,6 b' from __future__ import print_function'
17 17
18 18 # Standard library imports
19 19 import __builtin__
20 import atexit
21 20 import sys
22 21 import time
23 22 import traceback
@@ -36,25 +35,18 b' from zmq.eventloop.zmqstream import ZMQStream'
36 35
37 36 # Local imports
38 37 from IPython.config.configurable import Configurable
39 from IPython.config.application import boolean_flag, catch_config_error
40 from IPython.core.application import ProfileDir
41 38 from IPython.core.error import StdinNotImplementedError
42 39 from IPython.core import release
43 from IPython.core.shellapp import (
44 InteractiveShellApp, shell_flags, shell_aliases
45 )
46 40 from IPython.utils import io
47 41 from IPython.utils import py3compat
48 from IPython.utils.frame import extract_module_locals
49 42 from IPython.utils.jsonutil import json_clean
50 43 from IPython.utils.traitlets import (
51 44 Any, Instance, Float, Dict, CaselessStrEnum, List, Set, Integer, Unicode,
52 45 Type
53 46 )
54 47
55 from kernelapp import KernelApp, kernel_flags, kernel_aliases
56 48 from serialize import serialize_object, unpack_apply_message
57 from session import Session, Message
49 from session import Session
58 50 from zmqshell import ZMQInteractiveShell
59 51
60 52
@@ -785,139 +777,3 b' class Kernel(Configurable):'
785 777 self.log.debug("%s", self._shutdown_message)
786 778 [ s.flush(zmq.POLLOUT) for s in self.shell_streams ]
787 779
788 #-----------------------------------------------------------------------------
789 # Aliases and Flags for the IPKernelApp
790 #-----------------------------------------------------------------------------
791
792 flags = dict(kernel_flags)
793 flags.update(shell_flags)
794
795 addflag = lambda *args: flags.update(boolean_flag(*args))
796
797 flags['pylab'] = (
798 {'IPKernelApp' : {'pylab' : 'auto'}},
799 """Pre-load matplotlib and numpy for interactive use with
800 the default matplotlib backend."""
801 )
802
803 aliases = dict(kernel_aliases)
804 aliases.update(shell_aliases)
805
806 #-----------------------------------------------------------------------------
807 # The IPKernelApp class
808 #-----------------------------------------------------------------------------
809
810 class IPKernelApp(KernelApp, InteractiveShellApp):
811 name = 'ipkernel'
812
813 aliases = Dict(aliases)
814 flags = Dict(flags)
815 classes = [Kernel, ZMQInteractiveShell, ProfileDir, Session]
816
817 @catch_config_error
818 def initialize(self, argv=None):
819 super(IPKernelApp, self).initialize(argv)
820 self.init_path()
821 self.init_shell()
822 self.init_gui_pylab()
823 self.init_extensions()
824 self.init_code()
825
826 def init_kernel(self):
827
828 shell_stream = ZMQStream(self.shell_socket)
829
830 kernel = Kernel(config=self.config, session=self.session,
831 shell_streams=[shell_stream],
832 iopub_socket=self.iopub_socket,
833 stdin_socket=self.stdin_socket,
834 log=self.log,
835 profile_dir=self.profile_dir,
836 )
837 self.kernel = kernel
838 kernel.record_ports(self.ports)
839 shell = kernel.shell
840
841 def init_gui_pylab(self):
842 """Enable GUI event loop integration, taking pylab into account."""
843
844 # Provide a wrapper for :meth:`InteractiveShellApp.init_gui_pylab`
845 # to ensure that any exception is printed straight to stderr.
846 # Normally _showtraceback associates the reply with an execution,
847 # which means frontends will never draw it, as this exception
848 # is not associated with any execute request.
849
850 shell = self.shell
851 _showtraceback = shell._showtraceback
852 try:
853 # replace pyerr-sending traceback with stderr
854 def print_tb(etype, evalue, stb):
855 print ("GUI event loop or pylab initialization failed",
856 file=io.stderr)
857 print (shell.InteractiveTB.stb2text(stb), file=io.stderr)
858 shell._showtraceback = print_tb
859 InteractiveShellApp.init_gui_pylab(self)
860 finally:
861 shell._showtraceback = _showtraceback
862
863 def init_shell(self):
864 self.shell = self.kernel.shell
865 self.shell.configurables.append(self)
866
867
868 #-----------------------------------------------------------------------------
869 # Kernel main and launch functions
870 #-----------------------------------------------------------------------------
871
872
873 def embed_kernel(module=None, local_ns=None, **kwargs):
874 """Embed and start an IPython kernel in a given scope.
875
876 Parameters
877 ----------
878 module : ModuleType, optional
879 The module to load into IPython globals (default: caller)
880 local_ns : dict, optional
881 The namespace to load into IPython user namespace (default: caller)
882
883 kwargs : various, optional
884 Further keyword args are relayed to the KernelApp constructor,
885 allowing configuration of the Kernel. Will only have an effect
886 on the first embed_kernel call for a given process.
887
888 """
889 # get the app if it exists, or set it up if it doesn't
890 if IPKernelApp.initialized():
891 app = IPKernelApp.instance()
892 else:
893 app = IPKernelApp.instance(**kwargs)
894 app.initialize([])
895 # Undo unnecessary sys module mangling from init_sys_modules.
896 # This would not be necessary if we could prevent it
897 # in the first place by using a different InteractiveShell
898 # subclass, as in the regular embed case.
899 main = app.kernel.shell._orig_sys_modules_main_mod
900 if main is not None:
901 sys.modules[app.kernel.shell._orig_sys_modules_main_name] = main
902
903 # load the calling scope if not given
904 (caller_module, caller_locals) = extract_module_locals(1)
905 if module is None:
906 module = caller_module
907 if local_ns is None:
908 local_ns = caller_locals
909
910 app.kernel.user_module = module
911 app.kernel.user_ns = local_ns
912 app.shell.set_completer_frame()
913 app.start()
914
915 def main():
916 """Run an IPKernel as an application"""
917 app = IPKernelApp.instance()
918 app.initialize()
919 app.start()
920
921
922 if __name__ == '__main__':
923 main()
@@ -15,6 +15,8 b' Authors'
15 15 # Imports
16 16 #-----------------------------------------------------------------------------
17 17
18 from __future__ import print_function
19
18 20 # Standard library imports
19 21 import atexit
20 22 import json
@@ -25,12 +27,17 b' import signal'
25 27 # System library imports
26 28 import zmq
27 29 from zmq.eventloop import ioloop
30 from zmq.eventloop.zmqstream import ZMQStream
28 31
29 32 # IPython imports
30 33 from IPython.core.ultratb import FormattedTB
31 34 from IPython.core.application import (
32 35 BaseIPythonApplication, base_flags, base_aliases, catch_config_error
33 36 )
37 from IPython.core.profiledir import ProfileDir
38 from IPython.core.shellapp import (
39 InteractiveShellApp, shell_flags, shell_aliases
40 )
34 41 from IPython.utils import io
35 42 from IPython.utils.localinterfaces import LOCALHOST
36 43 from IPython.utils.path import filefind
@@ -41,13 +48,15 b' from IPython.utils.traitlets import ('
41 48 )
42 49 from IPython.utils.importstring import import_item
43 50 from IPython.kernel import write_connection_file
51
44 52 # local imports
45 from IPython.zmq.heartbeat import Heartbeat
46 from IPython.zmq.parentpoller import ParentPollerUnix, ParentPollerWindows
47 from IPython.zmq.session import (
53 from heartbeat import Heartbeat
54 from ipkernel import Kernel
55 from parentpoller import ParentPollerUnix, ParentPollerWindows
56 from session import (
48 57 Session, session_flags, session_aliases, default_secure,
49 58 )
50
59 from zmqshell import ZMQInteractiveShell
51 60
52 61 #-----------------------------------------------------------------------------
53 62 # Flags and Aliases
@@ -55,14 +64,14 b' from IPython.zmq.session import ('
55 64
56 65 kernel_aliases = dict(base_aliases)
57 66 kernel_aliases.update({
58 'ip' : 'KernelApp.ip',
59 'hb' : 'KernelApp.hb_port',
60 'shell' : 'KernelApp.shell_port',
61 'iopub' : 'KernelApp.iopub_port',
62 'stdin' : 'KernelApp.stdin_port',
63 'f' : 'KernelApp.connection_file',
64 'parent': 'KernelApp.parent',
65 'transport': 'KernelApp.transport',
67 'ip' : 'IPKernelApp.ip',
68 'hb' : 'IPKernelApp.hb_port',
69 'shell' : 'IPKernelApp.shell_port',
70 'iopub' : 'IPKernelApp.iopub_port',
71 'stdin' : 'IPKernelApp.stdin_port',
72 'f' : 'IPKernelApp.connection_file',
73 'parent': 'IPKernelApp.parent',
74 'transport': 'IPKernelApp.transport',
66 75 })
67 76 if sys.platform.startswith('win'):
68 77 kernel_aliases['interrupt'] = 'KernelApp.interrupt'
@@ -70,28 +79,34 b" if sys.platform.startswith('win'):"
70 79 kernel_flags = dict(base_flags)
71 80 kernel_flags.update({
72 81 'no-stdout' : (
73 {'KernelApp' : {'no_stdout' : True}},
82 {'IPKernelApp' : {'no_stdout' : True}},
74 83 "redirect stdout to the null device"),
75 84 'no-stderr' : (
76 {'KernelApp' : {'no_stderr' : True}},
85 {'IPKernelApp' : {'no_stderr' : True}},
77 86 "redirect stderr to the null device"),
87 'pylab' : (
88 {'IPKernelApp' : {'pylab' : 'auto'}},
89 """Pre-load matplotlib and numpy for interactive use with
90 the default matplotlib backend."""),
78 91 })
79 92
93 # inherit flags&aliases for any IPython shell apps
94 kernel_aliases.update(shell_aliases)
95 kernel_flags.update(shell_flags)
96
80 97 # inherit flags&aliases for Sessions
81 98 kernel_aliases.update(session_aliases)
82 99 kernel_flags.update(session_flags)
83 100
84
85
86 101 #-----------------------------------------------------------------------------
87 # Application class for starting a Kernel
102 # Application class for starting an IPython Kernel
88 103 #-----------------------------------------------------------------------------
89 104
90 class KernelApp(BaseIPythonApplication):
105 class IPKernelApp(BaseIPythonApplication, InteractiveShellApp):
91 106 name='ipkernel'
92 107 aliases = Dict(kernel_aliases)
93 108 flags = Dict(kernel_flags)
94 classes = [Session]
109 classes = [Kernel, ZMQInteractiveShell, ProfileDir, Session]
95 110 # the kernel class, as an importstring
96 111 kernel_class = DottedObjectName('IPython.zmq.ipkernel.Kernel')
97 112 kernel = Any()
@@ -332,18 +347,47 b' class KernelApp(BaseIPythonApplication):'
332 347
333 348 def init_kernel(self):
334 349 """Create the Kernel object itself"""
335 kernel_factory = import_item(str(self.kernel_class))
336 self.kernel = kernel_factory(config=self.config, session=self.session,
337 shell_socket=self.shell_socket,
350 shell_stream = ZMQStream(self.shell_socket)
351
352 kernel = Kernel(config=self.config, session=self.session,
353 shell_streams=[shell_stream],
338 354 iopub_socket=self.iopub_socket,
339 355 stdin_socket=self.stdin_socket,
340 log=self.log
356 log=self.log,
357 profile_dir=self.profile_dir,
341 358 )
342 self.kernel.record_ports(self.ports)
359 kernel.record_ports(self.ports)
360 self.kernel = kernel
361
362 def init_gui_pylab(self):
363 """Enable GUI event loop integration, taking pylab into account."""
364
365 # Provide a wrapper for :meth:`InteractiveShellApp.init_gui_pylab`
366 # to ensure that any exception is printed straight to stderr.
367 # Normally _showtraceback associates the reply with an execution,
368 # which means frontends will never draw it, as this exception
369 # is not associated with any execute request.
370
371 shell = self.shell
372 _showtraceback = shell._showtraceback
373 try:
374 # replace pyerr-sending traceback with stderr
375 def print_tb(etype, evalue, stb):
376 print ("GUI event loop or pylab initialization failed",
377 file=io.stderr)
378 print (shell.InteractiveTB.stb2text(stb), file=io.stderr)
379 shell._showtraceback = print_tb
380 InteractiveShellApp.init_gui_pylab(self)
381 finally:
382 shell._showtraceback = _showtraceback
383
384 def init_shell(self):
385 self.shell = self.kernel.shell
386 self.shell.configurables.append(self)
343 387
344 388 @catch_config_error
345 389 def initialize(self, argv=None):
346 super(KernelApp, self).initialize(argv)
390 super(IPKernelApp, self).initialize(argv)
347 391 self.init_blackhole()
348 392 self.init_connection_file()
349 393 self.init_session()
@@ -356,6 +400,12 b' class KernelApp(BaseIPythonApplication):'
356 400 self.init_io()
357 401 self.init_signal()
358 402 self.init_kernel()
403 # shell init steps
404 self.init_path()
405 self.init_shell()
406 self.init_gui_pylab()
407 self.init_extensions()
408 self.init_code()
359 409 # flush stdout/stderr, so that anything written to these streams during
360 410 # initialization do not get associated with the first execution request
361 411 sys.stdout.flush()
@@ -370,3 +420,13 b' class KernelApp(BaseIPythonApplication):'
370 420 except KeyboardInterrupt:
371 421 pass
372 422
423
424 def main():
425 """Run an IPKernel as an application"""
426 app = IPKernelApp.instance()
427 app.initialize()
428 app.start()
429
430
431 if __name__ == '__main__':
432 main()
@@ -903,7 +903,7 b' class KernelManager(Configurable):'
903 903 cmd = self.kernel_cmd
904 904 else:
905 905 cmd = make_ipkernel_cmd(
906 'from IPython.zmq.ipkernel import main; main()',
906 'from IPython.zmq.kernelapp import main; main()',
907 907 **kw
908 908 )
909 909 ns = dict(connection_file=self.connection_file)
General Comments 0
You need to be logged in to leave comments. Login now