Show More
@@ -0,0 +1,73 b'' | |||
|
1 | from IPython.core.debugger import Pdb | |
|
2 | ||
|
3 | from IPython.core.completer import IPCompleter | |
|
4 | from .ptutils import IPythonPTCompleter | |
|
5 | ||
|
6 | from prompt_toolkit.token import Token | |
|
7 | from prompt_toolkit.shortcuts import create_prompt_application | |
|
8 | from prompt_toolkit.interface import CommandLineInterface | |
|
9 | from prompt_toolkit.enums import EditingMode | |
|
10 | ||
|
11 | class TerminalPdb(Pdb): | |
|
12 | def __init__(self, *args, **kwargs): | |
|
13 | Pdb.__init__(self, *args, **kwargs) | |
|
14 | self._ptcomp = None | |
|
15 | self.pt_init() | |
|
16 | ||
|
17 | def pt_init(self): | |
|
18 | def get_prompt_tokens(cli): | |
|
19 | return [(Token.Prompt, self.prompt)] | |
|
20 | ||
|
21 | if self._ptcomp is None: | |
|
22 | compl = IPCompleter(shell=self.shell, | |
|
23 | namespace={}, | |
|
24 | global_namespace={}, | |
|
25 | use_readline=False, | |
|
26 | parent=self.shell, | |
|
27 | ) | |
|
28 | self._ptcomp = IPythonPTCompleter(compl) | |
|
29 | ||
|
30 | self._pt_app = create_prompt_application( | |
|
31 | editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()), | |
|
32 | history=self.shell.debugger_history, | |
|
33 | completer= self._ptcomp, | |
|
34 | enable_history_search=True, | |
|
35 | mouse_support=self.shell.mouse_support, | |
|
36 | get_prompt_tokens=get_prompt_tokens | |
|
37 | ) | |
|
38 | self.pt_cli = CommandLineInterface(self._pt_app, eventloop=self.shell._eventloop) | |
|
39 | ||
|
40 | def cmdloop(self, intro=None): | |
|
41 | """Repeatedly issue a prompt, accept input, parse an initial prefix | |
|
42 | off the received input, and dispatch to action methods, passing them | |
|
43 | the remainder of the line as argument. | |
|
44 | ||
|
45 | override the same methods from cmd.Cmd to provide prompt toolkit replacement. | |
|
46 | """ | |
|
47 | if not self.use_rawinput: | |
|
48 | raise ValueError('Sorry ipdb does not support use_rawinput=False') | |
|
49 | ||
|
50 | self.preloop() | |
|
51 | ||
|
52 | try: | |
|
53 | if intro is not None: | |
|
54 | self.intro = intro | |
|
55 | if self.intro: | |
|
56 | self.stdout.write(str(self.intro)+"\n") | |
|
57 | stop = None | |
|
58 | while not stop: | |
|
59 | if self.cmdqueue: | |
|
60 | line = self.cmdqueue.pop(0) | |
|
61 | else: | |
|
62 | self._ptcomp.ipy_completer.namespace = self.curframe_locals | |
|
63 | self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals | |
|
64 | try: | |
|
65 | line = self.pt_cli.run(reset_current_buffer=True).text | |
|
66 | except EOFError: | |
|
67 | line = 'EOF' | |
|
68 | line = self.precmd(line) | |
|
69 | stop = self.onecmd(line) | |
|
70 | stop = self.postcmd(stop, line) | |
|
71 | self.postloop() | |
|
72 | except Exception: | |
|
73 | raise |
@@ -1,661 +1,580 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | Pdb debugger class. |
|
4 | 4 | |
|
5 | 5 | Modified from the standard pdb.Pdb class to avoid including readline, so that |
|
6 | 6 | the command line completion of other programs which include this isn't |
|
7 | 7 | damaged. |
|
8 | 8 | |
|
9 | 9 | In the future, this class will be expanded with improvements over the standard |
|
10 | 10 | pdb. |
|
11 | 11 | |
|
12 | 12 | The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor |
|
13 | 13 | changes. Licensing should therefore be under the standard Python terms. For |
|
14 | 14 | details on the PSF (Python Software Foundation) standard license, see: |
|
15 | 15 | |
|
16 | 16 | http://www.python.org/2.2.3/license.html""" |
|
17 | 17 | |
|
18 | 18 | #***************************************************************************** |
|
19 | 19 | # |
|
20 | 20 | # This file is licensed under the PSF license. |
|
21 | 21 | # |
|
22 | 22 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
23 | 23 | # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu> |
|
24 | 24 | # |
|
25 | 25 | # |
|
26 | 26 | #***************************************************************************** |
|
27 | 27 | from __future__ import print_function |
|
28 | 28 | |
|
29 | 29 | import bdb |
|
30 | 30 | import functools |
|
31 | 31 | import inspect |
|
32 | 32 | import sys |
|
33 | 33 | |
|
34 | 34 | from IPython import get_ipython |
|
35 | 35 | from IPython.utils import PyColorize, ulinecache |
|
36 | 36 | from IPython.utils import coloransi, py3compat |
|
37 | from IPython.core.completer import IPCompleter | |
|
38 | 37 | from IPython.core.excolors import exception_colors |
|
39 | 38 | from IPython.testing.skipdoctest import skip_doctest |
|
40 | from IPython.terminal.ptutils import IPythonPTCompleter | |
|
41 | ||
|
42 | from prompt_toolkit.token import Token | |
|
43 | from prompt_toolkit.shortcuts import create_prompt_application | |
|
44 | from prompt_toolkit.interface import CommandLineInterface | |
|
45 | from prompt_toolkit.enums import EditingMode | |
|
46 | 39 | |
|
47 | 40 | |
|
48 | 41 | prompt = 'ipdb> ' |
|
49 | 42 | |
|
50 | 43 | #We have to check this directly from sys.argv, config struct not yet available |
|
51 | 44 | from pdb import Pdb as OldPdb |
|
52 | 45 | |
|
53 | 46 | # Allow the set_trace code to operate outside of an ipython instance, even if |
|
54 | 47 | # it does so with some limitations. The rest of this support is implemented in |
|
55 | 48 | # the Tracer constructor. |
|
56 | 49 | |
|
57 | 50 | def make_arrow(pad): |
|
58 | 51 | """generate the leading arrow in front of traceback or debugger""" |
|
59 | 52 | if pad >= 2: |
|
60 | 53 | return '-'*(pad-2) + '> ' |
|
61 | 54 | elif pad == 1: |
|
62 | 55 | return '>' |
|
63 | 56 | return '' |
|
64 | 57 | |
|
65 | 58 | |
|
66 | 59 | def BdbQuit_excepthook(et, ev, tb, excepthook=None): |
|
67 | 60 | """Exception hook which handles `BdbQuit` exceptions. |
|
68 | 61 | |
|
69 | 62 | All other exceptions are processed using the `excepthook` |
|
70 | 63 | parameter. |
|
71 | 64 | """ |
|
72 | 65 | if et==bdb.BdbQuit: |
|
73 | 66 | print('Exiting Debugger.') |
|
74 | 67 | elif excepthook is not None: |
|
75 | 68 | excepthook(et, ev, tb) |
|
76 | 69 | else: |
|
77 | 70 | # Backwards compatibility. Raise deprecation warning? |
|
78 | 71 | BdbQuit_excepthook.excepthook_ori(et,ev,tb) |
|
79 | 72 | |
|
80 | 73 | def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None): |
|
81 | 74 | print('Exiting Debugger.') |
|
82 | 75 | |
|
83 | 76 | |
|
84 | 77 | class Tracer(object): |
|
85 | 78 | """Class for local debugging, similar to pdb.set_trace. |
|
86 | 79 | |
|
87 | 80 | Instances of this class, when called, behave like pdb.set_trace, but |
|
88 | 81 | providing IPython's enhanced capabilities. |
|
89 | 82 | |
|
90 | 83 | This is implemented as a class which must be initialized in your own code |
|
91 | 84 | and not as a standalone function because we need to detect at runtime |
|
92 | 85 | whether IPython is already active or not. That detection is done in the |
|
93 | 86 | constructor, ensuring that this code plays nicely with a running IPython, |
|
94 | 87 | while functioning acceptably (though with limitations) if outside of it. |
|
95 | 88 | """ |
|
96 | 89 | |
|
97 | 90 | @skip_doctest |
|
98 | 91 | def __init__(self, colors=None): |
|
99 | 92 | """Create a local debugger instance. |
|
100 | 93 | |
|
101 | 94 | Parameters |
|
102 | 95 | ---------- |
|
103 | 96 | |
|
104 | 97 | colors : str, optional |
|
105 | 98 | The name of the color scheme to use, it must be one of IPython's |
|
106 | 99 | valid color schemes. If not given, the function will default to |
|
107 | 100 | the current IPython scheme when running inside IPython, and to |
|
108 | 101 | 'NoColor' otherwise. |
|
109 | 102 | |
|
110 | 103 | Examples |
|
111 | 104 | -------- |
|
112 | 105 | :: |
|
113 | 106 | |
|
114 | 107 | from IPython.core.debugger import Tracer; debug_here = Tracer() |
|
115 | 108 | |
|
116 | 109 | Later in your code:: |
|
117 | 110 | |
|
118 | 111 | debug_here() # -> will open up the debugger at that point. |
|
119 | 112 | |
|
120 | 113 | Once the debugger activates, you can use all of its regular commands to |
|
121 | 114 | step through code, set breakpoints, etc. See the pdb documentation |
|
122 | 115 | from the Python standard library for usage details. |
|
123 | 116 | """ |
|
124 | 117 | |
|
125 | 118 | ip = get_ipython() |
|
126 | 119 | if ip is None: |
|
127 | 120 | # Outside of ipython, we set our own exception hook manually |
|
128 | 121 | sys.excepthook = functools.partial(BdbQuit_excepthook, |
|
129 | 122 | excepthook=sys.excepthook) |
|
130 | 123 | def_colors = 'NoColor' |
|
131 | 124 | else: |
|
132 | 125 | # In ipython, we use its custom exception handler mechanism |
|
133 | 126 | def_colors = ip.colors |
|
134 | 127 | ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook) |
|
135 | 128 | |
|
136 | 129 | if colors is None: |
|
137 | 130 | colors = def_colors |
|
138 | 131 | |
|
139 | 132 | # The stdlib debugger internally uses a modified repr from the `repr` |
|
140 | 133 | # module, that limits the length of printed strings to a hardcoded |
|
141 | 134 | # limit of 30 characters. That much trimming is too aggressive, let's |
|
142 | 135 | # at least raise that limit to 80 chars, which should be enough for |
|
143 | 136 | # most interactive uses. |
|
144 | 137 | try: |
|
145 | 138 | try: |
|
146 | 139 | from reprlib import aRepr # Py 3 |
|
147 | 140 | except ImportError: |
|
148 | 141 | from repr import aRepr # Py 2 |
|
149 | 142 | aRepr.maxstring = 80 |
|
150 | 143 | except: |
|
151 | 144 | # This is only a user-facing convenience, so any error we encounter |
|
152 | 145 | # here can be warned about but can be otherwise ignored. These |
|
153 | 146 | # printouts will tell us about problems if this API changes |
|
154 | 147 | import traceback |
|
155 | 148 | traceback.print_exc() |
|
156 | 149 | |
|
157 | 150 | self.debugger = Pdb(colors) |
|
158 | 151 | |
|
159 | 152 | def __call__(self): |
|
160 | 153 | """Starts an interactive debugger at the point where called. |
|
161 | 154 | |
|
162 | 155 | This is similar to the pdb.set_trace() function from the std lib, but |
|
163 | 156 | using IPython's enhanced debugger.""" |
|
164 | 157 | |
|
165 | 158 | self.debugger.set_trace(sys._getframe().f_back) |
|
166 | 159 | |
|
167 | 160 | |
|
168 | 161 | def decorate_fn_with_doc(new_fn, old_fn, additional_text=""): |
|
169 | 162 | """Make new_fn have old_fn's doc string. This is particularly useful |
|
170 | 163 | for the ``do_...`` commands that hook into the help system. |
|
171 | 164 | Adapted from from a comp.lang.python posting |
|
172 | 165 | by Duncan Booth.""" |
|
173 | 166 | def wrapper(*args, **kw): |
|
174 | 167 | return new_fn(*args, **kw) |
|
175 | 168 | if old_fn.__doc__: |
|
176 | 169 | wrapper.__doc__ = old_fn.__doc__ + additional_text |
|
177 | 170 | return wrapper |
|
178 | 171 | |
|
179 | 172 | |
|
180 | 173 | def _file_lines(fname): |
|
181 | 174 | """Return the contents of a named file as a list of lines. |
|
182 | 175 | |
|
183 | 176 | This function never raises an IOError exception: if the file can't be |
|
184 | 177 | read, it simply returns an empty list.""" |
|
185 | 178 | |
|
186 | 179 | try: |
|
187 | 180 | outfile = open(fname) |
|
188 | 181 | except IOError: |
|
189 | 182 | return [] |
|
190 | 183 | else: |
|
191 | 184 | out = outfile.readlines() |
|
192 | 185 | outfile.close() |
|
193 | 186 | return out |
|
194 | 187 | |
|
195 | 188 | |
|
196 | 189 | class Pdb(OldPdb, object): |
|
197 | 190 | """Modified Pdb class, does not load readline.""" |
|
198 | 191 | |
|
199 | 192 | def __init__(self,color_scheme='NoColor',completekey=None, |
|
200 | 193 | stdin=None, stdout=None, context=5): |
|
201 | 194 | |
|
202 | 195 | # Parent constructor: |
|
203 | 196 | try: |
|
204 | 197 | self.context=int(context) |
|
205 | 198 | if self.context <= 0: |
|
206 | 199 | raise ValueError("Context must be a positive integer") |
|
207 | 200 | except (TypeError, ValueError): |
|
208 | 201 | raise ValueError("Context must be a positive integer") |
|
209 | 202 | |
|
210 | 203 | OldPdb.__init__(self, completekey, stdin, stdout) |
|
211 | 204 | |
|
212 | 205 | # IPython changes... |
|
213 | 206 | self.shell = get_ipython() |
|
214 | 207 | |
|
215 | 208 | if self.shell is None: |
|
216 | 209 | # No IPython instance running, we must create one |
|
217 | 210 | from IPython.terminal.interactiveshell import \ |
|
218 | 211 | TerminalInteractiveShell |
|
219 | 212 | self.shell = TerminalInteractiveShell.instance() |
|
220 | 213 | |
|
221 | 214 | # This is icky, but I'm not currently sure how best to test if we're |
|
222 | 215 | # in a terminal shell using prompt_toolkit |
|
223 | 216 | |
|
224 | 217 | self.aliases = {} |
|
225 | 218 | |
|
226 | 219 | # Create color table: we copy the default one from the traceback |
|
227 | 220 | # module and add a few attributes needed for debugging |
|
228 | 221 | self.color_scheme_table = exception_colors() |
|
229 | 222 | |
|
230 | 223 | # shorthands |
|
231 | 224 | C = coloransi.TermColors |
|
232 | 225 | cst = self.color_scheme_table |
|
233 | 226 | |
|
234 | 227 | cst['NoColor'].colors.prompt = C.NoColor |
|
235 | 228 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor |
|
236 | 229 | cst['NoColor'].colors.breakpoint_disabled = C.NoColor |
|
237 | 230 | |
|
238 | 231 | cst['Linux'].colors.prompt = C.Green |
|
239 | 232 | cst['Linux'].colors.breakpoint_enabled = C.LightRed |
|
240 | 233 | cst['Linux'].colors.breakpoint_disabled = C.Red |
|
241 | 234 | |
|
242 | 235 | cst['LightBG'].colors.prompt = C.Blue |
|
243 | 236 | cst['LightBG'].colors.breakpoint_enabled = C.LightRed |
|
244 | 237 | cst['LightBG'].colors.breakpoint_disabled = C.Red |
|
245 | 238 | |
|
246 | 239 | self.set_colors(color_scheme) |
|
247 | 240 | |
|
248 | 241 | # Add a python parser so we can syntax highlight source while |
|
249 | 242 | # debugging. |
|
250 | 243 | self.parser = PyColorize.Parser() |
|
251 | 244 | |
|
252 | 245 | # Set the prompt - the default prompt is '(Pdb)' |
|
253 | 246 | self.prompt = prompt |
|
254 | self._ptcomp = None | |
|
255 | self.pt_init() | |
|
256 | ||
|
257 | def pt_init(self): | |
|
258 | self.use_prompt_toolkit = hasattr(self.shell, 'pt_cli') | |
|
259 | ||
|
260 | if not self.use_prompt_toolkit: | |
|
261 | return | |
|
262 | ||
|
263 | def get_prompt_tokens(cli): | |
|
264 | return [(Token.Prompt, self.prompt)] | |
|
265 | ||
|
266 | if self._ptcomp is None: | |
|
267 | compl = IPCompleter(shell=self.shell, | |
|
268 | namespace={}, | |
|
269 | global_namespace={}, | |
|
270 | use_readline=False, | |
|
271 | parent=self.shell, | |
|
272 | ) | |
|
273 | self._ptcomp = IPythonPTCompleter(compl) | |
|
274 | ||
|
275 | self._pt_app = create_prompt_application( | |
|
276 | editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()), | |
|
277 | history=self.shell.debugger_history, | |
|
278 | completer= self._ptcomp, | |
|
279 | enable_history_search=True, | |
|
280 | mouse_support=self.shell.mouse_support, | |
|
281 | get_prompt_tokens=get_prompt_tokens | |
|
282 | ) | |
|
283 | self.pt_cli = CommandLineInterface(self._pt_app, eventloop=self.shell._eventloop) | |
|
284 | ||
|
285 | ||
|
286 | ||
|
287 | def cmdloop(self, intro=None): | |
|
288 | """Repeatedly issue a prompt, accept input, parse an initial prefix | |
|
289 | off the received input, and dispatch to action methods, passing them | |
|
290 | the remainder of the line as argument. | |
|
291 | ||
|
292 | override the same methods from cmd.Cmd to provide prompt toolkit replacement. | |
|
293 | """ | |
|
294 | if not self.use_prompt_toolkit: | |
|
295 | return OldPdb.cmdloop(self, intro) | |
|
296 | ||
|
297 | if not self.use_rawinput: | |
|
298 | raise ValueError('Sorry ipdb does not support raw_input=False') | |
|
299 | ||
|
300 | ||
|
301 | self.preloop() | |
|
302 | ||
|
303 | ||
|
304 | try: | |
|
305 | if intro is not None: | |
|
306 | self.intro = intro | |
|
307 | if self.intro: | |
|
308 | self.stdout.write(str(self.intro)+"\n") | |
|
309 | stop = None | |
|
310 | while not stop: | |
|
311 | if self.cmdqueue: | |
|
312 | line = self.cmdqueue.pop(0) | |
|
313 | else: | |
|
314 | self._ptcomp.ipy_completer.namespace = self.curframe_locals | |
|
315 | self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals | |
|
316 | try: | |
|
317 | line = self.pt_cli.run(reset_current_buffer=True).text | |
|
318 | except EOFError: | |
|
319 | line = 'EOF' | |
|
320 | line = self.precmd(line) | |
|
321 | stop = self.onecmd(line) | |
|
322 | stop = self.postcmd(stop, line) | |
|
323 | self.postloop() | |
|
324 | except Exception: | |
|
325 | raise | |
|
326 | ||
|
327 | ||
|
328 | 247 | |
|
329 | 248 | def set_colors(self, scheme): |
|
330 | 249 | """Shorthand access to the color table scheme selector method.""" |
|
331 | 250 | self.color_scheme_table.set_active_scheme(scheme) |
|
332 | 251 | |
|
333 | 252 | def interaction(self, frame, traceback): |
|
334 | 253 | try: |
|
335 | 254 | OldPdb.interaction(self, frame, traceback) |
|
336 | 255 | except KeyboardInterrupt: |
|
337 | 256 | sys.stdout.write('\n' + self.shell.get_exception_only()) |
|
338 | 257 | |
|
339 | 258 | def parseline(self, line): |
|
340 | 259 | if line.startswith("!!"): |
|
341 | 260 | # Force standard behavior. |
|
342 | 261 | return super(Pdb, self).parseline(line[2:]) |
|
343 | 262 | # "Smart command mode" from pdb++: don't execute commands if a variable |
|
344 | 263 | # with the same name exists. |
|
345 | 264 | cmd, arg, newline = super(Pdb, self).parseline(line) |
|
346 | 265 | if cmd in self.curframe.f_globals or cmd in self.curframe.f_locals: |
|
347 | 266 | return super(Pdb, self).parseline("!" + line) |
|
348 | 267 | return super(Pdb, self).parseline(line) |
|
349 | 268 | |
|
350 | 269 | def new_do_up(self, arg): |
|
351 | 270 | OldPdb.do_up(self, arg) |
|
352 | 271 | do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up) |
|
353 | 272 | |
|
354 | 273 | def new_do_down(self, arg): |
|
355 | 274 | OldPdb.do_down(self, arg) |
|
356 | 275 | |
|
357 | 276 | do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down) |
|
358 | 277 | |
|
359 | 278 | def new_do_frame(self, arg): |
|
360 | 279 | OldPdb.do_frame(self, arg) |
|
361 | 280 | |
|
362 | 281 | def new_do_quit(self, arg): |
|
363 | 282 | |
|
364 | 283 | if hasattr(self, 'old_all_completions'): |
|
365 | 284 | self.shell.Completer.all_completions=self.old_all_completions |
|
366 | 285 | |
|
367 | 286 | return OldPdb.do_quit(self, arg) |
|
368 | 287 | |
|
369 | 288 | do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit) |
|
370 | 289 | |
|
371 | 290 | def new_do_restart(self, arg): |
|
372 | 291 | """Restart command. In the context of ipython this is exactly the same |
|
373 | 292 | thing as 'quit'.""" |
|
374 | 293 | self.msg("Restart doesn't make sense here. Using 'quit' instead.") |
|
375 | 294 | return self.do_quit(arg) |
|
376 | 295 | |
|
377 | 296 | def print_stack_trace(self, context=None): |
|
378 | 297 | if context is None: |
|
379 | 298 | context = self.context |
|
380 | 299 | try: |
|
381 | 300 | context=int(context) |
|
382 | 301 | if context <= 0: |
|
383 | 302 | raise ValueError("Context must be a positive integer") |
|
384 | 303 | except (TypeError, ValueError): |
|
385 | 304 | raise ValueError("Context must be a positive integer") |
|
386 | 305 | try: |
|
387 | 306 | for frame_lineno in self.stack: |
|
388 | 307 | self.print_stack_entry(frame_lineno, context=context) |
|
389 | 308 | except KeyboardInterrupt: |
|
390 | 309 | pass |
|
391 | 310 | |
|
392 | 311 | def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ', |
|
393 | 312 | context=None): |
|
394 | 313 | if context is None: |
|
395 | 314 | context = self.context |
|
396 | 315 | try: |
|
397 | 316 | context=int(context) |
|
398 | 317 | if context <= 0: |
|
399 | 318 | raise ValueError("Context must be a positive integer") |
|
400 | 319 | except (TypeError, ValueError): |
|
401 | 320 | raise ValueError("Context must be a positive integer") |
|
402 | 321 | print(self.format_stack_entry(frame_lineno, '', context)) |
|
403 | 322 | |
|
404 | 323 | # vds: >> |
|
405 | 324 | frame, lineno = frame_lineno |
|
406 | 325 | filename = frame.f_code.co_filename |
|
407 | 326 | self.shell.hooks.synchronize_with_editor(filename, lineno, 0) |
|
408 | 327 | # vds: << |
|
409 | 328 | |
|
410 | 329 | def format_stack_entry(self, frame_lineno, lprefix=': ', context=None): |
|
411 | 330 | if context is None: |
|
412 | 331 | context = self.context |
|
413 | 332 | try: |
|
414 | 333 | context=int(context) |
|
415 | 334 | if context <= 0: |
|
416 | 335 | print("Context must be a positive integer") |
|
417 | 336 | except (TypeError, ValueError): |
|
418 | 337 | print("Context must be a positive integer") |
|
419 | 338 | try: |
|
420 | 339 | import reprlib # Py 3 |
|
421 | 340 | except ImportError: |
|
422 | 341 | import repr as reprlib # Py 2 |
|
423 | 342 | |
|
424 | 343 | ret = [] |
|
425 | 344 | |
|
426 | 345 | Colors = self.color_scheme_table.active_colors |
|
427 | 346 | ColorsNormal = Colors.Normal |
|
428 | 347 | tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal) |
|
429 | 348 | tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal) |
|
430 | 349 | tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) |
|
431 | 350 | tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, |
|
432 | 351 | ColorsNormal) |
|
433 | 352 | |
|
434 | 353 | frame, lineno = frame_lineno |
|
435 | 354 | |
|
436 | 355 | return_value = '' |
|
437 | 356 | if '__return__' in frame.f_locals: |
|
438 | 357 | rv = frame.f_locals['__return__'] |
|
439 | 358 | #return_value += '->' |
|
440 | 359 | return_value += reprlib.repr(rv) + '\n' |
|
441 | 360 | ret.append(return_value) |
|
442 | 361 | |
|
443 | 362 | #s = filename + '(' + `lineno` + ')' |
|
444 | 363 | filename = self.canonic(frame.f_code.co_filename) |
|
445 | 364 | link = tpl_link % py3compat.cast_unicode(filename) |
|
446 | 365 | |
|
447 | 366 | if frame.f_code.co_name: |
|
448 | 367 | func = frame.f_code.co_name |
|
449 | 368 | else: |
|
450 | 369 | func = "<lambda>" |
|
451 | 370 | |
|
452 | 371 | call = '' |
|
453 | 372 | if func != '?': |
|
454 | 373 | if '__args__' in frame.f_locals: |
|
455 | 374 | args = reprlib.repr(frame.f_locals['__args__']) |
|
456 | 375 | else: |
|
457 | 376 | args = '()' |
|
458 | 377 | call = tpl_call % (func, args) |
|
459 | 378 | |
|
460 | 379 | # The level info should be generated in the same format pdb uses, to |
|
461 | 380 | # avoid breaking the pdbtrack functionality of python-mode in *emacs. |
|
462 | 381 | if frame is self.curframe: |
|
463 | 382 | ret.append('> ') |
|
464 | 383 | else: |
|
465 | 384 | ret.append(' ') |
|
466 | 385 | ret.append(u'%s(%s)%s\n' % (link,lineno,call)) |
|
467 | 386 | |
|
468 | 387 | start = lineno - 1 - context//2 |
|
469 | 388 | lines = ulinecache.getlines(filename) |
|
470 | 389 | start = min(start, len(lines) - context) |
|
471 | 390 | start = max(start, 0) |
|
472 | 391 | lines = lines[start : start + context] |
|
473 | 392 | |
|
474 | 393 | for i,line in enumerate(lines): |
|
475 | 394 | show_arrow = (start + 1 + i == lineno) |
|
476 | 395 | linetpl = (frame is self.curframe or show_arrow) \ |
|
477 | 396 | and tpl_line_em \ |
|
478 | 397 | or tpl_line |
|
479 | 398 | ret.append(self.__format_line(linetpl, filename, |
|
480 | 399 | start + 1 + i, line, |
|
481 | 400 | arrow = show_arrow) ) |
|
482 | 401 | return ''.join(ret) |
|
483 | 402 | |
|
484 | 403 | def __format_line(self, tpl_line, filename, lineno, line, arrow = False): |
|
485 | 404 | bp_mark = "" |
|
486 | 405 | bp_mark_color = "" |
|
487 | 406 | |
|
488 | 407 | scheme = self.color_scheme_table.active_scheme_name |
|
489 | 408 | new_line, err = self.parser.format2(line, 'str', scheme) |
|
490 | 409 | if not err: line = new_line |
|
491 | 410 | |
|
492 | 411 | bp = None |
|
493 | 412 | if lineno in self.get_file_breaks(filename): |
|
494 | 413 | bps = self.get_breaks(filename, lineno) |
|
495 | 414 | bp = bps[-1] |
|
496 | 415 | |
|
497 | 416 | if bp: |
|
498 | 417 | Colors = self.color_scheme_table.active_colors |
|
499 | 418 | bp_mark = str(bp.number) |
|
500 | 419 | bp_mark_color = Colors.breakpoint_enabled |
|
501 | 420 | if not bp.enabled: |
|
502 | 421 | bp_mark_color = Colors.breakpoint_disabled |
|
503 | 422 | |
|
504 | 423 | numbers_width = 7 |
|
505 | 424 | if arrow: |
|
506 | 425 | # This is the line with the error |
|
507 | 426 | pad = numbers_width - len(str(lineno)) - len(bp_mark) |
|
508 | 427 | num = '%s%s' % (make_arrow(pad), str(lineno)) |
|
509 | 428 | else: |
|
510 | 429 | num = '%*s' % (numbers_width - len(bp_mark), str(lineno)) |
|
511 | 430 | |
|
512 | 431 | return tpl_line % (bp_mark_color + bp_mark, num, line) |
|
513 | 432 | |
|
514 | 433 | |
|
515 | 434 | def print_list_lines(self, filename, first, last): |
|
516 | 435 | """The printing (as opposed to the parsing part of a 'list' |
|
517 | 436 | command.""" |
|
518 | 437 | try: |
|
519 | 438 | Colors = self.color_scheme_table.active_colors |
|
520 | 439 | ColorsNormal = Colors.Normal |
|
521 | 440 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) |
|
522 | 441 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal) |
|
523 | 442 | src = [] |
|
524 | 443 | if filename == "<string>" and hasattr(self, "_exec_filename"): |
|
525 | 444 | filename = self._exec_filename |
|
526 | 445 | |
|
527 | 446 | for lineno in range(first, last+1): |
|
528 | 447 | line = ulinecache.getline(filename, lineno) |
|
529 | 448 | if not line: |
|
530 | 449 | break |
|
531 | 450 | |
|
532 | 451 | if lineno == self.curframe.f_lineno: |
|
533 | 452 | line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True) |
|
534 | 453 | else: |
|
535 | 454 | line = self.__format_line(tpl_line, filename, lineno, line, arrow = False) |
|
536 | 455 | |
|
537 | 456 | src.append(line) |
|
538 | 457 | self.lineno = lineno |
|
539 | 458 | |
|
540 | 459 | print(''.join(src)) |
|
541 | 460 | |
|
542 | 461 | except KeyboardInterrupt: |
|
543 | 462 | pass |
|
544 | 463 | |
|
545 | 464 | def do_list(self, arg): |
|
546 | 465 | self.lastcmd = 'list' |
|
547 | 466 | last = None |
|
548 | 467 | if arg: |
|
549 | 468 | try: |
|
550 | 469 | x = eval(arg, {}, {}) |
|
551 | 470 | if type(x) == type(()): |
|
552 | 471 | first, last = x |
|
553 | 472 | first = int(first) |
|
554 | 473 | last = int(last) |
|
555 | 474 | if last < first: |
|
556 | 475 | # Assume it's a count |
|
557 | 476 | last = first + last |
|
558 | 477 | else: |
|
559 | 478 | first = max(1, int(x) - 5) |
|
560 | 479 | except: |
|
561 | 480 | print('*** Error in argument:', repr(arg)) |
|
562 | 481 | return |
|
563 | 482 | elif self.lineno is None: |
|
564 | 483 | first = max(1, self.curframe.f_lineno - 5) |
|
565 | 484 | else: |
|
566 | 485 | first = self.lineno + 1 |
|
567 | 486 | if last is None: |
|
568 | 487 | last = first + 10 |
|
569 | 488 | self.print_list_lines(self.curframe.f_code.co_filename, first, last) |
|
570 | 489 | |
|
571 | 490 | # vds: >> |
|
572 | 491 | lineno = first |
|
573 | 492 | filename = self.curframe.f_code.co_filename |
|
574 | 493 | self.shell.hooks.synchronize_with_editor(filename, lineno, 0) |
|
575 | 494 | # vds: << |
|
576 | 495 | |
|
577 | 496 | do_l = do_list |
|
578 | 497 | |
|
579 | 498 | def getsourcelines(self, obj): |
|
580 | 499 | lines, lineno = inspect.findsource(obj) |
|
581 | 500 | if inspect.isframe(obj) and obj.f_globals is obj.f_locals: |
|
582 | 501 | # must be a module frame: do not try to cut a block out of it |
|
583 | 502 | return lines, 1 |
|
584 | 503 | elif inspect.ismodule(obj): |
|
585 | 504 | return lines, 1 |
|
586 | 505 | return inspect.getblock(lines[lineno:]), lineno+1 |
|
587 | 506 | |
|
588 | 507 | def do_longlist(self, arg): |
|
589 | 508 | self.lastcmd = 'longlist' |
|
590 | 509 | try: |
|
591 | 510 | lines, lineno = self.getsourcelines(self.curframe) |
|
592 | 511 | except OSError as err: |
|
593 | 512 | self.error(err) |
|
594 | 513 | return |
|
595 | 514 | last = lineno + len(lines) |
|
596 | 515 | self.print_list_lines(self.curframe.f_code.co_filename, lineno, last) |
|
597 | 516 | do_ll = do_longlist |
|
598 | 517 | |
|
599 | 518 | def do_pdef(self, arg): |
|
600 | 519 | """Print the call signature for any callable object. |
|
601 | 520 | |
|
602 | 521 | The debugger interface to %pdef""" |
|
603 | 522 | namespaces = [('Locals', self.curframe.f_locals), |
|
604 | 523 | ('Globals', self.curframe.f_globals)] |
|
605 | 524 | self.shell.find_line_magic('pdef')(arg, namespaces=namespaces) |
|
606 | 525 | |
|
607 | 526 | def do_pdoc(self, arg): |
|
608 | 527 | """Print the docstring for an object. |
|
609 | 528 | |
|
610 | 529 | The debugger interface to %pdoc.""" |
|
611 | 530 | namespaces = [('Locals', self.curframe.f_locals), |
|
612 | 531 | ('Globals', self.curframe.f_globals)] |
|
613 | 532 | self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces) |
|
614 | 533 | |
|
615 | 534 | def do_pfile(self, arg): |
|
616 | 535 | """Print (or run through pager) the file where an object is defined. |
|
617 | 536 | |
|
618 | 537 | The debugger interface to %pfile. |
|
619 | 538 | """ |
|
620 | 539 | namespaces = [('Locals', self.curframe.f_locals), |
|
621 | 540 | ('Globals', self.curframe.f_globals)] |
|
622 | 541 | self.shell.find_line_magic('pfile')(arg, namespaces=namespaces) |
|
623 | 542 | |
|
624 | 543 | def do_pinfo(self, arg): |
|
625 | 544 | """Provide detailed information about an object. |
|
626 | 545 | |
|
627 | 546 | The debugger interface to %pinfo, i.e., obj?.""" |
|
628 | 547 | namespaces = [('Locals', self.curframe.f_locals), |
|
629 | 548 | ('Globals', self.curframe.f_globals)] |
|
630 | 549 | self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces) |
|
631 | 550 | |
|
632 | 551 | def do_pinfo2(self, arg): |
|
633 | 552 | """Provide extra detailed information about an object. |
|
634 | 553 | |
|
635 | 554 | The debugger interface to %pinfo2, i.e., obj??.""" |
|
636 | 555 | namespaces = [('Locals', self.curframe.f_locals), |
|
637 | 556 | ('Globals', self.curframe.f_globals)] |
|
638 | 557 | self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces) |
|
639 | 558 | |
|
640 | 559 | def do_psource(self, arg): |
|
641 | 560 | """Print (or run through pager) the source code for an object.""" |
|
642 | 561 | namespaces = [('Locals', self.curframe.f_locals), |
|
643 | 562 | ('Globals', self.curframe.f_globals)] |
|
644 | 563 | self.shell.find_line_magic('psource')(arg, namespaces=namespaces) |
|
645 | 564 | |
|
646 | 565 | if sys.version_info > (3, ): |
|
647 | 566 | def do_where(self, arg): |
|
648 | 567 | """w(here) |
|
649 | 568 | Print a stack trace, with the most recent frame at the bottom. |
|
650 | 569 | An arrow indicates the "current frame", which determines the |
|
651 | 570 | context of most commands. 'bt' is an alias for this command. |
|
652 | 571 | |
|
653 | 572 | Take a number as argument as an (optional) number of context line to |
|
654 | 573 | print""" |
|
655 | 574 | if arg: |
|
656 | 575 | context = int(arg) |
|
657 | 576 | self.print_stack_trace(context) |
|
658 | 577 | else: |
|
659 | 578 | self.print_stack_trace() |
|
660 | 579 | |
|
661 | 580 | do_w = do_where |
@@ -1,3240 +1,3244 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Main IPython class.""" |
|
3 | 3 | |
|
4 | 4 | #----------------------------------------------------------------------------- |
|
5 | 5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
6 | 6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
7 | 7 | # Copyright (C) 2008-2011 The IPython Development Team |
|
8 | 8 | # |
|
9 | 9 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | 10 | # the file COPYING, distributed as part of this software. |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | |
|
13 | 13 | from __future__ import absolute_import, print_function |
|
14 | 14 | |
|
15 | 15 | import __future__ |
|
16 | 16 | import abc |
|
17 | 17 | import ast |
|
18 | 18 | import atexit |
|
19 | 19 | import functools |
|
20 | 20 | import os |
|
21 | 21 | import re |
|
22 | 22 | import runpy |
|
23 | 23 | import sys |
|
24 | 24 | import tempfile |
|
25 | 25 | import traceback |
|
26 | 26 | import types |
|
27 | 27 | import subprocess |
|
28 | 28 | import warnings |
|
29 | 29 | from io import open as io_open |
|
30 | 30 | |
|
31 | 31 | from pickleshare import PickleShareDB |
|
32 | 32 | |
|
33 | 33 | from traitlets.config.configurable import SingletonConfigurable |
|
34 | 34 | from IPython.core import oinspect |
|
35 | 35 | from IPython.core import magic |
|
36 | 36 | from IPython.core import page |
|
37 | 37 | from IPython.core import prefilter |
|
38 | 38 | from IPython.core import shadowns |
|
39 | 39 | from IPython.core import ultratb |
|
40 | 40 | from IPython.core.alias import Alias, AliasManager |
|
41 | 41 | from IPython.core.autocall import ExitAutocall |
|
42 | 42 | from IPython.core.builtin_trap import BuiltinTrap |
|
43 | 43 | from IPython.core.events import EventManager, available_events |
|
44 | 44 | from IPython.core.compilerop import CachingCompiler, check_linecache_ipython |
|
45 | from IPython.core.debugger import Pdb | |
|
45 | 46 | from IPython.core.display_trap import DisplayTrap |
|
46 | 47 | from IPython.core.displayhook import DisplayHook |
|
47 | 48 | from IPython.core.displaypub import DisplayPublisher |
|
48 | 49 | from IPython.core.error import InputRejected, UsageError |
|
49 | 50 | from IPython.core.extensions import ExtensionManager |
|
50 | 51 | from IPython.core.formatters import DisplayFormatter |
|
51 | 52 | from IPython.core.history import HistoryManager |
|
52 | 53 | from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2 |
|
53 | 54 | from IPython.core.logger import Logger |
|
54 | 55 | from IPython.core.macro import Macro |
|
55 | 56 | from IPython.core.payload import PayloadManager |
|
56 | 57 | from IPython.core.prefilter import PrefilterManager |
|
57 | 58 | from IPython.core.profiledir import ProfileDir |
|
58 | 59 | from IPython.core.prompts import PromptManager |
|
59 | 60 | from IPython.core.usage import default_banner |
|
60 | 61 | from IPython.testing.skipdoctest import skip_doctest_py2, skip_doctest |
|
61 | 62 | from IPython.utils import PyColorize |
|
62 | 63 | from IPython.utils import io |
|
63 | 64 | from IPython.utils import py3compat |
|
64 | 65 | from IPython.utils import openpy |
|
65 | 66 | from IPython.utils.contexts import NoOpContext |
|
66 | 67 | from IPython.utils.decorators import undoc |
|
67 | 68 | from IPython.utils.io import ask_yes_no |
|
68 | 69 | from IPython.utils.ipstruct import Struct |
|
69 | 70 | from IPython.paths import get_ipython_dir |
|
70 | 71 | from IPython.utils.path import get_home_dir, get_py_filename, unquote_filename, ensure_dir_exists |
|
71 | 72 | from IPython.utils.process import system, getoutput |
|
72 | 73 | from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types, |
|
73 | 74 | with_metaclass, iteritems) |
|
74 | 75 | from IPython.utils.strdispatch import StrDispatch |
|
75 | 76 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
76 | 77 | from IPython.utils.text import (format_screen, LSString, SList, |
|
77 | 78 | DollarFormatter) |
|
78 | 79 | from traitlets import ( |
|
79 | 80 | Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type, |
|
80 | 81 | observe, default, |
|
81 | 82 | ) |
|
82 | 83 | from warnings import warn |
|
83 | 84 | from logging import error |
|
84 | 85 | import IPython.core.hooks |
|
85 | 86 | |
|
86 | 87 | #----------------------------------------------------------------------------- |
|
87 | 88 | # Globals |
|
88 | 89 | #----------------------------------------------------------------------------- |
|
89 | 90 | |
|
90 | 91 | # compiled regexps for autoindent management |
|
91 | 92 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
92 | 93 | |
|
93 | 94 | #----------------------------------------------------------------------------- |
|
94 | 95 | # Utilities |
|
95 | 96 | #----------------------------------------------------------------------------- |
|
96 | 97 | |
|
97 | 98 | @undoc |
|
98 | 99 | def softspace(file, newvalue): |
|
99 | 100 | """Copied from code.py, to remove the dependency""" |
|
100 | 101 | |
|
101 | 102 | oldvalue = 0 |
|
102 | 103 | try: |
|
103 | 104 | oldvalue = file.softspace |
|
104 | 105 | except AttributeError: |
|
105 | 106 | pass |
|
106 | 107 | try: |
|
107 | 108 | file.softspace = newvalue |
|
108 | 109 | except (AttributeError, TypeError): |
|
109 | 110 | # "attribute-less object" or "read-only attributes" |
|
110 | 111 | pass |
|
111 | 112 | return oldvalue |
|
112 | 113 | |
|
113 | 114 | @undoc |
|
114 | 115 | def no_op(*a, **kw): pass |
|
115 | 116 | |
|
116 | 117 | |
|
117 | 118 | class SpaceInInput(Exception): pass |
|
118 | 119 | |
|
119 | 120 | |
|
120 | 121 | def get_default_colors(): |
|
121 | 122 | if sys.platform=='darwin': |
|
122 | 123 | return "LightBG" |
|
123 | 124 | elif os.name=='nt': |
|
124 | 125 | return 'Linux' |
|
125 | 126 | else: |
|
126 | 127 | return 'Linux' |
|
127 | 128 | |
|
128 | 129 | |
|
129 | 130 | class SeparateUnicode(Unicode): |
|
130 | 131 | r"""A Unicode subclass to validate separate_in, separate_out, etc. |
|
131 | 132 | |
|
132 | 133 | This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``. |
|
133 | 134 | """ |
|
134 | 135 | |
|
135 | 136 | def validate(self, obj, value): |
|
136 | 137 | if value == '0': value = '' |
|
137 | 138 | value = value.replace('\\n','\n') |
|
138 | 139 | return super(SeparateUnicode, self).validate(obj, value) |
|
139 | 140 | |
|
140 | 141 | |
|
141 | 142 | @undoc |
|
142 | 143 | class DummyMod(object): |
|
143 | 144 | """A dummy module used for IPython's interactive module when |
|
144 | 145 | a namespace must be assigned to the module's __dict__.""" |
|
145 | 146 | pass |
|
146 | 147 | |
|
147 | 148 | |
|
148 | 149 | class ExecutionResult(object): |
|
149 | 150 | """The result of a call to :meth:`InteractiveShell.run_cell` |
|
150 | 151 | |
|
151 | 152 | Stores information about what took place. |
|
152 | 153 | """ |
|
153 | 154 | execution_count = None |
|
154 | 155 | error_before_exec = None |
|
155 | 156 | error_in_exec = None |
|
156 | 157 | result = None |
|
157 | 158 | |
|
158 | 159 | @property |
|
159 | 160 | def success(self): |
|
160 | 161 | return (self.error_before_exec is None) and (self.error_in_exec is None) |
|
161 | 162 | |
|
162 | 163 | def raise_error(self): |
|
163 | 164 | """Reraises error if `success` is `False`, otherwise does nothing""" |
|
164 | 165 | if self.error_before_exec is not None: |
|
165 | 166 | raise self.error_before_exec |
|
166 | 167 | if self.error_in_exec is not None: |
|
167 | 168 | raise self.error_in_exec |
|
168 | 169 | |
|
169 | 170 | |
|
170 | 171 | class InteractiveShell(SingletonConfigurable): |
|
171 | 172 | """An enhanced, interactive shell for Python.""" |
|
172 | 173 | |
|
173 | 174 | _instance = None |
|
174 | 175 | |
|
175 | 176 | ast_transformers = List([], help= |
|
176 | 177 | """ |
|
177 | 178 | A list of ast.NodeTransformer subclass instances, which will be applied |
|
178 | 179 | to user input before code is run. |
|
179 | 180 | """ |
|
180 | 181 | ).tag(config=True) |
|
181 | 182 | |
|
182 | 183 | autocall = Enum((0,1,2), default_value=0, help= |
|
183 | 184 | """ |
|
184 | 185 | Make IPython automatically call any callable object even if you didn't |
|
185 | 186 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' |
|
186 | 187 | automatically. The value can be '0' to disable the feature, '1' for |
|
187 | 188 | 'smart' autocall, where it is not applied if there are no more |
|
188 | 189 | arguments on the line, and '2' for 'full' autocall, where all callable |
|
189 | 190 | objects are automatically called (even if no arguments are present). |
|
190 | 191 | """ |
|
191 | 192 | ).tag(config=True) |
|
192 | 193 | # TODO: remove all autoindent logic and put into frontends. |
|
193 | 194 | # We can't do this yet because even runlines uses the autoindent. |
|
194 | 195 | autoindent = Bool(True, help= |
|
195 | 196 | """ |
|
196 | 197 | Autoindent IPython code entered interactively. |
|
197 | 198 | """ |
|
198 | 199 | ).tag(config=True) |
|
199 | 200 | automagic = Bool(True, help= |
|
200 | 201 | """ |
|
201 | 202 | Enable magic commands to be called without the leading %. |
|
202 | 203 | """ |
|
203 | 204 | ).tag(config=True) |
|
204 | 205 | |
|
205 | 206 | banner1 = Unicode(default_banner, |
|
206 | 207 | help="""The part of the banner to be printed before the profile""" |
|
207 | 208 | ).tag(config=True) |
|
208 | 209 | banner2 = Unicode('', |
|
209 | 210 | help="""The part of the banner to be printed after the profile""" |
|
210 | 211 | ).tag(config=True) |
|
211 | 212 | |
|
212 | 213 | cache_size = Integer(1000, help= |
|
213 | 214 | """ |
|
214 | 215 | Set the size of the output cache. The default is 1000, you can |
|
215 | 216 | change it permanently in your config file. Setting it to 0 completely |
|
216 | 217 | disables the caching system, and the minimum value accepted is 20 (if |
|
217 | 218 | you provide a value less than 20, it is reset to 0 and a warning is |
|
218 | 219 | issued). This limit is defined because otherwise you'll spend more |
|
219 | 220 | time re-flushing a too small cache than working |
|
220 | 221 | """ |
|
221 | 222 | ).tag(config=True) |
|
222 | 223 | color_info = Bool(True, help= |
|
223 | 224 | """ |
|
224 | 225 | Use colors for displaying information about objects. Because this |
|
225 | 226 | information is passed through a pager (like 'less'), and some pagers |
|
226 | 227 | get confused with color codes, this capability can be turned off. |
|
227 | 228 | """ |
|
228 | 229 | ).tag(config=True) |
|
229 | 230 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
230 | 231 | default_value=get_default_colors(), |
|
231 | 232 | help="Set the color scheme (NoColor, Linux, or LightBG)." |
|
232 | 233 | ).tag(config=True) |
|
233 | 234 | colors_force = Bool(False, help= |
|
234 | 235 | """ |
|
235 | 236 | Force use of ANSI color codes, regardless of OS and readline |
|
236 | 237 | availability. |
|
237 | 238 | """ |
|
238 | 239 | # FIXME: This is essentially a hack to allow ZMQShell to show colors |
|
239 | 240 | # without readline on Win32. When the ZMQ formatting system is |
|
240 | 241 | # refactored, this should be removed. |
|
241 | 242 | ) |
|
242 | 243 | debug = Bool(False).tag(config=True) |
|
243 | 244 | deep_reload = Bool(False, help= |
|
244 | 245 | """ |
|
245 | 246 | **Deprecated** |
|
246 | 247 | |
|
247 | 248 | Will be removed in IPython 6.0 |
|
248 | 249 | |
|
249 | 250 | Enable deep (recursive) reloading by default. IPython can use the |
|
250 | 251 | deep_reload module which reloads changes in modules recursively (it |
|
251 | 252 | replaces the reload() function, so you don't need to change anything to |
|
252 | 253 | use it). `deep_reload` forces a full reload of modules whose code may |
|
253 | 254 | have changed, which the default reload() function does not. When |
|
254 | 255 | deep_reload is off, IPython will use the normal reload(), but |
|
255 | 256 | deep_reload will still be available as dreload(). |
|
256 | 257 | """ |
|
257 | 258 | ).tag(config=True) |
|
258 | 259 | disable_failing_post_execute = Bool(False, |
|
259 | 260 | help="Don't call post-execute functions that have failed in the past." |
|
260 | 261 | ).tag(config=True) |
|
261 | 262 | display_formatter = Instance(DisplayFormatter, allow_none=True) |
|
262 | 263 | displayhook_class = Type(DisplayHook) |
|
263 | 264 | display_pub_class = Type(DisplayPublisher) |
|
264 | 265 | data_pub_class = None |
|
265 | 266 | |
|
266 | 267 | exit_now = Bool(False) |
|
267 | 268 | exiter = Instance(ExitAutocall) |
|
268 | 269 | @default('exiter') |
|
269 | 270 | def _exiter_default(self): |
|
270 | 271 | return ExitAutocall(self) |
|
271 | 272 | # Monotonically increasing execution counter |
|
272 | 273 | execution_count = Integer(1) |
|
273 | 274 | filename = Unicode("<ipython console>") |
|
274 | 275 | ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__ |
|
275 | 276 | |
|
276 | 277 | # Input splitter, to transform input line by line and detect when a block |
|
277 | 278 | # is ready to be executed. |
|
278 | 279 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
279 | 280 | (), {'line_input_checker': True}) |
|
280 | 281 | |
|
281 | 282 | # This InputSplitter instance is used to transform completed cells before |
|
282 | 283 | # running them. It allows cell magics to contain blank lines. |
|
283 | 284 | input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
284 | 285 | (), {'line_input_checker': False}) |
|
285 | 286 | |
|
286 | 287 | logstart = Bool(False, help= |
|
287 | 288 | """ |
|
288 | 289 | Start logging to the default log file in overwrite mode. |
|
289 | 290 | Use `logappend` to specify a log file to **append** logs to. |
|
290 | 291 | """ |
|
291 | 292 | ).tag(config=True) |
|
292 | 293 | logfile = Unicode('', help= |
|
293 | 294 | """ |
|
294 | 295 | The name of the logfile to use. |
|
295 | 296 | """ |
|
296 | 297 | ).tag(config=True) |
|
297 | 298 | logappend = Unicode('', help= |
|
298 | 299 | """ |
|
299 | 300 | Start logging to the given file in append mode. |
|
300 | 301 | Use `logfile` to specify a log file to **overwrite** logs to. |
|
301 | 302 | """ |
|
302 | 303 | ).tag(config=True) |
|
303 | 304 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
304 | 305 | ).tag(config=True) |
|
305 | 306 | pdb = Bool(False, help= |
|
306 | 307 | """ |
|
307 | 308 | Automatically call the pdb debugger after every exception. |
|
308 | 309 | """ |
|
309 | 310 | ).tag(config=True) |
|
310 | 311 | multiline_history = Bool(sys.platform != 'win32', |
|
311 | 312 | help="Save multi-line entries as one entry in readline history" |
|
312 | 313 | ).tag(config=True) |
|
313 | 314 | display_page = Bool(False, |
|
314 | 315 | help="""If True, anything that would be passed to the pager |
|
315 | 316 | will be displayed as regular output instead.""" |
|
316 | 317 | ).tag(config=True) |
|
317 | 318 | |
|
318 | 319 | # deprecated prompt traits: |
|
319 | 320 | |
|
320 | 321 | prompt_in1 = Unicode('In [\\#]: ', |
|
321 | 322 | help="Deprecated, will be removed in IPython 5.0, use PromptManager.in_template" |
|
322 | 323 | ).tag(config=True) |
|
323 | 324 | prompt_in2 = Unicode(' .\\D.: ', |
|
324 | 325 | help="Deprecated, will be removed in IPython 5.0, use PromptManager.in2_template" |
|
325 | 326 | ).tag(config=True) |
|
326 | 327 | prompt_out = Unicode('Out[\\#]: ', |
|
327 | 328 | help="Deprecated, will be removed in IPython 5.0, use PromptManager.out_template" |
|
328 | 329 | ).tag(config=True) |
|
329 | 330 | prompts_pad_left = Bool(True, |
|
330 | 331 | help="Deprecated, will be removed in IPython 5.0, use PromptManager.justify" |
|
331 | 332 | ).tag(config=True) |
|
332 | 333 | |
|
333 | 334 | @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left') |
|
334 | 335 | def _prompt_trait_changed(self, change): |
|
335 | 336 | table = { |
|
336 | 337 | 'prompt_in1' : 'in_template', |
|
337 | 338 | 'prompt_in2' : 'in2_template', |
|
338 | 339 | 'prompt_out' : 'out_template', |
|
339 | 340 | 'prompts_pad_left' : 'justify', |
|
340 | 341 | } |
|
341 | 342 | name = change['name'] |
|
342 | 343 | warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format( |
|
343 | 344 | name=name, newname=table[name]) |
|
344 | 345 | ) |
|
345 | 346 | # protect against weird cases where self.config may not exist: |
|
346 | 347 | if self.config is not None: |
|
347 | 348 | # propagate to corresponding PromptManager trait |
|
348 | 349 | setattr(self.config.PromptManager, table[name], change['new']) |
|
349 | 350 | |
|
350 | 351 | show_rewritten_input = Bool(True, |
|
351 | 352 | help="Show rewritten input, e.g. for autocall." |
|
352 | 353 | ).tag(config=True) |
|
353 | 354 | |
|
354 | 355 | quiet = Bool(False).tag(config=True) |
|
355 | 356 | |
|
356 | 357 | history_length = Integer(10000, |
|
357 | 358 | help='Total length of command history' |
|
358 | 359 | ).tag(config=True) |
|
359 | 360 | |
|
360 | 361 | history_load_length = Integer(1000, help= |
|
361 | 362 | """ |
|
362 | 363 | The number of saved history entries to be loaded |
|
363 | 364 | into the readline buffer at startup. |
|
364 | 365 | """ |
|
365 | 366 | ).tag(config=True) |
|
366 | 367 | |
|
367 | 368 | # The readline stuff will eventually be moved to the terminal subclass |
|
368 | 369 | # but for now, we can't do that as readline is welded in everywhere. |
|
369 | 370 | readline_use = Bool(True).tag(config=True) |
|
370 | 371 | readline_remove_delims = Unicode('-/~').tag(config=True) |
|
371 | 372 | readline_delims = Unicode() # set by init_readline() |
|
372 | 373 | # don't use \M- bindings by default, because they |
|
373 | 374 | # conflict with 8-bit encodings. See gh-58,gh-88 |
|
374 | 375 | readline_parse_and_bind = List([ |
|
375 | 376 | 'tab: complete', |
|
376 | 377 | '"\C-l": clear-screen', |
|
377 | 378 | 'set show-all-if-ambiguous on', |
|
378 | 379 | '"\C-o": tab-insert', |
|
379 | 380 | '"\C-r": reverse-search-history', |
|
380 | 381 | '"\C-s": forward-search-history', |
|
381 | 382 | '"\C-p": history-search-backward', |
|
382 | 383 | '"\C-n": history-search-forward', |
|
383 | 384 | '"\e[A": history-search-backward', |
|
384 | 385 | '"\e[B": history-search-forward', |
|
385 | 386 | '"\C-k": kill-line', |
|
386 | 387 | '"\C-u": unix-line-discard', |
|
387 | 388 | ]).tag(config=True) |
|
388 | 389 | |
|
389 | 390 | _custom_readline_config = False |
|
390 | 391 | |
|
391 | 392 | @observe('readline_parse_and_bind') |
|
392 | 393 | def _readline_parse_and_bind_changed(self, change): |
|
393 | 394 | # notice that readline config is customized |
|
394 | 395 | # indicates that it should have higher priority than inputrc |
|
395 | 396 | self._custom_readline_config = True |
|
396 | 397 | |
|
397 | 398 | ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'], |
|
398 | 399 | default_value='last_expr', |
|
399 | 400 | help=""" |
|
400 | 401 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
401 | 402 | run interactively (displaying output from expressions).""" |
|
402 | 403 | ).tag(config=True) |
|
403 | 404 | |
|
404 | 405 | # TODO: this part of prompt management should be moved to the frontends. |
|
405 | 406 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
406 | 407 | separate_in = SeparateUnicode('\n').tag(config=True) |
|
407 | 408 | separate_out = SeparateUnicode('').tag(config=True) |
|
408 | 409 | separate_out2 = SeparateUnicode('').tag(config=True) |
|
409 | 410 | wildcards_case_sensitive = Bool(True).tag(config=True) |
|
410 | 411 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
411 | 412 | default_value='Context').tag(config=True) |
|
412 | 413 | |
|
413 | 414 | # Subcomponents of InteractiveShell |
|
414 | 415 | alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True) |
|
415 | 416 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True) |
|
416 | 417 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True) |
|
417 | 418 | display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True) |
|
418 | 419 | extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True) |
|
419 | 420 | payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True) |
|
420 | 421 | history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True) |
|
421 | 422 | magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True) |
|
422 | 423 | |
|
423 | 424 | profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True) |
|
424 | 425 | @property |
|
425 | 426 | def profile(self): |
|
426 | 427 | if self.profile_dir is not None: |
|
427 | 428 | name = os.path.basename(self.profile_dir.location) |
|
428 | 429 | return name.replace('profile_','') |
|
429 | 430 | |
|
430 | 431 | |
|
431 | 432 | # Private interface |
|
432 | 433 | _post_execute = Dict() |
|
433 | 434 | |
|
434 | 435 | # Tracks any GUI loop loaded for pylab |
|
435 | 436 | pylab_gui_select = None |
|
436 | 437 | |
|
437 | 438 | def __init__(self, ipython_dir=None, profile_dir=None, |
|
438 | 439 | user_module=None, user_ns=None, |
|
439 | 440 | custom_exceptions=((), None), **kwargs): |
|
440 | 441 | |
|
441 | 442 | # This is where traits with a config_key argument are updated |
|
442 | 443 | # from the values on config. |
|
443 | 444 | super(InteractiveShell, self).__init__(**kwargs) |
|
444 | 445 | self.configurables = [self] |
|
445 | 446 | |
|
446 | 447 | # These are relatively independent and stateless |
|
447 | 448 | self.init_ipython_dir(ipython_dir) |
|
448 | 449 | self.init_profile_dir(profile_dir) |
|
449 | 450 | self.init_instance_attrs() |
|
450 | 451 | self.init_environment() |
|
451 | 452 | |
|
452 | 453 | # Check if we're in a virtualenv, and set up sys.path. |
|
453 | 454 | self.init_virtualenv() |
|
454 | 455 | |
|
455 | 456 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
456 | 457 | self.init_create_namespaces(user_module, user_ns) |
|
457 | 458 | # This has to be done after init_create_namespaces because it uses |
|
458 | 459 | # something in self.user_ns, but before init_sys_modules, which |
|
459 | 460 | # is the first thing to modify sys. |
|
460 | 461 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
461 | 462 | # is created, we are saving the overridden ones here. Not sure if this |
|
462 | 463 | # is what we want to do. |
|
463 | 464 | self.save_sys_module_state() |
|
464 | 465 | self.init_sys_modules() |
|
465 | 466 | |
|
466 | 467 | # While we're trying to have each part of the code directly access what |
|
467 | 468 | # it needs without keeping redundant references to objects, we have too |
|
468 | 469 | # much legacy code that expects ip.db to exist. |
|
469 | 470 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) |
|
470 | 471 | |
|
471 | 472 | self.init_history() |
|
472 | 473 | self.init_encoding() |
|
473 | 474 | self.init_prefilter() |
|
474 | 475 | |
|
475 | 476 | self.init_syntax_highlighting() |
|
476 | 477 | self.init_hooks() |
|
477 | 478 | self.init_events() |
|
478 | 479 | self.init_pushd_popd_magic() |
|
479 | 480 | # self.init_traceback_handlers use to be here, but we moved it below |
|
480 | 481 | # because it and init_io have to come after init_readline. |
|
481 | 482 | self.init_user_ns() |
|
482 | 483 | self.init_logger() |
|
483 | 484 | self.init_builtins() |
|
484 | 485 | |
|
485 | 486 | # The following was in post_config_initialization |
|
486 | 487 | self.init_inspector() |
|
487 | 488 | # init_readline() must come before init_io(), because init_io uses |
|
488 | 489 | # readline related things. |
|
489 | 490 | self.init_readline() |
|
490 | 491 | # We save this here in case user code replaces raw_input, but it needs |
|
491 | 492 | # to be after init_readline(), because PyPy's readline works by replacing |
|
492 | 493 | # raw_input. |
|
493 | 494 | if py3compat.PY3: |
|
494 | 495 | self.raw_input_original = input |
|
495 | 496 | else: |
|
496 | 497 | self.raw_input_original = raw_input |
|
497 | 498 | # init_completer must come after init_readline, because it needs to |
|
498 | 499 | # know whether readline is present or not system-wide to configure the |
|
499 | 500 | # completers, since the completion machinery can now operate |
|
500 | 501 | # independently of readline (e.g. over the network) |
|
501 | 502 | self.init_completer() |
|
502 | 503 | # TODO: init_io() needs to happen before init_traceback handlers |
|
503 | 504 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
504 | 505 | # This logic in in debugger.Pdb and should eventually be changed. |
|
505 | 506 | self.init_io() |
|
506 | 507 | self.init_traceback_handlers(custom_exceptions) |
|
507 | 508 | self.init_prompts() |
|
508 | 509 | self.init_display_formatter() |
|
509 | 510 | self.init_display_pub() |
|
510 | 511 | self.init_data_pub() |
|
511 | 512 | self.init_displayhook() |
|
512 | 513 | self.init_magics() |
|
513 | 514 | self.init_alias() |
|
514 | 515 | self.init_logstart() |
|
515 | 516 | self.init_pdb() |
|
516 | 517 | self.init_extension_manager() |
|
517 | 518 | self.init_payload() |
|
518 | 519 | self.init_deprecation_warnings() |
|
519 | 520 | self.hooks.late_startup_hook() |
|
520 | 521 | self.events.trigger('shell_initialized', self) |
|
521 | 522 | atexit.register(self.atexit_operations) |
|
522 | 523 | |
|
523 | 524 | def get_ipython(self): |
|
524 | 525 | """Return the currently running IPython instance.""" |
|
525 | 526 | return self |
|
526 | 527 | |
|
527 | 528 | #------------------------------------------------------------------------- |
|
528 | 529 | # Trait changed handlers |
|
529 | 530 | #------------------------------------------------------------------------- |
|
530 | 531 | @observe('ipython_dir') |
|
531 | 532 | def _ipython_dir_changed(self, change): |
|
532 | 533 | ensure_dir_exists(change['new']) |
|
533 | 534 | |
|
534 | 535 | def set_autoindent(self,value=None): |
|
535 | 536 | """Set the autoindent flag. |
|
536 | 537 | |
|
537 | 538 | If called with no arguments, it acts as a toggle.""" |
|
538 | 539 | if value is None: |
|
539 | 540 | self.autoindent = not self.autoindent |
|
540 | 541 | else: |
|
541 | 542 | self.autoindent = value |
|
542 | 543 | |
|
543 | 544 | #------------------------------------------------------------------------- |
|
544 | 545 | # init_* methods called by __init__ |
|
545 | 546 | #------------------------------------------------------------------------- |
|
546 | 547 | |
|
547 | 548 | def init_ipython_dir(self, ipython_dir): |
|
548 | 549 | if ipython_dir is not None: |
|
549 | 550 | self.ipython_dir = ipython_dir |
|
550 | 551 | return |
|
551 | 552 | |
|
552 | 553 | self.ipython_dir = get_ipython_dir() |
|
553 | 554 | |
|
554 | 555 | def init_profile_dir(self, profile_dir): |
|
555 | 556 | if profile_dir is not None: |
|
556 | 557 | self.profile_dir = profile_dir |
|
557 | 558 | return |
|
558 | 559 | self.profile_dir =\ |
|
559 | 560 | ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default') |
|
560 | 561 | |
|
561 | 562 | def init_instance_attrs(self): |
|
562 | 563 | self.more = False |
|
563 | 564 | |
|
564 | 565 | # command compiler |
|
565 | 566 | self.compile = CachingCompiler() |
|
566 | 567 | |
|
567 | 568 | # Make an empty namespace, which extension writers can rely on both |
|
568 | 569 | # existing and NEVER being used by ipython itself. This gives them a |
|
569 | 570 | # convenient location for storing additional information and state |
|
570 | 571 | # their extensions may require, without fear of collisions with other |
|
571 | 572 | # ipython names that may develop later. |
|
572 | 573 | self.meta = Struct() |
|
573 | 574 | |
|
574 | 575 | # Temporary files used for various purposes. Deleted at exit. |
|
575 | 576 | self.tempfiles = [] |
|
576 | 577 | self.tempdirs = [] |
|
577 | 578 | |
|
578 | 579 | # Keep track of readline usage (later set by init_readline) |
|
579 | 580 | self.has_readline = False |
|
580 | 581 | |
|
581 | 582 | # keep track of where we started running (mainly for crash post-mortem) |
|
582 | 583 | # This is not being used anywhere currently. |
|
583 | 584 | self.starting_dir = py3compat.getcwd() |
|
584 | 585 | |
|
585 | 586 | # Indentation management |
|
586 | 587 | self.indent_current_nsp = 0 |
|
587 | 588 | |
|
588 | 589 | # Dict to track post-execution functions that have been registered |
|
589 | 590 | self._post_execute = {} |
|
590 | 591 | |
|
591 | 592 | def init_environment(self): |
|
592 | 593 | """Any changes we need to make to the user's environment.""" |
|
593 | 594 | pass |
|
594 | 595 | |
|
595 | 596 | def init_encoding(self): |
|
596 | 597 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
597 | 598 | # under Win32 have it set to None, and we need to have a known valid |
|
598 | 599 | # encoding to use in the raw_input() method |
|
599 | 600 | try: |
|
600 | 601 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
601 | 602 | except AttributeError: |
|
602 | 603 | self.stdin_encoding = 'ascii' |
|
603 | 604 | |
|
604 | 605 | def init_syntax_highlighting(self): |
|
605 | 606 | # Python source parser/formatter for syntax highlighting |
|
606 | 607 | pyformat = PyColorize.Parser().format |
|
607 | 608 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
608 | 609 | |
|
609 | 610 | def init_pushd_popd_magic(self): |
|
610 | 611 | # for pushd/popd management |
|
611 | 612 | self.home_dir = get_home_dir() |
|
612 | 613 | |
|
613 | 614 | self.dir_stack = [] |
|
614 | 615 | |
|
615 | 616 | def init_logger(self): |
|
616 | 617 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
617 | 618 | logmode='rotate') |
|
618 | 619 | |
|
619 | 620 | def init_logstart(self): |
|
620 | 621 | """Initialize logging in case it was requested at the command line. |
|
621 | 622 | """ |
|
622 | 623 | if self.logappend: |
|
623 | 624 | self.magic('logstart %s append' % self.logappend) |
|
624 | 625 | elif self.logfile: |
|
625 | 626 | self.magic('logstart %s' % self.logfile) |
|
626 | 627 | elif self.logstart: |
|
627 | 628 | self.magic('logstart') |
|
628 | 629 | |
|
629 | 630 | def init_deprecation_warnings(self): |
|
630 | 631 | """ |
|
631 | 632 | register default filter for deprecation warning. |
|
632 | 633 | |
|
633 | 634 | This will allow deprecation warning of function used interactively to show |
|
634 | 635 | warning to users, and still hide deprecation warning from libraries import. |
|
635 | 636 | """ |
|
636 | 637 | warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__")) |
|
637 | 638 | |
|
638 | 639 | def init_builtins(self): |
|
639 | 640 | # A single, static flag that we set to True. Its presence indicates |
|
640 | 641 | # that an IPython shell has been created, and we make no attempts at |
|
641 | 642 | # removing on exit or representing the existence of more than one |
|
642 | 643 | # IPython at a time. |
|
643 | 644 | builtin_mod.__dict__['__IPYTHON__'] = True |
|
644 | 645 | |
|
645 | 646 | # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to |
|
646 | 647 | # manage on enter/exit, but with all our shells it's virtually |
|
647 | 648 | # impossible to get all the cases right. We're leaving the name in for |
|
648 | 649 | # those who adapted their codes to check for this flag, but will |
|
649 | 650 | # eventually remove it after a few more releases. |
|
650 | 651 | builtin_mod.__dict__['__IPYTHON__active'] = \ |
|
651 | 652 | 'Deprecated, check for __IPYTHON__' |
|
652 | 653 | |
|
653 | 654 | self.builtin_trap = BuiltinTrap(shell=self) |
|
654 | 655 | |
|
655 | 656 | def init_inspector(self): |
|
656 | 657 | # Object inspector |
|
657 | 658 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
658 | 659 | PyColorize.ANSICodeColors, |
|
659 | 660 | 'NoColor', |
|
660 | 661 | self.object_info_string_level) |
|
661 | 662 | |
|
662 | 663 | def init_io(self): |
|
663 | 664 | # This will just use sys.stdout and sys.stderr. If you want to |
|
664 | 665 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
665 | 666 | # *before* instantiating this class, because io holds onto |
|
666 | 667 | # references to the underlying streams. |
|
667 | 668 | if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline: |
|
668 | 669 | io.stdout = io.stderr = io.IOStream(self.readline._outputfile) |
|
669 | 670 | else: |
|
670 | 671 | io.stdout = io.IOStream(sys.stdout) |
|
671 | 672 | io.stderr = io.IOStream(sys.stderr) |
|
672 | 673 | |
|
673 | 674 | def init_prompts(self): |
|
674 | 675 | self.prompt_manager = PromptManager(shell=self, parent=self) |
|
675 | 676 | self.configurables.append(self.prompt_manager) |
|
676 | 677 | # Set system prompts, so that scripts can decide if they are running |
|
677 | 678 | # interactively. |
|
678 | 679 | sys.ps1 = 'In : ' |
|
679 | 680 | sys.ps2 = '...: ' |
|
680 | 681 | sys.ps3 = 'Out: ' |
|
681 | 682 | |
|
682 | 683 | def init_display_formatter(self): |
|
683 | 684 | self.display_formatter = DisplayFormatter(parent=self) |
|
684 | 685 | self.configurables.append(self.display_formatter) |
|
685 | 686 | |
|
686 | 687 | def init_display_pub(self): |
|
687 | 688 | self.display_pub = self.display_pub_class(parent=self) |
|
688 | 689 | self.configurables.append(self.display_pub) |
|
689 | 690 | |
|
690 | 691 | def init_data_pub(self): |
|
691 | 692 | if not self.data_pub_class: |
|
692 | 693 | self.data_pub = None |
|
693 | 694 | return |
|
694 | 695 | self.data_pub = self.data_pub_class(parent=self) |
|
695 | 696 | self.configurables.append(self.data_pub) |
|
696 | 697 | |
|
697 | 698 | def init_displayhook(self): |
|
698 | 699 | # Initialize displayhook, set in/out prompts and printing system |
|
699 | 700 | self.displayhook = self.displayhook_class( |
|
700 | 701 | parent=self, |
|
701 | 702 | shell=self, |
|
702 | 703 | cache_size=self.cache_size, |
|
703 | 704 | ) |
|
704 | 705 | self.configurables.append(self.displayhook) |
|
705 | 706 | # This is a context manager that installs/revmoes the displayhook at |
|
706 | 707 | # the appropriate time. |
|
707 | 708 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
708 | 709 | |
|
709 | 710 | def init_virtualenv(self): |
|
710 | 711 | """Add a virtualenv to sys.path so the user can import modules from it. |
|
711 | 712 | This isn't perfect: it doesn't use the Python interpreter with which the |
|
712 | 713 | virtualenv was built, and it ignores the --no-site-packages option. A |
|
713 | 714 | warning will appear suggesting the user installs IPython in the |
|
714 | 715 | virtualenv, but for many cases, it probably works well enough. |
|
715 | 716 | |
|
716 | 717 | Adapted from code snippets online. |
|
717 | 718 | |
|
718 | 719 | http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv |
|
719 | 720 | """ |
|
720 | 721 | if 'VIRTUAL_ENV' not in os.environ: |
|
721 | 722 | # Not in a virtualenv |
|
722 | 723 | return |
|
723 | 724 | |
|
724 | 725 | # venv detection: |
|
725 | 726 | # stdlib venv may symlink sys.executable, so we can't use realpath. |
|
726 | 727 | # but others can symlink *to* the venv Python, so we can't just use sys.executable. |
|
727 | 728 | # So we just check every item in the symlink tree (generally <= 3) |
|
728 | 729 | p = os.path.normcase(sys.executable) |
|
729 | 730 | paths = [p] |
|
730 | 731 | while os.path.islink(p): |
|
731 | 732 | p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p))) |
|
732 | 733 | paths.append(p) |
|
733 | 734 | p_venv = os.path.normcase(os.environ['VIRTUAL_ENV']) |
|
734 | 735 | if any(p.startswith(p_venv) for p in paths): |
|
735 | 736 | # Running properly in the virtualenv, don't need to do anything |
|
736 | 737 | return |
|
737 | 738 | |
|
738 | 739 | warn("Attempting to work in a virtualenv. If you encounter problems, please " |
|
739 | 740 | "install IPython inside the virtualenv.") |
|
740 | 741 | if sys.platform == "win32": |
|
741 | 742 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') |
|
742 | 743 | else: |
|
743 | 744 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', |
|
744 | 745 | 'python%d.%d' % sys.version_info[:2], 'site-packages') |
|
745 | 746 | |
|
746 | 747 | import site |
|
747 | 748 | sys.path.insert(0, virtual_env) |
|
748 | 749 | site.addsitedir(virtual_env) |
|
749 | 750 | |
|
750 | 751 | #------------------------------------------------------------------------- |
|
751 | 752 | # Things related to injections into the sys module |
|
752 | 753 | #------------------------------------------------------------------------- |
|
753 | 754 | |
|
754 | 755 | def save_sys_module_state(self): |
|
755 | 756 | """Save the state of hooks in the sys module. |
|
756 | 757 | |
|
757 | 758 | This has to be called after self.user_module is created. |
|
758 | 759 | """ |
|
759 | 760 | self._orig_sys_module_state = {'stdin': sys.stdin, |
|
760 | 761 | 'stdout': sys.stdout, |
|
761 | 762 | 'stderr': sys.stderr, |
|
762 | 763 | 'excepthook': sys.excepthook} |
|
763 | 764 | self._orig_sys_modules_main_name = self.user_module.__name__ |
|
764 | 765 | self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) |
|
765 | 766 | |
|
766 | 767 | def restore_sys_module_state(self): |
|
767 | 768 | """Restore the state of the sys module.""" |
|
768 | 769 | try: |
|
769 | 770 | for k, v in iteritems(self._orig_sys_module_state): |
|
770 | 771 | setattr(sys, k, v) |
|
771 | 772 | except AttributeError: |
|
772 | 773 | pass |
|
773 | 774 | # Reset what what done in self.init_sys_modules |
|
774 | 775 | if self._orig_sys_modules_main_mod is not None: |
|
775 | 776 | sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod |
|
776 | 777 | |
|
777 | 778 | #------------------------------------------------------------------------- |
|
778 | 779 | # Things related to the banner |
|
779 | 780 | #------------------------------------------------------------------------- |
|
780 | 781 | |
|
781 | 782 | @property |
|
782 | 783 | def banner(self): |
|
783 | 784 | banner = self.banner1 |
|
784 | 785 | if self.profile and self.profile != 'default': |
|
785 | 786 | banner += '\nIPython profile: %s\n' % self.profile |
|
786 | 787 | if self.banner2: |
|
787 | 788 | banner += '\n' + self.banner2 |
|
788 | 789 | return banner |
|
789 | 790 | |
|
790 | 791 | def show_banner(self, banner=None): |
|
791 | 792 | if banner is None: |
|
792 | 793 | banner = self.banner |
|
793 | 794 | sys.stdout.write(banner) |
|
794 | 795 | |
|
795 | 796 | #------------------------------------------------------------------------- |
|
796 | 797 | # Things related to hooks |
|
797 | 798 | #------------------------------------------------------------------------- |
|
798 | 799 | |
|
799 | 800 | def init_hooks(self): |
|
800 | 801 | # hooks holds pointers used for user-side customizations |
|
801 | 802 | self.hooks = Struct() |
|
802 | 803 | |
|
803 | 804 | self.strdispatchers = {} |
|
804 | 805 | |
|
805 | 806 | # Set all default hooks, defined in the IPython.hooks module. |
|
806 | 807 | hooks = IPython.core.hooks |
|
807 | 808 | for hook_name in hooks.__all__: |
|
808 | 809 | # default hooks have priority 100, i.e. low; user hooks should have |
|
809 | 810 | # 0-100 priority |
|
810 | 811 | self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False) |
|
811 | 812 | |
|
812 | 813 | if self.display_page: |
|
813 | 814 | self.set_hook('show_in_pager', page.as_hook(page.display_page), 90) |
|
814 | 815 | |
|
815 | 816 | def set_hook(self,name,hook, priority=50, str_key=None, re_key=None, |
|
816 | 817 | _warn_deprecated=True): |
|
817 | 818 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
818 | 819 | |
|
819 | 820 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
820 | 821 | adding your function to one of these hooks, you can modify IPython's |
|
821 | 822 | behavior to call at runtime your own routines.""" |
|
822 | 823 | |
|
823 | 824 | # At some point in the future, this should validate the hook before it |
|
824 | 825 | # accepts it. Probably at least check that the hook takes the number |
|
825 | 826 | # of args it's supposed to. |
|
826 | 827 | |
|
827 | 828 | f = types.MethodType(hook,self) |
|
828 | 829 | |
|
829 | 830 | # check if the hook is for strdispatcher first |
|
830 | 831 | if str_key is not None: |
|
831 | 832 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
832 | 833 | sdp.add_s(str_key, f, priority ) |
|
833 | 834 | self.strdispatchers[name] = sdp |
|
834 | 835 | return |
|
835 | 836 | if re_key is not None: |
|
836 | 837 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
837 | 838 | sdp.add_re(re.compile(re_key), f, priority ) |
|
838 | 839 | self.strdispatchers[name] = sdp |
|
839 | 840 | return |
|
840 | 841 | |
|
841 | 842 | dp = getattr(self.hooks, name, None) |
|
842 | 843 | if name not in IPython.core.hooks.__all__: |
|
843 | 844 | print("Warning! Hook '%s' is not one of %s" % \ |
|
844 | 845 | (name, IPython.core.hooks.__all__ )) |
|
845 | 846 | |
|
846 | 847 | if _warn_deprecated and (name in IPython.core.hooks.deprecated): |
|
847 | 848 | alternative = IPython.core.hooks.deprecated[name] |
|
848 | 849 | warn("Hook {} is deprecated. Use {} instead.".format(name, alternative)) |
|
849 | 850 | |
|
850 | 851 | if not dp: |
|
851 | 852 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
852 | 853 | |
|
853 | 854 | try: |
|
854 | 855 | dp.add(f,priority) |
|
855 | 856 | except AttributeError: |
|
856 | 857 | # it was not commandchain, plain old func - replace |
|
857 | 858 | dp = f |
|
858 | 859 | |
|
859 | 860 | setattr(self.hooks,name, dp) |
|
860 | 861 | |
|
861 | 862 | #------------------------------------------------------------------------- |
|
862 | 863 | # Things related to events |
|
863 | 864 | #------------------------------------------------------------------------- |
|
864 | 865 | |
|
865 | 866 | def init_events(self): |
|
866 | 867 | self.events = EventManager(self, available_events) |
|
867 | 868 | |
|
868 | 869 | self.events.register("pre_execute", self._clear_warning_registry) |
|
869 | 870 | |
|
870 | 871 | def register_post_execute(self, func): |
|
871 | 872 | """DEPRECATED: Use ip.events.register('post_run_cell', func) |
|
872 | 873 | |
|
873 | 874 | Register a function for calling after code execution. |
|
874 | 875 | """ |
|
875 | 876 | warn("ip.register_post_execute is deprecated, use " |
|
876 | 877 | "ip.events.register('post_run_cell', func) instead.") |
|
877 | 878 | self.events.register('post_run_cell', func) |
|
878 | 879 | |
|
879 | 880 | def _clear_warning_registry(self): |
|
880 | 881 | # clear the warning registry, so that different code blocks with |
|
881 | 882 | # overlapping line number ranges don't cause spurious suppression of |
|
882 | 883 | # warnings (see gh-6611 for details) |
|
883 | 884 | if "__warningregistry__" in self.user_global_ns: |
|
884 | 885 | del self.user_global_ns["__warningregistry__"] |
|
885 | 886 | |
|
886 | 887 | #------------------------------------------------------------------------- |
|
887 | 888 | # Things related to the "main" module |
|
888 | 889 | #------------------------------------------------------------------------- |
|
889 | 890 | |
|
890 | 891 | def new_main_mod(self, filename, modname): |
|
891 | 892 | """Return a new 'main' module object for user code execution. |
|
892 | 893 | |
|
893 | 894 | ``filename`` should be the path of the script which will be run in the |
|
894 | 895 | module. Requests with the same filename will get the same module, with |
|
895 | 896 | its namespace cleared. |
|
896 | 897 | |
|
897 | 898 | ``modname`` should be the module name - normally either '__main__' or |
|
898 | 899 | the basename of the file without the extension. |
|
899 | 900 | |
|
900 | 901 | When scripts are executed via %run, we must keep a reference to their |
|
901 | 902 | __main__ module around so that Python doesn't |
|
902 | 903 | clear it, rendering references to module globals useless. |
|
903 | 904 | |
|
904 | 905 | This method keeps said reference in a private dict, keyed by the |
|
905 | 906 | absolute path of the script. This way, for multiple executions of the |
|
906 | 907 | same script we only keep one copy of the namespace (the last one), |
|
907 | 908 | thus preventing memory leaks from old references while allowing the |
|
908 | 909 | objects from the last execution to be accessible. |
|
909 | 910 | """ |
|
910 | 911 | filename = os.path.abspath(filename) |
|
911 | 912 | try: |
|
912 | 913 | main_mod = self._main_mod_cache[filename] |
|
913 | 914 | except KeyError: |
|
914 | 915 | main_mod = self._main_mod_cache[filename] = types.ModuleType( |
|
915 | 916 | py3compat.cast_bytes_py2(modname), |
|
916 | 917 | doc="Module created for script run in IPython") |
|
917 | 918 | else: |
|
918 | 919 | main_mod.__dict__.clear() |
|
919 | 920 | main_mod.__name__ = modname |
|
920 | 921 | |
|
921 | 922 | main_mod.__file__ = filename |
|
922 | 923 | # It seems pydoc (and perhaps others) needs any module instance to |
|
923 | 924 | # implement a __nonzero__ method |
|
924 | 925 | main_mod.__nonzero__ = lambda : True |
|
925 | 926 | |
|
926 | 927 | return main_mod |
|
927 | 928 | |
|
928 | 929 | def clear_main_mod_cache(self): |
|
929 | 930 | """Clear the cache of main modules. |
|
930 | 931 | |
|
931 | 932 | Mainly for use by utilities like %reset. |
|
932 | 933 | |
|
933 | 934 | Examples |
|
934 | 935 | -------- |
|
935 | 936 | |
|
936 | 937 | In [15]: import IPython |
|
937 | 938 | |
|
938 | 939 | In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython') |
|
939 | 940 | |
|
940 | 941 | In [17]: len(_ip._main_mod_cache) > 0 |
|
941 | 942 | Out[17]: True |
|
942 | 943 | |
|
943 | 944 | In [18]: _ip.clear_main_mod_cache() |
|
944 | 945 | |
|
945 | 946 | In [19]: len(_ip._main_mod_cache) == 0 |
|
946 | 947 | Out[19]: True |
|
947 | 948 | """ |
|
948 | 949 | self._main_mod_cache.clear() |
|
949 | 950 | |
|
950 | 951 | #------------------------------------------------------------------------- |
|
951 | 952 | # Things related to debugging |
|
952 | 953 | #------------------------------------------------------------------------- |
|
953 | 954 | |
|
954 | 955 | def init_pdb(self): |
|
955 | 956 | # Set calling of pdb on exceptions |
|
956 | 957 | # self.call_pdb is a property |
|
957 | 958 | self.call_pdb = self.pdb |
|
958 | 959 | |
|
959 | 960 | def _get_call_pdb(self): |
|
960 | 961 | return self._call_pdb |
|
961 | 962 | |
|
962 | 963 | def _set_call_pdb(self,val): |
|
963 | 964 | |
|
964 | 965 | if val not in (0,1,False,True): |
|
965 | 966 | raise ValueError('new call_pdb value must be boolean') |
|
966 | 967 | |
|
967 | 968 | # store value in instance |
|
968 | 969 | self._call_pdb = val |
|
969 | 970 | |
|
970 | 971 | # notify the actual exception handlers |
|
971 | 972 | self.InteractiveTB.call_pdb = val |
|
972 | 973 | |
|
973 | 974 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
974 | 975 | 'Control auto-activation of pdb at exceptions') |
|
975 | 976 | |
|
976 | 977 | def debugger(self,force=False): |
|
977 | 978 | """Call the pdb debugger. |
|
978 | 979 | |
|
979 | 980 | Keywords: |
|
980 | 981 | |
|
981 | 982 | - force(False): by default, this routine checks the instance call_pdb |
|
982 | 983 | flag and does not actually invoke the debugger if the flag is false. |
|
983 | 984 | The 'force' option forces the debugger to activate even if the flag |
|
984 | 985 | is false. |
|
985 | 986 | """ |
|
986 | 987 | |
|
987 | 988 | if not (force or self.call_pdb): |
|
988 | 989 | return |
|
989 | 990 | |
|
990 | 991 | if not hasattr(sys,'last_traceback'): |
|
991 | 992 | error('No traceback has been produced, nothing to debug.') |
|
992 | 993 | return |
|
993 | 994 | |
|
994 | 995 | |
|
995 | 996 | with self.readline_no_record: |
|
996 | 997 | self.InteractiveTB.debugger(force=True) |
|
997 | 998 | |
|
998 | 999 | #------------------------------------------------------------------------- |
|
999 | 1000 | # Things related to IPython's various namespaces |
|
1000 | 1001 | #------------------------------------------------------------------------- |
|
1001 | 1002 | default_user_namespaces = True |
|
1002 | 1003 | |
|
1003 | 1004 | def init_create_namespaces(self, user_module=None, user_ns=None): |
|
1004 | 1005 | # Create the namespace where the user will operate. user_ns is |
|
1005 | 1006 | # normally the only one used, and it is passed to the exec calls as |
|
1006 | 1007 | # the locals argument. But we do carry a user_global_ns namespace |
|
1007 | 1008 | # given as the exec 'globals' argument, This is useful in embedding |
|
1008 | 1009 | # situations where the ipython shell opens in a context where the |
|
1009 | 1010 | # distinction between locals and globals is meaningful. For |
|
1010 | 1011 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
1011 | 1012 | |
|
1012 | 1013 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
1013 | 1014 | # level as a dict instead of a module. This is a manual fix, but I |
|
1014 | 1015 | # should really track down where the problem is coming from. Alex |
|
1015 | 1016 | # Schmolck reported this problem first. |
|
1016 | 1017 | |
|
1017 | 1018 | # A useful post by Alex Martelli on this topic: |
|
1018 | 1019 | # Re: inconsistent value from __builtins__ |
|
1019 | 1020 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
1020 | 1021 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
1021 | 1022 | # Gruppen: comp.lang.python |
|
1022 | 1023 | |
|
1023 | 1024 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
1024 | 1025 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
1025 | 1026 | # > <type 'dict'> |
|
1026 | 1027 | # > >>> print type(__builtins__) |
|
1027 | 1028 | # > <type 'module'> |
|
1028 | 1029 | # > Is this difference in return value intentional? |
|
1029 | 1030 | |
|
1030 | 1031 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
1031 | 1032 | # or a module, and it's been that way for a long time. Whether it's |
|
1032 | 1033 | # intentional (or sensible), I don't know. In any case, the idea is |
|
1033 | 1034 | # that if you need to access the built-in namespace directly, you |
|
1034 | 1035 | # should start with "import __builtin__" (note, no 's') which will |
|
1035 | 1036 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
1036 | 1037 | |
|
1037 | 1038 | # These routines return a properly built module and dict as needed by |
|
1038 | 1039 | # the rest of the code, and can also be used by extension writers to |
|
1039 | 1040 | # generate properly initialized namespaces. |
|
1040 | 1041 | if (user_ns is not None) or (user_module is not None): |
|
1041 | 1042 | self.default_user_namespaces = False |
|
1042 | 1043 | self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) |
|
1043 | 1044 | |
|
1044 | 1045 | # A record of hidden variables we have added to the user namespace, so |
|
1045 | 1046 | # we can list later only variables defined in actual interactive use. |
|
1046 | 1047 | self.user_ns_hidden = {} |
|
1047 | 1048 | |
|
1048 | 1049 | # Now that FakeModule produces a real module, we've run into a nasty |
|
1049 | 1050 | # problem: after script execution (via %run), the module where the user |
|
1050 | 1051 | # code ran is deleted. Now that this object is a true module (needed |
|
1051 | 1052 | # so doctest and other tools work correctly), the Python module |
|
1052 | 1053 | # teardown mechanism runs over it, and sets to None every variable |
|
1053 | 1054 | # present in that module. Top-level references to objects from the |
|
1054 | 1055 | # script survive, because the user_ns is updated with them. However, |
|
1055 | 1056 | # calling functions defined in the script that use other things from |
|
1056 | 1057 | # the script will fail, because the function's closure had references |
|
1057 | 1058 | # to the original objects, which are now all None. So we must protect |
|
1058 | 1059 | # these modules from deletion by keeping a cache. |
|
1059 | 1060 | # |
|
1060 | 1061 | # To avoid keeping stale modules around (we only need the one from the |
|
1061 | 1062 | # last run), we use a dict keyed with the full path to the script, so |
|
1062 | 1063 | # only the last version of the module is held in the cache. Note, |
|
1063 | 1064 | # however, that we must cache the module *namespace contents* (their |
|
1064 | 1065 | # __dict__). Because if we try to cache the actual modules, old ones |
|
1065 | 1066 | # (uncached) could be destroyed while still holding references (such as |
|
1066 | 1067 | # those held by GUI objects that tend to be long-lived)> |
|
1067 | 1068 | # |
|
1068 | 1069 | # The %reset command will flush this cache. See the cache_main_mod() |
|
1069 | 1070 | # and clear_main_mod_cache() methods for details on use. |
|
1070 | 1071 | |
|
1071 | 1072 | # This is the cache used for 'main' namespaces |
|
1072 | 1073 | self._main_mod_cache = {} |
|
1073 | 1074 | |
|
1074 | 1075 | # A table holding all the namespaces IPython deals with, so that |
|
1075 | 1076 | # introspection facilities can search easily. |
|
1076 | 1077 | self.ns_table = {'user_global':self.user_module.__dict__, |
|
1077 | 1078 | 'user_local':self.user_ns, |
|
1078 | 1079 | 'builtin':builtin_mod.__dict__ |
|
1079 | 1080 | } |
|
1080 | 1081 | |
|
1081 | 1082 | @property |
|
1082 | 1083 | def user_global_ns(self): |
|
1083 | 1084 | return self.user_module.__dict__ |
|
1084 | 1085 | |
|
1085 | 1086 | def prepare_user_module(self, user_module=None, user_ns=None): |
|
1086 | 1087 | """Prepare the module and namespace in which user code will be run. |
|
1087 | 1088 | |
|
1088 | 1089 | When IPython is started normally, both parameters are None: a new module |
|
1089 | 1090 | is created automatically, and its __dict__ used as the namespace. |
|
1090 | 1091 | |
|
1091 | 1092 | If only user_module is provided, its __dict__ is used as the namespace. |
|
1092 | 1093 | If only user_ns is provided, a dummy module is created, and user_ns |
|
1093 | 1094 | becomes the global namespace. If both are provided (as they may be |
|
1094 | 1095 | when embedding), user_ns is the local namespace, and user_module |
|
1095 | 1096 | provides the global namespace. |
|
1096 | 1097 | |
|
1097 | 1098 | Parameters |
|
1098 | 1099 | ---------- |
|
1099 | 1100 | user_module : module, optional |
|
1100 | 1101 | The current user module in which IPython is being run. If None, |
|
1101 | 1102 | a clean module will be created. |
|
1102 | 1103 | user_ns : dict, optional |
|
1103 | 1104 | A namespace in which to run interactive commands. |
|
1104 | 1105 | |
|
1105 | 1106 | Returns |
|
1106 | 1107 | ------- |
|
1107 | 1108 | A tuple of user_module and user_ns, each properly initialised. |
|
1108 | 1109 | """ |
|
1109 | 1110 | if user_module is None and user_ns is not None: |
|
1110 | 1111 | user_ns.setdefault("__name__", "__main__") |
|
1111 | 1112 | user_module = DummyMod() |
|
1112 | 1113 | user_module.__dict__ = user_ns |
|
1113 | 1114 | |
|
1114 | 1115 | if user_module is None: |
|
1115 | 1116 | user_module = types.ModuleType("__main__", |
|
1116 | 1117 | doc="Automatically created module for IPython interactive environment") |
|
1117 | 1118 | |
|
1118 | 1119 | # We must ensure that __builtin__ (without the final 's') is always |
|
1119 | 1120 | # available and pointing to the __builtin__ *module*. For more details: |
|
1120 | 1121 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1121 | 1122 | user_module.__dict__.setdefault('__builtin__', builtin_mod) |
|
1122 | 1123 | user_module.__dict__.setdefault('__builtins__', builtin_mod) |
|
1123 | 1124 | |
|
1124 | 1125 | if user_ns is None: |
|
1125 | 1126 | user_ns = user_module.__dict__ |
|
1126 | 1127 | |
|
1127 | 1128 | return user_module, user_ns |
|
1128 | 1129 | |
|
1129 | 1130 | def init_sys_modules(self): |
|
1130 | 1131 | # We need to insert into sys.modules something that looks like a |
|
1131 | 1132 | # module but which accesses the IPython namespace, for shelve and |
|
1132 | 1133 | # pickle to work interactively. Normally they rely on getting |
|
1133 | 1134 | # everything out of __main__, but for embedding purposes each IPython |
|
1134 | 1135 | # instance has its own private namespace, so we can't go shoving |
|
1135 | 1136 | # everything into __main__. |
|
1136 | 1137 | |
|
1137 | 1138 | # note, however, that we should only do this for non-embedded |
|
1138 | 1139 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
1139 | 1140 | # namespace. Embedded instances, on the other hand, should not do |
|
1140 | 1141 | # this because they need to manage the user local/global namespaces |
|
1141 | 1142 | # only, but they live within a 'normal' __main__ (meaning, they |
|
1142 | 1143 | # shouldn't overtake the execution environment of the script they're |
|
1143 | 1144 | # embedded in). |
|
1144 | 1145 | |
|
1145 | 1146 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
1146 | 1147 | main_name = self.user_module.__name__ |
|
1147 | 1148 | sys.modules[main_name] = self.user_module |
|
1148 | 1149 | |
|
1149 | 1150 | def init_user_ns(self): |
|
1150 | 1151 | """Initialize all user-visible namespaces to their minimum defaults. |
|
1151 | 1152 | |
|
1152 | 1153 | Certain history lists are also initialized here, as they effectively |
|
1153 | 1154 | act as user namespaces. |
|
1154 | 1155 | |
|
1155 | 1156 | Notes |
|
1156 | 1157 | ----- |
|
1157 | 1158 | All data structures here are only filled in, they are NOT reset by this |
|
1158 | 1159 | method. If they were not empty before, data will simply be added to |
|
1159 | 1160 | therm. |
|
1160 | 1161 | """ |
|
1161 | 1162 | # This function works in two parts: first we put a few things in |
|
1162 | 1163 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
1163 | 1164 | # initial variables aren't shown by %who. After the sync, we add the |
|
1164 | 1165 | # rest of what we *do* want the user to see with %who even on a new |
|
1165 | 1166 | # session (probably nothing, so they really only see their own stuff) |
|
1166 | 1167 | |
|
1167 | 1168 | # The user dict must *always* have a __builtin__ reference to the |
|
1168 | 1169 | # Python standard __builtin__ namespace, which must be imported. |
|
1169 | 1170 | # This is so that certain operations in prompt evaluation can be |
|
1170 | 1171 | # reliably executed with builtins. Note that we can NOT use |
|
1171 | 1172 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
1172 | 1173 | # module, and can even mutate at runtime, depending on the context |
|
1173 | 1174 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
1174 | 1175 | # always a module object, though it must be explicitly imported. |
|
1175 | 1176 | |
|
1176 | 1177 | # For more details: |
|
1177 | 1178 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1178 | 1179 | ns = dict() |
|
1179 | 1180 | |
|
1180 | 1181 | # make global variables for user access to the histories |
|
1181 | 1182 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
1182 | 1183 | ns['_oh'] = self.history_manager.output_hist |
|
1183 | 1184 | ns['_dh'] = self.history_manager.dir_hist |
|
1184 | 1185 | |
|
1185 | 1186 | ns['_sh'] = shadowns |
|
1186 | 1187 | |
|
1187 | 1188 | # user aliases to input and output histories. These shouldn't show up |
|
1188 | 1189 | # in %who, as they can have very large reprs. |
|
1189 | 1190 | ns['In'] = self.history_manager.input_hist_parsed |
|
1190 | 1191 | ns['Out'] = self.history_manager.output_hist |
|
1191 | 1192 | |
|
1192 | 1193 | # Store myself as the public api!!! |
|
1193 | 1194 | ns['get_ipython'] = self.get_ipython |
|
1194 | 1195 | |
|
1195 | 1196 | ns['exit'] = self.exiter |
|
1196 | 1197 | ns['quit'] = self.exiter |
|
1197 | 1198 | |
|
1198 | 1199 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
1199 | 1200 | # by %who |
|
1200 | 1201 | self.user_ns_hidden.update(ns) |
|
1201 | 1202 | |
|
1202 | 1203 | # Anything put into ns now would show up in %who. Think twice before |
|
1203 | 1204 | # putting anything here, as we really want %who to show the user their |
|
1204 | 1205 | # stuff, not our variables. |
|
1205 | 1206 | |
|
1206 | 1207 | # Finally, update the real user's namespace |
|
1207 | 1208 | self.user_ns.update(ns) |
|
1208 | 1209 | |
|
1209 | 1210 | @property |
|
1210 | 1211 | def all_ns_refs(self): |
|
1211 | 1212 | """Get a list of references to all the namespace dictionaries in which |
|
1212 | 1213 | IPython might store a user-created object. |
|
1213 | 1214 | |
|
1214 | 1215 | Note that this does not include the displayhook, which also caches |
|
1215 | 1216 | objects from the output.""" |
|
1216 | 1217 | return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \ |
|
1217 | 1218 | [m.__dict__ for m in self._main_mod_cache.values()] |
|
1218 | 1219 | |
|
1219 | 1220 | def reset(self, new_session=True): |
|
1220 | 1221 | """Clear all internal namespaces, and attempt to release references to |
|
1221 | 1222 | user objects. |
|
1222 | 1223 | |
|
1223 | 1224 | If new_session is True, a new history session will be opened. |
|
1224 | 1225 | """ |
|
1225 | 1226 | # Clear histories |
|
1226 | 1227 | self.history_manager.reset(new_session) |
|
1227 | 1228 | # Reset counter used to index all histories |
|
1228 | 1229 | if new_session: |
|
1229 | 1230 | self.execution_count = 1 |
|
1230 | 1231 | |
|
1231 | 1232 | # Flush cached output items |
|
1232 | 1233 | if self.displayhook.do_full_cache: |
|
1233 | 1234 | self.displayhook.flush() |
|
1234 | 1235 | |
|
1235 | 1236 | # The main execution namespaces must be cleared very carefully, |
|
1236 | 1237 | # skipping the deletion of the builtin-related keys, because doing so |
|
1237 | 1238 | # would cause errors in many object's __del__ methods. |
|
1238 | 1239 | if self.user_ns is not self.user_global_ns: |
|
1239 | 1240 | self.user_ns.clear() |
|
1240 | 1241 | ns = self.user_global_ns |
|
1241 | 1242 | drop_keys = set(ns.keys()) |
|
1242 | 1243 | drop_keys.discard('__builtin__') |
|
1243 | 1244 | drop_keys.discard('__builtins__') |
|
1244 | 1245 | drop_keys.discard('__name__') |
|
1245 | 1246 | for k in drop_keys: |
|
1246 | 1247 | del ns[k] |
|
1247 | 1248 | |
|
1248 | 1249 | self.user_ns_hidden.clear() |
|
1249 | 1250 | |
|
1250 | 1251 | # Restore the user namespaces to minimal usability |
|
1251 | 1252 | self.init_user_ns() |
|
1252 | 1253 | |
|
1253 | 1254 | # Restore the default and user aliases |
|
1254 | 1255 | self.alias_manager.clear_aliases() |
|
1255 | 1256 | self.alias_manager.init_aliases() |
|
1256 | 1257 | |
|
1257 | 1258 | # Flush the private list of module references kept for script |
|
1258 | 1259 | # execution protection |
|
1259 | 1260 | self.clear_main_mod_cache() |
|
1260 | 1261 | |
|
1261 | 1262 | def del_var(self, varname, by_name=False): |
|
1262 | 1263 | """Delete a variable from the various namespaces, so that, as |
|
1263 | 1264 | far as possible, we're not keeping any hidden references to it. |
|
1264 | 1265 | |
|
1265 | 1266 | Parameters |
|
1266 | 1267 | ---------- |
|
1267 | 1268 | varname : str |
|
1268 | 1269 | The name of the variable to delete. |
|
1269 | 1270 | by_name : bool |
|
1270 | 1271 | If True, delete variables with the given name in each |
|
1271 | 1272 | namespace. If False (default), find the variable in the user |
|
1272 | 1273 | namespace, and delete references to it. |
|
1273 | 1274 | """ |
|
1274 | 1275 | if varname in ('__builtin__', '__builtins__'): |
|
1275 | 1276 | raise ValueError("Refusing to delete %s" % varname) |
|
1276 | 1277 | |
|
1277 | 1278 | ns_refs = self.all_ns_refs |
|
1278 | 1279 | |
|
1279 | 1280 | if by_name: # Delete by name |
|
1280 | 1281 | for ns in ns_refs: |
|
1281 | 1282 | try: |
|
1282 | 1283 | del ns[varname] |
|
1283 | 1284 | except KeyError: |
|
1284 | 1285 | pass |
|
1285 | 1286 | else: # Delete by object |
|
1286 | 1287 | try: |
|
1287 | 1288 | obj = self.user_ns[varname] |
|
1288 | 1289 | except KeyError: |
|
1289 | 1290 | raise NameError("name '%s' is not defined" % varname) |
|
1290 | 1291 | # Also check in output history |
|
1291 | 1292 | ns_refs.append(self.history_manager.output_hist) |
|
1292 | 1293 | for ns in ns_refs: |
|
1293 | 1294 | to_delete = [n for n, o in iteritems(ns) if o is obj] |
|
1294 | 1295 | for name in to_delete: |
|
1295 | 1296 | del ns[name] |
|
1296 | 1297 | |
|
1297 | 1298 | # displayhook keeps extra references, but not in a dictionary |
|
1298 | 1299 | for name in ('_', '__', '___'): |
|
1299 | 1300 | if getattr(self.displayhook, name) is obj: |
|
1300 | 1301 | setattr(self.displayhook, name, None) |
|
1301 | 1302 | |
|
1302 | 1303 | def reset_selective(self, regex=None): |
|
1303 | 1304 | """Clear selective variables from internal namespaces based on a |
|
1304 | 1305 | specified regular expression. |
|
1305 | 1306 | |
|
1306 | 1307 | Parameters |
|
1307 | 1308 | ---------- |
|
1308 | 1309 | regex : string or compiled pattern, optional |
|
1309 | 1310 | A regular expression pattern that will be used in searching |
|
1310 | 1311 | variable names in the users namespaces. |
|
1311 | 1312 | """ |
|
1312 | 1313 | if regex is not None: |
|
1313 | 1314 | try: |
|
1314 | 1315 | m = re.compile(regex) |
|
1315 | 1316 | except TypeError: |
|
1316 | 1317 | raise TypeError('regex must be a string or compiled pattern') |
|
1317 | 1318 | # Search for keys in each namespace that match the given regex |
|
1318 | 1319 | # If a match is found, delete the key/value pair. |
|
1319 | 1320 | for ns in self.all_ns_refs: |
|
1320 | 1321 | for var in ns: |
|
1321 | 1322 | if m.search(var): |
|
1322 | 1323 | del ns[var] |
|
1323 | 1324 | |
|
1324 | 1325 | def push(self, variables, interactive=True): |
|
1325 | 1326 | """Inject a group of variables into the IPython user namespace. |
|
1326 | 1327 | |
|
1327 | 1328 | Parameters |
|
1328 | 1329 | ---------- |
|
1329 | 1330 | variables : dict, str or list/tuple of str |
|
1330 | 1331 | The variables to inject into the user's namespace. If a dict, a |
|
1331 | 1332 | simple update is done. If a str, the string is assumed to have |
|
1332 | 1333 | variable names separated by spaces. A list/tuple of str can also |
|
1333 | 1334 | be used to give the variable names. If just the variable names are |
|
1334 | 1335 | give (list/tuple/str) then the variable values looked up in the |
|
1335 | 1336 | callers frame. |
|
1336 | 1337 | interactive : bool |
|
1337 | 1338 | If True (default), the variables will be listed with the ``who`` |
|
1338 | 1339 | magic. |
|
1339 | 1340 | """ |
|
1340 | 1341 | vdict = None |
|
1341 | 1342 | |
|
1342 | 1343 | # We need a dict of name/value pairs to do namespace updates. |
|
1343 | 1344 | if isinstance(variables, dict): |
|
1344 | 1345 | vdict = variables |
|
1345 | 1346 | elif isinstance(variables, string_types+(list, tuple)): |
|
1346 | 1347 | if isinstance(variables, string_types): |
|
1347 | 1348 | vlist = variables.split() |
|
1348 | 1349 | else: |
|
1349 | 1350 | vlist = variables |
|
1350 | 1351 | vdict = {} |
|
1351 | 1352 | cf = sys._getframe(1) |
|
1352 | 1353 | for name in vlist: |
|
1353 | 1354 | try: |
|
1354 | 1355 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1355 | 1356 | except: |
|
1356 | 1357 | print('Could not get variable %s from %s' % |
|
1357 | 1358 | (name,cf.f_code.co_name)) |
|
1358 | 1359 | else: |
|
1359 | 1360 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1360 | 1361 | |
|
1361 | 1362 | # Propagate variables to user namespace |
|
1362 | 1363 | self.user_ns.update(vdict) |
|
1363 | 1364 | |
|
1364 | 1365 | # And configure interactive visibility |
|
1365 | 1366 | user_ns_hidden = self.user_ns_hidden |
|
1366 | 1367 | if interactive: |
|
1367 | 1368 | for name in vdict: |
|
1368 | 1369 | user_ns_hidden.pop(name, None) |
|
1369 | 1370 | else: |
|
1370 | 1371 | user_ns_hidden.update(vdict) |
|
1371 | 1372 | |
|
1372 | 1373 | def drop_by_id(self, variables): |
|
1373 | 1374 | """Remove a dict of variables from the user namespace, if they are the |
|
1374 | 1375 | same as the values in the dictionary. |
|
1375 | 1376 | |
|
1376 | 1377 | This is intended for use by extensions: variables that they've added can |
|
1377 | 1378 | be taken back out if they are unloaded, without removing any that the |
|
1378 | 1379 | user has overwritten. |
|
1379 | 1380 | |
|
1380 | 1381 | Parameters |
|
1381 | 1382 | ---------- |
|
1382 | 1383 | variables : dict |
|
1383 | 1384 | A dictionary mapping object names (as strings) to the objects. |
|
1384 | 1385 | """ |
|
1385 | 1386 | for name, obj in iteritems(variables): |
|
1386 | 1387 | if name in self.user_ns and self.user_ns[name] is obj: |
|
1387 | 1388 | del self.user_ns[name] |
|
1388 | 1389 | self.user_ns_hidden.pop(name, None) |
|
1389 | 1390 | |
|
1390 | 1391 | #------------------------------------------------------------------------- |
|
1391 | 1392 | # Things related to object introspection |
|
1392 | 1393 | #------------------------------------------------------------------------- |
|
1393 | 1394 | |
|
1394 | 1395 | def _ofind(self, oname, namespaces=None): |
|
1395 | 1396 | """Find an object in the available namespaces. |
|
1396 | 1397 | |
|
1397 | 1398 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1398 | 1399 | |
|
1399 | 1400 | Has special code to detect magic functions. |
|
1400 | 1401 | """ |
|
1401 | 1402 | oname = oname.strip() |
|
1402 | 1403 | #print '1- oname: <%r>' % oname # dbg |
|
1403 | 1404 | if not oname.startswith(ESC_MAGIC) and \ |
|
1404 | 1405 | not oname.startswith(ESC_MAGIC2) and \ |
|
1405 | 1406 | not py3compat.isidentifier(oname, dotted=True): |
|
1406 | 1407 | return dict(found=False) |
|
1407 | 1408 | |
|
1408 | 1409 | if namespaces is None: |
|
1409 | 1410 | # Namespaces to search in: |
|
1410 | 1411 | # Put them in a list. The order is important so that we |
|
1411 | 1412 | # find things in the same order that Python finds them. |
|
1412 | 1413 | namespaces = [ ('Interactive', self.user_ns), |
|
1413 | 1414 | ('Interactive (global)', self.user_global_ns), |
|
1414 | 1415 | ('Python builtin', builtin_mod.__dict__), |
|
1415 | 1416 | ] |
|
1416 | 1417 | |
|
1417 | 1418 | # initialize results to 'null' |
|
1418 | 1419 | found = False; obj = None; ospace = None; |
|
1419 | 1420 | ismagic = False; isalias = False; parent = None |
|
1420 | 1421 | |
|
1421 | 1422 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1422 | 1423 | # function but should only be treated as one if print_function was |
|
1423 | 1424 | # loaded with a future import. In this case, just bail. |
|
1424 | 1425 | if (oname == 'print' and not py3compat.PY3 and not \ |
|
1425 | 1426 | (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1426 | 1427 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1427 | 1428 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1428 | 1429 | |
|
1429 | 1430 | # Look for the given name by splitting it in parts. If the head is |
|
1430 | 1431 | # found, then we look for all the remaining parts as members, and only |
|
1431 | 1432 | # declare success if we can find them all. |
|
1432 | 1433 | oname_parts = oname.split('.') |
|
1433 | 1434 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1434 | 1435 | for nsname,ns in namespaces: |
|
1435 | 1436 | try: |
|
1436 | 1437 | obj = ns[oname_head] |
|
1437 | 1438 | except KeyError: |
|
1438 | 1439 | continue |
|
1439 | 1440 | else: |
|
1440 | 1441 | #print 'oname_rest:', oname_rest # dbg |
|
1441 | 1442 | for idx, part in enumerate(oname_rest): |
|
1442 | 1443 | try: |
|
1443 | 1444 | parent = obj |
|
1444 | 1445 | # The last part is looked up in a special way to avoid |
|
1445 | 1446 | # descriptor invocation as it may raise or have side |
|
1446 | 1447 | # effects. |
|
1447 | 1448 | if idx == len(oname_rest) - 1: |
|
1448 | 1449 | obj = self._getattr_property(obj, part) |
|
1449 | 1450 | else: |
|
1450 | 1451 | obj = getattr(obj, part) |
|
1451 | 1452 | except: |
|
1452 | 1453 | # Blanket except b/c some badly implemented objects |
|
1453 | 1454 | # allow __getattr__ to raise exceptions other than |
|
1454 | 1455 | # AttributeError, which then crashes IPython. |
|
1455 | 1456 | break |
|
1456 | 1457 | else: |
|
1457 | 1458 | # If we finish the for loop (no break), we got all members |
|
1458 | 1459 | found = True |
|
1459 | 1460 | ospace = nsname |
|
1460 | 1461 | break # namespace loop |
|
1461 | 1462 | |
|
1462 | 1463 | # Try to see if it's magic |
|
1463 | 1464 | if not found: |
|
1464 | 1465 | obj = None |
|
1465 | 1466 | if oname.startswith(ESC_MAGIC2): |
|
1466 | 1467 | oname = oname.lstrip(ESC_MAGIC2) |
|
1467 | 1468 | obj = self.find_cell_magic(oname) |
|
1468 | 1469 | elif oname.startswith(ESC_MAGIC): |
|
1469 | 1470 | oname = oname.lstrip(ESC_MAGIC) |
|
1470 | 1471 | obj = self.find_line_magic(oname) |
|
1471 | 1472 | else: |
|
1472 | 1473 | # search without prefix, so run? will find %run? |
|
1473 | 1474 | obj = self.find_line_magic(oname) |
|
1474 | 1475 | if obj is None: |
|
1475 | 1476 | obj = self.find_cell_magic(oname) |
|
1476 | 1477 | if obj is not None: |
|
1477 | 1478 | found = True |
|
1478 | 1479 | ospace = 'IPython internal' |
|
1479 | 1480 | ismagic = True |
|
1480 | 1481 | isalias = isinstance(obj, Alias) |
|
1481 | 1482 | |
|
1482 | 1483 | # Last try: special-case some literals like '', [], {}, etc: |
|
1483 | 1484 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1484 | 1485 | obj = eval(oname_head) |
|
1485 | 1486 | found = True |
|
1486 | 1487 | ospace = 'Interactive' |
|
1487 | 1488 | |
|
1488 | 1489 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1489 | 1490 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1490 | 1491 | |
|
1491 | 1492 | @staticmethod |
|
1492 | 1493 | def _getattr_property(obj, attrname): |
|
1493 | 1494 | """Property-aware getattr to use in object finding. |
|
1494 | 1495 | |
|
1495 | 1496 | If attrname represents a property, return it unevaluated (in case it has |
|
1496 | 1497 | side effects or raises an error. |
|
1497 | 1498 | |
|
1498 | 1499 | """ |
|
1499 | 1500 | if not isinstance(obj, type): |
|
1500 | 1501 | try: |
|
1501 | 1502 | # `getattr(type(obj), attrname)` is not guaranteed to return |
|
1502 | 1503 | # `obj`, but does so for property: |
|
1503 | 1504 | # |
|
1504 | 1505 | # property.__get__(self, None, cls) -> self |
|
1505 | 1506 | # |
|
1506 | 1507 | # The universal alternative is to traverse the mro manually |
|
1507 | 1508 | # searching for attrname in class dicts. |
|
1508 | 1509 | attr = getattr(type(obj), attrname) |
|
1509 | 1510 | except AttributeError: |
|
1510 | 1511 | pass |
|
1511 | 1512 | else: |
|
1512 | 1513 | # This relies on the fact that data descriptors (with both |
|
1513 | 1514 | # __get__ & __set__ magic methods) take precedence over |
|
1514 | 1515 | # instance-level attributes: |
|
1515 | 1516 | # |
|
1516 | 1517 | # class A(object): |
|
1517 | 1518 | # @property |
|
1518 | 1519 | # def foobar(self): return 123 |
|
1519 | 1520 | # a = A() |
|
1520 | 1521 | # a.__dict__['foobar'] = 345 |
|
1521 | 1522 | # a.foobar # == 123 |
|
1522 | 1523 | # |
|
1523 | 1524 | # So, a property may be returned right away. |
|
1524 | 1525 | if isinstance(attr, property): |
|
1525 | 1526 | return attr |
|
1526 | 1527 | |
|
1527 | 1528 | # Nothing helped, fall back. |
|
1528 | 1529 | return getattr(obj, attrname) |
|
1529 | 1530 | |
|
1530 | 1531 | def _object_find(self, oname, namespaces=None): |
|
1531 | 1532 | """Find an object and return a struct with info about it.""" |
|
1532 | 1533 | return Struct(self._ofind(oname, namespaces)) |
|
1533 | 1534 | |
|
1534 | 1535 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1535 | 1536 | """Generic interface to the inspector system. |
|
1536 | 1537 | |
|
1537 | 1538 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1538 | 1539 | info = self._object_find(oname, namespaces) |
|
1539 | 1540 | if info.found: |
|
1540 | 1541 | pmethod = getattr(self.inspector, meth) |
|
1541 | 1542 | formatter = format_screen if info.ismagic else None |
|
1542 | 1543 | if meth == 'pdoc': |
|
1543 | 1544 | pmethod(info.obj, oname, formatter) |
|
1544 | 1545 | elif meth == 'pinfo': |
|
1545 | 1546 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1546 | 1547 | else: |
|
1547 | 1548 | pmethod(info.obj, oname) |
|
1548 | 1549 | else: |
|
1549 | 1550 | print('Object `%s` not found.' % oname) |
|
1550 | 1551 | return 'not found' # so callers can take other action |
|
1551 | 1552 | |
|
1552 | 1553 | def object_inspect(self, oname, detail_level=0): |
|
1553 | 1554 | """Get object info about oname""" |
|
1554 | 1555 | with self.builtin_trap: |
|
1555 | 1556 | info = self._object_find(oname) |
|
1556 | 1557 | if info.found: |
|
1557 | 1558 | return self.inspector.info(info.obj, oname, info=info, |
|
1558 | 1559 | detail_level=detail_level |
|
1559 | 1560 | ) |
|
1560 | 1561 | else: |
|
1561 | 1562 | return oinspect.object_info(name=oname, found=False) |
|
1562 | 1563 | |
|
1563 | 1564 | def object_inspect_text(self, oname, detail_level=0): |
|
1564 | 1565 | """Get object info as formatted text""" |
|
1565 | 1566 | with self.builtin_trap: |
|
1566 | 1567 | info = self._object_find(oname) |
|
1567 | 1568 | if info.found: |
|
1568 | 1569 | return self.inspector._format_info(info.obj, oname, info=info, |
|
1569 | 1570 | detail_level=detail_level |
|
1570 | 1571 | ) |
|
1571 | 1572 | else: |
|
1572 | 1573 | raise KeyError(oname) |
|
1573 | 1574 | |
|
1574 | 1575 | #------------------------------------------------------------------------- |
|
1575 | 1576 | # Things related to history management |
|
1576 | 1577 | #------------------------------------------------------------------------- |
|
1577 | 1578 | |
|
1578 | 1579 | def init_history(self): |
|
1579 | 1580 | """Sets up the command history, and starts regular autosaves.""" |
|
1580 | 1581 | self.history_manager = HistoryManager(shell=self, parent=self) |
|
1581 | 1582 | self.configurables.append(self.history_manager) |
|
1582 | 1583 | |
|
1583 | 1584 | #------------------------------------------------------------------------- |
|
1584 | 1585 | # Things related to exception handling and tracebacks (not debugging) |
|
1585 | 1586 | #------------------------------------------------------------------------- |
|
1586 | 1587 | |
|
1588 | debugger_cls = Pdb | |
|
1589 | ||
|
1587 | 1590 | def init_traceback_handlers(self, custom_exceptions): |
|
1588 | 1591 | # Syntax error handler. |
|
1589 | 1592 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1590 | 1593 | |
|
1591 | 1594 | # The interactive one is initialized with an offset, meaning we always |
|
1592 | 1595 | # want to remove the topmost item in the traceback, which is our own |
|
1593 | 1596 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1594 | 1597 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1595 | 1598 | color_scheme='NoColor', |
|
1596 | 1599 | tb_offset = 1, |
|
1597 |
check_cache=check_linecache_ipython |
|
|
1600 | check_cache=check_linecache_ipython, | |
|
1601 | debugger_cls=self.debugger_cls) | |
|
1598 | 1602 | |
|
1599 | 1603 | # The instance will store a pointer to the system-wide exception hook, |
|
1600 | 1604 | # so that runtime code (such as magics) can access it. This is because |
|
1601 | 1605 | # during the read-eval loop, it may get temporarily overwritten. |
|
1602 | 1606 | self.sys_excepthook = sys.excepthook |
|
1603 | 1607 | |
|
1604 | 1608 | # and add any custom exception handlers the user may have specified |
|
1605 | 1609 | self.set_custom_exc(*custom_exceptions) |
|
1606 | 1610 | |
|
1607 | 1611 | # Set the exception mode |
|
1608 | 1612 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1609 | 1613 | |
|
1610 | 1614 | def set_custom_exc(self, exc_tuple, handler): |
|
1611 | 1615 | """set_custom_exc(exc_tuple,handler) |
|
1612 | 1616 | |
|
1613 | 1617 | Set a custom exception handler, which will be called if any of the |
|
1614 | 1618 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1615 | 1619 | run_code() method). |
|
1616 | 1620 | |
|
1617 | 1621 | Parameters |
|
1618 | 1622 | ---------- |
|
1619 | 1623 | |
|
1620 | 1624 | exc_tuple : tuple of exception classes |
|
1621 | 1625 | A *tuple* of exception classes, for which to call the defined |
|
1622 | 1626 | handler. It is very important that you use a tuple, and NOT A |
|
1623 | 1627 | LIST here, because of the way Python's except statement works. If |
|
1624 | 1628 | you only want to trap a single exception, use a singleton tuple:: |
|
1625 | 1629 | |
|
1626 | 1630 | exc_tuple == (MyCustomException,) |
|
1627 | 1631 | |
|
1628 | 1632 | handler : callable |
|
1629 | 1633 | handler must have the following signature:: |
|
1630 | 1634 | |
|
1631 | 1635 | def my_handler(self, etype, value, tb, tb_offset=None): |
|
1632 | 1636 | ... |
|
1633 | 1637 | return structured_traceback |
|
1634 | 1638 | |
|
1635 | 1639 | Your handler must return a structured traceback (a list of strings), |
|
1636 | 1640 | or None. |
|
1637 | 1641 | |
|
1638 | 1642 | This will be made into an instance method (via types.MethodType) |
|
1639 | 1643 | of IPython itself, and it will be called if any of the exceptions |
|
1640 | 1644 | listed in the exc_tuple are caught. If the handler is None, an |
|
1641 | 1645 | internal basic one is used, which just prints basic info. |
|
1642 | 1646 | |
|
1643 | 1647 | To protect IPython from crashes, if your handler ever raises an |
|
1644 | 1648 | exception or returns an invalid result, it will be immediately |
|
1645 | 1649 | disabled. |
|
1646 | 1650 | |
|
1647 | 1651 | WARNING: by putting in your own exception handler into IPython's main |
|
1648 | 1652 | execution loop, you run a very good chance of nasty crashes. This |
|
1649 | 1653 | facility should only be used if you really know what you are doing.""" |
|
1650 | 1654 | |
|
1651 | 1655 | assert type(exc_tuple)==type(()) , \ |
|
1652 | 1656 | "The custom exceptions must be given AS A TUPLE." |
|
1653 | 1657 | |
|
1654 | 1658 | def dummy_handler(self,etype,value,tb,tb_offset=None): |
|
1655 | 1659 | print('*** Simple custom exception handler ***') |
|
1656 | 1660 | print('Exception type :',etype) |
|
1657 | 1661 | print('Exception value:',value) |
|
1658 | 1662 | print('Traceback :',tb) |
|
1659 | 1663 | #print 'Source code :','\n'.join(self.buffer) |
|
1660 | 1664 | |
|
1661 | 1665 | def validate_stb(stb): |
|
1662 | 1666 | """validate structured traceback return type |
|
1663 | 1667 | |
|
1664 | 1668 | return type of CustomTB *should* be a list of strings, but allow |
|
1665 | 1669 | single strings or None, which are harmless. |
|
1666 | 1670 | |
|
1667 | 1671 | This function will *always* return a list of strings, |
|
1668 | 1672 | and will raise a TypeError if stb is inappropriate. |
|
1669 | 1673 | """ |
|
1670 | 1674 | msg = "CustomTB must return list of strings, not %r" % stb |
|
1671 | 1675 | if stb is None: |
|
1672 | 1676 | return [] |
|
1673 | 1677 | elif isinstance(stb, string_types): |
|
1674 | 1678 | return [stb] |
|
1675 | 1679 | elif not isinstance(stb, list): |
|
1676 | 1680 | raise TypeError(msg) |
|
1677 | 1681 | # it's a list |
|
1678 | 1682 | for line in stb: |
|
1679 | 1683 | # check every element |
|
1680 | 1684 | if not isinstance(line, string_types): |
|
1681 | 1685 | raise TypeError(msg) |
|
1682 | 1686 | return stb |
|
1683 | 1687 | |
|
1684 | 1688 | if handler is None: |
|
1685 | 1689 | wrapped = dummy_handler |
|
1686 | 1690 | else: |
|
1687 | 1691 | def wrapped(self,etype,value,tb,tb_offset=None): |
|
1688 | 1692 | """wrap CustomTB handler, to protect IPython from user code |
|
1689 | 1693 | |
|
1690 | 1694 | This makes it harder (but not impossible) for custom exception |
|
1691 | 1695 | handlers to crash IPython. |
|
1692 | 1696 | """ |
|
1693 | 1697 | try: |
|
1694 | 1698 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) |
|
1695 | 1699 | return validate_stb(stb) |
|
1696 | 1700 | except: |
|
1697 | 1701 | # clear custom handler immediately |
|
1698 | 1702 | self.set_custom_exc((), None) |
|
1699 | 1703 | print("Custom TB Handler failed, unregistering", file=sys.stderr) |
|
1700 | 1704 | # show the exception in handler first |
|
1701 | 1705 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) |
|
1702 | 1706 | print(self.InteractiveTB.stb2text(stb)) |
|
1703 | 1707 | print("The original exception:") |
|
1704 | 1708 | stb = self.InteractiveTB.structured_traceback( |
|
1705 | 1709 | (etype,value,tb), tb_offset=tb_offset |
|
1706 | 1710 | ) |
|
1707 | 1711 | return stb |
|
1708 | 1712 | |
|
1709 | 1713 | self.CustomTB = types.MethodType(wrapped,self) |
|
1710 | 1714 | self.custom_exceptions = exc_tuple |
|
1711 | 1715 | |
|
1712 | 1716 | def excepthook(self, etype, value, tb): |
|
1713 | 1717 | """One more defense for GUI apps that call sys.excepthook. |
|
1714 | 1718 | |
|
1715 | 1719 | GUI frameworks like wxPython trap exceptions and call |
|
1716 | 1720 | sys.excepthook themselves. I guess this is a feature that |
|
1717 | 1721 | enables them to keep running after exceptions that would |
|
1718 | 1722 | otherwise kill their mainloop. This is a bother for IPython |
|
1719 | 1723 | which excepts to catch all of the program exceptions with a try: |
|
1720 | 1724 | except: statement. |
|
1721 | 1725 | |
|
1722 | 1726 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1723 | 1727 | any app directly invokes sys.excepthook, it will look to the user like |
|
1724 | 1728 | IPython crashed. In order to work around this, we can disable the |
|
1725 | 1729 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1726 | 1730 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1727 | 1731 | call sys.excepthook will generate a regular-looking exception from |
|
1728 | 1732 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1729 | 1733 | crashes. |
|
1730 | 1734 | |
|
1731 | 1735 | This hook should be used sparingly, only in places which are not likely |
|
1732 | 1736 | to be true IPython errors. |
|
1733 | 1737 | """ |
|
1734 | 1738 | self.showtraceback((etype, value, tb), tb_offset=0) |
|
1735 | 1739 | |
|
1736 | 1740 | def _get_exc_info(self, exc_tuple=None): |
|
1737 | 1741 | """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. |
|
1738 | 1742 | |
|
1739 | 1743 | Ensures sys.last_type,value,traceback hold the exc_info we found, |
|
1740 | 1744 | from whichever source. |
|
1741 | 1745 | |
|
1742 | 1746 | raises ValueError if none of these contain any information |
|
1743 | 1747 | """ |
|
1744 | 1748 | if exc_tuple is None: |
|
1745 | 1749 | etype, value, tb = sys.exc_info() |
|
1746 | 1750 | else: |
|
1747 | 1751 | etype, value, tb = exc_tuple |
|
1748 | 1752 | |
|
1749 | 1753 | if etype is None: |
|
1750 | 1754 | if hasattr(sys, 'last_type'): |
|
1751 | 1755 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1752 | 1756 | sys.last_traceback |
|
1753 | 1757 | |
|
1754 | 1758 | if etype is None: |
|
1755 | 1759 | raise ValueError("No exception to find") |
|
1756 | 1760 | |
|
1757 | 1761 | # Now store the exception info in sys.last_type etc. |
|
1758 | 1762 | # WARNING: these variables are somewhat deprecated and not |
|
1759 | 1763 | # necessarily safe to use in a threaded environment, but tools |
|
1760 | 1764 | # like pdb depend on their existence, so let's set them. If we |
|
1761 | 1765 | # find problems in the field, we'll need to revisit their use. |
|
1762 | 1766 | sys.last_type = etype |
|
1763 | 1767 | sys.last_value = value |
|
1764 | 1768 | sys.last_traceback = tb |
|
1765 | 1769 | |
|
1766 | 1770 | return etype, value, tb |
|
1767 | 1771 | |
|
1768 | 1772 | def show_usage_error(self, exc): |
|
1769 | 1773 | """Show a short message for UsageErrors |
|
1770 | 1774 | |
|
1771 | 1775 | These are special exceptions that shouldn't show a traceback. |
|
1772 | 1776 | """ |
|
1773 | 1777 | print("UsageError: %s" % exc, file=sys.stderr) |
|
1774 | 1778 | |
|
1775 | 1779 | def get_exception_only(self, exc_tuple=None): |
|
1776 | 1780 | """ |
|
1777 | 1781 | Return as a string (ending with a newline) the exception that |
|
1778 | 1782 | just occurred, without any traceback. |
|
1779 | 1783 | """ |
|
1780 | 1784 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
1781 | 1785 | msg = traceback.format_exception_only(etype, value) |
|
1782 | 1786 | return ''.join(msg) |
|
1783 | 1787 | |
|
1784 | 1788 | def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None, |
|
1785 | 1789 | exception_only=False): |
|
1786 | 1790 | """Display the exception that just occurred. |
|
1787 | 1791 | |
|
1788 | 1792 | If nothing is known about the exception, this is the method which |
|
1789 | 1793 | should be used throughout the code for presenting user tracebacks, |
|
1790 | 1794 | rather than directly invoking the InteractiveTB object. |
|
1791 | 1795 | |
|
1792 | 1796 | A specific showsyntaxerror() also exists, but this method can take |
|
1793 | 1797 | care of calling it if needed, so unless you are explicitly catching a |
|
1794 | 1798 | SyntaxError exception, don't try to analyze the stack manually and |
|
1795 | 1799 | simply call this method.""" |
|
1796 | 1800 | |
|
1797 | 1801 | try: |
|
1798 | 1802 | try: |
|
1799 | 1803 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
1800 | 1804 | except ValueError: |
|
1801 | 1805 | print('No traceback available to show.', file=sys.stderr) |
|
1802 | 1806 | return |
|
1803 | 1807 | |
|
1804 | 1808 | if issubclass(etype, SyntaxError): |
|
1805 | 1809 | # Though this won't be called by syntax errors in the input |
|
1806 | 1810 | # line, there may be SyntaxError cases with imported code. |
|
1807 | 1811 | self.showsyntaxerror(filename) |
|
1808 | 1812 | elif etype is UsageError: |
|
1809 | 1813 | self.show_usage_error(value) |
|
1810 | 1814 | else: |
|
1811 | 1815 | if exception_only: |
|
1812 | 1816 | stb = ['An exception has occurred, use %tb to see ' |
|
1813 | 1817 | 'the full traceback.\n'] |
|
1814 | 1818 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1815 | 1819 | value)) |
|
1816 | 1820 | else: |
|
1817 | 1821 | try: |
|
1818 | 1822 | # Exception classes can customise their traceback - we |
|
1819 | 1823 | # use this in IPython.parallel for exceptions occurring |
|
1820 | 1824 | # in the engines. This should return a list of strings. |
|
1821 | 1825 | stb = value._render_traceback_() |
|
1822 | 1826 | except Exception: |
|
1823 | 1827 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1824 | 1828 | value, tb, tb_offset=tb_offset) |
|
1825 | 1829 | |
|
1826 | 1830 | self._showtraceback(etype, value, stb) |
|
1827 | 1831 | if self.call_pdb: |
|
1828 | 1832 | # drop into debugger |
|
1829 | 1833 | self.debugger(force=True) |
|
1830 | 1834 | return |
|
1831 | 1835 | |
|
1832 | 1836 | # Actually show the traceback |
|
1833 | 1837 | self._showtraceback(etype, value, stb) |
|
1834 | 1838 | |
|
1835 | 1839 | except KeyboardInterrupt: |
|
1836 | 1840 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
1837 | 1841 | |
|
1838 | 1842 | def _showtraceback(self, etype, evalue, stb): |
|
1839 | 1843 | """Actually show a traceback. |
|
1840 | 1844 | |
|
1841 | 1845 | Subclasses may override this method to put the traceback on a different |
|
1842 | 1846 | place, like a side channel. |
|
1843 | 1847 | """ |
|
1844 | 1848 | print(self.InteractiveTB.stb2text(stb)) |
|
1845 | 1849 | |
|
1846 | 1850 | def showsyntaxerror(self, filename=None): |
|
1847 | 1851 | """Display the syntax error that just occurred. |
|
1848 | 1852 | |
|
1849 | 1853 | This doesn't display a stack trace because there isn't one. |
|
1850 | 1854 | |
|
1851 | 1855 | If a filename is given, it is stuffed in the exception instead |
|
1852 | 1856 | of what was there before (because Python's parser always uses |
|
1853 | 1857 | "<string>" when reading from a string). |
|
1854 | 1858 | """ |
|
1855 | 1859 | etype, value, last_traceback = self._get_exc_info() |
|
1856 | 1860 | |
|
1857 | 1861 | if filename and issubclass(etype, SyntaxError): |
|
1858 | 1862 | try: |
|
1859 | 1863 | value.filename = filename |
|
1860 | 1864 | except: |
|
1861 | 1865 | # Not the format we expect; leave it alone |
|
1862 | 1866 | pass |
|
1863 | 1867 | |
|
1864 | 1868 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1865 | 1869 | self._showtraceback(etype, value, stb) |
|
1866 | 1870 | |
|
1867 | 1871 | # This is overridden in TerminalInteractiveShell to show a message about |
|
1868 | 1872 | # the %paste magic. |
|
1869 | 1873 | def showindentationerror(self): |
|
1870 | 1874 | """Called by run_cell when there's an IndentationError in code entered |
|
1871 | 1875 | at the prompt. |
|
1872 | 1876 | |
|
1873 | 1877 | This is overridden in TerminalInteractiveShell to show a message about |
|
1874 | 1878 | the %paste magic.""" |
|
1875 | 1879 | self.showsyntaxerror() |
|
1876 | 1880 | |
|
1877 | 1881 | #------------------------------------------------------------------------- |
|
1878 | 1882 | # Things related to readline |
|
1879 | 1883 | #------------------------------------------------------------------------- |
|
1880 | 1884 | |
|
1881 | 1885 | def init_readline(self): |
|
1882 | 1886 | """Moved to terminal subclass, here only to simplify the init logic.""" |
|
1883 | 1887 | self.readline = None |
|
1884 | 1888 | # Set a number of methods that depend on readline to be no-op |
|
1885 | 1889 | self.readline_no_record = NoOpContext() |
|
1886 | 1890 | self.set_readline_completer = no_op |
|
1887 | 1891 | self.set_custom_completer = no_op |
|
1888 | 1892 | |
|
1889 | 1893 | @skip_doctest |
|
1890 | 1894 | def set_next_input(self, s, replace=False): |
|
1891 | 1895 | """ Sets the 'default' input string for the next command line. |
|
1892 | 1896 | |
|
1893 | 1897 | Example:: |
|
1894 | 1898 | |
|
1895 | 1899 | In [1]: _ip.set_next_input("Hello Word") |
|
1896 | 1900 | In [2]: Hello Word_ # cursor is here |
|
1897 | 1901 | """ |
|
1898 | 1902 | self.rl_next_input = py3compat.cast_bytes_py2(s) |
|
1899 | 1903 | |
|
1900 | 1904 | def _indent_current_str(self): |
|
1901 | 1905 | """return the current level of indentation as a string""" |
|
1902 | 1906 | return self.input_splitter.indent_spaces * ' ' |
|
1903 | 1907 | |
|
1904 | 1908 | #------------------------------------------------------------------------- |
|
1905 | 1909 | # Things related to text completion |
|
1906 | 1910 | #------------------------------------------------------------------------- |
|
1907 | 1911 | |
|
1908 | 1912 | def init_completer(self): |
|
1909 | 1913 | """Initialize the completion machinery. |
|
1910 | 1914 | |
|
1911 | 1915 | This creates completion machinery that can be used by client code, |
|
1912 | 1916 | either interactively in-process (typically triggered by the readline |
|
1913 | 1917 | library), programmatically (such as in test suites) or out-of-process |
|
1914 | 1918 | (typically over the network by remote frontends). |
|
1915 | 1919 | """ |
|
1916 | 1920 | from IPython.core.completer import IPCompleter |
|
1917 | 1921 | from IPython.core.completerlib import (module_completer, |
|
1918 | 1922 | magic_run_completer, cd_completer, reset_completer) |
|
1919 | 1923 | |
|
1920 | 1924 | self.Completer = IPCompleter(shell=self, |
|
1921 | 1925 | namespace=self.user_ns, |
|
1922 | 1926 | global_namespace=self.user_global_ns, |
|
1923 | 1927 | use_readline=self.has_readline, |
|
1924 | 1928 | parent=self, |
|
1925 | 1929 | ) |
|
1926 | 1930 | self.configurables.append(self.Completer) |
|
1927 | 1931 | |
|
1928 | 1932 | # Add custom completers to the basic ones built into IPCompleter |
|
1929 | 1933 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1930 | 1934 | self.strdispatchers['complete_command'] = sdisp |
|
1931 | 1935 | self.Completer.custom_completers = sdisp |
|
1932 | 1936 | |
|
1933 | 1937 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1934 | 1938 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1935 | 1939 | self.set_hook('complete_command', module_completer, str_key = '%aimport') |
|
1936 | 1940 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1937 | 1941 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1938 | 1942 | self.set_hook('complete_command', reset_completer, str_key = '%reset') |
|
1939 | 1943 | |
|
1940 | 1944 | |
|
1941 | 1945 | @skip_doctest_py2 |
|
1942 | 1946 | def complete(self, text, line=None, cursor_pos=None): |
|
1943 | 1947 | """Return the completed text and a list of completions. |
|
1944 | 1948 | |
|
1945 | 1949 | Parameters |
|
1946 | 1950 | ---------- |
|
1947 | 1951 | |
|
1948 | 1952 | text : string |
|
1949 | 1953 | A string of text to be completed on. It can be given as empty and |
|
1950 | 1954 | instead a line/position pair are given. In this case, the |
|
1951 | 1955 | completer itself will split the line like readline does. |
|
1952 | 1956 | |
|
1953 | 1957 | line : string, optional |
|
1954 | 1958 | The complete line that text is part of. |
|
1955 | 1959 | |
|
1956 | 1960 | cursor_pos : int, optional |
|
1957 | 1961 | The position of the cursor on the input line. |
|
1958 | 1962 | |
|
1959 | 1963 | Returns |
|
1960 | 1964 | ------- |
|
1961 | 1965 | text : string |
|
1962 | 1966 | The actual text that was completed. |
|
1963 | 1967 | |
|
1964 | 1968 | matches : list |
|
1965 | 1969 | A sorted list with all possible completions. |
|
1966 | 1970 | |
|
1967 | 1971 | The optional arguments allow the completion to take more context into |
|
1968 | 1972 | account, and are part of the low-level completion API. |
|
1969 | 1973 | |
|
1970 | 1974 | This is a wrapper around the completion mechanism, similar to what |
|
1971 | 1975 | readline does at the command line when the TAB key is hit. By |
|
1972 | 1976 | exposing it as a method, it can be used by other non-readline |
|
1973 | 1977 | environments (such as GUIs) for text completion. |
|
1974 | 1978 | |
|
1975 | 1979 | Simple usage example: |
|
1976 | 1980 | |
|
1977 | 1981 | In [1]: x = 'hello' |
|
1978 | 1982 | |
|
1979 | 1983 | In [2]: _ip.complete('x.l') |
|
1980 | 1984 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
1981 | 1985 | """ |
|
1982 | 1986 | |
|
1983 | 1987 | # Inject names into __builtin__ so we can complete on the added names. |
|
1984 | 1988 | with self.builtin_trap: |
|
1985 | 1989 | return self.Completer.complete(text, line, cursor_pos) |
|
1986 | 1990 | |
|
1987 | 1991 | def set_custom_completer(self, completer, pos=0): |
|
1988 | 1992 | """Adds a new custom completer function. |
|
1989 | 1993 | |
|
1990 | 1994 | The position argument (defaults to 0) is the index in the completers |
|
1991 | 1995 | list where you want the completer to be inserted.""" |
|
1992 | 1996 | |
|
1993 | 1997 | newcomp = types.MethodType(completer,self.Completer) |
|
1994 | 1998 | self.Completer.matchers.insert(pos,newcomp) |
|
1995 | 1999 | |
|
1996 | 2000 | def set_completer_frame(self, frame=None): |
|
1997 | 2001 | """Set the frame of the completer.""" |
|
1998 | 2002 | if frame: |
|
1999 | 2003 | self.Completer.namespace = frame.f_locals |
|
2000 | 2004 | self.Completer.global_namespace = frame.f_globals |
|
2001 | 2005 | else: |
|
2002 | 2006 | self.Completer.namespace = self.user_ns |
|
2003 | 2007 | self.Completer.global_namespace = self.user_global_ns |
|
2004 | 2008 | |
|
2005 | 2009 | #------------------------------------------------------------------------- |
|
2006 | 2010 | # Things related to magics |
|
2007 | 2011 | #------------------------------------------------------------------------- |
|
2008 | 2012 | |
|
2009 | 2013 | def init_magics(self): |
|
2010 | 2014 | from IPython.core import magics as m |
|
2011 | 2015 | self.magics_manager = magic.MagicsManager(shell=self, |
|
2012 | 2016 | parent=self, |
|
2013 | 2017 | user_magics=m.UserMagics(self)) |
|
2014 | 2018 | self.configurables.append(self.magics_manager) |
|
2015 | 2019 | |
|
2016 | 2020 | # Expose as public API from the magics manager |
|
2017 | 2021 | self.register_magics = self.magics_manager.register |
|
2018 | 2022 | self.define_magic = self.magics_manager.define_magic |
|
2019 | 2023 | |
|
2020 | 2024 | self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, |
|
2021 | 2025 | m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics, |
|
2022 | 2026 | m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, |
|
2023 | 2027 | m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics, |
|
2024 | 2028 | ) |
|
2025 | 2029 | |
|
2026 | 2030 | # Register Magic Aliases |
|
2027 | 2031 | mman = self.magics_manager |
|
2028 | 2032 | # FIXME: magic aliases should be defined by the Magics classes |
|
2029 | 2033 | # or in MagicsManager, not here |
|
2030 | 2034 | mman.register_alias('ed', 'edit') |
|
2031 | 2035 | mman.register_alias('hist', 'history') |
|
2032 | 2036 | mman.register_alias('rep', 'recall') |
|
2033 | 2037 | mman.register_alias('SVG', 'svg', 'cell') |
|
2034 | 2038 | mman.register_alias('HTML', 'html', 'cell') |
|
2035 | 2039 | mman.register_alias('file', 'writefile', 'cell') |
|
2036 | 2040 | |
|
2037 | 2041 | # FIXME: Move the color initialization to the DisplayHook, which |
|
2038 | 2042 | # should be split into a prompt manager and displayhook. We probably |
|
2039 | 2043 | # even need a centralize colors management object. |
|
2040 | 2044 | self.magic('colors %s' % self.colors) |
|
2041 | 2045 | |
|
2042 | 2046 | # Defined here so that it's included in the documentation |
|
2043 | 2047 | @functools.wraps(magic.MagicsManager.register_function) |
|
2044 | 2048 | def register_magic_function(self, func, magic_kind='line', magic_name=None): |
|
2045 | 2049 | self.magics_manager.register_function(func, |
|
2046 | 2050 | magic_kind=magic_kind, magic_name=magic_name) |
|
2047 | 2051 | |
|
2048 | 2052 | def run_line_magic(self, magic_name, line): |
|
2049 | 2053 | """Execute the given line magic. |
|
2050 | 2054 | |
|
2051 | 2055 | Parameters |
|
2052 | 2056 | ---------- |
|
2053 | 2057 | magic_name : str |
|
2054 | 2058 | Name of the desired magic function, without '%' prefix. |
|
2055 | 2059 | |
|
2056 | 2060 | line : str |
|
2057 | 2061 | The rest of the input line as a single string. |
|
2058 | 2062 | """ |
|
2059 | 2063 | fn = self.find_line_magic(magic_name) |
|
2060 | 2064 | if fn is None: |
|
2061 | 2065 | cm = self.find_cell_magic(magic_name) |
|
2062 | 2066 | etpl = "Line magic function `%%%s` not found%s." |
|
2063 | 2067 | extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' |
|
2064 | 2068 | 'did you mean that instead?)' % magic_name ) |
|
2065 | 2069 | error(etpl % (magic_name, extra)) |
|
2066 | 2070 | else: |
|
2067 | 2071 | # Note: this is the distance in the stack to the user's frame. |
|
2068 | 2072 | # This will need to be updated if the internal calling logic gets |
|
2069 | 2073 | # refactored, or else we'll be expanding the wrong variables. |
|
2070 | 2074 | stack_depth = 2 |
|
2071 | 2075 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2072 | 2076 | # Put magic args in a list so we can call with f(*a) syntax |
|
2073 | 2077 | args = [magic_arg_s] |
|
2074 | 2078 | kwargs = {} |
|
2075 | 2079 | # Grab local namespace if we need it: |
|
2076 | 2080 | if getattr(fn, "needs_local_scope", False): |
|
2077 | 2081 | kwargs['local_ns'] = sys._getframe(stack_depth).f_locals |
|
2078 | 2082 | with self.builtin_trap: |
|
2079 | 2083 | result = fn(*args,**kwargs) |
|
2080 | 2084 | return result |
|
2081 | 2085 | |
|
2082 | 2086 | def run_cell_magic(self, magic_name, line, cell): |
|
2083 | 2087 | """Execute the given cell magic. |
|
2084 | 2088 | |
|
2085 | 2089 | Parameters |
|
2086 | 2090 | ---------- |
|
2087 | 2091 | magic_name : str |
|
2088 | 2092 | Name of the desired magic function, without '%' prefix. |
|
2089 | 2093 | |
|
2090 | 2094 | line : str |
|
2091 | 2095 | The rest of the first input line as a single string. |
|
2092 | 2096 | |
|
2093 | 2097 | cell : str |
|
2094 | 2098 | The body of the cell as a (possibly multiline) string. |
|
2095 | 2099 | """ |
|
2096 | 2100 | fn = self.find_cell_magic(magic_name) |
|
2097 | 2101 | if fn is None: |
|
2098 | 2102 | lm = self.find_line_magic(magic_name) |
|
2099 | 2103 | etpl = "Cell magic `%%{0}` not found{1}." |
|
2100 | 2104 | extra = '' if lm is None else (' (But line magic `%{0}` exists, ' |
|
2101 | 2105 | 'did you mean that instead?)'.format(magic_name)) |
|
2102 | 2106 | error(etpl.format(magic_name, extra)) |
|
2103 | 2107 | elif cell == '': |
|
2104 | 2108 | message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name) |
|
2105 | 2109 | if self.find_line_magic(magic_name) is not None: |
|
2106 | 2110 | message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name) |
|
2107 | 2111 | raise UsageError(message) |
|
2108 | 2112 | else: |
|
2109 | 2113 | # Note: this is the distance in the stack to the user's frame. |
|
2110 | 2114 | # This will need to be updated if the internal calling logic gets |
|
2111 | 2115 | # refactored, or else we'll be expanding the wrong variables. |
|
2112 | 2116 | stack_depth = 2 |
|
2113 | 2117 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2114 | 2118 | with self.builtin_trap: |
|
2115 | 2119 | result = fn(magic_arg_s, cell) |
|
2116 | 2120 | return result |
|
2117 | 2121 | |
|
2118 | 2122 | def find_line_magic(self, magic_name): |
|
2119 | 2123 | """Find and return a line magic by name. |
|
2120 | 2124 | |
|
2121 | 2125 | Returns None if the magic isn't found.""" |
|
2122 | 2126 | return self.magics_manager.magics['line'].get(magic_name) |
|
2123 | 2127 | |
|
2124 | 2128 | def find_cell_magic(self, magic_name): |
|
2125 | 2129 | """Find and return a cell magic by name. |
|
2126 | 2130 | |
|
2127 | 2131 | Returns None if the magic isn't found.""" |
|
2128 | 2132 | return self.magics_manager.magics['cell'].get(magic_name) |
|
2129 | 2133 | |
|
2130 | 2134 | def find_magic(self, magic_name, magic_kind='line'): |
|
2131 | 2135 | """Find and return a magic of the given type by name. |
|
2132 | 2136 | |
|
2133 | 2137 | Returns None if the magic isn't found.""" |
|
2134 | 2138 | return self.magics_manager.magics[magic_kind].get(magic_name) |
|
2135 | 2139 | |
|
2136 | 2140 | def magic(self, arg_s): |
|
2137 | 2141 | """DEPRECATED. Use run_line_magic() instead. |
|
2138 | 2142 | |
|
2139 | 2143 | Call a magic function by name. |
|
2140 | 2144 | |
|
2141 | 2145 | Input: a string containing the name of the magic function to call and |
|
2142 | 2146 | any additional arguments to be passed to the magic. |
|
2143 | 2147 | |
|
2144 | 2148 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
2145 | 2149 | prompt: |
|
2146 | 2150 | |
|
2147 | 2151 | In[1]: %name -opt foo bar |
|
2148 | 2152 | |
|
2149 | 2153 | To call a magic without arguments, simply use magic('name'). |
|
2150 | 2154 | |
|
2151 | 2155 | This provides a proper Python function to call IPython's magics in any |
|
2152 | 2156 | valid Python code you can type at the interpreter, including loops and |
|
2153 | 2157 | compound statements. |
|
2154 | 2158 | """ |
|
2155 | 2159 | # TODO: should we issue a loud deprecation warning here? |
|
2156 | 2160 | magic_name, _, magic_arg_s = arg_s.partition(' ') |
|
2157 | 2161 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
2158 | 2162 | return self.run_line_magic(magic_name, magic_arg_s) |
|
2159 | 2163 | |
|
2160 | 2164 | #------------------------------------------------------------------------- |
|
2161 | 2165 | # Things related to macros |
|
2162 | 2166 | #------------------------------------------------------------------------- |
|
2163 | 2167 | |
|
2164 | 2168 | def define_macro(self, name, themacro): |
|
2165 | 2169 | """Define a new macro |
|
2166 | 2170 | |
|
2167 | 2171 | Parameters |
|
2168 | 2172 | ---------- |
|
2169 | 2173 | name : str |
|
2170 | 2174 | The name of the macro. |
|
2171 | 2175 | themacro : str or Macro |
|
2172 | 2176 | The action to do upon invoking the macro. If a string, a new |
|
2173 | 2177 | Macro object is created by passing the string to it. |
|
2174 | 2178 | """ |
|
2175 | 2179 | |
|
2176 | 2180 | from IPython.core import macro |
|
2177 | 2181 | |
|
2178 | 2182 | if isinstance(themacro, string_types): |
|
2179 | 2183 | themacro = macro.Macro(themacro) |
|
2180 | 2184 | if not isinstance(themacro, macro.Macro): |
|
2181 | 2185 | raise ValueError('A macro must be a string or a Macro instance.') |
|
2182 | 2186 | self.user_ns[name] = themacro |
|
2183 | 2187 | |
|
2184 | 2188 | #------------------------------------------------------------------------- |
|
2185 | 2189 | # Things related to the running of system commands |
|
2186 | 2190 | #------------------------------------------------------------------------- |
|
2187 | 2191 | |
|
2188 | 2192 | def system_piped(self, cmd): |
|
2189 | 2193 | """Call the given cmd in a subprocess, piping stdout/err |
|
2190 | 2194 | |
|
2191 | 2195 | Parameters |
|
2192 | 2196 | ---------- |
|
2193 | 2197 | cmd : str |
|
2194 | 2198 | Command to execute (can not end in '&', as background processes are |
|
2195 | 2199 | not supported. Should not be a command that expects input |
|
2196 | 2200 | other than simple text. |
|
2197 | 2201 | """ |
|
2198 | 2202 | if cmd.rstrip().endswith('&'): |
|
2199 | 2203 | # this is *far* from a rigorous test |
|
2200 | 2204 | # We do not support backgrounding processes because we either use |
|
2201 | 2205 | # pexpect or pipes to read from. Users can always just call |
|
2202 | 2206 | # os.system() or use ip.system=ip.system_raw |
|
2203 | 2207 | # if they really want a background process. |
|
2204 | 2208 | raise OSError("Background processes not supported.") |
|
2205 | 2209 | |
|
2206 | 2210 | # we explicitly do NOT return the subprocess status code, because |
|
2207 | 2211 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2208 | 2212 | # Instead, we store the exit_code in user_ns. |
|
2209 | 2213 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) |
|
2210 | 2214 | |
|
2211 | 2215 | def system_raw(self, cmd): |
|
2212 | 2216 | """Call the given cmd in a subprocess using os.system on Windows or |
|
2213 | 2217 | subprocess.call using the system shell on other platforms. |
|
2214 | 2218 | |
|
2215 | 2219 | Parameters |
|
2216 | 2220 | ---------- |
|
2217 | 2221 | cmd : str |
|
2218 | 2222 | Command to execute. |
|
2219 | 2223 | """ |
|
2220 | 2224 | cmd = self.var_expand(cmd, depth=1) |
|
2221 | 2225 | # protect os.system from UNC paths on Windows, which it can't handle: |
|
2222 | 2226 | if sys.platform == 'win32': |
|
2223 | 2227 | from IPython.utils._process_win32 import AvoidUNCPath |
|
2224 | 2228 | with AvoidUNCPath() as path: |
|
2225 | 2229 | if path is not None: |
|
2226 | 2230 | cmd = '"pushd %s &&"%s' % (path, cmd) |
|
2227 | 2231 | cmd = py3compat.unicode_to_str(cmd) |
|
2228 | 2232 | try: |
|
2229 | 2233 | ec = os.system(cmd) |
|
2230 | 2234 | except KeyboardInterrupt: |
|
2231 | 2235 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
2232 | 2236 | ec = -2 |
|
2233 | 2237 | else: |
|
2234 | 2238 | cmd = py3compat.unicode_to_str(cmd) |
|
2235 | 2239 | # For posix the result of the subprocess.call() below is an exit |
|
2236 | 2240 | # code, which by convention is zero for success, positive for |
|
2237 | 2241 | # program failure. Exit codes above 128 are reserved for signals, |
|
2238 | 2242 | # and the formula for converting a signal to an exit code is usually |
|
2239 | 2243 | # signal_number+128. To more easily differentiate between exit |
|
2240 | 2244 | # codes and signals, ipython uses negative numbers. For instance |
|
2241 | 2245 | # since control-c is signal 2 but exit code 130, ipython's |
|
2242 | 2246 | # _exit_code variable will read -2. Note that some shells like |
|
2243 | 2247 | # csh and fish don't follow sh/bash conventions for exit codes. |
|
2244 | 2248 | executable = os.environ.get('SHELL', None) |
|
2245 | 2249 | try: |
|
2246 | 2250 | # Use env shell instead of default /bin/sh |
|
2247 | 2251 | ec = subprocess.call(cmd, shell=True, executable=executable) |
|
2248 | 2252 | except KeyboardInterrupt: |
|
2249 | 2253 | # intercept control-C; a long traceback is not useful here |
|
2250 | 2254 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
2251 | 2255 | ec = 130 |
|
2252 | 2256 | if ec > 128: |
|
2253 | 2257 | ec = -(ec - 128) |
|
2254 | 2258 | |
|
2255 | 2259 | # We explicitly do NOT return the subprocess status code, because |
|
2256 | 2260 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2257 | 2261 | # Instead, we store the exit_code in user_ns. Note the semantics |
|
2258 | 2262 | # of _exit_code: for control-c, _exit_code == -signal.SIGNIT, |
|
2259 | 2263 | # but raising SystemExit(_exit_code) will give status 254! |
|
2260 | 2264 | self.user_ns['_exit_code'] = ec |
|
2261 | 2265 | |
|
2262 | 2266 | # use piped system by default, because it is better behaved |
|
2263 | 2267 | system = system_piped |
|
2264 | 2268 | |
|
2265 | 2269 | def getoutput(self, cmd, split=True, depth=0): |
|
2266 | 2270 | """Get output (possibly including stderr) from a subprocess. |
|
2267 | 2271 | |
|
2268 | 2272 | Parameters |
|
2269 | 2273 | ---------- |
|
2270 | 2274 | cmd : str |
|
2271 | 2275 | Command to execute (can not end in '&', as background processes are |
|
2272 | 2276 | not supported. |
|
2273 | 2277 | split : bool, optional |
|
2274 | 2278 | If True, split the output into an IPython SList. Otherwise, an |
|
2275 | 2279 | IPython LSString is returned. These are objects similar to normal |
|
2276 | 2280 | lists and strings, with a few convenience attributes for easier |
|
2277 | 2281 | manipulation of line-based output. You can use '?' on them for |
|
2278 | 2282 | details. |
|
2279 | 2283 | depth : int, optional |
|
2280 | 2284 | How many frames above the caller are the local variables which should |
|
2281 | 2285 | be expanded in the command string? The default (0) assumes that the |
|
2282 | 2286 | expansion variables are in the stack frame calling this function. |
|
2283 | 2287 | """ |
|
2284 | 2288 | if cmd.rstrip().endswith('&'): |
|
2285 | 2289 | # this is *far* from a rigorous test |
|
2286 | 2290 | raise OSError("Background processes not supported.") |
|
2287 | 2291 | out = getoutput(self.var_expand(cmd, depth=depth+1)) |
|
2288 | 2292 | if split: |
|
2289 | 2293 | out = SList(out.splitlines()) |
|
2290 | 2294 | else: |
|
2291 | 2295 | out = LSString(out) |
|
2292 | 2296 | return out |
|
2293 | 2297 | |
|
2294 | 2298 | #------------------------------------------------------------------------- |
|
2295 | 2299 | # Things related to aliases |
|
2296 | 2300 | #------------------------------------------------------------------------- |
|
2297 | 2301 | |
|
2298 | 2302 | def init_alias(self): |
|
2299 | 2303 | self.alias_manager = AliasManager(shell=self, parent=self) |
|
2300 | 2304 | self.configurables.append(self.alias_manager) |
|
2301 | 2305 | |
|
2302 | 2306 | #------------------------------------------------------------------------- |
|
2303 | 2307 | # Things related to extensions |
|
2304 | 2308 | #------------------------------------------------------------------------- |
|
2305 | 2309 | |
|
2306 | 2310 | def init_extension_manager(self): |
|
2307 | 2311 | self.extension_manager = ExtensionManager(shell=self, parent=self) |
|
2308 | 2312 | self.configurables.append(self.extension_manager) |
|
2309 | 2313 | |
|
2310 | 2314 | #------------------------------------------------------------------------- |
|
2311 | 2315 | # Things related to payloads |
|
2312 | 2316 | #------------------------------------------------------------------------- |
|
2313 | 2317 | |
|
2314 | 2318 | def init_payload(self): |
|
2315 | 2319 | self.payload_manager = PayloadManager(parent=self) |
|
2316 | 2320 | self.configurables.append(self.payload_manager) |
|
2317 | 2321 | |
|
2318 | 2322 | #------------------------------------------------------------------------- |
|
2319 | 2323 | # Things related to the prefilter |
|
2320 | 2324 | #------------------------------------------------------------------------- |
|
2321 | 2325 | |
|
2322 | 2326 | def init_prefilter(self): |
|
2323 | 2327 | self.prefilter_manager = PrefilterManager(shell=self, parent=self) |
|
2324 | 2328 | self.configurables.append(self.prefilter_manager) |
|
2325 | 2329 | # Ultimately this will be refactored in the new interpreter code, but |
|
2326 | 2330 | # for now, we should expose the main prefilter method (there's legacy |
|
2327 | 2331 | # code out there that may rely on this). |
|
2328 | 2332 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
2329 | 2333 | |
|
2330 | 2334 | def auto_rewrite_input(self, cmd): |
|
2331 | 2335 | """Print to the screen the rewritten form of the user's command. |
|
2332 | 2336 | |
|
2333 | 2337 | This shows visual feedback by rewriting input lines that cause |
|
2334 | 2338 | automatic calling to kick in, like:: |
|
2335 | 2339 | |
|
2336 | 2340 | /f x |
|
2337 | 2341 | |
|
2338 | 2342 | into:: |
|
2339 | 2343 | |
|
2340 | 2344 | ------> f(x) |
|
2341 | 2345 | |
|
2342 | 2346 | after the user's input prompt. This helps the user understand that the |
|
2343 | 2347 | input line was transformed automatically by IPython. |
|
2344 | 2348 | """ |
|
2345 | 2349 | if not self.show_rewritten_input: |
|
2346 | 2350 | return |
|
2347 | 2351 | |
|
2348 | 2352 | rw = self.prompt_manager.render('rewrite') + cmd |
|
2349 | 2353 | |
|
2350 | 2354 | try: |
|
2351 | 2355 | # plain ascii works better w/ pyreadline, on some machines, so |
|
2352 | 2356 | # we use it and only print uncolored rewrite if we have unicode |
|
2353 | 2357 | rw = str(rw) |
|
2354 | 2358 | print(rw) |
|
2355 | 2359 | except UnicodeEncodeError: |
|
2356 | 2360 | print("------> " + cmd) |
|
2357 | 2361 | |
|
2358 | 2362 | #------------------------------------------------------------------------- |
|
2359 | 2363 | # Things related to extracting values/expressions from kernel and user_ns |
|
2360 | 2364 | #------------------------------------------------------------------------- |
|
2361 | 2365 | |
|
2362 | 2366 | def _user_obj_error(self): |
|
2363 | 2367 | """return simple exception dict |
|
2364 | 2368 | |
|
2365 | 2369 | for use in user_expressions |
|
2366 | 2370 | """ |
|
2367 | 2371 | |
|
2368 | 2372 | etype, evalue, tb = self._get_exc_info() |
|
2369 | 2373 | stb = self.InteractiveTB.get_exception_only(etype, evalue) |
|
2370 | 2374 | |
|
2371 | 2375 | exc_info = { |
|
2372 | 2376 | u'status' : 'error', |
|
2373 | 2377 | u'traceback' : stb, |
|
2374 | 2378 | u'ename' : unicode_type(etype.__name__), |
|
2375 | 2379 | u'evalue' : py3compat.safe_unicode(evalue), |
|
2376 | 2380 | } |
|
2377 | 2381 | |
|
2378 | 2382 | return exc_info |
|
2379 | 2383 | |
|
2380 | 2384 | def _format_user_obj(self, obj): |
|
2381 | 2385 | """format a user object to display dict |
|
2382 | 2386 | |
|
2383 | 2387 | for use in user_expressions |
|
2384 | 2388 | """ |
|
2385 | 2389 | |
|
2386 | 2390 | data, md = self.display_formatter.format(obj) |
|
2387 | 2391 | value = { |
|
2388 | 2392 | 'status' : 'ok', |
|
2389 | 2393 | 'data' : data, |
|
2390 | 2394 | 'metadata' : md, |
|
2391 | 2395 | } |
|
2392 | 2396 | return value |
|
2393 | 2397 | |
|
2394 | 2398 | def user_expressions(self, expressions): |
|
2395 | 2399 | """Evaluate a dict of expressions in the user's namespace. |
|
2396 | 2400 | |
|
2397 | 2401 | Parameters |
|
2398 | 2402 | ---------- |
|
2399 | 2403 | expressions : dict |
|
2400 | 2404 | A dict with string keys and string values. The expression values |
|
2401 | 2405 | should be valid Python expressions, each of which will be evaluated |
|
2402 | 2406 | in the user namespace. |
|
2403 | 2407 | |
|
2404 | 2408 | Returns |
|
2405 | 2409 | ------- |
|
2406 | 2410 | A dict, keyed like the input expressions dict, with the rich mime-typed |
|
2407 | 2411 | display_data of each value. |
|
2408 | 2412 | """ |
|
2409 | 2413 | out = {} |
|
2410 | 2414 | user_ns = self.user_ns |
|
2411 | 2415 | global_ns = self.user_global_ns |
|
2412 | 2416 | |
|
2413 | 2417 | for key, expr in iteritems(expressions): |
|
2414 | 2418 | try: |
|
2415 | 2419 | value = self._format_user_obj(eval(expr, global_ns, user_ns)) |
|
2416 | 2420 | except: |
|
2417 | 2421 | value = self._user_obj_error() |
|
2418 | 2422 | out[key] = value |
|
2419 | 2423 | return out |
|
2420 | 2424 | |
|
2421 | 2425 | #------------------------------------------------------------------------- |
|
2422 | 2426 | # Things related to the running of code |
|
2423 | 2427 | #------------------------------------------------------------------------- |
|
2424 | 2428 | |
|
2425 | 2429 | def ex(self, cmd): |
|
2426 | 2430 | """Execute a normal python statement in user namespace.""" |
|
2427 | 2431 | with self.builtin_trap: |
|
2428 | 2432 | exec(cmd, self.user_global_ns, self.user_ns) |
|
2429 | 2433 | |
|
2430 | 2434 | def ev(self, expr): |
|
2431 | 2435 | """Evaluate python expression expr in user namespace. |
|
2432 | 2436 | |
|
2433 | 2437 | Returns the result of evaluation |
|
2434 | 2438 | """ |
|
2435 | 2439 | with self.builtin_trap: |
|
2436 | 2440 | return eval(expr, self.user_global_ns, self.user_ns) |
|
2437 | 2441 | |
|
2438 | 2442 | def safe_execfile(self, fname, *where, **kw): |
|
2439 | 2443 | """A safe version of the builtin execfile(). |
|
2440 | 2444 | |
|
2441 | 2445 | This version will never throw an exception, but instead print |
|
2442 | 2446 | helpful error messages to the screen. This only works on pure |
|
2443 | 2447 | Python files with the .py extension. |
|
2444 | 2448 | |
|
2445 | 2449 | Parameters |
|
2446 | 2450 | ---------- |
|
2447 | 2451 | fname : string |
|
2448 | 2452 | The name of the file to be executed. |
|
2449 | 2453 | where : tuple |
|
2450 | 2454 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2451 | 2455 | If only one is given, it is passed as both. |
|
2452 | 2456 | exit_ignore : bool (False) |
|
2453 | 2457 | If True, then silence SystemExit for non-zero status (it is always |
|
2454 | 2458 | silenced for zero status, as it is so common). |
|
2455 | 2459 | raise_exceptions : bool (False) |
|
2456 | 2460 | If True raise exceptions everywhere. Meant for testing. |
|
2457 | 2461 | shell_futures : bool (False) |
|
2458 | 2462 | If True, the code will share future statements with the interactive |
|
2459 | 2463 | shell. It will both be affected by previous __future__ imports, and |
|
2460 | 2464 | any __future__ imports in the code will affect the shell. If False, |
|
2461 | 2465 | __future__ imports are not shared in either direction. |
|
2462 | 2466 | |
|
2463 | 2467 | """ |
|
2464 | 2468 | kw.setdefault('exit_ignore', False) |
|
2465 | 2469 | kw.setdefault('raise_exceptions', False) |
|
2466 | 2470 | kw.setdefault('shell_futures', False) |
|
2467 | 2471 | |
|
2468 | 2472 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2469 | 2473 | |
|
2470 | 2474 | # Make sure we can open the file |
|
2471 | 2475 | try: |
|
2472 | 2476 | with open(fname): |
|
2473 | 2477 | pass |
|
2474 | 2478 | except: |
|
2475 | 2479 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2476 | 2480 | return |
|
2477 | 2481 | |
|
2478 | 2482 | # Find things also in current directory. This is needed to mimic the |
|
2479 | 2483 | # behavior of running a script from the system command line, where |
|
2480 | 2484 | # Python inserts the script's directory into sys.path |
|
2481 | 2485 | dname = os.path.dirname(fname) |
|
2482 | 2486 | |
|
2483 | 2487 | with prepended_to_syspath(dname): |
|
2484 | 2488 | try: |
|
2485 | 2489 | glob, loc = (where + (None, ))[:2] |
|
2486 | 2490 | py3compat.execfile( |
|
2487 | 2491 | fname, glob, loc, |
|
2488 | 2492 | self.compile if kw['shell_futures'] else None) |
|
2489 | 2493 | except SystemExit as status: |
|
2490 | 2494 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2491 | 2495 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2492 | 2496 | # these are considered normal by the OS: |
|
2493 | 2497 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2494 | 2498 | # 0 |
|
2495 | 2499 | # > python -c'import sys;sys.exit()'; echo $? |
|
2496 | 2500 | # 0 |
|
2497 | 2501 | # For other exit status, we show the exception unless |
|
2498 | 2502 | # explicitly silenced, but only in short form. |
|
2499 | 2503 | if status.code: |
|
2500 | 2504 | if kw['raise_exceptions']: |
|
2501 | 2505 | raise |
|
2502 | 2506 | if not kw['exit_ignore']: |
|
2503 | 2507 | self.showtraceback(exception_only=True) |
|
2504 | 2508 | except: |
|
2505 | 2509 | if kw['raise_exceptions']: |
|
2506 | 2510 | raise |
|
2507 | 2511 | # tb offset is 2 because we wrap execfile |
|
2508 | 2512 | self.showtraceback(tb_offset=2) |
|
2509 | 2513 | |
|
2510 | 2514 | def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False): |
|
2511 | 2515 | """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax. |
|
2512 | 2516 | |
|
2513 | 2517 | Parameters |
|
2514 | 2518 | ---------- |
|
2515 | 2519 | fname : str |
|
2516 | 2520 | The name of the file to execute. The filename must have a |
|
2517 | 2521 | .ipy or .ipynb extension. |
|
2518 | 2522 | shell_futures : bool (False) |
|
2519 | 2523 | If True, the code will share future statements with the interactive |
|
2520 | 2524 | shell. It will both be affected by previous __future__ imports, and |
|
2521 | 2525 | any __future__ imports in the code will affect the shell. If False, |
|
2522 | 2526 | __future__ imports are not shared in either direction. |
|
2523 | 2527 | raise_exceptions : bool (False) |
|
2524 | 2528 | If True raise exceptions everywhere. Meant for testing. |
|
2525 | 2529 | """ |
|
2526 | 2530 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2527 | 2531 | |
|
2528 | 2532 | # Make sure we can open the file |
|
2529 | 2533 | try: |
|
2530 | 2534 | with open(fname): |
|
2531 | 2535 | pass |
|
2532 | 2536 | except: |
|
2533 | 2537 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2534 | 2538 | return |
|
2535 | 2539 | |
|
2536 | 2540 | # Find things also in current directory. This is needed to mimic the |
|
2537 | 2541 | # behavior of running a script from the system command line, where |
|
2538 | 2542 | # Python inserts the script's directory into sys.path |
|
2539 | 2543 | dname = os.path.dirname(fname) |
|
2540 | 2544 | |
|
2541 | 2545 | def get_cells(): |
|
2542 | 2546 | """generator for sequence of code blocks to run""" |
|
2543 | 2547 | if fname.endswith('.ipynb'): |
|
2544 | 2548 | from nbformat import read |
|
2545 | 2549 | with io_open(fname) as f: |
|
2546 | 2550 | nb = read(f, as_version=4) |
|
2547 | 2551 | if not nb.cells: |
|
2548 | 2552 | return |
|
2549 | 2553 | for cell in nb.cells: |
|
2550 | 2554 | if cell.cell_type == 'code': |
|
2551 | 2555 | yield cell.source |
|
2552 | 2556 | else: |
|
2553 | 2557 | with open(fname) as f: |
|
2554 | 2558 | yield f.read() |
|
2555 | 2559 | |
|
2556 | 2560 | with prepended_to_syspath(dname): |
|
2557 | 2561 | try: |
|
2558 | 2562 | for cell in get_cells(): |
|
2559 | 2563 | result = self.run_cell(cell, silent=True, shell_futures=shell_futures) |
|
2560 | 2564 | if raise_exceptions: |
|
2561 | 2565 | result.raise_error() |
|
2562 | 2566 | elif not result.success: |
|
2563 | 2567 | break |
|
2564 | 2568 | except: |
|
2565 | 2569 | if raise_exceptions: |
|
2566 | 2570 | raise |
|
2567 | 2571 | self.showtraceback() |
|
2568 | 2572 | warn('Unknown failure executing file: <%s>' % fname) |
|
2569 | 2573 | |
|
2570 | 2574 | def safe_run_module(self, mod_name, where): |
|
2571 | 2575 | """A safe version of runpy.run_module(). |
|
2572 | 2576 | |
|
2573 | 2577 | This version will never throw an exception, but instead print |
|
2574 | 2578 | helpful error messages to the screen. |
|
2575 | 2579 | |
|
2576 | 2580 | `SystemExit` exceptions with status code 0 or None are ignored. |
|
2577 | 2581 | |
|
2578 | 2582 | Parameters |
|
2579 | 2583 | ---------- |
|
2580 | 2584 | mod_name : string |
|
2581 | 2585 | The name of the module to be executed. |
|
2582 | 2586 | where : dict |
|
2583 | 2587 | The globals namespace. |
|
2584 | 2588 | """ |
|
2585 | 2589 | try: |
|
2586 | 2590 | try: |
|
2587 | 2591 | where.update( |
|
2588 | 2592 | runpy.run_module(str(mod_name), run_name="__main__", |
|
2589 | 2593 | alter_sys=True) |
|
2590 | 2594 | ) |
|
2591 | 2595 | except SystemExit as status: |
|
2592 | 2596 | if status.code: |
|
2593 | 2597 | raise |
|
2594 | 2598 | except: |
|
2595 | 2599 | self.showtraceback() |
|
2596 | 2600 | warn('Unknown failure executing module: <%s>' % mod_name) |
|
2597 | 2601 | |
|
2598 | 2602 | def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True): |
|
2599 | 2603 | """Run a complete IPython cell. |
|
2600 | 2604 | |
|
2601 | 2605 | Parameters |
|
2602 | 2606 | ---------- |
|
2603 | 2607 | raw_cell : str |
|
2604 | 2608 | The code (including IPython code such as %magic functions) to run. |
|
2605 | 2609 | store_history : bool |
|
2606 | 2610 | If True, the raw and translated cell will be stored in IPython's |
|
2607 | 2611 | history. For user code calling back into IPython's machinery, this |
|
2608 | 2612 | should be set to False. |
|
2609 | 2613 | silent : bool |
|
2610 | 2614 | If True, avoid side-effects, such as implicit displayhooks and |
|
2611 | 2615 | and logging. silent=True forces store_history=False. |
|
2612 | 2616 | shell_futures : bool |
|
2613 | 2617 | If True, the code will share future statements with the interactive |
|
2614 | 2618 | shell. It will both be affected by previous __future__ imports, and |
|
2615 | 2619 | any __future__ imports in the code will affect the shell. If False, |
|
2616 | 2620 | __future__ imports are not shared in either direction. |
|
2617 | 2621 | |
|
2618 | 2622 | Returns |
|
2619 | 2623 | ------- |
|
2620 | 2624 | result : :class:`ExecutionResult` |
|
2621 | 2625 | """ |
|
2622 | 2626 | result = ExecutionResult() |
|
2623 | 2627 | |
|
2624 | 2628 | if (not raw_cell) or raw_cell.isspace(): |
|
2625 | 2629 | return result |
|
2626 | 2630 | |
|
2627 | 2631 | if silent: |
|
2628 | 2632 | store_history = False |
|
2629 | 2633 | |
|
2630 | 2634 | if store_history: |
|
2631 | 2635 | result.execution_count = self.execution_count |
|
2632 | 2636 | |
|
2633 | 2637 | def error_before_exec(value): |
|
2634 | 2638 | result.error_before_exec = value |
|
2635 | 2639 | return result |
|
2636 | 2640 | |
|
2637 | 2641 | self.events.trigger('pre_execute') |
|
2638 | 2642 | if not silent: |
|
2639 | 2643 | self.events.trigger('pre_run_cell') |
|
2640 | 2644 | |
|
2641 | 2645 | # If any of our input transformation (input_transformer_manager or |
|
2642 | 2646 | # prefilter_manager) raises an exception, we store it in this variable |
|
2643 | 2647 | # so that we can display the error after logging the input and storing |
|
2644 | 2648 | # it in the history. |
|
2645 | 2649 | preprocessing_exc_tuple = None |
|
2646 | 2650 | try: |
|
2647 | 2651 | # Static input transformations |
|
2648 | 2652 | cell = self.input_transformer_manager.transform_cell(raw_cell) |
|
2649 | 2653 | except SyntaxError: |
|
2650 | 2654 | preprocessing_exc_tuple = sys.exc_info() |
|
2651 | 2655 | cell = raw_cell # cell has to exist so it can be stored/logged |
|
2652 | 2656 | else: |
|
2653 | 2657 | if len(cell.splitlines()) == 1: |
|
2654 | 2658 | # Dynamic transformations - only applied for single line commands |
|
2655 | 2659 | with self.builtin_trap: |
|
2656 | 2660 | try: |
|
2657 | 2661 | # use prefilter_lines to handle trailing newlines |
|
2658 | 2662 | # restore trailing newline for ast.parse |
|
2659 | 2663 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' |
|
2660 | 2664 | except Exception: |
|
2661 | 2665 | # don't allow prefilter errors to crash IPython |
|
2662 | 2666 | preprocessing_exc_tuple = sys.exc_info() |
|
2663 | 2667 | |
|
2664 | 2668 | # Store raw and processed history |
|
2665 | 2669 | if store_history: |
|
2666 | 2670 | self.history_manager.store_inputs(self.execution_count, |
|
2667 | 2671 | cell, raw_cell) |
|
2668 | 2672 | if not silent: |
|
2669 | 2673 | self.logger.log(cell, raw_cell) |
|
2670 | 2674 | |
|
2671 | 2675 | # Display the exception if input processing failed. |
|
2672 | 2676 | if preprocessing_exc_tuple is not None: |
|
2673 | 2677 | self.showtraceback(preprocessing_exc_tuple) |
|
2674 | 2678 | if store_history: |
|
2675 | 2679 | self.execution_count += 1 |
|
2676 | 2680 | return error_before_exec(preprocessing_exc_tuple[2]) |
|
2677 | 2681 | |
|
2678 | 2682 | # Our own compiler remembers the __future__ environment. If we want to |
|
2679 | 2683 | # run code with a separate __future__ environment, use the default |
|
2680 | 2684 | # compiler |
|
2681 | 2685 | compiler = self.compile if shell_futures else CachingCompiler() |
|
2682 | 2686 | |
|
2683 | 2687 | with self.builtin_trap: |
|
2684 | 2688 | cell_name = self.compile.cache(cell, self.execution_count) |
|
2685 | 2689 | |
|
2686 | 2690 | with self.display_trap: |
|
2687 | 2691 | # Compile to bytecode |
|
2688 | 2692 | try: |
|
2689 | 2693 | code_ast = compiler.ast_parse(cell, filename=cell_name) |
|
2690 | 2694 | except IndentationError as e: |
|
2691 | 2695 | self.showindentationerror() |
|
2692 | 2696 | if store_history: |
|
2693 | 2697 | self.execution_count += 1 |
|
2694 | 2698 | return error_before_exec(e) |
|
2695 | 2699 | except (OverflowError, SyntaxError, ValueError, TypeError, |
|
2696 | 2700 | MemoryError) as e: |
|
2697 | 2701 | self.showsyntaxerror() |
|
2698 | 2702 | if store_history: |
|
2699 | 2703 | self.execution_count += 1 |
|
2700 | 2704 | return error_before_exec(e) |
|
2701 | 2705 | |
|
2702 | 2706 | # Apply AST transformations |
|
2703 | 2707 | try: |
|
2704 | 2708 | code_ast = self.transform_ast(code_ast) |
|
2705 | 2709 | except InputRejected as e: |
|
2706 | 2710 | self.showtraceback() |
|
2707 | 2711 | if store_history: |
|
2708 | 2712 | self.execution_count += 1 |
|
2709 | 2713 | return error_before_exec(e) |
|
2710 | 2714 | |
|
2711 | 2715 | # Give the displayhook a reference to our ExecutionResult so it |
|
2712 | 2716 | # can fill in the output value. |
|
2713 | 2717 | self.displayhook.exec_result = result |
|
2714 | 2718 | |
|
2715 | 2719 | # Execute the user code |
|
2716 | 2720 | interactivity = "none" if silent else self.ast_node_interactivity |
|
2717 | 2721 | self.run_ast_nodes(code_ast.body, cell_name, |
|
2718 | 2722 | interactivity=interactivity, compiler=compiler, result=result) |
|
2719 | 2723 | |
|
2720 | 2724 | # Reset this so later displayed values do not modify the |
|
2721 | 2725 | # ExecutionResult |
|
2722 | 2726 | self.displayhook.exec_result = None |
|
2723 | 2727 | |
|
2724 | 2728 | self.events.trigger('post_execute') |
|
2725 | 2729 | if not silent: |
|
2726 | 2730 | self.events.trigger('post_run_cell') |
|
2727 | 2731 | |
|
2728 | 2732 | if store_history: |
|
2729 | 2733 | # Write output to the database. Does nothing unless |
|
2730 | 2734 | # history output logging is enabled. |
|
2731 | 2735 | self.history_manager.store_output(self.execution_count) |
|
2732 | 2736 | # Each cell is a *single* input, regardless of how many lines it has |
|
2733 | 2737 | self.execution_count += 1 |
|
2734 | 2738 | |
|
2735 | 2739 | return result |
|
2736 | 2740 | |
|
2737 | 2741 | def transform_ast(self, node): |
|
2738 | 2742 | """Apply the AST transformations from self.ast_transformers |
|
2739 | 2743 | |
|
2740 | 2744 | Parameters |
|
2741 | 2745 | ---------- |
|
2742 | 2746 | node : ast.Node |
|
2743 | 2747 | The root node to be transformed. Typically called with the ast.Module |
|
2744 | 2748 | produced by parsing user input. |
|
2745 | 2749 | |
|
2746 | 2750 | Returns |
|
2747 | 2751 | ------- |
|
2748 | 2752 | An ast.Node corresponding to the node it was called with. Note that it |
|
2749 | 2753 | may also modify the passed object, so don't rely on references to the |
|
2750 | 2754 | original AST. |
|
2751 | 2755 | """ |
|
2752 | 2756 | for transformer in self.ast_transformers: |
|
2753 | 2757 | try: |
|
2754 | 2758 | node = transformer.visit(node) |
|
2755 | 2759 | except InputRejected: |
|
2756 | 2760 | # User-supplied AST transformers can reject an input by raising |
|
2757 | 2761 | # an InputRejected. Short-circuit in this case so that we |
|
2758 | 2762 | # don't unregister the transform. |
|
2759 | 2763 | raise |
|
2760 | 2764 | except Exception: |
|
2761 | 2765 | warn("AST transformer %r threw an error. It will be unregistered." % transformer) |
|
2762 | 2766 | self.ast_transformers.remove(transformer) |
|
2763 | 2767 | |
|
2764 | 2768 | if self.ast_transformers: |
|
2765 | 2769 | ast.fix_missing_locations(node) |
|
2766 | 2770 | return node |
|
2767 | 2771 | |
|
2768 | 2772 | |
|
2769 | 2773 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr', |
|
2770 | 2774 | compiler=compile, result=None): |
|
2771 | 2775 | """Run a sequence of AST nodes. The execution mode depends on the |
|
2772 | 2776 | interactivity parameter. |
|
2773 | 2777 | |
|
2774 | 2778 | Parameters |
|
2775 | 2779 | ---------- |
|
2776 | 2780 | nodelist : list |
|
2777 | 2781 | A sequence of AST nodes to run. |
|
2778 | 2782 | cell_name : str |
|
2779 | 2783 | Will be passed to the compiler as the filename of the cell. Typically |
|
2780 | 2784 | the value returned by ip.compile.cache(cell). |
|
2781 | 2785 | interactivity : str |
|
2782 | 2786 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
2783 | 2787 | run interactively (displaying output from expressions). 'last_expr' |
|
2784 | 2788 | will run the last node interactively only if it is an expression (i.e. |
|
2785 | 2789 | expressions in loops or other blocks are not displayed. Other values |
|
2786 | 2790 | for this parameter will raise a ValueError. |
|
2787 | 2791 | compiler : callable |
|
2788 | 2792 | A function with the same interface as the built-in compile(), to turn |
|
2789 | 2793 | the AST nodes into code objects. Default is the built-in compile(). |
|
2790 | 2794 | result : ExecutionResult, optional |
|
2791 | 2795 | An object to store exceptions that occur during execution. |
|
2792 | 2796 | |
|
2793 | 2797 | Returns |
|
2794 | 2798 | ------- |
|
2795 | 2799 | True if an exception occurred while running code, False if it finished |
|
2796 | 2800 | running. |
|
2797 | 2801 | """ |
|
2798 | 2802 | if not nodelist: |
|
2799 | 2803 | return |
|
2800 | 2804 | |
|
2801 | 2805 | if interactivity == 'last_expr': |
|
2802 | 2806 | if isinstance(nodelist[-1], ast.Expr): |
|
2803 | 2807 | interactivity = "last" |
|
2804 | 2808 | else: |
|
2805 | 2809 | interactivity = "none" |
|
2806 | 2810 | |
|
2807 | 2811 | if interactivity == 'none': |
|
2808 | 2812 | to_run_exec, to_run_interactive = nodelist, [] |
|
2809 | 2813 | elif interactivity == 'last': |
|
2810 | 2814 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] |
|
2811 | 2815 | elif interactivity == 'all': |
|
2812 | 2816 | to_run_exec, to_run_interactive = [], nodelist |
|
2813 | 2817 | else: |
|
2814 | 2818 | raise ValueError("Interactivity was %r" % interactivity) |
|
2815 | 2819 | |
|
2816 | 2820 | try: |
|
2817 | 2821 | for i, node in enumerate(to_run_exec): |
|
2818 | 2822 | mod = ast.Module([node]) |
|
2819 | 2823 | code = compiler(mod, cell_name, "exec") |
|
2820 | 2824 | if self.run_code(code, result): |
|
2821 | 2825 | return True |
|
2822 | 2826 | |
|
2823 | 2827 | for i, node in enumerate(to_run_interactive): |
|
2824 | 2828 | mod = ast.Interactive([node]) |
|
2825 | 2829 | code = compiler(mod, cell_name, "single") |
|
2826 | 2830 | if self.run_code(code, result): |
|
2827 | 2831 | return True |
|
2828 | 2832 | |
|
2829 | 2833 | # Flush softspace |
|
2830 | 2834 | if softspace(sys.stdout, 0): |
|
2831 | 2835 | print() |
|
2832 | 2836 | |
|
2833 | 2837 | except: |
|
2834 | 2838 | # It's possible to have exceptions raised here, typically by |
|
2835 | 2839 | # compilation of odd code (such as a naked 'return' outside a |
|
2836 | 2840 | # function) that did parse but isn't valid. Typically the exception |
|
2837 | 2841 | # is a SyntaxError, but it's safest just to catch anything and show |
|
2838 | 2842 | # the user a traceback. |
|
2839 | 2843 | |
|
2840 | 2844 | # We do only one try/except outside the loop to minimize the impact |
|
2841 | 2845 | # on runtime, and also because if any node in the node list is |
|
2842 | 2846 | # broken, we should stop execution completely. |
|
2843 | 2847 | if result: |
|
2844 | 2848 | result.error_before_exec = sys.exc_info()[1] |
|
2845 | 2849 | self.showtraceback() |
|
2846 | 2850 | return True |
|
2847 | 2851 | |
|
2848 | 2852 | return False |
|
2849 | 2853 | |
|
2850 | 2854 | def run_code(self, code_obj, result=None): |
|
2851 | 2855 | """Execute a code object. |
|
2852 | 2856 | |
|
2853 | 2857 | When an exception occurs, self.showtraceback() is called to display a |
|
2854 | 2858 | traceback. |
|
2855 | 2859 | |
|
2856 | 2860 | Parameters |
|
2857 | 2861 | ---------- |
|
2858 | 2862 | code_obj : code object |
|
2859 | 2863 | A compiled code object, to be executed |
|
2860 | 2864 | result : ExecutionResult, optional |
|
2861 | 2865 | An object to store exceptions that occur during execution. |
|
2862 | 2866 | |
|
2863 | 2867 | Returns |
|
2864 | 2868 | ------- |
|
2865 | 2869 | False : successful execution. |
|
2866 | 2870 | True : an error occurred. |
|
2867 | 2871 | """ |
|
2868 | 2872 | # Set our own excepthook in case the user code tries to call it |
|
2869 | 2873 | # directly, so that the IPython crash handler doesn't get triggered |
|
2870 | 2874 | old_excepthook, sys.excepthook = sys.excepthook, self.excepthook |
|
2871 | 2875 | |
|
2872 | 2876 | # we save the original sys.excepthook in the instance, in case config |
|
2873 | 2877 | # code (such as magics) needs access to it. |
|
2874 | 2878 | self.sys_excepthook = old_excepthook |
|
2875 | 2879 | outflag = 1 # happens in more places, so it's easier as default |
|
2876 | 2880 | try: |
|
2877 | 2881 | try: |
|
2878 | 2882 | self.hooks.pre_run_code_hook() |
|
2879 | 2883 | #rprint('Running code', repr(code_obj)) # dbg |
|
2880 | 2884 | exec(code_obj, self.user_global_ns, self.user_ns) |
|
2881 | 2885 | finally: |
|
2882 | 2886 | # Reset our crash handler in place |
|
2883 | 2887 | sys.excepthook = old_excepthook |
|
2884 | 2888 | except SystemExit as e: |
|
2885 | 2889 | if result is not None: |
|
2886 | 2890 | result.error_in_exec = e |
|
2887 | 2891 | self.showtraceback(exception_only=True) |
|
2888 | 2892 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1) |
|
2889 | 2893 | except self.custom_exceptions: |
|
2890 | 2894 | etype, value, tb = sys.exc_info() |
|
2891 | 2895 | if result is not None: |
|
2892 | 2896 | result.error_in_exec = value |
|
2893 | 2897 | self.CustomTB(etype, value, tb) |
|
2894 | 2898 | except: |
|
2895 | 2899 | if result is not None: |
|
2896 | 2900 | result.error_in_exec = sys.exc_info()[1] |
|
2897 | 2901 | self.showtraceback() |
|
2898 | 2902 | else: |
|
2899 | 2903 | outflag = 0 |
|
2900 | 2904 | return outflag |
|
2901 | 2905 | |
|
2902 | 2906 | # For backwards compatibility |
|
2903 | 2907 | runcode = run_code |
|
2904 | 2908 | |
|
2905 | 2909 | #------------------------------------------------------------------------- |
|
2906 | 2910 | # Things related to GUI support and pylab |
|
2907 | 2911 | #------------------------------------------------------------------------- |
|
2908 | 2912 | |
|
2909 | 2913 | def enable_gui(self, gui=None): |
|
2910 | 2914 | raise NotImplementedError('Implement enable_gui in a subclass') |
|
2911 | 2915 | |
|
2912 | 2916 | def enable_matplotlib(self, gui=None): |
|
2913 | 2917 | """Enable interactive matplotlib and inline figure support. |
|
2914 | 2918 | |
|
2915 | 2919 | This takes the following steps: |
|
2916 | 2920 | |
|
2917 | 2921 | 1. select the appropriate eventloop and matplotlib backend |
|
2918 | 2922 | 2. set up matplotlib for interactive use with that backend |
|
2919 | 2923 | 3. configure formatters for inline figure display |
|
2920 | 2924 | 4. enable the selected gui eventloop |
|
2921 | 2925 | |
|
2922 | 2926 | Parameters |
|
2923 | 2927 | ---------- |
|
2924 | 2928 | gui : optional, string |
|
2925 | 2929 | If given, dictates the choice of matplotlib GUI backend to use |
|
2926 | 2930 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
2927 | 2931 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
2928 | 2932 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
2929 | 2933 | user's matplotlibrc configuration file). Note that not all backends |
|
2930 | 2934 | make sense in all contexts, for example a terminal ipython can't |
|
2931 | 2935 | display figures inline. |
|
2932 | 2936 | """ |
|
2933 | 2937 | from IPython.core import pylabtools as pt |
|
2934 | 2938 | gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select) |
|
2935 | 2939 | |
|
2936 | 2940 | if gui != 'inline': |
|
2937 | 2941 | # If we have our first gui selection, store it |
|
2938 | 2942 | if self.pylab_gui_select is None: |
|
2939 | 2943 | self.pylab_gui_select = gui |
|
2940 | 2944 | # Otherwise if they are different |
|
2941 | 2945 | elif gui != self.pylab_gui_select: |
|
2942 | 2946 | print ('Warning: Cannot change to a different GUI toolkit: %s.' |
|
2943 | 2947 | ' Using %s instead.' % (gui, self.pylab_gui_select)) |
|
2944 | 2948 | gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) |
|
2945 | 2949 | |
|
2946 | 2950 | pt.activate_matplotlib(backend) |
|
2947 | 2951 | pt.configure_inline_support(self, backend) |
|
2948 | 2952 | |
|
2949 | 2953 | # Now we must activate the gui pylab wants to use, and fix %run to take |
|
2950 | 2954 | # plot updates into account |
|
2951 | 2955 | self.enable_gui(gui) |
|
2952 | 2956 | self.magics_manager.registry['ExecutionMagics'].default_runner = \ |
|
2953 | 2957 | pt.mpl_runner(self.safe_execfile) |
|
2954 | 2958 | |
|
2955 | 2959 | return gui, backend |
|
2956 | 2960 | |
|
2957 | 2961 | def enable_pylab(self, gui=None, import_all=True, welcome_message=False): |
|
2958 | 2962 | """Activate pylab support at runtime. |
|
2959 | 2963 | |
|
2960 | 2964 | This turns on support for matplotlib, preloads into the interactive |
|
2961 | 2965 | namespace all of numpy and pylab, and configures IPython to correctly |
|
2962 | 2966 | interact with the GUI event loop. The GUI backend to be used can be |
|
2963 | 2967 | optionally selected with the optional ``gui`` argument. |
|
2964 | 2968 | |
|
2965 | 2969 | This method only adds preloading the namespace to InteractiveShell.enable_matplotlib. |
|
2966 | 2970 | |
|
2967 | 2971 | Parameters |
|
2968 | 2972 | ---------- |
|
2969 | 2973 | gui : optional, string |
|
2970 | 2974 | If given, dictates the choice of matplotlib GUI backend to use |
|
2971 | 2975 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
2972 | 2976 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
2973 | 2977 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
2974 | 2978 | user's matplotlibrc configuration file). Note that not all backends |
|
2975 | 2979 | make sense in all contexts, for example a terminal ipython can't |
|
2976 | 2980 | display figures inline. |
|
2977 | 2981 | import_all : optional, bool, default: True |
|
2978 | 2982 | Whether to do `from numpy import *` and `from pylab import *` |
|
2979 | 2983 | in addition to module imports. |
|
2980 | 2984 | welcome_message : deprecated |
|
2981 | 2985 | This argument is ignored, no welcome message will be displayed. |
|
2982 | 2986 | """ |
|
2983 | 2987 | from IPython.core.pylabtools import import_pylab |
|
2984 | 2988 | |
|
2985 | 2989 | gui, backend = self.enable_matplotlib(gui) |
|
2986 | 2990 | |
|
2987 | 2991 | # We want to prevent the loading of pylab to pollute the user's |
|
2988 | 2992 | # namespace as shown by the %who* magics, so we execute the activation |
|
2989 | 2993 | # code in an empty namespace, and we update *both* user_ns and |
|
2990 | 2994 | # user_ns_hidden with this information. |
|
2991 | 2995 | ns = {} |
|
2992 | 2996 | import_pylab(ns, import_all) |
|
2993 | 2997 | # warn about clobbered names |
|
2994 | 2998 | ignored = {"__builtins__"} |
|
2995 | 2999 | both = set(ns).intersection(self.user_ns).difference(ignored) |
|
2996 | 3000 | clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ] |
|
2997 | 3001 | self.user_ns.update(ns) |
|
2998 | 3002 | self.user_ns_hidden.update(ns) |
|
2999 | 3003 | return gui, backend, clobbered |
|
3000 | 3004 | |
|
3001 | 3005 | #------------------------------------------------------------------------- |
|
3002 | 3006 | # Utilities |
|
3003 | 3007 | #------------------------------------------------------------------------- |
|
3004 | 3008 | |
|
3005 | 3009 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): |
|
3006 | 3010 | """Expand python variables in a string. |
|
3007 | 3011 | |
|
3008 | 3012 | The depth argument indicates how many frames above the caller should |
|
3009 | 3013 | be walked to look for the local namespace where to expand variables. |
|
3010 | 3014 | |
|
3011 | 3015 | The global namespace for expansion is always the user's interactive |
|
3012 | 3016 | namespace. |
|
3013 | 3017 | """ |
|
3014 | 3018 | ns = self.user_ns.copy() |
|
3015 | 3019 | try: |
|
3016 | 3020 | frame = sys._getframe(depth+1) |
|
3017 | 3021 | except ValueError: |
|
3018 | 3022 | # This is thrown if there aren't that many frames on the stack, |
|
3019 | 3023 | # e.g. if a script called run_line_magic() directly. |
|
3020 | 3024 | pass |
|
3021 | 3025 | else: |
|
3022 | 3026 | ns.update(frame.f_locals) |
|
3023 | 3027 | |
|
3024 | 3028 | try: |
|
3025 | 3029 | # We have to use .vformat() here, because 'self' is a valid and common |
|
3026 | 3030 | # name, and expanding **ns for .format() would make it collide with |
|
3027 | 3031 | # the 'self' argument of the method. |
|
3028 | 3032 | cmd = formatter.vformat(cmd, args=[], kwargs=ns) |
|
3029 | 3033 | except Exception: |
|
3030 | 3034 | # if formatter couldn't format, just let it go untransformed |
|
3031 | 3035 | pass |
|
3032 | 3036 | return cmd |
|
3033 | 3037 | |
|
3034 | 3038 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
3035 | 3039 | """Make a new tempfile and return its filename. |
|
3036 | 3040 | |
|
3037 | 3041 | This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp), |
|
3038 | 3042 | but it registers the created filename internally so ipython cleans it up |
|
3039 | 3043 | at exit time. |
|
3040 | 3044 | |
|
3041 | 3045 | Optional inputs: |
|
3042 | 3046 | |
|
3043 | 3047 | - data(None): if data is given, it gets written out to the temp file |
|
3044 | 3048 | immediately, and the file is closed again.""" |
|
3045 | 3049 | |
|
3046 | 3050 | dirname = tempfile.mkdtemp(prefix=prefix) |
|
3047 | 3051 | self.tempdirs.append(dirname) |
|
3048 | 3052 | |
|
3049 | 3053 | handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname) |
|
3050 | 3054 | os.close(handle) # On Windows, there can only be one open handle on a file |
|
3051 | 3055 | self.tempfiles.append(filename) |
|
3052 | 3056 | |
|
3053 | 3057 | if data: |
|
3054 | 3058 | tmp_file = open(filename,'w') |
|
3055 | 3059 | tmp_file.write(data) |
|
3056 | 3060 | tmp_file.close() |
|
3057 | 3061 | return filename |
|
3058 | 3062 | |
|
3059 | 3063 | @undoc |
|
3060 | 3064 | def write(self,data): |
|
3061 | 3065 | """DEPRECATED: Write a string to the default output""" |
|
3062 | 3066 | warn('InteractiveShell.write() is deprecated, use sys.stdout instead', |
|
3063 | 3067 | DeprecationWarning, stacklevel=2) |
|
3064 | 3068 | sys.stdout.write(data) |
|
3065 | 3069 | |
|
3066 | 3070 | @undoc |
|
3067 | 3071 | def write_err(self,data): |
|
3068 | 3072 | """DEPRECATED: Write a string to the default error output""" |
|
3069 | 3073 | warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead', |
|
3070 | 3074 | DeprecationWarning, stacklevel=2) |
|
3071 | 3075 | sys.stderr.write(data) |
|
3072 | 3076 | |
|
3073 | 3077 | def ask_yes_no(self, prompt, default=None, interrupt=None): |
|
3074 | 3078 | if self.quiet: |
|
3075 | 3079 | return True |
|
3076 | 3080 | return ask_yes_no(prompt,default,interrupt) |
|
3077 | 3081 | |
|
3078 | 3082 | def show_usage(self): |
|
3079 | 3083 | """Show a usage message""" |
|
3080 | 3084 | page.page(IPython.core.usage.interactive_usage) |
|
3081 | 3085 | |
|
3082 | 3086 | def extract_input_lines(self, range_str, raw=False): |
|
3083 | 3087 | """Return as a string a set of input history slices. |
|
3084 | 3088 | |
|
3085 | 3089 | Parameters |
|
3086 | 3090 | ---------- |
|
3087 | 3091 | range_str : string |
|
3088 | 3092 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", |
|
3089 | 3093 | since this function is for use by magic functions which get their |
|
3090 | 3094 | arguments as strings. The number before the / is the session |
|
3091 | 3095 | number: ~n goes n back from the current session. |
|
3092 | 3096 | |
|
3093 | 3097 | raw : bool, optional |
|
3094 | 3098 | By default, the processed input is used. If this is true, the raw |
|
3095 | 3099 | input history is used instead. |
|
3096 | 3100 | |
|
3097 | 3101 | Notes |
|
3098 | 3102 | ----- |
|
3099 | 3103 | |
|
3100 | 3104 | Slices can be described with two notations: |
|
3101 | 3105 | |
|
3102 | 3106 | * ``N:M`` -> standard python form, means including items N...(M-1). |
|
3103 | 3107 | * ``N-M`` -> include items N..M (closed endpoint). |
|
3104 | 3108 | """ |
|
3105 | 3109 | lines = self.history_manager.get_range_by_str(range_str, raw=raw) |
|
3106 | 3110 | return "\n".join(x for _, _, x in lines) |
|
3107 | 3111 | |
|
3108 | 3112 | def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False): |
|
3109 | 3113 | """Get a code string from history, file, url, or a string or macro. |
|
3110 | 3114 | |
|
3111 | 3115 | This is mainly used by magic functions. |
|
3112 | 3116 | |
|
3113 | 3117 | Parameters |
|
3114 | 3118 | ---------- |
|
3115 | 3119 | |
|
3116 | 3120 | target : str |
|
3117 | 3121 | |
|
3118 | 3122 | A string specifying code to retrieve. This will be tried respectively |
|
3119 | 3123 | as: ranges of input history (see %history for syntax), url, |
|
3120 | 3124 | corresponding .py file, filename, or an expression evaluating to a |
|
3121 | 3125 | string or Macro in the user namespace. |
|
3122 | 3126 | |
|
3123 | 3127 | raw : bool |
|
3124 | 3128 | If true (default), retrieve raw history. Has no effect on the other |
|
3125 | 3129 | retrieval mechanisms. |
|
3126 | 3130 | |
|
3127 | 3131 | py_only : bool (default False) |
|
3128 | 3132 | Only try to fetch python code, do not try alternative methods to decode file |
|
3129 | 3133 | if unicode fails. |
|
3130 | 3134 | |
|
3131 | 3135 | Returns |
|
3132 | 3136 | ------- |
|
3133 | 3137 | A string of code. |
|
3134 | 3138 | |
|
3135 | 3139 | ValueError is raised if nothing is found, and TypeError if it evaluates |
|
3136 | 3140 | to an object of another type. In each case, .args[0] is a printable |
|
3137 | 3141 | message. |
|
3138 | 3142 | """ |
|
3139 | 3143 | code = self.extract_input_lines(target, raw=raw) # Grab history |
|
3140 | 3144 | if code: |
|
3141 | 3145 | return code |
|
3142 | 3146 | utarget = unquote_filename(target) |
|
3143 | 3147 | try: |
|
3144 | 3148 | if utarget.startswith(('http://', 'https://')): |
|
3145 | 3149 | return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie) |
|
3146 | 3150 | except UnicodeDecodeError: |
|
3147 | 3151 | if not py_only : |
|
3148 | 3152 | # Deferred import |
|
3149 | 3153 | try: |
|
3150 | 3154 | from urllib.request import urlopen # Py3 |
|
3151 | 3155 | except ImportError: |
|
3152 | 3156 | from urllib import urlopen |
|
3153 | 3157 | response = urlopen(target) |
|
3154 | 3158 | return response.read().decode('latin1') |
|
3155 | 3159 | raise ValueError(("'%s' seem to be unreadable.") % utarget) |
|
3156 | 3160 | |
|
3157 | 3161 | potential_target = [target] |
|
3158 | 3162 | try : |
|
3159 | 3163 | potential_target.insert(0,get_py_filename(target)) |
|
3160 | 3164 | except IOError: |
|
3161 | 3165 | pass |
|
3162 | 3166 | |
|
3163 | 3167 | for tgt in potential_target : |
|
3164 | 3168 | if os.path.isfile(tgt): # Read file |
|
3165 | 3169 | try : |
|
3166 | 3170 | return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie) |
|
3167 | 3171 | except UnicodeDecodeError : |
|
3168 | 3172 | if not py_only : |
|
3169 | 3173 | with io_open(tgt,'r', encoding='latin1') as f : |
|
3170 | 3174 | return f.read() |
|
3171 | 3175 | raise ValueError(("'%s' seem to be unreadable.") % target) |
|
3172 | 3176 | elif os.path.isdir(os.path.expanduser(tgt)): |
|
3173 | 3177 | raise ValueError("'%s' is a directory, not a regular file." % target) |
|
3174 | 3178 | |
|
3175 | 3179 | if search_ns: |
|
3176 | 3180 | # Inspect namespace to load object source |
|
3177 | 3181 | object_info = self.object_inspect(target, detail_level=1) |
|
3178 | 3182 | if object_info['found'] and object_info['source']: |
|
3179 | 3183 | return object_info['source'] |
|
3180 | 3184 | |
|
3181 | 3185 | try: # User namespace |
|
3182 | 3186 | codeobj = eval(target, self.user_ns) |
|
3183 | 3187 | except Exception: |
|
3184 | 3188 | raise ValueError(("'%s' was not found in history, as a file, url, " |
|
3185 | 3189 | "nor in the user namespace.") % target) |
|
3186 | 3190 | |
|
3187 | 3191 | if isinstance(codeobj, string_types): |
|
3188 | 3192 | return codeobj |
|
3189 | 3193 | elif isinstance(codeobj, Macro): |
|
3190 | 3194 | return codeobj.value |
|
3191 | 3195 | |
|
3192 | 3196 | raise TypeError("%s is neither a string nor a macro." % target, |
|
3193 | 3197 | codeobj) |
|
3194 | 3198 | |
|
3195 | 3199 | #------------------------------------------------------------------------- |
|
3196 | 3200 | # Things related to IPython exiting |
|
3197 | 3201 | #------------------------------------------------------------------------- |
|
3198 | 3202 | def atexit_operations(self): |
|
3199 | 3203 | """This will be executed at the time of exit. |
|
3200 | 3204 | |
|
3201 | 3205 | Cleanup operations and saving of persistent data that is done |
|
3202 | 3206 | unconditionally by IPython should be performed here. |
|
3203 | 3207 | |
|
3204 | 3208 | For things that may depend on startup flags or platform specifics (such |
|
3205 | 3209 | as having readline or not), register a separate atexit function in the |
|
3206 | 3210 | code that has the appropriate information, rather than trying to |
|
3207 | 3211 | clutter |
|
3208 | 3212 | """ |
|
3209 | 3213 | # Close the history session (this stores the end time and line count) |
|
3210 | 3214 | # this must be *before* the tempfile cleanup, in case of temporary |
|
3211 | 3215 | # history db |
|
3212 | 3216 | self.history_manager.end_session() |
|
3213 | 3217 | |
|
3214 | 3218 | # Cleanup all tempfiles and folders left around |
|
3215 | 3219 | for tfile in self.tempfiles: |
|
3216 | 3220 | try: |
|
3217 | 3221 | os.unlink(tfile) |
|
3218 | 3222 | except OSError: |
|
3219 | 3223 | pass |
|
3220 | 3224 | |
|
3221 | 3225 | for tdir in self.tempdirs: |
|
3222 | 3226 | try: |
|
3223 | 3227 | os.rmdir(tdir) |
|
3224 | 3228 | except OSError: |
|
3225 | 3229 | pass |
|
3226 | 3230 | |
|
3227 | 3231 | # Clear all user namespaces to release all references cleanly. |
|
3228 | 3232 | self.reset(new_session=False) |
|
3229 | 3233 | |
|
3230 | 3234 | # Run user hooks |
|
3231 | 3235 | self.hooks.shutdown_hook() |
|
3232 | 3236 | |
|
3233 | 3237 | def cleanup(self): |
|
3234 | 3238 | self.restore_sys_module_state() |
|
3235 | 3239 | |
|
3236 | 3240 | |
|
3237 | 3241 | class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)): |
|
3238 | 3242 | """An abstract base class for InteractiveShell.""" |
|
3239 | 3243 | |
|
3240 | 3244 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,1490 +1,1492 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | Verbose and colourful traceback formatting. |
|
4 | 4 | |
|
5 | 5 | **ColorTB** |
|
6 | 6 | |
|
7 | 7 | I've always found it a bit hard to visually parse tracebacks in Python. The |
|
8 | 8 | ColorTB class is a solution to that problem. It colors the different parts of a |
|
9 | 9 | traceback in a manner similar to what you would expect from a syntax-highlighting |
|
10 | 10 | text editor. |
|
11 | 11 | |
|
12 | 12 | Installation instructions for ColorTB:: |
|
13 | 13 | |
|
14 | 14 | import sys,ultratb |
|
15 | 15 | sys.excepthook = ultratb.ColorTB() |
|
16 | 16 | |
|
17 | 17 | **VerboseTB** |
|
18 | 18 | |
|
19 | 19 | I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds |
|
20 | 20 | of useful info when a traceback occurs. Ping originally had it spit out HTML |
|
21 | 21 | and intended it for CGI programmers, but why should they have all the fun? I |
|
22 | 22 | altered it to spit out colored text to the terminal. It's a bit overwhelming, |
|
23 | 23 | but kind of neat, and maybe useful for long-running programs that you believe |
|
24 | 24 | are bug-free. If a crash *does* occur in that type of program you want details. |
|
25 | 25 | Give it a shot--you'll love it or you'll hate it. |
|
26 | 26 | |
|
27 | 27 | .. note:: |
|
28 | 28 | |
|
29 | 29 | The Verbose mode prints the variables currently visible where the exception |
|
30 | 30 | happened (shortening their strings if too long). This can potentially be |
|
31 | 31 | very slow, if you happen to have a huge data structure whose string |
|
32 | 32 | representation is complex to compute. Your computer may appear to freeze for |
|
33 | 33 | a while with cpu usage at 100%. If this occurs, you can cancel the traceback |
|
34 | 34 | with Ctrl-C (maybe hitting it more than once). |
|
35 | 35 | |
|
36 | 36 | If you encounter this kind of situation often, you may want to use the |
|
37 | 37 | Verbose_novars mode instead of the regular Verbose, which avoids formatting |
|
38 | 38 | variables (but otherwise includes the information and context given by |
|
39 | 39 | Verbose). |
|
40 | 40 | |
|
41 | 41 | .. note:: |
|
42 | 42 | |
|
43 | 43 | The verbose mode print all variables in the stack, which means it can |
|
44 | 44 | potentially leak sensitive information like access keys, or unencryted |
|
45 | 45 | password. |
|
46 | 46 | |
|
47 | 47 | Installation instructions for VerboseTB:: |
|
48 | 48 | |
|
49 | 49 | import sys,ultratb |
|
50 | 50 | sys.excepthook = ultratb.VerboseTB() |
|
51 | 51 | |
|
52 | 52 | Note: Much of the code in this module was lifted verbatim from the standard |
|
53 | 53 | library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'. |
|
54 | 54 | |
|
55 | 55 | Color schemes |
|
56 | 56 | ------------- |
|
57 | 57 | |
|
58 | 58 | The colors are defined in the class TBTools through the use of the |
|
59 | 59 | ColorSchemeTable class. Currently the following exist: |
|
60 | 60 | |
|
61 | 61 | - NoColor: allows all of this module to be used in any terminal (the color |
|
62 | 62 | escapes are just dummy blank strings). |
|
63 | 63 | |
|
64 | 64 | - Linux: is meant to look good in a terminal like the Linux console (black |
|
65 | 65 | or very dark background). |
|
66 | 66 | |
|
67 | 67 | - LightBG: similar to Linux but swaps dark/light colors to be more readable |
|
68 | 68 | in light background terminals. |
|
69 | 69 | |
|
70 | 70 | You can implement other color schemes easily, the syntax is fairly |
|
71 | 71 | self-explanatory. Please send back new schemes you develop to the author for |
|
72 | 72 | possible inclusion in future releases. |
|
73 | 73 | |
|
74 | 74 | Inheritance diagram: |
|
75 | 75 | |
|
76 | 76 | .. inheritance-diagram:: IPython.core.ultratb |
|
77 | 77 | :parts: 3 |
|
78 | 78 | """ |
|
79 | 79 | |
|
80 | 80 | #***************************************************************************** |
|
81 | 81 | # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu> |
|
82 | 82 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> |
|
83 | 83 | # |
|
84 | 84 | # Distributed under the terms of the BSD License. The full license is in |
|
85 | 85 | # the file COPYING, distributed as part of this software. |
|
86 | 86 | #***************************************************************************** |
|
87 | 87 | |
|
88 | 88 | from __future__ import absolute_import |
|
89 | 89 | from __future__ import unicode_literals |
|
90 | 90 | from __future__ import print_function |
|
91 | 91 | |
|
92 | 92 | import dis |
|
93 | 93 | import inspect |
|
94 | 94 | import keyword |
|
95 | 95 | import linecache |
|
96 | 96 | import os |
|
97 | 97 | import pydoc |
|
98 | 98 | import re |
|
99 | 99 | import sys |
|
100 | 100 | import time |
|
101 | 101 | import tokenize |
|
102 | 102 | import traceback |
|
103 | 103 | import types |
|
104 | 104 | |
|
105 | 105 | try: # Python 2 |
|
106 | 106 | generate_tokens = tokenize.generate_tokens |
|
107 | 107 | except AttributeError: # Python 3 |
|
108 | 108 | generate_tokens = tokenize.tokenize |
|
109 | 109 | |
|
110 | 110 | # For purposes of monkeypatching inspect to fix a bug in it. |
|
111 | 111 | from inspect import getsourcefile, getfile, getmodule, \ |
|
112 | 112 | ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode |
|
113 | 113 | |
|
114 | 114 | # IPython's own modules |
|
115 | 115 | # Modified pdb which doesn't damage IPython's readline handling |
|
116 | 116 | from IPython import get_ipython |
|
117 | 117 | from IPython.core import debugger |
|
118 | 118 | from IPython.core.display_trap import DisplayTrap |
|
119 | 119 | from IPython.core.excolors import exception_colors |
|
120 | 120 | from IPython.utils import PyColorize |
|
121 | 121 | from IPython.utils import openpy |
|
122 | 122 | from IPython.utils import path as util_path |
|
123 | 123 | from IPython.utils import py3compat |
|
124 | 124 | from IPython.utils import ulinecache |
|
125 | 125 | from IPython.utils.data import uniq_stable |
|
126 | 126 | from IPython.utils.terminal import get_terminal_size |
|
127 | 127 | from logging import info, error |
|
128 | 128 | |
|
129 | 129 | import IPython.utils.colorable as colorable |
|
130 | 130 | |
|
131 | 131 | # Globals |
|
132 | 132 | # amount of space to put line numbers before verbose tracebacks |
|
133 | 133 | INDENT_SIZE = 8 |
|
134 | 134 | |
|
135 | 135 | # Default color scheme. This is used, for example, by the traceback |
|
136 | 136 | # formatter. When running in an actual IPython instance, the user's rc.colors |
|
137 | 137 | # value is used, but having a module global makes this functionality available |
|
138 | 138 | # to users of ultratb who are NOT running inside ipython. |
|
139 | 139 | DEFAULT_SCHEME = 'NoColor' |
|
140 | 140 | |
|
141 | 141 | # --------------------------------------------------------------------------- |
|
142 | 142 | # Code begins |
|
143 | 143 | |
|
144 | 144 | # Utility functions |
|
145 | 145 | def inspect_error(): |
|
146 | 146 | """Print a message about internal inspect errors. |
|
147 | 147 | |
|
148 | 148 | These are unfortunately quite common.""" |
|
149 | 149 | |
|
150 | 150 | error('Internal Python error in the inspect module.\n' |
|
151 | 151 | 'Below is the traceback from this internal error.\n') |
|
152 | 152 | |
|
153 | 153 | |
|
154 | 154 | # This function is a monkeypatch we apply to the Python inspect module. We have |
|
155 | 155 | # now found when it's needed (see discussion on issue gh-1456), and we have a |
|
156 | 156 | # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if |
|
157 | 157 | # the monkeypatch is not applied. TK, Aug 2012. |
|
158 | 158 | def findsource(object): |
|
159 | 159 | """Return the entire source file and starting line number for an object. |
|
160 | 160 | |
|
161 | 161 | The argument may be a module, class, method, function, traceback, frame, |
|
162 | 162 | or code object. The source code is returned as a list of all the lines |
|
163 | 163 | in the file and the line number indexes a line in that list. An IOError |
|
164 | 164 | is raised if the source code cannot be retrieved. |
|
165 | 165 | |
|
166 | 166 | FIXED version with which we monkeypatch the stdlib to work around a bug.""" |
|
167 | 167 | |
|
168 | 168 | file = getsourcefile(object) or getfile(object) |
|
169 | 169 | # If the object is a frame, then trying to get the globals dict from its |
|
170 | 170 | # module won't work. Instead, the frame object itself has the globals |
|
171 | 171 | # dictionary. |
|
172 | 172 | globals_dict = None |
|
173 | 173 | if inspect.isframe(object): |
|
174 | 174 | # XXX: can this ever be false? |
|
175 | 175 | globals_dict = object.f_globals |
|
176 | 176 | else: |
|
177 | 177 | module = getmodule(object, file) |
|
178 | 178 | if module: |
|
179 | 179 | globals_dict = module.__dict__ |
|
180 | 180 | lines = linecache.getlines(file, globals_dict) |
|
181 | 181 | if not lines: |
|
182 | 182 | raise IOError('could not get source code') |
|
183 | 183 | |
|
184 | 184 | if ismodule(object): |
|
185 | 185 | return lines, 0 |
|
186 | 186 | |
|
187 | 187 | if isclass(object): |
|
188 | 188 | name = object.__name__ |
|
189 | 189 | pat = re.compile(r'^(\s*)class\s*' + name + r'\b') |
|
190 | 190 | # make some effort to find the best matching class definition: |
|
191 | 191 | # use the one with the least indentation, which is the one |
|
192 | 192 | # that's most probably not inside a function definition. |
|
193 | 193 | candidates = [] |
|
194 | 194 | for i in range(len(lines)): |
|
195 | 195 | match = pat.match(lines[i]) |
|
196 | 196 | if match: |
|
197 | 197 | # if it's at toplevel, it's already the best one |
|
198 | 198 | if lines[i][0] == 'c': |
|
199 | 199 | return lines, i |
|
200 | 200 | # else add whitespace to candidate list |
|
201 | 201 | candidates.append((match.group(1), i)) |
|
202 | 202 | if candidates: |
|
203 | 203 | # this will sort by whitespace, and by line number, |
|
204 | 204 | # less whitespace first |
|
205 | 205 | candidates.sort() |
|
206 | 206 | return lines, candidates[0][1] |
|
207 | 207 | else: |
|
208 | 208 | raise IOError('could not find class definition') |
|
209 | 209 | |
|
210 | 210 | if ismethod(object): |
|
211 | 211 | object = object.__func__ |
|
212 | 212 | if isfunction(object): |
|
213 | 213 | object = object.__code__ |
|
214 | 214 | if istraceback(object): |
|
215 | 215 | object = object.tb_frame |
|
216 | 216 | if isframe(object): |
|
217 | 217 | object = object.f_code |
|
218 | 218 | if iscode(object): |
|
219 | 219 | if not hasattr(object, 'co_firstlineno'): |
|
220 | 220 | raise IOError('could not find function definition') |
|
221 | 221 | pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') |
|
222 | 222 | pmatch = pat.match |
|
223 | 223 | # fperez - fix: sometimes, co_firstlineno can give a number larger than |
|
224 | 224 | # the length of lines, which causes an error. Safeguard against that. |
|
225 | 225 | lnum = min(object.co_firstlineno, len(lines)) - 1 |
|
226 | 226 | while lnum > 0: |
|
227 | 227 | if pmatch(lines[lnum]): |
|
228 | 228 | break |
|
229 | 229 | lnum -= 1 |
|
230 | 230 | |
|
231 | 231 | return lines, lnum |
|
232 | 232 | raise IOError('could not find code object') |
|
233 | 233 | |
|
234 | 234 | |
|
235 | 235 | # This is a patched version of inspect.getargs that applies the (unmerged) |
|
236 | 236 | # patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes |
|
237 | 237 | # https://github.com/ipython/ipython/issues/8205 and |
|
238 | 238 | # https://github.com/ipython/ipython/issues/8293 |
|
239 | 239 | def getargs(co): |
|
240 | 240 | """Get information about the arguments accepted by a code object. |
|
241 | 241 | |
|
242 | 242 | Three things are returned: (args, varargs, varkw), where 'args' is |
|
243 | 243 | a list of argument names (possibly containing nested lists), and |
|
244 | 244 | 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" |
|
245 | 245 | if not iscode(co): |
|
246 | 246 | raise TypeError('{!r} is not a code object'.format(co)) |
|
247 | 247 | |
|
248 | 248 | nargs = co.co_argcount |
|
249 | 249 | names = co.co_varnames |
|
250 | 250 | args = list(names[:nargs]) |
|
251 | 251 | step = 0 |
|
252 | 252 | |
|
253 | 253 | # The following acrobatics are for anonymous (tuple) arguments. |
|
254 | 254 | for i in range(nargs): |
|
255 | 255 | if args[i][:1] in ('', '.'): |
|
256 | 256 | stack, remain, count = [], [], [] |
|
257 | 257 | while step < len(co.co_code): |
|
258 | 258 | op = ord(co.co_code[step]) |
|
259 | 259 | step = step + 1 |
|
260 | 260 | if op >= dis.HAVE_ARGUMENT: |
|
261 | 261 | opname = dis.opname[op] |
|
262 | 262 | value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256 |
|
263 | 263 | step = step + 2 |
|
264 | 264 | if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'): |
|
265 | 265 | remain.append(value) |
|
266 | 266 | count.append(value) |
|
267 | 267 | elif opname in ('STORE_FAST', 'STORE_DEREF'): |
|
268 | 268 | if op in dis.haslocal: |
|
269 | 269 | stack.append(co.co_varnames[value]) |
|
270 | 270 | elif op in dis.hasfree: |
|
271 | 271 | stack.append((co.co_cellvars + co.co_freevars)[value]) |
|
272 | 272 | # Special case for sublists of length 1: def foo((bar)) |
|
273 | 273 | # doesn't generate the UNPACK_TUPLE bytecode, so if |
|
274 | 274 | # `remain` is empty here, we have such a sublist. |
|
275 | 275 | if not remain: |
|
276 | 276 | stack[0] = [stack[0]] |
|
277 | 277 | break |
|
278 | 278 | else: |
|
279 | 279 | remain[-1] = remain[-1] - 1 |
|
280 | 280 | while remain[-1] == 0: |
|
281 | 281 | remain.pop() |
|
282 | 282 | size = count.pop() |
|
283 | 283 | stack[-size:] = [stack[-size:]] |
|
284 | 284 | if not remain: |
|
285 | 285 | break |
|
286 | 286 | remain[-1] = remain[-1] - 1 |
|
287 | 287 | if not remain: |
|
288 | 288 | break |
|
289 | 289 | args[i] = stack[0] |
|
290 | 290 | |
|
291 | 291 | varargs = None |
|
292 | 292 | if co.co_flags & inspect.CO_VARARGS: |
|
293 | 293 | varargs = co.co_varnames[nargs] |
|
294 | 294 | nargs = nargs + 1 |
|
295 | 295 | varkw = None |
|
296 | 296 | if co.co_flags & inspect.CO_VARKEYWORDS: |
|
297 | 297 | varkw = co.co_varnames[nargs] |
|
298 | 298 | return inspect.Arguments(args, varargs, varkw) |
|
299 | 299 | |
|
300 | 300 | |
|
301 | 301 | # Monkeypatch inspect to apply our bugfix. |
|
302 | 302 | def with_patch_inspect(f): |
|
303 | 303 | """decorator for monkeypatching inspect.findsource""" |
|
304 | 304 | |
|
305 | 305 | def wrapped(*args, **kwargs): |
|
306 | 306 | save_findsource = inspect.findsource |
|
307 | 307 | save_getargs = inspect.getargs |
|
308 | 308 | inspect.findsource = findsource |
|
309 | 309 | inspect.getargs = getargs |
|
310 | 310 | try: |
|
311 | 311 | return f(*args, **kwargs) |
|
312 | 312 | finally: |
|
313 | 313 | inspect.findsource = save_findsource |
|
314 | 314 | inspect.getargs = save_getargs |
|
315 | 315 | |
|
316 | 316 | return wrapped |
|
317 | 317 | |
|
318 | 318 | |
|
319 | 319 | if py3compat.PY3: |
|
320 | 320 | fixed_getargvalues = inspect.getargvalues |
|
321 | 321 | else: |
|
322 | 322 | # Fixes for https://github.com/ipython/ipython/issues/8293 |
|
323 | 323 | # and https://github.com/ipython/ipython/issues/8205. |
|
324 | 324 | # The relevant bug is caused by failure to correctly handle anonymous tuple |
|
325 | 325 | # unpacking, which only exists in Python 2. |
|
326 | 326 | fixed_getargvalues = with_patch_inspect(inspect.getargvalues) |
|
327 | 327 | |
|
328 | 328 | |
|
329 | 329 | def fix_frame_records_filenames(records): |
|
330 | 330 | """Try to fix the filenames in each record from inspect.getinnerframes(). |
|
331 | 331 | |
|
332 | 332 | Particularly, modules loaded from within zip files have useless filenames |
|
333 | 333 | attached to their code object, and inspect.getinnerframes() just uses it. |
|
334 | 334 | """ |
|
335 | 335 | fixed_records = [] |
|
336 | 336 | for frame, filename, line_no, func_name, lines, index in records: |
|
337 | 337 | # Look inside the frame's globals dictionary for __file__, |
|
338 | 338 | # which should be better. However, keep Cython filenames since |
|
339 | 339 | # we prefer the source filenames over the compiled .so file. |
|
340 | 340 | filename = py3compat.cast_unicode_py2(filename, "utf-8") |
|
341 | 341 | if not filename.endswith(('.pyx', '.pxd', '.pxi')): |
|
342 | 342 | better_fn = frame.f_globals.get('__file__', None) |
|
343 | 343 | if isinstance(better_fn, str): |
|
344 | 344 | # Check the type just in case someone did something weird with |
|
345 | 345 | # __file__. It might also be None if the error occurred during |
|
346 | 346 | # import. |
|
347 | 347 | filename = better_fn |
|
348 | 348 | fixed_records.append((frame, filename, line_no, func_name, lines, index)) |
|
349 | 349 | return fixed_records |
|
350 | 350 | |
|
351 | 351 | |
|
352 | 352 | @with_patch_inspect |
|
353 | 353 | def _fixed_getinnerframes(etb, context=1, tb_offset=0): |
|
354 | 354 | LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5 |
|
355 | 355 | |
|
356 | 356 | records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) |
|
357 | 357 | # If the error is at the console, don't build any context, since it would |
|
358 | 358 | # otherwise produce 5 blank lines printed out (there is no file at the |
|
359 | 359 | # console) |
|
360 | 360 | rec_check = records[tb_offset:] |
|
361 | 361 | try: |
|
362 | 362 | rname = rec_check[0][1] |
|
363 | 363 | if rname == '<ipython console>' or rname.endswith('<string>'): |
|
364 | 364 | return rec_check |
|
365 | 365 | except IndexError: |
|
366 | 366 | pass |
|
367 | 367 | |
|
368 | 368 | aux = traceback.extract_tb(etb) |
|
369 | 369 | assert len(records) == len(aux) |
|
370 | 370 | for i, (file, lnum, _, _) in zip(range(len(records)), aux): |
|
371 | 371 | maybeStart = lnum - 1 - context // 2 |
|
372 | 372 | start = max(maybeStart, 0) |
|
373 | 373 | end = start + context |
|
374 | 374 | lines = ulinecache.getlines(file)[start:end] |
|
375 | 375 | buf = list(records[i]) |
|
376 | 376 | buf[LNUM_POS] = lnum |
|
377 | 377 | buf[INDEX_POS] = lnum - 1 - start |
|
378 | 378 | buf[LINES_POS] = lines |
|
379 | 379 | records[i] = tuple(buf) |
|
380 | 380 | return records[tb_offset:] |
|
381 | 381 | |
|
382 | 382 | # Helper function -- largely belongs to VerboseTB, but we need the same |
|
383 | 383 | # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they |
|
384 | 384 | # can be recognized properly by ipython.el's py-traceback-line-re |
|
385 | 385 | # (SyntaxErrors have to be treated specially because they have no traceback) |
|
386 | 386 | |
|
387 | 387 | _parser = PyColorize.Parser() |
|
388 | 388 | |
|
389 | 389 | |
|
390 | 390 | def _format_traceback_lines(lnum, index, lines, Colors, lvals=None, scheme=None): |
|
391 | 391 | numbers_width = INDENT_SIZE - 1 |
|
392 | 392 | res = [] |
|
393 | 393 | i = lnum - index |
|
394 | 394 | |
|
395 | 395 | # This lets us get fully syntax-highlighted tracebacks. |
|
396 | 396 | if scheme is None: |
|
397 | 397 | ipinst = get_ipython() |
|
398 | 398 | if ipinst is not None: |
|
399 | 399 | scheme = ipinst.colors |
|
400 | 400 | else: |
|
401 | 401 | scheme = DEFAULT_SCHEME |
|
402 | 402 | |
|
403 | 403 | _line_format = _parser.format2 |
|
404 | 404 | |
|
405 | 405 | for line in lines: |
|
406 | 406 | line = py3compat.cast_unicode(line) |
|
407 | 407 | |
|
408 | 408 | new_line, err = _line_format(line, 'str', scheme) |
|
409 | 409 | if not err: line = new_line |
|
410 | 410 | |
|
411 | 411 | if i == lnum: |
|
412 | 412 | # This is the line with the error |
|
413 | 413 | pad = numbers_width - len(str(i)) |
|
414 | 414 | num = '%s%s' % (debugger.make_arrow(pad), str(lnum)) |
|
415 | 415 | line = '%s%s%s %s%s' % (Colors.linenoEm, num, |
|
416 | 416 | Colors.line, line, Colors.Normal) |
|
417 | 417 | else: |
|
418 | 418 | num = '%*s' % (numbers_width, i) |
|
419 | 419 | line = '%s%s%s %s' % (Colors.lineno, num, |
|
420 | 420 | Colors.Normal, line) |
|
421 | 421 | |
|
422 | 422 | res.append(line) |
|
423 | 423 | if lvals and i == lnum: |
|
424 | 424 | res.append(lvals + '\n') |
|
425 | 425 | i = i + 1 |
|
426 | 426 | return res |
|
427 | 427 | |
|
428 | 428 | def is_recursion_error(etype, value, records): |
|
429 | 429 | try: |
|
430 | 430 | # RecursionError is new in Python 3.5 |
|
431 | 431 | recursion_error_type = RecursionError |
|
432 | 432 | except NameError: |
|
433 | 433 | recursion_error_type = RuntimeError |
|
434 | 434 | |
|
435 | 435 | # The default recursion limit is 1000, but some of that will be taken up |
|
436 | 436 | # by stack frames in IPython itself. >500 frames probably indicates |
|
437 | 437 | # a recursion error. |
|
438 | 438 | return (etype is recursion_error_type) \ |
|
439 | 439 | and "recursion" in str(value).lower() \ |
|
440 | 440 | and len(records) > 500 |
|
441 | 441 | |
|
442 | 442 | def find_recursion(etype, value, records): |
|
443 | 443 | """Identify the repeating stack frames from a RecursionError traceback |
|
444 | 444 | |
|
445 | 445 | 'records' is a list as returned by VerboseTB.get_records() |
|
446 | 446 | |
|
447 | 447 | Returns (last_unique, repeat_length) |
|
448 | 448 | """ |
|
449 | 449 | # This involves a bit of guesswork - we want to show enough of the traceback |
|
450 | 450 | # to indicate where the recursion is occurring. We guess that the innermost |
|
451 | 451 | # quarter of the traceback (250 frames by default) is repeats, and find the |
|
452 | 452 | # first frame (from in to out) that looks different. |
|
453 | 453 | if not is_recursion_error(etype, value, records): |
|
454 | 454 | return len(records), 0 |
|
455 | 455 | |
|
456 | 456 | # Select filename, lineno, func_name to track frames with |
|
457 | 457 | records = [r[1:4] for r in records] |
|
458 | 458 | inner_frames = records[-(len(records)//4):] |
|
459 | 459 | frames_repeated = set(inner_frames) |
|
460 | 460 | |
|
461 | 461 | last_seen_at = {} |
|
462 | 462 | longest_repeat = 0 |
|
463 | 463 | i = len(records) |
|
464 | 464 | for frame in reversed(records): |
|
465 | 465 | i -= 1 |
|
466 | 466 | if frame not in frames_repeated: |
|
467 | 467 | last_unique = i |
|
468 | 468 | break |
|
469 | 469 | |
|
470 | 470 | if frame in last_seen_at: |
|
471 | 471 | distance = last_seen_at[frame] - i |
|
472 | 472 | longest_repeat = max(longest_repeat, distance) |
|
473 | 473 | |
|
474 | 474 | last_seen_at[frame] = i |
|
475 | 475 | else: |
|
476 | 476 | last_unique = 0 # The whole traceback was recursion |
|
477 | 477 | |
|
478 | 478 | return last_unique, longest_repeat |
|
479 | 479 | |
|
480 | 480 | #--------------------------------------------------------------------------- |
|
481 | 481 | # Module classes |
|
482 | 482 | class TBTools(colorable.Colorable): |
|
483 | 483 | """Basic tools used by all traceback printer classes.""" |
|
484 | 484 | |
|
485 | 485 | # Number of frames to skip when reporting tracebacks |
|
486 | 486 | tb_offset = 0 |
|
487 | 487 | |
|
488 | 488 | def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None): |
|
489 | 489 | # Whether to call the interactive pdb debugger after printing |
|
490 | 490 | # tracebacks or not |
|
491 | 491 | super(TBTools, self).__init__(parent=parent, config=config) |
|
492 | 492 | self.call_pdb = call_pdb |
|
493 | 493 | |
|
494 | 494 | # Output stream to write to. Note that we store the original value in |
|
495 | 495 | # a private attribute and then make the public ostream a property, so |
|
496 | 496 | # that we can delay accessing io.stdout until runtime. The way |
|
497 | 497 | # things are written now, the io.stdout object is dynamically managed |
|
498 | 498 | # so a reference to it should NEVER be stored statically. This |
|
499 | 499 | # property approach confines this detail to a single location, and all |
|
500 | 500 | # subclasses can simply access self.ostream for writing. |
|
501 | 501 | self._ostream = ostream |
|
502 | 502 | |
|
503 | 503 | # Create color table |
|
504 | 504 | self.color_scheme_table = exception_colors() |
|
505 | 505 | |
|
506 | 506 | self.set_colors(color_scheme) |
|
507 | 507 | self.old_scheme = color_scheme # save initial value for toggles |
|
508 | 508 | |
|
509 | 509 | if call_pdb: |
|
510 | 510 | self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name) |
|
511 | 511 | else: |
|
512 | 512 | self.pdb = None |
|
513 | 513 | |
|
514 | 514 | def _get_ostream(self): |
|
515 | 515 | """Output stream that exceptions are written to. |
|
516 | 516 | |
|
517 | 517 | Valid values are: |
|
518 | 518 | |
|
519 | 519 | - None: the default, which means that IPython will dynamically resolve |
|
520 | 520 | to io.stdout. This ensures compatibility with most tools, including |
|
521 | 521 | Windows (where plain stdout doesn't recognize ANSI escapes). |
|
522 | 522 | |
|
523 | 523 | - Any object with 'write' and 'flush' attributes. |
|
524 | 524 | """ |
|
525 | 525 | return sys.stdout if self._ostream is None else self._ostream |
|
526 | 526 | |
|
527 | 527 | def _set_ostream(self, val): |
|
528 | 528 | assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush')) |
|
529 | 529 | self._ostream = val |
|
530 | 530 | |
|
531 | 531 | ostream = property(_get_ostream, _set_ostream) |
|
532 | 532 | |
|
533 | 533 | def set_colors(self, *args, **kw): |
|
534 | 534 | """Shorthand access to the color table scheme selector method.""" |
|
535 | 535 | |
|
536 | 536 | # Set own color table |
|
537 | 537 | self.color_scheme_table.set_active_scheme(*args, **kw) |
|
538 | 538 | # for convenience, set Colors to the active scheme |
|
539 | 539 | self.Colors = self.color_scheme_table.active_colors |
|
540 | 540 | # Also set colors of debugger |
|
541 | 541 | if hasattr(self, 'pdb') and self.pdb is not None: |
|
542 | 542 | self.pdb.set_colors(*args, **kw) |
|
543 | 543 | |
|
544 | 544 | def color_toggle(self): |
|
545 | 545 | """Toggle between the currently active color scheme and NoColor.""" |
|
546 | 546 | |
|
547 | 547 | if self.color_scheme_table.active_scheme_name == 'NoColor': |
|
548 | 548 | self.color_scheme_table.set_active_scheme(self.old_scheme) |
|
549 | 549 | self.Colors = self.color_scheme_table.active_colors |
|
550 | 550 | else: |
|
551 | 551 | self.old_scheme = self.color_scheme_table.active_scheme_name |
|
552 | 552 | self.color_scheme_table.set_active_scheme('NoColor') |
|
553 | 553 | self.Colors = self.color_scheme_table.active_colors |
|
554 | 554 | |
|
555 | 555 | def stb2text(self, stb): |
|
556 | 556 | """Convert a structured traceback (a list) to a string.""" |
|
557 | 557 | return '\n'.join(stb) |
|
558 | 558 | |
|
559 | 559 | def text(self, etype, value, tb, tb_offset=None, context=5): |
|
560 | 560 | """Return formatted traceback. |
|
561 | 561 | |
|
562 | 562 | Subclasses may override this if they add extra arguments. |
|
563 | 563 | """ |
|
564 | 564 | tb_list = self.structured_traceback(etype, value, tb, |
|
565 | 565 | tb_offset, context) |
|
566 | 566 | return self.stb2text(tb_list) |
|
567 | 567 | |
|
568 | 568 | def structured_traceback(self, etype, evalue, tb, tb_offset=None, |
|
569 | 569 | context=5, mode=None): |
|
570 | 570 | """Return a list of traceback frames. |
|
571 | 571 | |
|
572 | 572 | Must be implemented by each class. |
|
573 | 573 | """ |
|
574 | 574 | raise NotImplementedError() |
|
575 | 575 | |
|
576 | 576 | |
|
577 | 577 | #--------------------------------------------------------------------------- |
|
578 | 578 | class ListTB(TBTools): |
|
579 | 579 | """Print traceback information from a traceback list, with optional color. |
|
580 | 580 | |
|
581 | 581 | Calling requires 3 arguments: (etype, evalue, elist) |
|
582 | 582 | as would be obtained by:: |
|
583 | 583 | |
|
584 | 584 | etype, evalue, tb = sys.exc_info() |
|
585 | 585 | if tb: |
|
586 | 586 | elist = traceback.extract_tb(tb) |
|
587 | 587 | else: |
|
588 | 588 | elist = None |
|
589 | 589 | |
|
590 | 590 | It can thus be used by programs which need to process the traceback before |
|
591 | 591 | printing (such as console replacements based on the code module from the |
|
592 | 592 | standard library). |
|
593 | 593 | |
|
594 | 594 | Because they are meant to be called without a full traceback (only a |
|
595 | 595 | list), instances of this class can't call the interactive pdb debugger.""" |
|
596 | 596 | |
|
597 | 597 | def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None): |
|
598 | 598 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
599 | 599 | ostream=ostream, parent=parent) |
|
600 | 600 | |
|
601 | 601 | def __call__(self, etype, value, elist): |
|
602 | 602 | self.ostream.flush() |
|
603 | 603 | self.ostream.write(self.text(etype, value, elist)) |
|
604 | 604 | self.ostream.write('\n') |
|
605 | 605 | |
|
606 | 606 | def structured_traceback(self, etype, value, elist, tb_offset=None, |
|
607 | 607 | context=5): |
|
608 | 608 | """Return a color formatted string with the traceback info. |
|
609 | 609 | |
|
610 | 610 | Parameters |
|
611 | 611 | ---------- |
|
612 | 612 | etype : exception type |
|
613 | 613 | Type of the exception raised. |
|
614 | 614 | |
|
615 | 615 | value : object |
|
616 | 616 | Data stored in the exception |
|
617 | 617 | |
|
618 | 618 | elist : list |
|
619 | 619 | List of frames, see class docstring for details. |
|
620 | 620 | |
|
621 | 621 | tb_offset : int, optional |
|
622 | 622 | Number of frames in the traceback to skip. If not given, the |
|
623 | 623 | instance value is used (set in constructor). |
|
624 | 624 | |
|
625 | 625 | context : int, optional |
|
626 | 626 | Number of lines of context information to print. |
|
627 | 627 | |
|
628 | 628 | Returns |
|
629 | 629 | ------- |
|
630 | 630 | String with formatted exception. |
|
631 | 631 | """ |
|
632 | 632 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
633 | 633 | Colors = self.Colors |
|
634 | 634 | out_list = [] |
|
635 | 635 | if elist: |
|
636 | 636 | |
|
637 | 637 | if tb_offset and len(elist) > tb_offset: |
|
638 | 638 | elist = elist[tb_offset:] |
|
639 | 639 | |
|
640 | 640 | out_list.append('Traceback %s(most recent call last)%s:' % |
|
641 | 641 | (Colors.normalEm, Colors.Normal) + '\n') |
|
642 | 642 | out_list.extend(self._format_list(elist)) |
|
643 | 643 | # The exception info should be a single entry in the list. |
|
644 | 644 | lines = ''.join(self._format_exception_only(etype, value)) |
|
645 | 645 | out_list.append(lines) |
|
646 | 646 | |
|
647 | 647 | # Note: this code originally read: |
|
648 | 648 | |
|
649 | 649 | ## for line in lines[:-1]: |
|
650 | 650 | ## out_list.append(" "+line) |
|
651 | 651 | ## out_list.append(lines[-1]) |
|
652 | 652 | |
|
653 | 653 | # This means it was indenting everything but the last line by a little |
|
654 | 654 | # bit. I've disabled this for now, but if we see ugliness somewhere we |
|
655 | 655 | # can restore it. |
|
656 | 656 | |
|
657 | 657 | return out_list |
|
658 | 658 | |
|
659 | 659 | def _format_list(self, extracted_list): |
|
660 | 660 | """Format a list of traceback entry tuples for printing. |
|
661 | 661 | |
|
662 | 662 | Given a list of tuples as returned by extract_tb() or |
|
663 | 663 | extract_stack(), return a list of strings ready for printing. |
|
664 | 664 | Each string in the resulting list corresponds to the item with the |
|
665 | 665 | same index in the argument list. Each string ends in a newline; |
|
666 | 666 | the strings may contain internal newlines as well, for those items |
|
667 | 667 | whose source text line is not None. |
|
668 | 668 | |
|
669 | 669 | Lifted almost verbatim from traceback.py |
|
670 | 670 | """ |
|
671 | 671 | |
|
672 | 672 | Colors = self.Colors |
|
673 | 673 | list = [] |
|
674 | 674 | for filename, lineno, name, line in extracted_list[:-1]: |
|
675 | 675 | item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \ |
|
676 | 676 | (Colors.filename, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.Normal, |
|
677 | 677 | Colors.lineno, lineno, Colors.Normal, |
|
678 | 678 | Colors.name, py3compat.cast_unicode_py2(name, "utf-8"), Colors.Normal) |
|
679 | 679 | if line: |
|
680 | 680 | item += ' %s\n' % line.strip() |
|
681 | 681 | list.append(item) |
|
682 | 682 | # Emphasize the last entry |
|
683 | 683 | filename, lineno, name, line = extracted_list[-1] |
|
684 | 684 | item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \ |
|
685 | 685 | (Colors.normalEm, |
|
686 | 686 | Colors.filenameEm, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.normalEm, |
|
687 | 687 | Colors.linenoEm, lineno, Colors.normalEm, |
|
688 | 688 | Colors.nameEm, py3compat.cast_unicode_py2(name, "utf-8"), Colors.normalEm, |
|
689 | 689 | Colors.Normal) |
|
690 | 690 | if line: |
|
691 | 691 | item += '%s %s%s\n' % (Colors.line, line.strip(), |
|
692 | 692 | Colors.Normal) |
|
693 | 693 | list.append(item) |
|
694 | 694 | return list |
|
695 | 695 | |
|
696 | 696 | def _format_exception_only(self, etype, value): |
|
697 | 697 | """Format the exception part of a traceback. |
|
698 | 698 | |
|
699 | 699 | The arguments are the exception type and value such as given by |
|
700 | 700 | sys.exc_info()[:2]. The return value is a list of strings, each ending |
|
701 | 701 | in a newline. Normally, the list contains a single string; however, |
|
702 | 702 | for SyntaxError exceptions, it contains several lines that (when |
|
703 | 703 | printed) display detailed information about where the syntax error |
|
704 | 704 | occurred. The message indicating which exception occurred is the |
|
705 | 705 | always last string in the list. |
|
706 | 706 | |
|
707 | 707 | Also lifted nearly verbatim from traceback.py |
|
708 | 708 | """ |
|
709 | 709 | have_filedata = False |
|
710 | 710 | Colors = self.Colors |
|
711 | 711 | list = [] |
|
712 | 712 | stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal) |
|
713 | 713 | if value is None: |
|
714 | 714 | # Not sure if this can still happen in Python 2.6 and above |
|
715 | 715 | list.append(stype + '\n') |
|
716 | 716 | else: |
|
717 | 717 | if issubclass(etype, SyntaxError): |
|
718 | 718 | have_filedata = True |
|
719 | 719 | if not value.filename: value.filename = "<string>" |
|
720 | 720 | if value.lineno: |
|
721 | 721 | lineno = value.lineno |
|
722 | 722 | textline = ulinecache.getline(value.filename, value.lineno) |
|
723 | 723 | else: |
|
724 | 724 | lineno = 'unknown' |
|
725 | 725 | textline = '' |
|
726 | 726 | list.append('%s File %s"%s"%s, line %s%s%s\n' % \ |
|
727 | 727 | (Colors.normalEm, |
|
728 | 728 | Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm, |
|
729 | 729 | Colors.linenoEm, lineno, Colors.Normal )) |
|
730 | 730 | if textline == '': |
|
731 | 731 | textline = py3compat.cast_unicode(value.text, "utf-8") |
|
732 | 732 | |
|
733 | 733 | if textline is not None: |
|
734 | 734 | i = 0 |
|
735 | 735 | while i < len(textline) and textline[i].isspace(): |
|
736 | 736 | i += 1 |
|
737 | 737 | list.append('%s %s%s\n' % (Colors.line, |
|
738 | 738 | textline.strip(), |
|
739 | 739 | Colors.Normal)) |
|
740 | 740 | if value.offset is not None: |
|
741 | 741 | s = ' ' |
|
742 | 742 | for c in textline[i:value.offset - 1]: |
|
743 | 743 | if c.isspace(): |
|
744 | 744 | s += c |
|
745 | 745 | else: |
|
746 | 746 | s += ' ' |
|
747 | 747 | list.append('%s%s^%s\n' % (Colors.caret, s, |
|
748 | 748 | Colors.Normal)) |
|
749 | 749 | |
|
750 | 750 | try: |
|
751 | 751 | s = value.msg |
|
752 | 752 | except Exception: |
|
753 | 753 | s = self._some_str(value) |
|
754 | 754 | if s: |
|
755 | 755 | list.append('%s%s:%s %s\n' % (stype, Colors.excName, |
|
756 | 756 | Colors.Normal, s)) |
|
757 | 757 | else: |
|
758 | 758 | list.append('%s\n' % stype) |
|
759 | 759 | |
|
760 | 760 | # sync with user hooks |
|
761 | 761 | if have_filedata: |
|
762 | 762 | ipinst = get_ipython() |
|
763 | 763 | if ipinst is not None: |
|
764 | 764 | ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0) |
|
765 | 765 | |
|
766 | 766 | return list |
|
767 | 767 | |
|
768 | 768 | def get_exception_only(self, etype, value): |
|
769 | 769 | """Only print the exception type and message, without a traceback. |
|
770 | 770 | |
|
771 | 771 | Parameters |
|
772 | 772 | ---------- |
|
773 | 773 | etype : exception type |
|
774 | 774 | value : exception value |
|
775 | 775 | """ |
|
776 | 776 | return ListTB.structured_traceback(self, etype, value, []) |
|
777 | 777 | |
|
778 | 778 | def show_exception_only(self, etype, evalue): |
|
779 | 779 | """Only print the exception type and message, without a traceback. |
|
780 | 780 | |
|
781 | 781 | Parameters |
|
782 | 782 | ---------- |
|
783 | 783 | etype : exception type |
|
784 | 784 | value : exception value |
|
785 | 785 | """ |
|
786 | 786 | # This method needs to use __call__ from *this* class, not the one from |
|
787 | 787 | # a subclass whose signature or behavior may be different |
|
788 | 788 | ostream = self.ostream |
|
789 | 789 | ostream.flush() |
|
790 | 790 | ostream.write('\n'.join(self.get_exception_only(etype, evalue))) |
|
791 | 791 | ostream.flush() |
|
792 | 792 | |
|
793 | 793 | def _some_str(self, value): |
|
794 | 794 | # Lifted from traceback.py |
|
795 | 795 | try: |
|
796 | 796 | return py3compat.cast_unicode(str(value)) |
|
797 | 797 | except: |
|
798 | 798 | return u'<unprintable %s object>' % type(value).__name__ |
|
799 | 799 | |
|
800 | 800 | |
|
801 | 801 | #---------------------------------------------------------------------------- |
|
802 | 802 | class VerboseTB(TBTools): |
|
803 | 803 | """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead |
|
804 | 804 | of HTML. Requires inspect and pydoc. Crazy, man. |
|
805 | 805 | |
|
806 | 806 | Modified version which optionally strips the topmost entries from the |
|
807 | 807 | traceback, to be used with alternate interpreters (because their own code |
|
808 | 808 | would appear in the traceback).""" |
|
809 | 809 | |
|
810 | 810 | def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None, |
|
811 | 811 | tb_offset=0, long_header=False, include_vars=True, |
|
812 | check_cache=None): | |
|
812 | check_cache=None, debugger_cls = None): | |
|
813 | 813 | """Specify traceback offset, headers and color scheme. |
|
814 | 814 | |
|
815 | 815 | Define how many frames to drop from the tracebacks. Calling it with |
|
816 | 816 | tb_offset=1 allows use of this handler in interpreters which will have |
|
817 | 817 | their own code at the top of the traceback (VerboseTB will first |
|
818 | 818 | remove that frame before printing the traceback info).""" |
|
819 | 819 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
820 | 820 | ostream=ostream) |
|
821 | 821 | self.tb_offset = tb_offset |
|
822 | 822 | self.long_header = long_header |
|
823 | 823 | self.include_vars = include_vars |
|
824 | 824 | # By default we use linecache.checkcache, but the user can provide a |
|
825 | 825 | # different check_cache implementation. This is used by the IPython |
|
826 | 826 | # kernel to provide tracebacks for interactive code that is cached, |
|
827 | 827 | # by a compiler instance that flushes the linecache but preserves its |
|
828 | 828 | # own code cache. |
|
829 | 829 | if check_cache is None: |
|
830 | 830 | check_cache = linecache.checkcache |
|
831 | 831 | self.check_cache = check_cache |
|
832 | 832 | |
|
833 | self.debugger_cls = debugger_cls or debugger.Pdb | |
|
834 | ||
|
833 | 835 | def format_records(self, records, last_unique, recursion_repeat): |
|
834 | 836 | """Format the stack frames of the traceback""" |
|
835 | 837 | frames = [] |
|
836 | 838 | for r in records[:last_unique+recursion_repeat+1]: |
|
837 | 839 | #print '*** record:',file,lnum,func,lines,index # dbg |
|
838 | 840 | frames.append(self.format_record(*r)) |
|
839 | 841 | |
|
840 | 842 | if recursion_repeat: |
|
841 | 843 | frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat) |
|
842 | 844 | frames.append(self.format_record(*records[last_unique+recursion_repeat+1])) |
|
843 | 845 | |
|
844 | 846 | return frames |
|
845 | 847 | |
|
846 | 848 | def format_record(self, frame, file, lnum, func, lines, index): |
|
847 | 849 | """Format a single stack frame""" |
|
848 | 850 | Colors = self.Colors # just a shorthand + quicker name lookup |
|
849 | 851 | ColorsNormal = Colors.Normal # used a lot |
|
850 | 852 | col_scheme = self.color_scheme_table.active_scheme_name |
|
851 | 853 | indent = ' ' * INDENT_SIZE |
|
852 | 854 | em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal) |
|
853 | 855 | undefined = '%sundefined%s' % (Colors.em, ColorsNormal) |
|
854 | 856 | tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal) |
|
855 | 857 | tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, |
|
856 | 858 | ColorsNormal) |
|
857 | 859 | tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \ |
|
858 | 860 | (Colors.vName, Colors.valEm, ColorsNormal) |
|
859 | 861 | tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal) |
|
860 | 862 | tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal, |
|
861 | 863 | Colors.vName, ColorsNormal) |
|
862 | 864 | tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal) |
|
863 | 865 | |
|
864 | 866 | tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal) |
|
865 | 867 | tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm, Colors.line, |
|
866 | 868 | ColorsNormal) |
|
867 | 869 | |
|
868 | 870 | abspath = os.path.abspath |
|
869 | 871 | |
|
870 | 872 | |
|
871 | 873 | if not file: |
|
872 | 874 | file = '?' |
|
873 | 875 | elif file.startswith(str("<")) and file.endswith(str(">")): |
|
874 | 876 | # Not a real filename, no problem... |
|
875 | 877 | pass |
|
876 | 878 | elif not os.path.isabs(file): |
|
877 | 879 | # Try to make the filename absolute by trying all |
|
878 | 880 | # sys.path entries (which is also what linecache does) |
|
879 | 881 | for dirname in sys.path: |
|
880 | 882 | try: |
|
881 | 883 | fullname = os.path.join(dirname, file) |
|
882 | 884 | if os.path.isfile(fullname): |
|
883 | 885 | file = os.path.abspath(fullname) |
|
884 | 886 | break |
|
885 | 887 | except Exception: |
|
886 | 888 | # Just in case that sys.path contains very |
|
887 | 889 | # strange entries... |
|
888 | 890 | pass |
|
889 | 891 | |
|
890 | 892 | file = py3compat.cast_unicode(file, util_path.fs_encoding) |
|
891 | 893 | link = tpl_link % file |
|
892 | 894 | args, varargs, varkw, locals = fixed_getargvalues(frame) |
|
893 | 895 | |
|
894 | 896 | if func == '?': |
|
895 | 897 | call = '' |
|
896 | 898 | else: |
|
897 | 899 | # Decide whether to include variable details or not |
|
898 | 900 | var_repr = self.include_vars and eqrepr or nullrepr |
|
899 | 901 | try: |
|
900 | 902 | call = tpl_call % (func, inspect.formatargvalues(args, |
|
901 | 903 | varargs, varkw, |
|
902 | 904 | locals, formatvalue=var_repr)) |
|
903 | 905 | except KeyError: |
|
904 | 906 | # This happens in situations like errors inside generator |
|
905 | 907 | # expressions, where local variables are listed in the |
|
906 | 908 | # line, but can't be extracted from the frame. I'm not |
|
907 | 909 | # 100% sure this isn't actually a bug in inspect itself, |
|
908 | 910 | # but since there's no info for us to compute with, the |
|
909 | 911 | # best we can do is report the failure and move on. Here |
|
910 | 912 | # we must *not* call any traceback construction again, |
|
911 | 913 | # because that would mess up use of %debug later on. So we |
|
912 | 914 | # simply report the failure and move on. The only |
|
913 | 915 | # limitation will be that this frame won't have locals |
|
914 | 916 | # listed in the call signature. Quite subtle problem... |
|
915 | 917 | # I can't think of a good way to validate this in a unit |
|
916 | 918 | # test, but running a script consisting of: |
|
917 | 919 | # dict( (k,v.strip()) for (k,v) in range(10) ) |
|
918 | 920 | # will illustrate the error, if this exception catch is |
|
919 | 921 | # disabled. |
|
920 | 922 | call = tpl_call_fail % func |
|
921 | 923 | |
|
922 | 924 | # Don't attempt to tokenize binary files. |
|
923 | 925 | if file.endswith(('.so', '.pyd', '.dll')): |
|
924 | 926 | return '%s %s\n' % (link, call) |
|
925 | 927 | |
|
926 | 928 | elif file.endswith(('.pyc', '.pyo')): |
|
927 | 929 | # Look up the corresponding source file. |
|
928 | 930 | try: |
|
929 | 931 | file = openpy.source_from_cache(file) |
|
930 | 932 | except ValueError: |
|
931 | 933 | # Failed to get the source file for some reason |
|
932 | 934 | # E.g. https://github.com/ipython/ipython/issues/9486 |
|
933 | 935 | return '%s %s\n' % (link, call) |
|
934 | 936 | |
|
935 | 937 | def linereader(file=file, lnum=[lnum], getline=ulinecache.getline): |
|
936 | 938 | line = getline(file, lnum[0]) |
|
937 | 939 | lnum[0] += 1 |
|
938 | 940 | return line |
|
939 | 941 | |
|
940 | 942 | # Build the list of names on this line of code where the exception |
|
941 | 943 | # occurred. |
|
942 | 944 | try: |
|
943 | 945 | names = [] |
|
944 | 946 | name_cont = False |
|
945 | 947 | |
|
946 | 948 | for token_type, token, start, end, line in generate_tokens(linereader): |
|
947 | 949 | # build composite names |
|
948 | 950 | if token_type == tokenize.NAME and token not in keyword.kwlist: |
|
949 | 951 | if name_cont: |
|
950 | 952 | # Continuation of a dotted name |
|
951 | 953 | try: |
|
952 | 954 | names[-1].append(token) |
|
953 | 955 | except IndexError: |
|
954 | 956 | names.append([token]) |
|
955 | 957 | name_cont = False |
|
956 | 958 | else: |
|
957 | 959 | # Regular new names. We append everything, the caller |
|
958 | 960 | # will be responsible for pruning the list later. It's |
|
959 | 961 | # very tricky to try to prune as we go, b/c composite |
|
960 | 962 | # names can fool us. The pruning at the end is easy |
|
961 | 963 | # to do (or the caller can print a list with repeated |
|
962 | 964 | # names if so desired. |
|
963 | 965 | names.append([token]) |
|
964 | 966 | elif token == '.': |
|
965 | 967 | name_cont = True |
|
966 | 968 | elif token_type == tokenize.NEWLINE: |
|
967 | 969 | break |
|
968 | 970 | |
|
969 | 971 | except (IndexError, UnicodeDecodeError, SyntaxError): |
|
970 | 972 | # signals exit of tokenizer |
|
971 | 973 | # SyntaxError can occur if the file is not actually Python |
|
972 | 974 | # - see gh-6300 |
|
973 | 975 | pass |
|
974 | 976 | except tokenize.TokenError as msg: |
|
975 | 977 | _m = ("An unexpected error occurred while tokenizing input\n" |
|
976 | 978 | "The following traceback may be corrupted or invalid\n" |
|
977 | 979 | "The error message is: %s\n" % msg) |
|
978 | 980 | error(_m) |
|
979 | 981 | |
|
980 | 982 | # Join composite names (e.g. "dict.fromkeys") |
|
981 | 983 | names = ['.'.join(n) for n in names] |
|
982 | 984 | # prune names list of duplicates, but keep the right order |
|
983 | 985 | unique_names = uniq_stable(names) |
|
984 | 986 | |
|
985 | 987 | # Start loop over vars |
|
986 | 988 | lvals = [] |
|
987 | 989 | if self.include_vars: |
|
988 | 990 | for name_full in unique_names: |
|
989 | 991 | name_base = name_full.split('.', 1)[0] |
|
990 | 992 | if name_base in frame.f_code.co_varnames: |
|
991 | 993 | if name_base in locals: |
|
992 | 994 | try: |
|
993 | 995 | value = repr(eval(name_full, locals)) |
|
994 | 996 | except: |
|
995 | 997 | value = undefined |
|
996 | 998 | else: |
|
997 | 999 | value = undefined |
|
998 | 1000 | name = tpl_local_var % name_full |
|
999 | 1001 | else: |
|
1000 | 1002 | if name_base in frame.f_globals: |
|
1001 | 1003 | try: |
|
1002 | 1004 | value = repr(eval(name_full, frame.f_globals)) |
|
1003 | 1005 | except: |
|
1004 | 1006 | value = undefined |
|
1005 | 1007 | else: |
|
1006 | 1008 | value = undefined |
|
1007 | 1009 | name = tpl_global_var % name_full |
|
1008 | 1010 | lvals.append(tpl_name_val % (name, value)) |
|
1009 | 1011 | if lvals: |
|
1010 | 1012 | lvals = '%s%s' % (indent, em_normal.join(lvals)) |
|
1011 | 1013 | else: |
|
1012 | 1014 | lvals = '' |
|
1013 | 1015 | |
|
1014 | 1016 | level = '%s %s\n' % (link, call) |
|
1015 | 1017 | |
|
1016 | 1018 | if index is None: |
|
1017 | 1019 | return level |
|
1018 | 1020 | else: |
|
1019 | 1021 | return '%s%s' % (level, ''.join( |
|
1020 | 1022 | _format_traceback_lines(lnum, index, lines, Colors, lvals, |
|
1021 | 1023 | col_scheme))) |
|
1022 | 1024 | |
|
1023 | 1025 | def prepare_chained_exception_message(self, cause): |
|
1024 | 1026 | direct_cause = "\nThe above exception was the direct cause of the following exception:\n" |
|
1025 | 1027 | exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n" |
|
1026 | 1028 | |
|
1027 | 1029 | if cause: |
|
1028 | 1030 | message = [[direct_cause]] |
|
1029 | 1031 | else: |
|
1030 | 1032 | message = [[exception_during_handling]] |
|
1031 | 1033 | return message |
|
1032 | 1034 | |
|
1033 | 1035 | def prepare_header(self, etype, long_version=False): |
|
1034 | 1036 | colors = self.Colors # just a shorthand + quicker name lookup |
|
1035 | 1037 | colorsnormal = colors.Normal # used a lot |
|
1036 | 1038 | exc = '%s%s%s' % (colors.excName, etype, colorsnormal) |
|
1037 | 1039 | width = min(75, get_terminal_size()[0]) |
|
1038 | 1040 | if long_version: |
|
1039 | 1041 | # Header with the exception type, python version, and date |
|
1040 | 1042 | pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable |
|
1041 | 1043 | date = time.ctime(time.time()) |
|
1042 | 1044 | |
|
1043 | 1045 | head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal, |
|
1044 | 1046 | exc, ' ' * (width - len(str(etype)) - len(pyver)), |
|
1045 | 1047 | pyver, date.rjust(width) ) |
|
1046 | 1048 | head += "\nA problem occurred executing Python code. Here is the sequence of function" \ |
|
1047 | 1049 | "\ncalls leading up to the error, with the most recent (innermost) call last." |
|
1048 | 1050 | else: |
|
1049 | 1051 | # Simplified header |
|
1050 | 1052 | head = '%s%s' % (exc, 'Traceback (most recent call last)'. \ |
|
1051 | 1053 | rjust(width - len(str(etype))) ) |
|
1052 | 1054 | |
|
1053 | 1055 | return head |
|
1054 | 1056 | |
|
1055 | 1057 | def format_exception(self, etype, evalue): |
|
1056 | 1058 | colors = self.Colors # just a shorthand + quicker name lookup |
|
1057 | 1059 | colorsnormal = colors.Normal # used a lot |
|
1058 | 1060 | indent = ' ' * INDENT_SIZE |
|
1059 | 1061 | # Get (safely) a string form of the exception info |
|
1060 | 1062 | try: |
|
1061 | 1063 | etype_str, evalue_str = map(str, (etype, evalue)) |
|
1062 | 1064 | except: |
|
1063 | 1065 | # User exception is improperly defined. |
|
1064 | 1066 | etype, evalue = str, sys.exc_info()[:2] |
|
1065 | 1067 | etype_str, evalue_str = map(str, (etype, evalue)) |
|
1066 | 1068 | # ... and format it |
|
1067 | 1069 | exception = ['%s%s%s: %s' % (colors.excName, etype_str, |
|
1068 | 1070 | colorsnormal, py3compat.cast_unicode(evalue_str))] |
|
1069 | 1071 | |
|
1070 | 1072 | if (not py3compat.PY3) and type(evalue) is types.InstanceType: |
|
1071 | 1073 | try: |
|
1072 | 1074 | names = [w for w in dir(evalue) if isinstance(w, py3compat.string_types)] |
|
1073 | 1075 | except: |
|
1074 | 1076 | # Every now and then, an object with funny internals blows up |
|
1075 | 1077 | # when dir() is called on it. We do the best we can to report |
|
1076 | 1078 | # the problem and continue |
|
1077 | 1079 | _m = '%sException reporting error (object with broken dir())%s:' |
|
1078 | 1080 | exception.append(_m % (colors.excName, colorsnormal)) |
|
1079 | 1081 | etype_str, evalue_str = map(str, sys.exc_info()[:2]) |
|
1080 | 1082 | exception.append('%s%s%s: %s' % (colors.excName, etype_str, |
|
1081 | 1083 | colorsnormal, py3compat.cast_unicode(evalue_str))) |
|
1082 | 1084 | names = [] |
|
1083 | 1085 | for name in names: |
|
1084 | 1086 | value = text_repr(getattr(evalue, name)) |
|
1085 | 1087 | exception.append('\n%s%s = %s' % (indent, name, value)) |
|
1086 | 1088 | |
|
1087 | 1089 | return exception |
|
1088 | 1090 | |
|
1089 | 1091 | def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset): |
|
1090 | 1092 | """Formats the header, traceback and exception message for a single exception. |
|
1091 | 1093 | |
|
1092 | 1094 | This may be called multiple times by Python 3 exception chaining |
|
1093 | 1095 | (PEP 3134). |
|
1094 | 1096 | """ |
|
1095 | 1097 | # some locals |
|
1096 | 1098 | orig_etype = etype |
|
1097 | 1099 | try: |
|
1098 | 1100 | etype = etype.__name__ |
|
1099 | 1101 | except AttributeError: |
|
1100 | 1102 | pass |
|
1101 | 1103 | |
|
1102 | 1104 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
1103 | 1105 | head = self.prepare_header(etype, self.long_header) |
|
1104 | 1106 | records = self.get_records(etb, number_of_lines_of_context, tb_offset) |
|
1105 | 1107 | |
|
1106 | 1108 | if records is None: |
|
1107 | 1109 | return "" |
|
1108 | 1110 | |
|
1109 | 1111 | last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records) |
|
1110 | 1112 | |
|
1111 | 1113 | frames = self.format_records(records, last_unique, recursion_repeat) |
|
1112 | 1114 | |
|
1113 | 1115 | formatted_exception = self.format_exception(etype, evalue) |
|
1114 | 1116 | if records: |
|
1115 | 1117 | filepath, lnum = records[-1][1:3] |
|
1116 | 1118 | filepath = os.path.abspath(filepath) |
|
1117 | 1119 | ipinst = get_ipython() |
|
1118 | 1120 | if ipinst is not None: |
|
1119 | 1121 | ipinst.hooks.synchronize_with_editor(filepath, lnum, 0) |
|
1120 | 1122 | |
|
1121 | 1123 | return [[head] + frames + [''.join(formatted_exception[0])]] |
|
1122 | 1124 | |
|
1123 | 1125 | def get_records(self, etb, number_of_lines_of_context, tb_offset): |
|
1124 | 1126 | try: |
|
1125 | 1127 | # Try the default getinnerframes and Alex's: Alex's fixes some |
|
1126 | 1128 | # problems, but it generates empty tracebacks for console errors |
|
1127 | 1129 | # (5 blanks lines) where none should be returned. |
|
1128 | 1130 | return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset) |
|
1129 | 1131 | except: |
|
1130 | 1132 | # FIXME: I've been getting many crash reports from python 2.3 |
|
1131 | 1133 | # users, traceable to inspect.py. If I can find a small test-case |
|
1132 | 1134 | # to reproduce this, I should either write a better workaround or |
|
1133 | 1135 | # file a bug report against inspect (if that's the real problem). |
|
1134 | 1136 | # So far, I haven't been able to find an isolated example to |
|
1135 | 1137 | # reproduce the problem. |
|
1136 | 1138 | inspect_error() |
|
1137 | 1139 | traceback.print_exc(file=self.ostream) |
|
1138 | 1140 | info('\nUnfortunately, your original traceback can not be constructed.\n') |
|
1139 | 1141 | return None |
|
1140 | 1142 | |
|
1141 | 1143 | def get_parts_of_chained_exception(self, evalue): |
|
1142 | 1144 | def get_chained_exception(exception_value): |
|
1143 | 1145 | cause = getattr(exception_value, '__cause__', None) |
|
1144 | 1146 | if cause: |
|
1145 | 1147 | return cause |
|
1146 | 1148 | if getattr(exception_value, '__suppress_context__', False): |
|
1147 | 1149 | return None |
|
1148 | 1150 | return getattr(exception_value, '__context__', None) |
|
1149 | 1151 | |
|
1150 | 1152 | chained_evalue = get_chained_exception(evalue) |
|
1151 | 1153 | |
|
1152 | 1154 | if chained_evalue: |
|
1153 | 1155 | return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__ |
|
1154 | 1156 | |
|
1155 | 1157 | def structured_traceback(self, etype, evalue, etb, tb_offset=None, |
|
1156 | 1158 | number_of_lines_of_context=5): |
|
1157 | 1159 | """Return a nice text document describing the traceback.""" |
|
1158 | 1160 | |
|
1159 | 1161 | formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context, |
|
1160 | 1162 | tb_offset) |
|
1161 | 1163 | |
|
1162 | 1164 | colors = self.Colors # just a shorthand + quicker name lookup |
|
1163 | 1165 | colorsnormal = colors.Normal # used a lot |
|
1164 | 1166 | head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal) |
|
1165 | 1167 | structured_traceback_parts = [head] |
|
1166 | 1168 | if py3compat.PY3: |
|
1167 | 1169 | chained_exceptions_tb_offset = 0 |
|
1168 | 1170 | lines_of_context = 3 |
|
1169 | 1171 | formatted_exceptions = formatted_exception |
|
1170 | 1172 | exception = self.get_parts_of_chained_exception(evalue) |
|
1171 | 1173 | if exception: |
|
1172 | 1174 | formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__) |
|
1173 | 1175 | etype, evalue, etb = exception |
|
1174 | 1176 | else: |
|
1175 | 1177 | evalue = None |
|
1176 | 1178 | chained_exc_ids = set() |
|
1177 | 1179 | while evalue: |
|
1178 | 1180 | formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context, |
|
1179 | 1181 | chained_exceptions_tb_offset) |
|
1180 | 1182 | exception = self.get_parts_of_chained_exception(evalue) |
|
1181 | 1183 | |
|
1182 | 1184 | if exception and not id(exception[1]) in chained_exc_ids: |
|
1183 | 1185 | chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop |
|
1184 | 1186 | formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__) |
|
1185 | 1187 | etype, evalue, etb = exception |
|
1186 | 1188 | else: |
|
1187 | 1189 | evalue = None |
|
1188 | 1190 | |
|
1189 | 1191 | # we want to see exceptions in a reversed order: |
|
1190 | 1192 | # the first exception should be on top |
|
1191 | 1193 | for formatted_exception in reversed(formatted_exceptions): |
|
1192 | 1194 | structured_traceback_parts += formatted_exception |
|
1193 | 1195 | else: |
|
1194 | 1196 | structured_traceback_parts += formatted_exception[0] |
|
1195 | 1197 | |
|
1196 | 1198 | return structured_traceback_parts |
|
1197 | 1199 | |
|
1198 | 1200 | def debugger(self, force=False): |
|
1199 | 1201 | """Call up the pdb debugger if desired, always clean up the tb |
|
1200 | 1202 | reference. |
|
1201 | 1203 | |
|
1202 | 1204 | Keywords: |
|
1203 | 1205 | |
|
1204 | 1206 | - force(False): by default, this routine checks the instance call_pdb |
|
1205 | 1207 | flag and does not actually invoke the debugger if the flag is false. |
|
1206 | 1208 | The 'force' option forces the debugger to activate even if the flag |
|
1207 | 1209 | is false. |
|
1208 | 1210 | |
|
1209 | 1211 | If the call_pdb flag is set, the pdb interactive debugger is |
|
1210 | 1212 | invoked. In all cases, the self.tb reference to the current traceback |
|
1211 | 1213 | is deleted to prevent lingering references which hamper memory |
|
1212 | 1214 | management. |
|
1213 | 1215 | |
|
1214 | 1216 | Note that each call to pdb() does an 'import readline', so if your app |
|
1215 | 1217 | requires a special setup for the readline completers, you'll have to |
|
1216 | 1218 | fix that by hand after invoking the exception handler.""" |
|
1217 | 1219 | |
|
1218 | 1220 | if force or self.call_pdb: |
|
1219 | 1221 | if self.pdb is None: |
|
1220 |
self.pdb = |
|
|
1222 | self.pdb = self.debugger_cls( | |
|
1221 | 1223 | self.color_scheme_table.active_scheme_name) |
|
1222 | 1224 | # the system displayhook may have changed, restore the original |
|
1223 | 1225 | # for pdb |
|
1224 | 1226 | display_trap = DisplayTrap(hook=sys.__displayhook__) |
|
1225 | 1227 | with display_trap: |
|
1226 | 1228 | self.pdb.reset() |
|
1227 | 1229 | # Find the right frame so we don't pop up inside ipython itself |
|
1228 | 1230 | if hasattr(self, 'tb') and self.tb is not None: |
|
1229 | 1231 | etb = self.tb |
|
1230 | 1232 | else: |
|
1231 | 1233 | etb = self.tb = sys.last_traceback |
|
1232 | 1234 | while self.tb is not None and self.tb.tb_next is not None: |
|
1233 | 1235 | self.tb = self.tb.tb_next |
|
1234 | 1236 | if etb and etb.tb_next: |
|
1235 | 1237 | etb = etb.tb_next |
|
1236 | 1238 | self.pdb.botframe = etb.tb_frame |
|
1237 | 1239 | self.pdb.interaction(self.tb.tb_frame, self.tb) |
|
1238 | 1240 | |
|
1239 | 1241 | if hasattr(self, 'tb'): |
|
1240 | 1242 | del self.tb |
|
1241 | 1243 | |
|
1242 | 1244 | def handler(self, info=None): |
|
1243 | 1245 | (etype, evalue, etb) = info or sys.exc_info() |
|
1244 | 1246 | self.tb = etb |
|
1245 | 1247 | ostream = self.ostream |
|
1246 | 1248 | ostream.flush() |
|
1247 | 1249 | ostream.write(self.text(etype, evalue, etb)) |
|
1248 | 1250 | ostream.write('\n') |
|
1249 | 1251 | ostream.flush() |
|
1250 | 1252 | |
|
1251 | 1253 | # Changed so an instance can just be called as VerboseTB_inst() and print |
|
1252 | 1254 | # out the right info on its own. |
|
1253 | 1255 | def __call__(self, etype=None, evalue=None, etb=None): |
|
1254 | 1256 | """This hook can replace sys.excepthook (for Python 2.1 or higher).""" |
|
1255 | 1257 | if etb is None: |
|
1256 | 1258 | self.handler() |
|
1257 | 1259 | else: |
|
1258 | 1260 | self.handler((etype, evalue, etb)) |
|
1259 | 1261 | try: |
|
1260 | 1262 | self.debugger() |
|
1261 | 1263 | except KeyboardInterrupt: |
|
1262 | 1264 | print("\nKeyboardInterrupt") |
|
1263 | 1265 | |
|
1264 | 1266 | |
|
1265 | 1267 | #---------------------------------------------------------------------------- |
|
1266 | 1268 | class FormattedTB(VerboseTB, ListTB): |
|
1267 | 1269 | """Subclass ListTB but allow calling with a traceback. |
|
1268 | 1270 | |
|
1269 | 1271 | It can thus be used as a sys.excepthook for Python > 2.1. |
|
1270 | 1272 | |
|
1271 | 1273 | Also adds 'Context' and 'Verbose' modes, not available in ListTB. |
|
1272 | 1274 | |
|
1273 | 1275 | Allows a tb_offset to be specified. This is useful for situations where |
|
1274 | 1276 | one needs to remove a number of topmost frames from the traceback (such as |
|
1275 | 1277 | occurs with python programs that themselves execute other python code, |
|
1276 | 1278 | like Python shells). """ |
|
1277 | 1279 | |
|
1278 | 1280 | def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False, |
|
1279 | 1281 | ostream=None, |
|
1280 | 1282 | tb_offset=0, long_header=False, include_vars=False, |
|
1281 | check_cache=None): | |
|
1283 | check_cache=None, debugger_cls=None): | |
|
1282 | 1284 | |
|
1283 | 1285 | # NEVER change the order of this list. Put new modes at the end: |
|
1284 | 1286 | self.valid_modes = ['Plain', 'Context', 'Verbose'] |
|
1285 | 1287 | self.verbose_modes = self.valid_modes[1:3] |
|
1286 | 1288 | |
|
1287 | 1289 | VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
1288 | 1290 | ostream=ostream, tb_offset=tb_offset, |
|
1289 | 1291 | long_header=long_header, include_vars=include_vars, |
|
1290 | check_cache=check_cache) | |
|
1292 | check_cache=check_cache, debugger_cls=debugger_cls) | |
|
1291 | 1293 | |
|
1292 | 1294 | # Different types of tracebacks are joined with different separators to |
|
1293 | 1295 | # form a single string. They are taken from this dict |
|
1294 | 1296 | self._join_chars = dict(Plain='', Context='\n', Verbose='\n') |
|
1295 | 1297 | # set_mode also sets the tb_join_char attribute |
|
1296 | 1298 | self.set_mode(mode) |
|
1297 | 1299 | |
|
1298 | 1300 | def _extract_tb(self, tb): |
|
1299 | 1301 | if tb: |
|
1300 | 1302 | return traceback.extract_tb(tb) |
|
1301 | 1303 | else: |
|
1302 | 1304 | return None |
|
1303 | 1305 | |
|
1304 | 1306 | def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5): |
|
1305 | 1307 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
1306 | 1308 | mode = self.mode |
|
1307 | 1309 | if mode in self.verbose_modes: |
|
1308 | 1310 | # Verbose modes need a full traceback |
|
1309 | 1311 | return VerboseTB.structured_traceback( |
|
1310 | 1312 | self, etype, value, tb, tb_offset, number_of_lines_of_context |
|
1311 | 1313 | ) |
|
1312 | 1314 | else: |
|
1313 | 1315 | # We must check the source cache because otherwise we can print |
|
1314 | 1316 | # out-of-date source code. |
|
1315 | 1317 | self.check_cache() |
|
1316 | 1318 | # Now we can extract and format the exception |
|
1317 | 1319 | elist = self._extract_tb(tb) |
|
1318 | 1320 | return ListTB.structured_traceback( |
|
1319 | 1321 | self, etype, value, elist, tb_offset, number_of_lines_of_context |
|
1320 | 1322 | ) |
|
1321 | 1323 | |
|
1322 | 1324 | def stb2text(self, stb): |
|
1323 | 1325 | """Convert a structured traceback (a list) to a string.""" |
|
1324 | 1326 | return self.tb_join_char.join(stb) |
|
1325 | 1327 | |
|
1326 | 1328 | |
|
1327 | 1329 | def set_mode(self, mode=None): |
|
1328 | 1330 | """Switch to the desired mode. |
|
1329 | 1331 | |
|
1330 | 1332 | If mode is not specified, cycles through the available modes.""" |
|
1331 | 1333 | |
|
1332 | 1334 | if not mode: |
|
1333 | 1335 | new_idx = (self.valid_modes.index(self.mode) + 1 ) % \ |
|
1334 | 1336 | len(self.valid_modes) |
|
1335 | 1337 | self.mode = self.valid_modes[new_idx] |
|
1336 | 1338 | elif mode not in self.valid_modes: |
|
1337 | 1339 | raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n' |
|
1338 | 1340 | 'Valid modes: ' + str(self.valid_modes)) |
|
1339 | 1341 | else: |
|
1340 | 1342 | self.mode = mode |
|
1341 | 1343 | # include variable details only in 'Verbose' mode |
|
1342 | 1344 | self.include_vars = (self.mode == self.valid_modes[2]) |
|
1343 | 1345 | # Set the join character for generating text tracebacks |
|
1344 | 1346 | self.tb_join_char = self._join_chars[self.mode] |
|
1345 | 1347 | |
|
1346 | 1348 | # some convenient shortcuts |
|
1347 | 1349 | def plain(self): |
|
1348 | 1350 | self.set_mode(self.valid_modes[0]) |
|
1349 | 1351 | |
|
1350 | 1352 | def context(self): |
|
1351 | 1353 | self.set_mode(self.valid_modes[1]) |
|
1352 | 1354 | |
|
1353 | 1355 | def verbose(self): |
|
1354 | 1356 | self.set_mode(self.valid_modes[2]) |
|
1355 | 1357 | |
|
1356 | 1358 | |
|
1357 | 1359 | #---------------------------------------------------------------------------- |
|
1358 | 1360 | class AutoFormattedTB(FormattedTB): |
|
1359 | 1361 | """A traceback printer which can be called on the fly. |
|
1360 | 1362 | |
|
1361 | 1363 | It will find out about exceptions by itself. |
|
1362 | 1364 | |
|
1363 | 1365 | A brief example:: |
|
1364 | 1366 | |
|
1365 | 1367 | AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux') |
|
1366 | 1368 | try: |
|
1367 | 1369 | ... |
|
1368 | 1370 | except: |
|
1369 | 1371 | AutoTB() # or AutoTB(out=logfile) where logfile is an open file object |
|
1370 | 1372 | """ |
|
1371 | 1373 | |
|
1372 | 1374 | def __call__(self, etype=None, evalue=None, etb=None, |
|
1373 | 1375 | out=None, tb_offset=None): |
|
1374 | 1376 | """Print out a formatted exception traceback. |
|
1375 | 1377 | |
|
1376 | 1378 | Optional arguments: |
|
1377 | 1379 | - out: an open file-like object to direct output to. |
|
1378 | 1380 | |
|
1379 | 1381 | - tb_offset: the number of frames to skip over in the stack, on a |
|
1380 | 1382 | per-call basis (this overrides temporarily the instance's tb_offset |
|
1381 | 1383 | given at initialization time. """ |
|
1382 | 1384 | |
|
1383 | 1385 | if out is None: |
|
1384 | 1386 | out = self.ostream |
|
1385 | 1387 | out.flush() |
|
1386 | 1388 | out.write(self.text(etype, evalue, etb, tb_offset)) |
|
1387 | 1389 | out.write('\n') |
|
1388 | 1390 | out.flush() |
|
1389 | 1391 | # FIXME: we should remove the auto pdb behavior from here and leave |
|
1390 | 1392 | # that to the clients. |
|
1391 | 1393 | try: |
|
1392 | 1394 | self.debugger() |
|
1393 | 1395 | except KeyboardInterrupt: |
|
1394 | 1396 | print("\nKeyboardInterrupt") |
|
1395 | 1397 | |
|
1396 | 1398 | def structured_traceback(self, etype=None, value=None, tb=None, |
|
1397 | 1399 | tb_offset=None, number_of_lines_of_context=5): |
|
1398 | 1400 | if etype is None: |
|
1399 | 1401 | etype, value, tb = sys.exc_info() |
|
1400 | 1402 | self.tb = tb |
|
1401 | 1403 | return FormattedTB.structured_traceback( |
|
1402 | 1404 | self, etype, value, tb, tb_offset, number_of_lines_of_context) |
|
1403 | 1405 | |
|
1404 | 1406 | |
|
1405 | 1407 | #--------------------------------------------------------------------------- |
|
1406 | 1408 | |
|
1407 | 1409 | # A simple class to preserve Nathan's original functionality. |
|
1408 | 1410 | class ColorTB(FormattedTB): |
|
1409 | 1411 | """Shorthand to initialize a FormattedTB in Linux colors mode.""" |
|
1410 | 1412 | |
|
1411 | 1413 | def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs): |
|
1412 | 1414 | FormattedTB.__init__(self, color_scheme=color_scheme, |
|
1413 | 1415 | call_pdb=call_pdb, **kwargs) |
|
1414 | 1416 | |
|
1415 | 1417 | |
|
1416 | 1418 | class SyntaxTB(ListTB): |
|
1417 | 1419 | """Extension which holds some state: the last exception value""" |
|
1418 | 1420 | |
|
1419 | 1421 | def __init__(self, color_scheme='NoColor'): |
|
1420 | 1422 | ListTB.__init__(self, color_scheme) |
|
1421 | 1423 | self.last_syntax_error = None |
|
1422 | 1424 | |
|
1423 | 1425 | def __call__(self, etype, value, elist): |
|
1424 | 1426 | self.last_syntax_error = value |
|
1425 | 1427 | |
|
1426 | 1428 | ListTB.__call__(self, etype, value, elist) |
|
1427 | 1429 | |
|
1428 | 1430 | def structured_traceback(self, etype, value, elist, tb_offset=None, |
|
1429 | 1431 | context=5): |
|
1430 | 1432 | # If the source file has been edited, the line in the syntax error can |
|
1431 | 1433 | # be wrong (retrieved from an outdated cache). This replaces it with |
|
1432 | 1434 | # the current value. |
|
1433 | 1435 | if isinstance(value, SyntaxError) \ |
|
1434 | 1436 | and isinstance(value.filename, py3compat.string_types) \ |
|
1435 | 1437 | and isinstance(value.lineno, int): |
|
1436 | 1438 | linecache.checkcache(value.filename) |
|
1437 | 1439 | newtext = ulinecache.getline(value.filename, value.lineno) |
|
1438 | 1440 | if newtext: |
|
1439 | 1441 | value.text = newtext |
|
1440 | 1442 | self.last_syntax_error = value |
|
1441 | 1443 | return super(SyntaxTB, self).structured_traceback(etype, value, elist, |
|
1442 | 1444 | tb_offset=tb_offset, context=context) |
|
1443 | 1445 | |
|
1444 | 1446 | def clear_err_state(self): |
|
1445 | 1447 | """Return the current error state and clear it""" |
|
1446 | 1448 | e = self.last_syntax_error |
|
1447 | 1449 | self.last_syntax_error = None |
|
1448 | 1450 | return e |
|
1449 | 1451 | |
|
1450 | 1452 | def stb2text(self, stb): |
|
1451 | 1453 | """Convert a structured traceback (a list) to a string.""" |
|
1452 | 1454 | return ''.join(stb) |
|
1453 | 1455 | |
|
1454 | 1456 | |
|
1455 | 1457 | # some internal-use functions |
|
1456 | 1458 | def text_repr(value): |
|
1457 | 1459 | """Hopefully pretty robust repr equivalent.""" |
|
1458 | 1460 | # this is pretty horrible but should always return *something* |
|
1459 | 1461 | try: |
|
1460 | 1462 | return pydoc.text.repr(value) |
|
1461 | 1463 | except KeyboardInterrupt: |
|
1462 | 1464 | raise |
|
1463 | 1465 | except: |
|
1464 | 1466 | try: |
|
1465 | 1467 | return repr(value) |
|
1466 | 1468 | except KeyboardInterrupt: |
|
1467 | 1469 | raise |
|
1468 | 1470 | except: |
|
1469 | 1471 | try: |
|
1470 | 1472 | # all still in an except block so we catch |
|
1471 | 1473 | # getattr raising |
|
1472 | 1474 | name = getattr(value, '__name__', None) |
|
1473 | 1475 | if name: |
|
1474 | 1476 | # ick, recursion |
|
1475 | 1477 | return text_repr(name) |
|
1476 | 1478 | klass = getattr(value, '__class__', None) |
|
1477 | 1479 | if klass: |
|
1478 | 1480 | return '%s instance' % text_repr(klass) |
|
1479 | 1481 | except KeyboardInterrupt: |
|
1480 | 1482 | raise |
|
1481 | 1483 | except: |
|
1482 | 1484 | return 'UNRECOVERABLE REPR FAILURE' |
|
1483 | 1485 | |
|
1484 | 1486 | |
|
1485 | 1487 | def eqrepr(value, repr=text_repr): |
|
1486 | 1488 | return '=%s' % repr(value) |
|
1487 | 1489 | |
|
1488 | 1490 | |
|
1489 | 1491 | def nullrepr(value, repr=text_repr): |
|
1490 | 1492 | return '' |
@@ -1,426 +1,428 b'' | |||
|
1 | 1 | """IPython terminal interface using prompt_toolkit in place of readline""" |
|
2 | 2 | from __future__ import print_function |
|
3 | 3 | |
|
4 | 4 | import os |
|
5 | 5 | import sys |
|
6 | 6 | import signal |
|
7 | 7 | from warnings import warn |
|
8 | 8 | |
|
9 | 9 | from IPython.core.error import TryNext |
|
10 | 10 | from IPython.core.interactiveshell import InteractiveShell |
|
11 | 11 | from IPython.utils.py3compat import cast_unicode_py2, input |
|
12 | 12 | from IPython.utils.terminal import toggle_set_term_title, set_term_title |
|
13 | 13 | from IPython.utils.process import abbrev_cwd |
|
14 | 14 | from traitlets import Bool, Unicode, Dict, Integer, observe |
|
15 | 15 | |
|
16 | 16 | from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER, EditingMode |
|
17 | 17 | from prompt_toolkit.filters import HasFocus, HasSelection, Condition, ViInsertMode, EmacsInsertMode, IsDone |
|
18 | 18 | from prompt_toolkit.history import InMemoryHistory |
|
19 | 19 | from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop, create_prompt_layout |
|
20 | 20 | from prompt_toolkit.interface import CommandLineInterface |
|
21 | 21 | from prompt_toolkit.key_binding.manager import KeyBindingManager |
|
22 | 22 | from prompt_toolkit.keys import Keys |
|
23 | 23 | from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor |
|
24 | 24 | from prompt_toolkit.styles import PygmentsStyle, DynamicStyle |
|
25 | 25 | |
|
26 | 26 | from pygments.styles import get_style_by_name, get_all_styles |
|
27 | 27 | from pygments.token import Token |
|
28 | 28 | |
|
29 | from .debugger import TerminalPdb | |
|
29 | 30 | from .pt_inputhooks import get_inputhook_func |
|
30 | 31 | from .interactiveshell import get_default_editor, TerminalMagics |
|
31 | 32 | from .ptutils import IPythonPTCompleter, IPythonPTLexer |
|
32 | 33 | |
|
33 | 34 | |
|
34 | 35 | class TerminalInteractiveShell(InteractiveShell): |
|
35 | 36 | colors_force = True |
|
36 | 37 | |
|
37 | 38 | space_for_menu = Integer(6, help='Number of line at the bottom of the screen ' |
|
38 | 39 | 'to reserve for the completion menu' |
|
39 | 40 | ).tag(config=True) |
|
40 | 41 | |
|
41 | 42 | def _space_for_menu_changed(self, old, new): |
|
42 | 43 | self._update_layout() |
|
43 | 44 | |
|
44 | 45 | pt_cli = None |
|
45 | 46 | debugger_history = None |
|
47 | debugger_cls = TerminalPdb | |
|
46 | 48 | |
|
47 | 49 | autoedit_syntax = Bool(False, |
|
48 | 50 | help="auto editing of files with syntax errors.", |
|
49 | 51 | ).tag(config=True) |
|
50 | 52 | |
|
51 | 53 | |
|
52 | 54 | confirm_exit = Bool(True, |
|
53 | 55 | help=""" |
|
54 | 56 | Set to confirm when you try to exit IPython with an EOF (Control-D |
|
55 | 57 | in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit', |
|
56 | 58 | you can force a direct exit without any confirmation.""", |
|
57 | 59 | ).tag(config=True) |
|
58 | 60 | |
|
59 | 61 | editing_mode = Unicode('emacs', |
|
60 | 62 | help="Shortcut style to use at the prompt. 'vi' or 'emacs'.", |
|
61 | 63 | ).tag(config=True) |
|
62 | 64 | |
|
63 | 65 | mouse_support = Bool(False, |
|
64 | 66 | help="Enable mouse support in the prompt" |
|
65 | 67 | ).tag(config=True) |
|
66 | 68 | |
|
67 | 69 | highlighting_style = Unicode('default', |
|
68 | 70 | help="The name of a Pygments style to use for syntax highlighting: \n %s" % ', '.join(get_all_styles()) |
|
69 | 71 | ).tag(config=True) |
|
70 | 72 | |
|
71 | 73 | |
|
72 | 74 | @observe('highlighting_style') |
|
73 | 75 | def _highlighting_style_changed(self, change): |
|
74 | 76 | self._style = self._make_style_from_name(self.highlighting_style) |
|
75 | 77 | |
|
76 | 78 | highlighting_style_overrides = Dict( |
|
77 | 79 | help="Override highlighting format for specific tokens" |
|
78 | 80 | ).tag(config=True) |
|
79 | 81 | |
|
80 | 82 | editor = Unicode(get_default_editor(), |
|
81 | 83 | help="Set the editor used by IPython (default to $EDITOR/vi/notepad)." |
|
82 | 84 | ).tag(config=True) |
|
83 | 85 | |
|
84 | 86 | term_title = Bool(True, |
|
85 | 87 | help="Automatically set the terminal title" |
|
86 | 88 | ).tag(config=True) |
|
87 | 89 | |
|
88 | 90 | display_completions_in_columns = Bool(False, |
|
89 | 91 | help="Display a multi column completion menu.", |
|
90 | 92 | ).tag(config=True) |
|
91 | 93 | |
|
92 | 94 | highlight_matching_brackets = Bool(True, |
|
93 | 95 | help="Highlight matching brackets .", |
|
94 | 96 | ).tag(config=True) |
|
95 | 97 | |
|
96 | 98 | @observe('term_title') |
|
97 | 99 | def init_term_title(self, change=None): |
|
98 | 100 | # Enable or disable the terminal title. |
|
99 | 101 | if self.term_title: |
|
100 | 102 | toggle_set_term_title(True) |
|
101 | 103 | set_term_title('IPython: ' + abbrev_cwd()) |
|
102 | 104 | else: |
|
103 | 105 | toggle_set_term_title(False) |
|
104 | 106 | |
|
105 | 107 | def get_prompt_tokens(self, cli): |
|
106 | 108 | return [ |
|
107 | 109 | (Token.Prompt, 'In ['), |
|
108 | 110 | (Token.PromptNum, str(self.execution_count)), |
|
109 | 111 | (Token.Prompt, ']: '), |
|
110 | 112 | ] |
|
111 | 113 | |
|
112 | 114 | def get_continuation_tokens(self, cli, width): |
|
113 | 115 | return [ |
|
114 | 116 | (Token.Prompt, (' ' * (width - 5)) + '...: '), |
|
115 | 117 | ] |
|
116 | 118 | |
|
117 | 119 | def init_prompt_toolkit_cli(self): |
|
118 | 120 | if ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or not sys.stdin.isatty(): |
|
119 | 121 | # Fall back to plain non-interactive output for tests. |
|
120 | 122 | # This is very limited, and only accepts a single line. |
|
121 | 123 | def prompt(): |
|
122 | 124 | return cast_unicode_py2(input('In [%d]: ' % self.execution_count)) |
|
123 | 125 | self.prompt_for_code = prompt |
|
124 | 126 | return |
|
125 | 127 | |
|
126 | 128 | kbmanager = KeyBindingManager.for_prompt() |
|
127 | 129 | insert_mode = ViInsertMode() | EmacsInsertMode() |
|
128 | 130 | # Ctrl+J == Enter, seemingly |
|
129 | 131 | @kbmanager.registry.add_binding(Keys.ControlJ, |
|
130 | 132 | filter=(HasFocus(DEFAULT_BUFFER) |
|
131 | 133 | & ~HasSelection() |
|
132 | 134 | & insert_mode |
|
133 | 135 | )) |
|
134 | 136 | def _(event): |
|
135 | 137 | b = event.current_buffer |
|
136 | 138 | d = b.document |
|
137 | 139 | if not (d.on_last_line or d.cursor_position_row >= d.line_count |
|
138 | 140 | - d.empty_line_count_at_the_end()): |
|
139 | 141 | b.newline() |
|
140 | 142 | return |
|
141 | 143 | |
|
142 | 144 | status, indent = self.input_splitter.check_complete(d.text) |
|
143 | 145 | |
|
144 | 146 | if (status != 'incomplete') and b.accept_action.is_returnable: |
|
145 | 147 | b.accept_action.validate_and_handle(event.cli, b) |
|
146 | 148 | else: |
|
147 | 149 | b.insert_text('\n' + (' ' * (indent or 0))) |
|
148 | 150 | |
|
149 | 151 | @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER)) |
|
150 | 152 | def _reset_buffer(event): |
|
151 | 153 | event.current_buffer.reset() |
|
152 | 154 | |
|
153 | 155 | @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(SEARCH_BUFFER)) |
|
154 | 156 | def _reset_search_buffer(event): |
|
155 | 157 | if event.current_buffer.document.text: |
|
156 | 158 | event.current_buffer.reset() |
|
157 | 159 | else: |
|
158 | 160 | event.cli.push_focus(DEFAULT_BUFFER) |
|
159 | 161 | |
|
160 | 162 | supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP')) |
|
161 | 163 | |
|
162 | 164 | @kbmanager.registry.add_binding(Keys.ControlZ, filter=supports_suspend) |
|
163 | 165 | def _suspend_to_bg(event): |
|
164 | 166 | event.cli.suspend_to_background() |
|
165 | 167 | |
|
166 | 168 | @Condition |
|
167 | 169 | def cursor_in_leading_ws(cli): |
|
168 | 170 | before = cli.application.buffer.document.current_line_before_cursor |
|
169 | 171 | return (not before) or before.isspace() |
|
170 | 172 | |
|
171 | 173 | # Ctrl+I == Tab |
|
172 | 174 | @kbmanager.registry.add_binding(Keys.ControlI, |
|
173 | 175 | filter=(HasFocus(DEFAULT_BUFFER) |
|
174 | 176 | & ~HasSelection() |
|
175 | 177 | & insert_mode |
|
176 | 178 | & cursor_in_leading_ws |
|
177 | 179 | )) |
|
178 | 180 | def _indent_buffer(event): |
|
179 | 181 | event.current_buffer.insert_text(' ' * 4) |
|
180 | 182 | |
|
181 | 183 | # Pre-populate history from IPython's history database |
|
182 | 184 | history = InMemoryHistory() |
|
183 | 185 | last_cell = u"" |
|
184 | 186 | for __, ___, cell in self.history_manager.get_tail(self.history_load_length, |
|
185 | 187 | include_latest=True): |
|
186 | 188 | # Ignore blank lines and consecutive duplicates |
|
187 | 189 | cell = cell.rstrip() |
|
188 | 190 | if cell and (cell != last_cell): |
|
189 | 191 | history.append(cell) |
|
190 | 192 | |
|
191 | 193 | self._style = self._make_style_from_name(self.highlighting_style) |
|
192 | 194 | style = DynamicStyle(lambda: self._style) |
|
193 | 195 | |
|
194 | 196 | editing_mode = getattr(EditingMode, self.editing_mode.upper()) |
|
195 | 197 | |
|
196 | 198 | self._app = create_prompt_application( |
|
197 | 199 | editing_mode=editing_mode, |
|
198 | 200 | key_bindings_registry=kbmanager.registry, |
|
199 | 201 | history=history, |
|
200 | 202 | completer=IPythonPTCompleter(self.Completer), |
|
201 | 203 | enable_history_search=True, |
|
202 | 204 | style=style, |
|
203 | 205 | mouse_support=self.mouse_support, |
|
204 | 206 | **self._layout_options() |
|
205 | 207 | ) |
|
206 | 208 | self._eventloop = create_eventloop(self.inputhook) |
|
207 | 209 | self.pt_cli = CommandLineInterface(self._app, eventloop=self._eventloop) |
|
208 | 210 | |
|
209 | 211 | def _make_style_from_name(self, name): |
|
210 | 212 | """ |
|
211 | 213 | Small wrapper that make an IPython compatible style from a style name |
|
212 | 214 | |
|
213 | 215 | We need that to add style for prompt ... etc. |
|
214 | 216 | """ |
|
215 | 217 | style_cls = get_style_by_name(name) |
|
216 | 218 | style_overrides = { |
|
217 | 219 | Token.Prompt: '#009900', |
|
218 | 220 | Token.PromptNum: '#00ff00 bold', |
|
219 | 221 | } |
|
220 | 222 | if name == 'default': |
|
221 | 223 | style_cls = get_style_by_name('default') |
|
222 | 224 | # The default theme needs to be visible on both a dark background |
|
223 | 225 | # and a light background, because we can't tell what the terminal |
|
224 | 226 | # looks like. These tweaks to the default theme help with that. |
|
225 | 227 | style_overrides.update({ |
|
226 | 228 | Token.Number: '#007700', |
|
227 | 229 | Token.Operator: 'noinherit', |
|
228 | 230 | Token.String: '#BB6622', |
|
229 | 231 | Token.Name.Function: '#2080D0', |
|
230 | 232 | Token.Name.Class: 'bold #2080D0', |
|
231 | 233 | Token.Name.Namespace: 'bold #2080D0', |
|
232 | 234 | }) |
|
233 | 235 | style_overrides.update(self.highlighting_style_overrides) |
|
234 | 236 | style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, |
|
235 | 237 | style_dict=style_overrides) |
|
236 | 238 | |
|
237 | 239 | return style |
|
238 | 240 | |
|
239 | 241 | def _layout_options(self): |
|
240 | 242 | """ |
|
241 | 243 | Return the current layout option for the current Terminal InteractiveShell |
|
242 | 244 | """ |
|
243 | 245 | return { |
|
244 | 246 | 'lexer':IPythonPTLexer(), |
|
245 | 247 | 'reserve_space_for_menu':self.space_for_menu, |
|
246 | 248 | 'get_prompt_tokens':self.get_prompt_tokens, |
|
247 | 249 | 'get_continuation_tokens':self.get_continuation_tokens, |
|
248 | 250 | 'multiline':True, |
|
249 | 251 | 'display_completions_in_columns': self.display_completions_in_columns, |
|
250 | 252 | |
|
251 | 253 | # Highlight matching brackets, but only when this setting is |
|
252 | 254 | # enabled, and only when the DEFAULT_BUFFER has the focus. |
|
253 | 255 | 'extra_input_processors': [ConditionalProcessor( |
|
254 | 256 | processor=HighlightMatchingBracketProcessor(chars='[](){}'), |
|
255 | 257 | filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() & |
|
256 | 258 | Condition(lambda cli: self.highlight_matching_brackets))], |
|
257 | 259 | } |
|
258 | 260 | |
|
259 | 261 | def _update_layout(self): |
|
260 | 262 | """ |
|
261 | 263 | Ask for a re computation of the application layout, if for example , |
|
262 | 264 | some configuration options have changed. |
|
263 | 265 | """ |
|
264 | 266 | self._app.layout = create_prompt_layout(**self._layout_options()) |
|
265 | 267 | |
|
266 | 268 | def prompt_for_code(self): |
|
267 | 269 | document = self.pt_cli.run( |
|
268 | 270 | pre_run=self.pre_prompt, reset_current_buffer=True) |
|
269 | 271 | return document.text |
|
270 | 272 | |
|
271 | 273 | def init_io(self): |
|
272 | 274 | if sys.platform not in {'win32', 'cli'}: |
|
273 | 275 | return |
|
274 | 276 | |
|
275 | 277 | import colorama |
|
276 | 278 | colorama.init() |
|
277 | 279 | |
|
278 | 280 | # For some reason we make these wrappers around stdout/stderr. |
|
279 | 281 | # For now, we need to reset them so all output gets coloured. |
|
280 | 282 | # https://github.com/ipython/ipython/issues/8669 |
|
281 | 283 | from IPython.utils import io |
|
282 | 284 | io.stdout = io.IOStream(sys.stdout) |
|
283 | 285 | io.stderr = io.IOStream(sys.stderr) |
|
284 | 286 | |
|
285 | 287 | def init_magics(self): |
|
286 | 288 | super(TerminalInteractiveShell, self).init_magics() |
|
287 | 289 | self.register_magics(TerminalMagics) |
|
288 | 290 | |
|
289 | 291 | def init_alias(self): |
|
290 | 292 | # The parent class defines aliases that can be safely used with any |
|
291 | 293 | # frontend. |
|
292 | 294 | super(TerminalInteractiveShell, self).init_alias() |
|
293 | 295 | |
|
294 | 296 | # Now define aliases that only make sense on the terminal, because they |
|
295 | 297 | # need direct access to the console in a way that we can't emulate in |
|
296 | 298 | # GUI or web frontend |
|
297 | 299 | if os.name == 'posix': |
|
298 | 300 | for cmd in ['clear', 'more', 'less', 'man']: |
|
299 | 301 | self.alias_manager.soft_define_alias(cmd, cmd) |
|
300 | 302 | |
|
301 | 303 | |
|
302 | 304 | def __init__(self, *args, **kwargs): |
|
303 | 305 | super(TerminalInteractiveShell, self).__init__(*args, **kwargs) |
|
304 | 306 | self.init_prompt_toolkit_cli() |
|
305 | 307 | self.init_term_title() |
|
306 | 308 | self.keep_running = True |
|
307 | 309 | |
|
308 | 310 | self.debugger_history = InMemoryHistory() |
|
309 | 311 | |
|
310 | 312 | def ask_exit(self): |
|
311 | 313 | self.keep_running = False |
|
312 | 314 | |
|
313 | 315 | rl_next_input = None |
|
314 | 316 | |
|
315 | 317 | def pre_prompt(self): |
|
316 | 318 | if self.rl_next_input: |
|
317 | 319 | self.pt_cli.application.buffer.text = cast_unicode_py2(self.rl_next_input) |
|
318 | 320 | self.rl_next_input = None |
|
319 | 321 | |
|
320 | 322 | def interact(self): |
|
321 | 323 | while self.keep_running: |
|
322 | 324 | print(self.separate_in, end='') |
|
323 | 325 | |
|
324 | 326 | try: |
|
325 | 327 | code = self.prompt_for_code() |
|
326 | 328 | except EOFError: |
|
327 | 329 | if (not self.confirm_exit) \ |
|
328 | 330 | or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'): |
|
329 | 331 | self.ask_exit() |
|
330 | 332 | |
|
331 | 333 | else: |
|
332 | 334 | if code: |
|
333 | 335 | self.run_cell(code, store_history=True) |
|
334 | 336 | if self.autoedit_syntax and self.SyntaxTB.last_syntax_error: |
|
335 | 337 | self.edit_syntax_error() |
|
336 | 338 | |
|
337 | 339 | def mainloop(self): |
|
338 | 340 | # An extra layer of protection in case someone mashing Ctrl-C breaks |
|
339 | 341 | # out of our internal code. |
|
340 | 342 | while True: |
|
341 | 343 | try: |
|
342 | 344 | self.interact() |
|
343 | 345 | break |
|
344 | 346 | except KeyboardInterrupt: |
|
345 | 347 | print("\nKeyboardInterrupt escaped interact()\n") |
|
346 | 348 | |
|
347 | 349 | if hasattr(self, '_eventloop'): |
|
348 | 350 | self._eventloop.close() |
|
349 | 351 | |
|
350 | 352 | _inputhook = None |
|
351 | 353 | def inputhook(self, context): |
|
352 | 354 | if self._inputhook is not None: |
|
353 | 355 | self._inputhook(context) |
|
354 | 356 | |
|
355 | 357 | def enable_gui(self, gui=None): |
|
356 | 358 | if gui: |
|
357 | 359 | self._inputhook = get_inputhook_func(gui) |
|
358 | 360 | else: |
|
359 | 361 | self._inputhook = None |
|
360 | 362 | |
|
361 | 363 | # Methods to support auto-editing of SyntaxErrors: |
|
362 | 364 | |
|
363 | 365 | def edit_syntax_error(self): |
|
364 | 366 | """The bottom half of the syntax error handler called in the main loop. |
|
365 | 367 | |
|
366 | 368 | Loop until syntax error is fixed or user cancels. |
|
367 | 369 | """ |
|
368 | 370 | |
|
369 | 371 | while self.SyntaxTB.last_syntax_error: |
|
370 | 372 | # copy and clear last_syntax_error |
|
371 | 373 | err = self.SyntaxTB.clear_err_state() |
|
372 | 374 | if not self._should_recompile(err): |
|
373 | 375 | return |
|
374 | 376 | try: |
|
375 | 377 | # may set last_syntax_error again if a SyntaxError is raised |
|
376 | 378 | self.safe_execfile(err.filename, self.user_ns) |
|
377 | 379 | except: |
|
378 | 380 | self.showtraceback() |
|
379 | 381 | else: |
|
380 | 382 | try: |
|
381 | 383 | with open(err.filename) as f: |
|
382 | 384 | # This should be inside a display_trap block and I |
|
383 | 385 | # think it is. |
|
384 | 386 | sys.displayhook(f.read()) |
|
385 | 387 | except: |
|
386 | 388 | self.showtraceback() |
|
387 | 389 | |
|
388 | 390 | def _should_recompile(self, e): |
|
389 | 391 | """Utility routine for edit_syntax_error""" |
|
390 | 392 | |
|
391 | 393 | if e.filename in ('<ipython console>', '<input>', '<string>', |
|
392 | 394 | '<console>', '<BackgroundJob compilation>', |
|
393 | 395 | None): |
|
394 | 396 | return False |
|
395 | 397 | try: |
|
396 | 398 | if (self.autoedit_syntax and |
|
397 | 399 | not self.ask_yes_no( |
|
398 | 400 | 'Return to editor to correct syntax error? ' |
|
399 | 401 | '[Y/n] ', 'y')): |
|
400 | 402 | return False |
|
401 | 403 | except EOFError: |
|
402 | 404 | return False |
|
403 | 405 | |
|
404 | 406 | def int0(x): |
|
405 | 407 | try: |
|
406 | 408 | return int(x) |
|
407 | 409 | except TypeError: |
|
408 | 410 | return 0 |
|
409 | 411 | |
|
410 | 412 | # always pass integer line and offset values to editor hook |
|
411 | 413 | try: |
|
412 | 414 | self.hooks.fix_error_editor(e.filename, |
|
413 | 415 | int0(e.lineno), int0(e.offset), |
|
414 | 416 | e.msg) |
|
415 | 417 | except TryNext: |
|
416 | 418 | warn('Could not open editor') |
|
417 | 419 | return False |
|
418 | 420 | return True |
|
419 | 421 | |
|
420 | 422 | # Run !system commands directly, not through pipes, so terminal programs |
|
421 | 423 | # work correctly. |
|
422 | 424 | system = InteractiveShell.system_raw |
|
423 | 425 | |
|
424 | 426 | |
|
425 | 427 | if __name__ == '__main__': |
|
426 | 428 | TerminalInteractiveShell.instance().interact() |
General Comments 0
You need to be logged in to leave comments.
Login now