You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
2.0 KiB

4 years ago
  1. """Simple function for embedding an IPython kernel
  2. """
  3. #-----------------------------------------------------------------------------
  4. # Imports
  5. #-----------------------------------------------------------------------------
  6. import sys
  7. from IPython.utils.frame import extract_module_locals
  8. from .kernelapp import IPKernelApp
  9. #-----------------------------------------------------------------------------
  10. # Code
  11. #-----------------------------------------------------------------------------
  12. def embed_kernel(module=None, local_ns=None, **kwargs):
  13. """Embed and start an IPython kernel in a given scope.
  14. Parameters
  15. ----------
  16. module : ModuleType, optional
  17. The module to load into IPython globals (default: caller)
  18. local_ns : dict, optional
  19. The namespace to load into IPython user namespace (default: caller)
  20. kwargs : various, optional
  21. Further keyword args are relayed to the IPKernelApp constructor,
  22. allowing configuration of the Kernel. Will only have an effect
  23. on the first embed_kernel call for a given process.
  24. """
  25. # get the app if it exists, or set it up if it doesn't
  26. if IPKernelApp.initialized():
  27. app = IPKernelApp.instance()
  28. else:
  29. app = IPKernelApp.instance(**kwargs)
  30. app.initialize([])
  31. # Undo unnecessary sys module mangling from init_sys_modules.
  32. # This would not be necessary if we could prevent it
  33. # in the first place by using a different InteractiveShell
  34. # subclass, as in the regular embed case.
  35. main = app.kernel.shell._orig_sys_modules_main_mod
  36. if main is not None:
  37. sys.modules[app.kernel.shell._orig_sys_modules_main_name] = main
  38. # load the calling scope if not given
  39. (caller_module, caller_locals) = extract_module_locals(1)
  40. if module is None:
  41. module = caller_module
  42. if local_ns is None:
  43. local_ns = caller_locals
  44. app.kernel.user_module = module
  45. app.kernel.user_ns = local_ns
  46. app.shell.set_completer_frame()
  47. app.start()