embed.py 15 KB

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