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