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