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