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