embed.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. # encoding: utf-8
  2. """
  3. An embedded IPython shell.
  4. """
  5. # Copyright (c) IPython Development Team.
  6. # Distributed under the terms of the Modified BSD License.
  7. from __future__ import with_statement
  8. from __future__ import print_function
  9. import sys
  10. import warnings
  11. from IPython.core import ultratb, compilerop
  12. from IPython.core.magic import Magics, magics_class, line_magic
  13. from IPython.core.interactiveshell import DummyMod, InteractiveShell
  14. from IPython.terminal.interactiveshell import TerminalInteractiveShell
  15. from IPython.terminal.ipapp import load_default_config
  16. from traitlets import Bool, CBool, Unicode
  17. from IPython.utils.io import ask_yes_no
  18. class KillEmbeded(Exception):pass
  19. # This is an additional magic that is exposed in embedded shells.
  20. @magics_class
  21. class EmbeddedMagics(Magics):
  22. @line_magic
  23. def kill_embedded(self, parameter_s=''):
  24. """%kill_embedded : deactivate for good the current embedded IPython.
  25. This function (after asking for confirmation) sets an internal flag so
  26. that an embedded IPython will never activate again. This is useful to
  27. permanently disable a shell that is being called inside a loop: once
  28. you've figured out what you needed from it, you may then kill it and
  29. the program will then continue to run without the interactive shell
  30. interfering again.
  31. """
  32. kill = ask_yes_no("Are you sure you want to kill this embedded instance? [y/N] ",'n')
  33. if kill:
  34. self.shell.embedded_active = False
  35. print ("This embedded IPython will not reactivate anymore "
  36. "once you exit.")
  37. @line_magic
  38. def exit_raise(self, parameter_s=''):
  39. """%exit_raise Make the current embedded kernel exit and raise and exception.
  40. This function sets an internal flag so that an embedded IPython will
  41. raise a `IPython.terminal.embed.KillEmbeded` Exception on exit, and then exit the current I. This is
  42. useful to permanently exit a loop that create IPython embed instance.
  43. """
  44. self.shell.should_raise = True
  45. self.shell.ask_exit()
  46. class InteractiveShellEmbed(TerminalInteractiveShell):
  47. dummy_mode = Bool(False)
  48. exit_msg = Unicode('')
  49. embedded = CBool(True)
  50. should_raise = CBool(False)
  51. # Like the base class display_banner is not configurable, but here it
  52. # is True by default.
  53. display_banner = CBool(True)
  54. exit_msg = Unicode()
  55. # When embedding, by default we don't change the terminal title
  56. term_title = Bool(False,
  57. help="Automatically set the terminal title"
  58. ).tag(config=True)
  59. _inactive_locations = set()
  60. @property
  61. def embedded_active(self):
  62. return self._call_location_id not in InteractiveShellEmbed._inactive_locations
  63. @embedded_active.setter
  64. def embedded_active(self, value):
  65. if value :
  66. if self._call_location_id in InteractiveShellEmbed._inactive_locations:
  67. InteractiveShellEmbed._inactive_locations.remove(self._call_location_id)
  68. else:
  69. InteractiveShellEmbed._inactive_locations.add(self._call_location_id)
  70. def __init__(self, **kw):
  71. if kw.get('user_global_ns', None) is not None:
  72. raise DeprecationWarning("Key word argument `user_global_ns` has been replaced by `user_module` since IPython 4.0.")
  73. self._call_location_id = kw.pop('_call_location_id', None)
  74. super(InteractiveShellEmbed,self).__init__(**kw)
  75. if not self._call_location_id:
  76. frame = sys._getframe(1)
  77. self._call_location_id = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno)
  78. # don't use the ipython crash handler so that user exceptions aren't
  79. # trapped
  80. sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors,
  81. mode=self.xmode,
  82. call_pdb=self.pdb)
  83. def init_sys_modules(self):
  84. pass
  85. def init_magics(self):
  86. super(InteractiveShellEmbed, self).init_magics()
  87. self.register_magics(EmbeddedMagics)
  88. def __call__(self, header='', local_ns=None, module=None, dummy=None,
  89. stack_depth=1, global_ns=None, compile_flags=None):
  90. """Activate the interactive interpreter.
  91. __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start
  92. the interpreter shell with the given local and global namespaces, and
  93. optionally print a header string at startup.
  94. The shell can be globally activated/deactivated using the
  95. dummy_mode attribute. This allows you to turn off a shell used
  96. for debugging globally.
  97. However, *each* time you call the shell you can override the current
  98. state of dummy_mode with the optional keyword parameter 'dummy'. For
  99. example, if you set dummy mode on with IPShell.dummy_mode = True, you
  100. can still have a specific call work by making it as IPShell(dummy=False).
  101. """
  102. # If the user has turned it off, go away
  103. if not self.embedded_active:
  104. return
  105. # Normal exits from interactive mode set this flag, so the shell can't
  106. # re-enter (it checks this variable at the start of interactive mode).
  107. self.exit_now = False
  108. # Allow the dummy parameter to override the global __dummy_mode
  109. if dummy or (dummy != 0 and self.dummy_mode):
  110. return
  111. # self.banner is auto computed
  112. if header:
  113. self.old_banner2 = self.banner2
  114. self.banner2 = self.banner2 + '\n' + header + '\n'
  115. else:
  116. self.old_banner2 = ''
  117. if self.display_banner:
  118. self.show_banner()
  119. # Call the embedding code with a stack depth of 1 so it can skip over
  120. # our call and get the original caller's namespaces.
  121. self.mainloop(local_ns, module, stack_depth=stack_depth,
  122. global_ns=global_ns, compile_flags=compile_flags)
  123. self.banner2 = self.old_banner2
  124. if self.exit_msg is not None:
  125. print(self.exit_msg)
  126. if self.should_raise:
  127. raise KillEmbeded('Embedded IPython raising error, as user requested.')
  128. def mainloop(self, local_ns=None, module=None, stack_depth=0,
  129. display_banner=None, global_ns=None, compile_flags=None):
  130. """Embeds IPython into a running python program.
  131. Parameters
  132. ----------
  133. local_ns, module
  134. Working local namespace (a dict) and module (a module or similar
  135. object). If given as None, they are automatically taken from the scope
  136. where the shell was called, so that program variables become visible.
  137. stack_depth : int
  138. How many levels in the stack to go to looking for namespaces (when
  139. local_ns or module is None). This allows an intermediate caller to
  140. make sure that this function gets the namespace from the intended
  141. level in the stack. By default (0) it will get its locals and globals
  142. from the immediate caller.
  143. compile_flags
  144. A bit field identifying the __future__ features
  145. that are enabled, as passed to the builtin :func:`compile` function.
  146. If given as None, they are automatically taken from the scope where
  147. the shell was called.
  148. """
  149. if (global_ns is not None) and (module is None):
  150. raise DeprecationWarning("'global_ns' keyword argument is deprecated, and has been removed in IPython 5.0 use `module` keyword argument instead.")
  151. if (display_banner is not None):
  152. warnings.warn("The display_banner parameter is deprecated since IPython 4.0", DeprecationWarning)
  153. # Get locals and globals from caller
  154. if ((local_ns is None or module is None or compile_flags is None)
  155. and self.default_user_namespaces):
  156. call_frame = sys._getframe(stack_depth).f_back
  157. if local_ns is None:
  158. local_ns = call_frame.f_locals
  159. if module is None:
  160. global_ns = call_frame.f_globals
  161. try:
  162. module = sys.modules[global_ns['__name__']]
  163. except KeyError:
  164. warnings.warn("Failed to get module %s" % \
  165. global_ns.get('__name__', 'unknown module')
  166. )
  167. module = DummyMod()
  168. module.__dict__ = global_ns
  169. if compile_flags is None:
  170. compile_flags = (call_frame.f_code.co_flags &
  171. compilerop.PyCF_MASK)
  172. # Save original namespace and module so we can restore them after
  173. # embedding; otherwise the shell doesn't shut down correctly.
  174. orig_user_module = self.user_module
  175. orig_user_ns = self.user_ns
  176. orig_compile_flags = self.compile.flags
  177. # Update namespaces and fire up interpreter
  178. # The global one is easy, we can just throw it in
  179. if module is not None:
  180. self.user_module = module
  181. # But the user/local one is tricky: ipython needs it to store internal
  182. # data, but we also need the locals. We'll throw our hidden variables
  183. # like _ih and get_ipython() into the local namespace, but delete them
  184. # later.
  185. if local_ns is not None:
  186. reentrant_local_ns = {k: v for (k, v) in local_ns.items() if k not in self.user_ns_hidden.keys()}
  187. self.user_ns = reentrant_local_ns
  188. self.init_user_ns()
  189. # Compiler flags
  190. if compile_flags is not None:
  191. self.compile.flags = compile_flags
  192. # make sure the tab-completer has the correct frame information, so it
  193. # actually completes using the frame's locals/globals
  194. self.set_completer_frame()
  195. with self.builtin_trap, self.display_trap:
  196. self.interact()
  197. # now, purge out the local namespace of IPython's hidden variables.
  198. if local_ns is not None:
  199. local_ns.update({k: v for (k, v) in self.user_ns.items() if k not in self.user_ns_hidden.keys()})
  200. # Restore original namespace so shell can shut down when we exit.
  201. self.user_module = orig_user_module
  202. self.user_ns = orig_user_ns
  203. self.compile.flags = orig_compile_flags
  204. def embed(**kwargs):
  205. """Call this to embed IPython at the current point in your program.
  206. The first invocation of this will create an :class:`InteractiveShellEmbed`
  207. instance and then call it. Consecutive calls just call the already
  208. created instance.
  209. If you don't want the kernel to initialize the namespace
  210. from the scope of the surrounding function,
  211. and/or you want to load full IPython configuration,
  212. you probably want `IPython.start_ipython()` instead.
  213. Here is a simple example::
  214. from IPython import embed
  215. a = 10
  216. b = 20
  217. embed(header='First time')
  218. c = 30
  219. d = 40
  220. embed()
  221. Full customization can be done by passing a :class:`Config` in as the
  222. config argument.
  223. """
  224. config = kwargs.get('config')
  225. header = kwargs.pop('header', u'')
  226. compile_flags = kwargs.pop('compile_flags', None)
  227. if config is None:
  228. config = load_default_config()
  229. config.InteractiveShellEmbed = config.TerminalInteractiveShell
  230. kwargs['config'] = config
  231. #save ps1/ps2 if defined
  232. ps1 = None
  233. ps2 = None
  234. try:
  235. ps1 = sys.ps1
  236. ps2 = sys.ps2
  237. except AttributeError:
  238. pass
  239. #save previous instance
  240. saved_shell_instance = InteractiveShell._instance
  241. if saved_shell_instance is not None:
  242. cls = type(saved_shell_instance)
  243. cls.clear_instance()
  244. frame = sys._getframe(1)
  245. shell = InteractiveShellEmbed.instance(_call_location_id='%s:%s' % (frame.f_code.co_filename, frame.f_lineno), **kwargs)
  246. shell(header=header, stack_depth=2, compile_flags=compile_flags)
  247. InteractiveShellEmbed.clear_instance()
  248. #restore previous instance
  249. if saved_shell_instance is not None:
  250. cls = type(saved_shell_instance)
  251. cls.clear_instance()
  252. for subclass in cls._walk_mro():
  253. subclass._instance = saved_shell_instance
  254. if ps1 is not None:
  255. sys.ps1 = ps1
  256. sys.ps2 = ps2