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