##// END OF EJS Templates
Backport PR #12359: Implement understanding on __tracebackhide__
Matthias Bussonnier -
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -0,0 +1,11 b''
1 The default tracebackmode will now skip frames that are marked with
2 ``__tracebackhide__ = True`` and show how many traceback frames have been
3 skipped. This can be toggled by using :magic:`xmode` with the ``--show`` or
4 ``--hide`` attribute. It will have no effect on non verbose traceback modes.
5
6 The ipython debugger also now understand ``__tracebackhide__`` as well and will
7 skip hidden frames when displaying. Movement up and down the stack will skip the
8 hidden frames and will show how many frames were hidden. Internal IPython frames
9 are also now hidden by default. The behavior can be changed with the
10 ``skip_hidden`` command and accepts "yes", "no", "true" and "false" case
11 insensitive parameters.
@@ -1,671 +1,804 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Pdb debugger class.
3 Pdb debugger class.
4
4
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
5 Modified from the standard pdb.Pdb class to avoid including readline, so that
6 the command line completion of other programs which include this isn't
6 the command line completion of other programs which include this isn't
7 damaged.
7 damaged.
8
8
9 In the future, this class will be expanded with improvements over the standard
9 In the future, this class will be expanded with improvements over the standard
10 pdb.
10 pdb.
11
11
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
12 The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor
13 changes. Licensing should therefore be under the standard Python terms. For
13 changes. Licensing should therefore be under the standard Python terms. For
14 details on the PSF (Python Software Foundation) standard license, see:
14 details on the PSF (Python Software Foundation) standard license, see:
15
15
16 https://docs.python.org/2/license.html
16 https://docs.python.org/2/license.html
17 """
17 """
18
18
19 #*****************************************************************************
19 #*****************************************************************************
20 #
20 #
21 # This file is licensed under the PSF license.
21 # This file is licensed under the PSF license.
22 #
22 #
23 # Copyright (C) 2001 Python Software Foundation, www.python.org
23 # Copyright (C) 2001 Python Software Foundation, www.python.org
24 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
24 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
25 #
25 #
26 #
26 #
27 #*****************************************************************************
27 #*****************************************************************************
28
28
29 import bdb
29 import bdb
30 import functools
30 import functools
31 import inspect
31 import inspect
32 import linecache
32 import linecache
33 import sys
33 import sys
34 import warnings
34 import warnings
35 import re
35 import re
36
36
37 from IPython import get_ipython
37 from IPython import get_ipython
38 from IPython.utils import PyColorize
38 from IPython.utils import PyColorize
39 from IPython.utils import coloransi, py3compat
39 from IPython.utils import coloransi, py3compat
40 from IPython.core.excolors import exception_colors
40 from IPython.core.excolors import exception_colors
41 from IPython.testing.skipdoctest import skip_doctest
41 from IPython.testing.skipdoctest import skip_doctest
42
42
43
43
44 prompt = 'ipdb> '
44 prompt = 'ipdb> '
45
45
46 #We have to check this directly from sys.argv, config struct not yet available
46 #We have to check this directly from sys.argv, config struct not yet available
47 from pdb import Pdb as OldPdb
47 from pdb import Pdb as OldPdb
48
48
49 # Allow the set_trace code to operate outside of an ipython instance, even if
49 # Allow the set_trace code to operate outside of an ipython instance, even if
50 # it does so with some limitations. The rest of this support is implemented in
50 # it does so with some limitations. The rest of this support is implemented in
51 # the Tracer constructor.
51 # the Tracer constructor.
52
52
53 def make_arrow(pad):
53 def make_arrow(pad):
54 """generate the leading arrow in front of traceback or debugger"""
54 """generate the leading arrow in front of traceback or debugger"""
55 if pad >= 2:
55 if pad >= 2:
56 return '-'*(pad-2) + '> '
56 return '-'*(pad-2) + '> '
57 elif pad == 1:
57 elif pad == 1:
58 return '>'
58 return '>'
59 return ''
59 return ''
60
60
61
61
62 def BdbQuit_excepthook(et, ev, tb, excepthook=None):
62 def BdbQuit_excepthook(et, ev, tb, excepthook=None):
63 """Exception hook which handles `BdbQuit` exceptions.
63 """Exception hook which handles `BdbQuit` exceptions.
64
64
65 All other exceptions are processed using the `excepthook`
65 All other exceptions are processed using the `excepthook`
66 parameter.
66 parameter.
67 """
67 """
68 warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1",
68 warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1",
69 DeprecationWarning, stacklevel=2)
69 DeprecationWarning, stacklevel=2)
70 if et==bdb.BdbQuit:
70 if et==bdb.BdbQuit:
71 print('Exiting Debugger.')
71 print('Exiting Debugger.')
72 elif excepthook is not None:
72 elif excepthook is not None:
73 excepthook(et, ev, tb)
73 excepthook(et, ev, tb)
74 else:
74 else:
75 # Backwards compatibility. Raise deprecation warning?
75 # Backwards compatibility. Raise deprecation warning?
76 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
76 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
77
77
78
78
79 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
79 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
80 warnings.warn(
80 warnings.warn(
81 "`BdbQuit_IPython_excepthook` is deprecated since version 5.1",
81 "`BdbQuit_IPython_excepthook` is deprecated since version 5.1",
82 DeprecationWarning, stacklevel=2)
82 DeprecationWarning, stacklevel=2)
83 print('Exiting Debugger.')
83 print('Exiting Debugger.')
84
84
85
85
86 class Tracer(object):
86 class Tracer(object):
87 """
87 """
88 DEPRECATED
88 DEPRECATED
89
89
90 Class for local debugging, similar to pdb.set_trace.
90 Class for local debugging, similar to pdb.set_trace.
91
91
92 Instances of this class, when called, behave like pdb.set_trace, but
92 Instances of this class, when called, behave like pdb.set_trace, but
93 providing IPython's enhanced capabilities.
93 providing IPython's enhanced capabilities.
94
94
95 This is implemented as a class which must be initialized in your own code
95 This is implemented as a class which must be initialized in your own code
96 and not as a standalone function because we need to detect at runtime
96 and not as a standalone function because we need to detect at runtime
97 whether IPython is already active or not. That detection is done in the
97 whether IPython is already active or not. That detection is done in the
98 constructor, ensuring that this code plays nicely with a running IPython,
98 constructor, ensuring that this code plays nicely with a running IPython,
99 while functioning acceptably (though with limitations) if outside of it.
99 while functioning acceptably (though with limitations) if outside of it.
100 """
100 """
101
101
102 @skip_doctest
102 @skip_doctest
103 def __init__(self, colors=None):
103 def __init__(self, colors=None):
104 """
104 """
105 DEPRECATED
105 DEPRECATED
106
106
107 Create a local debugger instance.
107 Create a local debugger instance.
108
108
109 Parameters
109 Parameters
110 ----------
110 ----------
111
111
112 colors : str, optional
112 colors : str, optional
113 The name of the color scheme to use, it must be one of IPython's
113 The name of the color scheme to use, it must be one of IPython's
114 valid color schemes. If not given, the function will default to
114 valid color schemes. If not given, the function will default to
115 the current IPython scheme when running inside IPython, and to
115 the current IPython scheme when running inside IPython, and to
116 'NoColor' otherwise.
116 'NoColor' otherwise.
117
117
118 Examples
118 Examples
119 --------
119 --------
120 ::
120 ::
121
121
122 from IPython.core.debugger import Tracer; debug_here = Tracer()
122 from IPython.core.debugger import Tracer; debug_here = Tracer()
123
123
124 Later in your code::
124 Later in your code::
125
125
126 debug_here() # -> will open up the debugger at that point.
126 debug_here() # -> will open up the debugger at that point.
127
127
128 Once the debugger activates, you can use all of its regular commands to
128 Once the debugger activates, you can use all of its regular commands to
129 step through code, set breakpoints, etc. See the pdb documentation
129 step through code, set breakpoints, etc. See the pdb documentation
130 from the Python standard library for usage details.
130 from the Python standard library for usage details.
131 """
131 """
132 warnings.warn("`Tracer` is deprecated since version 5.1, directly use "
132 warnings.warn("`Tracer` is deprecated since version 5.1, directly use "
133 "`IPython.core.debugger.Pdb.set_trace()`",
133 "`IPython.core.debugger.Pdb.set_trace()`",
134 DeprecationWarning, stacklevel=2)
134 DeprecationWarning, stacklevel=2)
135
135
136 ip = get_ipython()
136 ip = get_ipython()
137 if ip is None:
137 if ip is None:
138 # Outside of ipython, we set our own exception hook manually
138 # Outside of ipython, we set our own exception hook manually
139 sys.excepthook = functools.partial(BdbQuit_excepthook,
139 sys.excepthook = functools.partial(BdbQuit_excepthook,
140 excepthook=sys.excepthook)
140 excepthook=sys.excepthook)
141 def_colors = 'NoColor'
141 def_colors = 'NoColor'
142 else:
142 else:
143 # In ipython, we use its custom exception handler mechanism
143 # In ipython, we use its custom exception handler mechanism
144 def_colors = ip.colors
144 def_colors = ip.colors
145 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
145 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
146
146
147 if colors is None:
147 if colors is None:
148 colors = def_colors
148 colors = def_colors
149
149
150 # The stdlib debugger internally uses a modified repr from the `repr`
150 # The stdlib debugger internally uses a modified repr from the `repr`
151 # module, that limits the length of printed strings to a hardcoded
151 # module, that limits the length of printed strings to a hardcoded
152 # limit of 30 characters. That much trimming is too aggressive, let's
152 # limit of 30 characters. That much trimming is too aggressive, let's
153 # at least raise that limit to 80 chars, which should be enough for
153 # at least raise that limit to 80 chars, which should be enough for
154 # most interactive uses.
154 # most interactive uses.
155 try:
155 try:
156 from reprlib import aRepr
156 from reprlib import aRepr
157 aRepr.maxstring = 80
157 aRepr.maxstring = 80
158 except:
158 except:
159 # This is only a user-facing convenience, so any error we encounter
159 # This is only a user-facing convenience, so any error we encounter
160 # here can be warned about but can be otherwise ignored. These
160 # here can be warned about but can be otherwise ignored. These
161 # printouts will tell us about problems if this API changes
161 # printouts will tell us about problems if this API changes
162 import traceback
162 import traceback
163 traceback.print_exc()
163 traceback.print_exc()
164
164
165 self.debugger = Pdb(colors)
165 self.debugger = Pdb(colors)
166
166
167 def __call__(self):
167 def __call__(self):
168 """Starts an interactive debugger at the point where called.
168 """Starts an interactive debugger at the point where called.
169
169
170 This is similar to the pdb.set_trace() function from the std lib, but
170 This is similar to the pdb.set_trace() function from the std lib, but
171 using IPython's enhanced debugger."""
171 using IPython's enhanced debugger."""
172
172
173 self.debugger.set_trace(sys._getframe().f_back)
173 self.debugger.set_trace(sys._getframe().f_back)
174
174
175
175
176 RGX_EXTRA_INDENT = re.compile(r'(?<=\n)\s+')
176 RGX_EXTRA_INDENT = re.compile(r'(?<=\n)\s+')
177
177
178
178
179 def strip_indentation(multiline_string):
179 def strip_indentation(multiline_string):
180 return RGX_EXTRA_INDENT.sub('', multiline_string)
180 return RGX_EXTRA_INDENT.sub('', multiline_string)
181
181
182
182
183 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
183 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
184 """Make new_fn have old_fn's doc string. This is particularly useful
184 """Make new_fn have old_fn's doc string. This is particularly useful
185 for the ``do_...`` commands that hook into the help system.
185 for the ``do_...`` commands that hook into the help system.
186 Adapted from from a comp.lang.python posting
186 Adapted from from a comp.lang.python posting
187 by Duncan Booth."""
187 by Duncan Booth."""
188 def wrapper(*args, **kw):
188 def wrapper(*args, **kw):
189 return new_fn(*args, **kw)
189 return new_fn(*args, **kw)
190 if old_fn.__doc__:
190 if old_fn.__doc__:
191 wrapper.__doc__ = strip_indentation(old_fn.__doc__) + additional_text
191 wrapper.__doc__ = strip_indentation(old_fn.__doc__) + additional_text
192 return wrapper
192 return wrapper
193
193
194
194
195 class Pdb(OldPdb):
195 class Pdb(OldPdb):
196 """Modified Pdb class, does not load readline.
196 """Modified Pdb class, does not load readline.
197
197
198 for a standalone version that uses prompt_toolkit, see
198 for a standalone version that uses prompt_toolkit, see
199 `IPython.terminal.debugger.TerminalPdb` and
199 `IPython.terminal.debugger.TerminalPdb` and
200 `IPython.terminal.debugger.set_trace()`
200 `IPython.terminal.debugger.set_trace()`
201 """
201 """
202
202
203 def __init__(self, color_scheme=None, completekey=None,
203 def __init__(self, color_scheme=None, completekey=None,
204 stdin=None, stdout=None, context=5, **kwargs):
204 stdin=None, stdout=None, context=5, **kwargs):
205 """Create a new IPython debugger.
205 """Create a new IPython debugger.
206
206
207 :param color_scheme: Deprecated, do not use.
207 :param color_scheme: Deprecated, do not use.
208 :param completekey: Passed to pdb.Pdb.
208 :param completekey: Passed to pdb.Pdb.
209 :param stdin: Passed to pdb.Pdb.
209 :param stdin: Passed to pdb.Pdb.
210 :param stdout: Passed to pdb.Pdb.
210 :param stdout: Passed to pdb.Pdb.
211 :param context: Number of lines of source code context to show when
211 :param context: Number of lines of source code context to show when
212 displaying stacktrace information.
212 displaying stacktrace information.
213 :param kwargs: Passed to pdb.Pdb.
213 :param kwargs: Passed to pdb.Pdb.
214 The possibilities are python version dependent, see the python
214 The possibilities are python version dependent, see the python
215 docs for more info.
215 docs for more info.
216 """
216 """
217
217
218 # Parent constructor:
218 # Parent constructor:
219 try:
219 try:
220 self.context = int(context)
220 self.context = int(context)
221 if self.context <= 0:
221 if self.context <= 0:
222 raise ValueError("Context must be a positive integer")
222 raise ValueError("Context must be a positive integer")
223 except (TypeError, ValueError):
223 except (TypeError, ValueError):
224 raise ValueError("Context must be a positive integer")
224 raise ValueError("Context must be a positive integer")
225
225
226 # `kwargs` ensures full compatibility with stdlib's `pdb.Pdb`.
226 # `kwargs` ensures full compatibility with stdlib's `pdb.Pdb`.
227 OldPdb.__init__(self, completekey, stdin, stdout, **kwargs)
227 OldPdb.__init__(self, completekey, stdin, stdout, **kwargs)
228
228
229 # IPython changes...
229 # IPython changes...
230 self.shell = get_ipython()
230 self.shell = get_ipython()
231
231
232 if self.shell is None:
232 if self.shell is None:
233 save_main = sys.modules['__main__']
233 save_main = sys.modules['__main__']
234 # No IPython instance running, we must create one
234 # No IPython instance running, we must create one
235 from IPython.terminal.interactiveshell import \
235 from IPython.terminal.interactiveshell import \
236 TerminalInteractiveShell
236 TerminalInteractiveShell
237 self.shell = TerminalInteractiveShell.instance()
237 self.shell = TerminalInteractiveShell.instance()
238 # needed by any code which calls __import__("__main__") after
238 # needed by any code which calls __import__("__main__") after
239 # the debugger was entered. See also #9941.
239 # the debugger was entered. See also #9941.
240 sys.modules['__main__'] = save_main
240 sys.modules['__main__'] = save_main
241
241
242 if color_scheme is not None:
242 if color_scheme is not None:
243 warnings.warn(
243 warnings.warn(
244 "The `color_scheme` argument is deprecated since version 5.1",
244 "The `color_scheme` argument is deprecated since version 5.1",
245 DeprecationWarning, stacklevel=2)
245 DeprecationWarning, stacklevel=2)
246 else:
246 else:
247 color_scheme = self.shell.colors
247 color_scheme = self.shell.colors
248
248
249 self.aliases = {}
249 self.aliases = {}
250
250
251 # Create color table: we copy the default one from the traceback
251 # Create color table: we copy the default one from the traceback
252 # module and add a few attributes needed for debugging
252 # module and add a few attributes needed for debugging
253 self.color_scheme_table = exception_colors()
253 self.color_scheme_table = exception_colors()
254
254
255 # shorthands
255 # shorthands
256 C = coloransi.TermColors
256 C = coloransi.TermColors
257 cst = self.color_scheme_table
257 cst = self.color_scheme_table
258
258
259 cst['NoColor'].colors.prompt = C.NoColor
259 cst['NoColor'].colors.prompt = C.NoColor
260 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
260 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
261 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
261 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
262
262
263 cst['Linux'].colors.prompt = C.Green
263 cst['Linux'].colors.prompt = C.Green
264 cst['Linux'].colors.breakpoint_enabled = C.LightRed
264 cst['Linux'].colors.breakpoint_enabled = C.LightRed
265 cst['Linux'].colors.breakpoint_disabled = C.Red
265 cst['Linux'].colors.breakpoint_disabled = C.Red
266
266
267 cst['LightBG'].colors.prompt = C.Blue
267 cst['LightBG'].colors.prompt = C.Blue
268 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
268 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
269 cst['LightBG'].colors.breakpoint_disabled = C.Red
269 cst['LightBG'].colors.breakpoint_disabled = C.Red
270
270
271 cst['Neutral'].colors.prompt = C.Blue
271 cst['Neutral'].colors.prompt = C.Blue
272 cst['Neutral'].colors.breakpoint_enabled = C.LightRed
272 cst['Neutral'].colors.breakpoint_enabled = C.LightRed
273 cst['Neutral'].colors.breakpoint_disabled = C.Red
273 cst['Neutral'].colors.breakpoint_disabled = C.Red
274
274
275
275
276 # Add a python parser so we can syntax highlight source while
276 # Add a python parser so we can syntax highlight source while
277 # debugging.
277 # debugging.
278 self.parser = PyColorize.Parser(style=color_scheme)
278 self.parser = PyColorize.Parser(style=color_scheme)
279 self.set_colors(color_scheme)
279 self.set_colors(color_scheme)
280
280
281 # Set the prompt - the default prompt is '(Pdb)'
281 # Set the prompt - the default prompt is '(Pdb)'
282 self.prompt = prompt
282 self.prompt = prompt
283 self.skip_hidden = True
283
284
284 def set_colors(self, scheme):
285 def set_colors(self, scheme):
285 """Shorthand access to the color table scheme selector method."""
286 """Shorthand access to the color table scheme selector method."""
286 self.color_scheme_table.set_active_scheme(scheme)
287 self.color_scheme_table.set_active_scheme(scheme)
287 self.parser.style = scheme
288 self.parser.style = scheme
288
289
290
291 def hidden_frames(self, stack):
292 """
293 Given an index in the stack return wether it should be skipped.
294
295 This is used in up/down and where to skip frames.
296 """
297 ip_hide = [s[0].f_locals.get("__tracebackhide__", False) for s in stack]
298 ip_start = [i for i, s in enumerate(ip_hide) if s == "__ipython_bottom__"]
299 if ip_start:
300 ip_hide = [h if i > ip_start[0] else True for (i, h) in enumerate(ip_hide)]
301 return ip_hide
302
289 def interaction(self, frame, traceback):
303 def interaction(self, frame, traceback):
290 try:
304 try:
291 OldPdb.interaction(self, frame, traceback)
305 OldPdb.interaction(self, frame, traceback)
292 except KeyboardInterrupt:
306 except KeyboardInterrupt:
293 self.stdout.write('\n' + self.shell.get_exception_only())
307 self.stdout.write("\n" + self.shell.get_exception_only())
294
295 def new_do_up(self, arg):
296 OldPdb.do_up(self, arg)
297 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
298
299 def new_do_down(self, arg):
300 OldPdb.do_down(self, arg)
301
302 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
303
308
304 def new_do_frame(self, arg):
309 def new_do_frame(self, arg):
305 OldPdb.do_frame(self, arg)
310 OldPdb.do_frame(self, arg)
306
311
307 def new_do_quit(self, arg):
312 def new_do_quit(self, arg):
308
313
309 if hasattr(self, 'old_all_completions'):
314 if hasattr(self, 'old_all_completions'):
310 self.shell.Completer.all_completions=self.old_all_completions
315 self.shell.Completer.all_completions=self.old_all_completions
311
316
312 return OldPdb.do_quit(self, arg)
317 return OldPdb.do_quit(self, arg)
313
318
314 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
319 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
315
320
316 def new_do_restart(self, arg):
321 def new_do_restart(self, arg):
317 """Restart command. In the context of ipython this is exactly the same
322 """Restart command. In the context of ipython this is exactly the same
318 thing as 'quit'."""
323 thing as 'quit'."""
319 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
324 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
320 return self.do_quit(arg)
325 return self.do_quit(arg)
321
326
322 def print_stack_trace(self, context=None):
327 def print_stack_trace(self, context=None):
328 Colors = self.color_scheme_table.active_colors
329 ColorsNormal = Colors.Normal
323 if context is None:
330 if context is None:
324 context = self.context
331 context = self.context
325 try:
332 try:
326 context=int(context)
333 context=int(context)
327 if context <= 0:
334 if context <= 0:
328 raise ValueError("Context must be a positive integer")
335 raise ValueError("Context must be a positive integer")
329 except (TypeError, ValueError):
336 except (TypeError, ValueError):
330 raise ValueError("Context must be a positive integer")
337 raise ValueError("Context must be a positive integer")
331 try:
338 try:
332 for frame_lineno in self.stack:
339 skipped = 0
340 for hidden, frame_lineno in zip(self.hidden_frames(self.stack), self.stack):
341 if hidden and self.skip_hidden:
342 skipped += 1
343 continue
344 if skipped:
345 print(
346 f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n"
347 )
348 skipped = 0
333 self.print_stack_entry(frame_lineno, context=context)
349 self.print_stack_entry(frame_lineno, context=context)
350 if skipped:
351 print(
352 f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n"
353 )
334 except KeyboardInterrupt:
354 except KeyboardInterrupt:
335 pass
355 pass
336
356
337 def print_stack_entry(self, frame_lineno, prompt_prefix='\n-> ',
357 def print_stack_entry(self, frame_lineno, prompt_prefix='\n-> ',
338 context=None):
358 context=None):
339 if context is None:
359 if context is None:
340 context = self.context
360 context = self.context
341 try:
361 try:
342 context=int(context)
362 context=int(context)
343 if context <= 0:
363 if context <= 0:
344 raise ValueError("Context must be a positive integer")
364 raise ValueError("Context must be a positive integer")
345 except (TypeError, ValueError):
365 except (TypeError, ValueError):
346 raise ValueError("Context must be a positive integer")
366 raise ValueError("Context must be a positive integer")
347 print(self.format_stack_entry(frame_lineno, '', context), file=self.stdout)
367 print(self.format_stack_entry(frame_lineno, '', context), file=self.stdout)
348
368
349 # vds: >>
369 # vds: >>
350 frame, lineno = frame_lineno
370 frame, lineno = frame_lineno
351 filename = frame.f_code.co_filename
371 filename = frame.f_code.co_filename
352 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
372 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
353 # vds: <<
373 # vds: <<
354
374
355 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
375 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
356 if context is None:
376 if context is None:
357 context = self.context
377 context = self.context
358 try:
378 try:
359 context=int(context)
379 context=int(context)
360 if context <= 0:
380 if context <= 0:
361 print("Context must be a positive integer", file=self.stdout)
381 print("Context must be a positive integer", file=self.stdout)
362 except (TypeError, ValueError):
382 except (TypeError, ValueError):
363 print("Context must be a positive integer", file=self.stdout)
383 print("Context must be a positive integer", file=self.stdout)
364 try:
384 try:
365 import reprlib # Py 3
385 import reprlib # Py 3
366 except ImportError:
386 except ImportError:
367 import repr as reprlib # Py 2
387 import repr as reprlib # Py 2
368
388
369 ret = []
389 ret = []
370
390
371 Colors = self.color_scheme_table.active_colors
391 Colors = self.color_scheme_table.active_colors
372 ColorsNormal = Colors.Normal
392 ColorsNormal = Colors.Normal
373 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
393 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
374 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
394 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
375 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
395 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
376 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
396 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
377 ColorsNormal)
397 ColorsNormal)
378
398
379 frame, lineno = frame_lineno
399 frame, lineno = frame_lineno
380
400
381 return_value = ''
401 return_value = ''
382 if '__return__' in frame.f_locals:
402 if '__return__' in frame.f_locals:
383 rv = frame.f_locals['__return__']
403 rv = frame.f_locals['__return__']
384 #return_value += '->'
404 #return_value += '->'
385 return_value += reprlib.repr(rv) + '\n'
405 return_value += reprlib.repr(rv) + '\n'
386 ret.append(return_value)
406 ret.append(return_value)
387
407
388 #s = filename + '(' + `lineno` + ')'
408 #s = filename + '(' + `lineno` + ')'
389 filename = self.canonic(frame.f_code.co_filename)
409 filename = self.canonic(frame.f_code.co_filename)
390 link = tpl_link % py3compat.cast_unicode(filename)
410 link = tpl_link % py3compat.cast_unicode(filename)
391
411
392 if frame.f_code.co_name:
412 if frame.f_code.co_name:
393 func = frame.f_code.co_name
413 func = frame.f_code.co_name
394 else:
414 else:
395 func = "<lambda>"
415 func = "<lambda>"
396
416
397 call = ''
417 call = ''
398 if func != '?':
418 if func != '?':
399 if '__args__' in frame.f_locals:
419 if '__args__' in frame.f_locals:
400 args = reprlib.repr(frame.f_locals['__args__'])
420 args = reprlib.repr(frame.f_locals['__args__'])
401 else:
421 else:
402 args = '()'
422 args = '()'
403 call = tpl_call % (func, args)
423 call = tpl_call % (func, args)
404
424
405 # The level info should be generated in the same format pdb uses, to
425 # The level info should be generated in the same format pdb uses, to
406 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
426 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
407 if frame is self.curframe:
427 if frame is self.curframe:
408 ret.append('> ')
428 ret.append('> ')
409 else:
429 else:
410 ret.append(' ')
430 ret.append(' ')
411 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
431 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
412
432
413 start = lineno - 1 - context//2
433 start = lineno - 1 - context//2
414 lines = linecache.getlines(filename)
434 lines = linecache.getlines(filename)
415 start = min(start, len(lines) - context)
435 start = min(start, len(lines) - context)
416 start = max(start, 0)
436 start = max(start, 0)
417 lines = lines[start : start + context]
437 lines = lines[start : start + context]
418
438
419 for i,line in enumerate(lines):
439 for i,line in enumerate(lines):
420 show_arrow = (start + 1 + i == lineno)
440 show_arrow = (start + 1 + i == lineno)
421 linetpl = (frame is self.curframe or show_arrow) \
441 linetpl = (frame is self.curframe or show_arrow) \
422 and tpl_line_em \
442 and tpl_line_em \
423 or tpl_line
443 or tpl_line
424 ret.append(self.__format_line(linetpl, filename,
444 ret.append(self.__format_line(linetpl, filename,
425 start + 1 + i, line,
445 start + 1 + i, line,
426 arrow = show_arrow) )
446 arrow = show_arrow) )
427 return ''.join(ret)
447 return ''.join(ret)
428
448
429 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
449 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
430 bp_mark = ""
450 bp_mark = ""
431 bp_mark_color = ""
451 bp_mark_color = ""
432
452
433 new_line, err = self.parser.format2(line, 'str')
453 new_line, err = self.parser.format2(line, 'str')
434 if not err:
454 if not err:
435 line = new_line
455 line = new_line
436
456
437 bp = None
457 bp = None
438 if lineno in self.get_file_breaks(filename):
458 if lineno in self.get_file_breaks(filename):
439 bps = self.get_breaks(filename, lineno)
459 bps = self.get_breaks(filename, lineno)
440 bp = bps[-1]
460 bp = bps[-1]
441
461
442 if bp:
462 if bp:
443 Colors = self.color_scheme_table.active_colors
463 Colors = self.color_scheme_table.active_colors
444 bp_mark = str(bp.number)
464 bp_mark = str(bp.number)
445 bp_mark_color = Colors.breakpoint_enabled
465 bp_mark_color = Colors.breakpoint_enabled
446 if not bp.enabled:
466 if not bp.enabled:
447 bp_mark_color = Colors.breakpoint_disabled
467 bp_mark_color = Colors.breakpoint_disabled
448
468
449 numbers_width = 7
469 numbers_width = 7
450 if arrow:
470 if arrow:
451 # This is the line with the error
471 # This is the line with the error
452 pad = numbers_width - len(str(lineno)) - len(bp_mark)
472 pad = numbers_width - len(str(lineno)) - len(bp_mark)
453 num = '%s%s' % (make_arrow(pad), str(lineno))
473 num = '%s%s' % (make_arrow(pad), str(lineno))
454 else:
474 else:
455 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
475 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
456
476
457 return tpl_line % (bp_mark_color + bp_mark, num, line)
477 return tpl_line % (bp_mark_color + bp_mark, num, line)
458
478
459
479
460 def print_list_lines(self, filename, first, last):
480 def print_list_lines(self, filename, first, last):
461 """The printing (as opposed to the parsing part of a 'list'
481 """The printing (as opposed to the parsing part of a 'list'
462 command."""
482 command."""
463 try:
483 try:
464 Colors = self.color_scheme_table.active_colors
484 Colors = self.color_scheme_table.active_colors
465 ColorsNormal = Colors.Normal
485 ColorsNormal = Colors.Normal
466 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
486 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
467 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
487 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
468 src = []
488 src = []
469 if filename == "<string>" and hasattr(self, "_exec_filename"):
489 if filename == "<string>" and hasattr(self, "_exec_filename"):
470 filename = self._exec_filename
490 filename = self._exec_filename
471
491
472 for lineno in range(first, last+1):
492 for lineno in range(first, last+1):
473 line = linecache.getline(filename, lineno)
493 line = linecache.getline(filename, lineno)
474 if not line:
494 if not line:
475 break
495 break
476
496
477 if lineno == self.curframe.f_lineno:
497 if lineno == self.curframe.f_lineno:
478 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
498 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
479 else:
499 else:
480 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
500 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
481
501
482 src.append(line)
502 src.append(line)
483 self.lineno = lineno
503 self.lineno = lineno
484
504
485 print(''.join(src), file=self.stdout)
505 print(''.join(src), file=self.stdout)
486
506
487 except KeyboardInterrupt:
507 except KeyboardInterrupt:
488 pass
508 pass
489
509
510 def do_skip_hidden(self, arg):
511 """
512 Change whether or not we should skip frames with the
513 __tracebackhide__ attribute.
514 """
515 if arg.strip().lower() in ("true", "yes"):
516 self.skip_hidden = True
517 elif arg.strip().lower() in ("false", "no"):
518 self.skip_hidden = False
519
490 def do_list(self, arg):
520 def do_list(self, arg):
491 """Print lines of code from the current stack frame
521 """Print lines of code from the current stack frame
492 """
522 """
493 self.lastcmd = 'list'
523 self.lastcmd = 'list'
494 last = None
524 last = None
495 if arg:
525 if arg:
496 try:
526 try:
497 x = eval(arg, {}, {})
527 x = eval(arg, {}, {})
498 if type(x) == type(()):
528 if type(x) == type(()):
499 first, last = x
529 first, last = x
500 first = int(first)
530 first = int(first)
501 last = int(last)
531 last = int(last)
502 if last < first:
532 if last < first:
503 # Assume it's a count
533 # Assume it's a count
504 last = first + last
534 last = first + last
505 else:
535 else:
506 first = max(1, int(x) - 5)
536 first = max(1, int(x) - 5)
507 except:
537 except:
508 print('*** Error in argument:', repr(arg), file=self.stdout)
538 print('*** Error in argument:', repr(arg), file=self.stdout)
509 return
539 return
510 elif self.lineno is None:
540 elif self.lineno is None:
511 first = max(1, self.curframe.f_lineno - 5)
541 first = max(1, self.curframe.f_lineno - 5)
512 else:
542 else:
513 first = self.lineno + 1
543 first = self.lineno + 1
514 if last is None:
544 if last is None:
515 last = first + 10
545 last = first + 10
516 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
546 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
517
547
518 # vds: >>
548 # vds: >>
519 lineno = first
549 lineno = first
520 filename = self.curframe.f_code.co_filename
550 filename = self.curframe.f_code.co_filename
521 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
551 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
522 # vds: <<
552 # vds: <<
523
553
524 do_l = do_list
554 do_l = do_list
525
555
526 def getsourcelines(self, obj):
556 def getsourcelines(self, obj):
527 lines, lineno = inspect.findsource(obj)
557 lines, lineno = inspect.findsource(obj)
528 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
558 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
529 # must be a module frame: do not try to cut a block out of it
559 # must be a module frame: do not try to cut a block out of it
530 return lines, 1
560 return lines, 1
531 elif inspect.ismodule(obj):
561 elif inspect.ismodule(obj):
532 return lines, 1
562 return lines, 1
533 return inspect.getblock(lines[lineno:]), lineno+1
563 return inspect.getblock(lines[lineno:]), lineno+1
534
564
535 def do_longlist(self, arg):
565 def do_longlist(self, arg):
536 """Print lines of code from the current stack frame.
566 """Print lines of code from the current stack frame.
537
567
538 Shows more lines than 'list' does.
568 Shows more lines than 'list' does.
539 """
569 """
540 self.lastcmd = 'longlist'
570 self.lastcmd = 'longlist'
541 try:
571 try:
542 lines, lineno = self.getsourcelines(self.curframe)
572 lines, lineno = self.getsourcelines(self.curframe)
543 except OSError as err:
573 except OSError as err:
544 self.error(err)
574 self.error(err)
545 return
575 return
546 last = lineno + len(lines)
576 last = lineno + len(lines)
547 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
577 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
548 do_ll = do_longlist
578 do_ll = do_longlist
549
579
550 def do_debug(self, arg):
580 def do_debug(self, arg):
551 """debug code
581 """debug code
552 Enter a recursive debugger that steps through the code
582 Enter a recursive debugger that steps through the code
553 argument (which is an arbitrary expression or statement to be
583 argument (which is an arbitrary expression or statement to be
554 executed in the current environment).
584 executed in the current environment).
555 """
585 """
556 sys.settrace(None)
586 sys.settrace(None)
557 globals = self.curframe.f_globals
587 globals = self.curframe.f_globals
558 locals = self.curframe_locals
588 locals = self.curframe_locals
559 p = self.__class__(completekey=self.completekey,
589 p = self.__class__(completekey=self.completekey,
560 stdin=self.stdin, stdout=self.stdout)
590 stdin=self.stdin, stdout=self.stdout)
561 p.use_rawinput = self.use_rawinput
591 p.use_rawinput = self.use_rawinput
562 p.prompt = "(%s) " % self.prompt.strip()
592 p.prompt = "(%s) " % self.prompt.strip()
563 self.message("ENTERING RECURSIVE DEBUGGER")
593 self.message("ENTERING RECURSIVE DEBUGGER")
564 sys.call_tracing(p.run, (arg, globals, locals))
594 sys.call_tracing(p.run, (arg, globals, locals))
565 self.message("LEAVING RECURSIVE DEBUGGER")
595 self.message("LEAVING RECURSIVE DEBUGGER")
566 sys.settrace(self.trace_dispatch)
596 sys.settrace(self.trace_dispatch)
567 self.lastcmd = p.lastcmd
597 self.lastcmd = p.lastcmd
568
598
569 def do_pdef(self, arg):
599 def do_pdef(self, arg):
570 """Print the call signature for any callable object.
600 """Print the call signature for any callable object.
571
601
572 The debugger interface to %pdef"""
602 The debugger interface to %pdef"""
573 namespaces = [('Locals', self.curframe.f_locals),
603 namespaces = [('Locals', self.curframe.f_locals),
574 ('Globals', self.curframe.f_globals)]
604 ('Globals', self.curframe.f_globals)]
575 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
605 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
576
606
577 def do_pdoc(self, arg):
607 def do_pdoc(self, arg):
578 """Print the docstring for an object.
608 """Print the docstring for an object.
579
609
580 The debugger interface to %pdoc."""
610 The debugger interface to %pdoc."""
581 namespaces = [('Locals', self.curframe.f_locals),
611 namespaces = [('Locals', self.curframe.f_locals),
582 ('Globals', self.curframe.f_globals)]
612 ('Globals', self.curframe.f_globals)]
583 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
613 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
584
614
585 def do_pfile(self, arg):
615 def do_pfile(self, arg):
586 """Print (or run through pager) the file where an object is defined.
616 """Print (or run through pager) the file where an object is defined.
587
617
588 The debugger interface to %pfile.
618 The debugger interface to %pfile.
589 """
619 """
590 namespaces = [('Locals', self.curframe.f_locals),
620 namespaces = [('Locals', self.curframe.f_locals),
591 ('Globals', self.curframe.f_globals)]
621 ('Globals', self.curframe.f_globals)]
592 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
622 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
593
623
594 def do_pinfo(self, arg):
624 def do_pinfo(self, arg):
595 """Provide detailed information about an object.
625 """Provide detailed information about an object.
596
626
597 The debugger interface to %pinfo, i.e., obj?."""
627 The debugger interface to %pinfo, i.e., obj?."""
598 namespaces = [('Locals', self.curframe.f_locals),
628 namespaces = [('Locals', self.curframe.f_locals),
599 ('Globals', self.curframe.f_globals)]
629 ('Globals', self.curframe.f_globals)]
600 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
630 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
601
631
602 def do_pinfo2(self, arg):
632 def do_pinfo2(self, arg):
603 """Provide extra detailed information about an object.
633 """Provide extra detailed information about an object.
604
634
605 The debugger interface to %pinfo2, i.e., obj??."""
635 The debugger interface to %pinfo2, i.e., obj??."""
606 namespaces = [('Locals', self.curframe.f_locals),
636 namespaces = [('Locals', self.curframe.f_locals),
607 ('Globals', self.curframe.f_globals)]
637 ('Globals', self.curframe.f_globals)]
608 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
638 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
609
639
610 def do_psource(self, arg):
640 def do_psource(self, arg):
611 """Print (or run through pager) the source code for an object."""
641 """Print (or run through pager) the source code for an object."""
612 namespaces = [('Locals', self.curframe.f_locals),
642 namespaces = [('Locals', self.curframe.f_locals),
613 ('Globals', self.curframe.f_globals)]
643 ('Globals', self.curframe.f_globals)]
614 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
644 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
615
645
616 def do_where(self, arg):
646 def do_where(self, arg):
617 """w(here)
647 """w(here)
618 Print a stack trace, with the most recent frame at the bottom.
648 Print a stack trace, with the most recent frame at the bottom.
619 An arrow indicates the "current frame", which determines the
649 An arrow indicates the "current frame", which determines the
620 context of most commands. 'bt' is an alias for this command.
650 context of most commands. 'bt' is an alias for this command.
621
651
622 Take a number as argument as an (optional) number of context line to
652 Take a number as argument as an (optional) number of context line to
623 print"""
653 print"""
624 if arg:
654 if arg:
625 try:
655 try:
626 context = int(arg)
656 context = int(arg)
627 except ValueError as err:
657 except ValueError as err:
628 self.error(err)
658 self.error(err)
629 return
659 return
630 self.print_stack_trace(context)
660 self.print_stack_trace(context)
631 else:
661 else:
632 self.print_stack_trace()
662 self.print_stack_trace()
633
663
634 do_w = do_where
664 do_w = do_where
635
665
666 def stop_here(self, frame):
667 hidden = False
668 if self.skip_hidden:
669 hidden = frame.f_locals.get("__tracebackhide__", False)
670 if hidden:
671 Colors = self.color_scheme_table.active_colors
672 ColorsNormal = Colors.Normal
673 print(f"{Colors.excName} [... skipped 1 hidden frame]{ColorsNormal}\n")
674
675 return super().stop_here(frame)
676
677 def do_up(self, arg):
678 """u(p) [count]
679 Move the current frame count (default one) levels up in the
680 stack trace (to an older frame).
681
682 Will skip hidden frames.
683 """
684 ## modified version of upstream that skips
685 # frames with __tracebackide__
686 if self.curindex == 0:
687 self.error("Oldest frame")
688 return
689 try:
690 count = int(arg or 1)
691 except ValueError:
692 self.error("Invalid frame count (%s)" % arg)
693 return
694 skipped = 0
695 if count < 0:
696 _newframe = 0
697 else:
698 _newindex = self.curindex
699 counter = 0
700 hidden_frames = self.hidden_frames(self.stack)
701 for i in range(self.curindex - 1, -1, -1):
702 frame = self.stack[i][0]
703 if hidden_frames[i] and self.skip_hidden:
704 skipped += 1
705 continue
706 counter += 1
707 if counter >= count:
708 break
709 else:
710 # if no break occured.
711 self.error("all frames above hidden")
712 return
713
714 Colors = self.color_scheme_table.active_colors
715 ColorsNormal = Colors.Normal
716 _newframe = i
717 self._select_frame(_newframe)
718 if skipped:
719 print(
720 f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n"
721 )
722
723 def do_down(self, arg):
724 """d(own) [count]
725 Move the current frame count (default one) levels down in the
726 stack trace (to a newer frame).
727
728 Will skip hidden frames.
729 """
730 if self.curindex + 1 == len(self.stack):
731 self.error("Newest frame")
732 return
733 try:
734 count = int(arg or 1)
735 except ValueError:
736 self.error("Invalid frame count (%s)" % arg)
737 return
738 if count < 0:
739 _newframe = len(self.stack) - 1
740 else:
741 _newindex = self.curindex
742 counter = 0
743 skipped = 0
744 hidden_frames = self.hidden_frames(self.stack)
745 for i in range(self.curindex + 1, len(self.stack)):
746 frame = self.stack[i][0]
747 if hidden_frames[i] and self.skip_hidden:
748 skipped += 1
749 continue
750 counter += 1
751 if counter >= count:
752 break
753 else:
754 self.error("all frames bellow hidden")
755 return
756
757 Colors = self.color_scheme_table.active_colors
758 ColorsNormal = Colors.Normal
759 if skipped:
760 print(
761 f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n"
762 )
763 _newframe = i
764
765 self._select_frame(_newframe)
766
767 do_d = do_down
768 do_u = do_up
636
769
637 class InterruptiblePdb(Pdb):
770 class InterruptiblePdb(Pdb):
638 """Version of debugger where KeyboardInterrupt exits the debugger altogether."""
771 """Version of debugger where KeyboardInterrupt exits the debugger altogether."""
639
772
640 def cmdloop(self):
773 def cmdloop(self):
641 """Wrap cmdloop() such that KeyboardInterrupt stops the debugger."""
774 """Wrap cmdloop() such that KeyboardInterrupt stops the debugger."""
642 try:
775 try:
643 return OldPdb.cmdloop(self)
776 return OldPdb.cmdloop(self)
644 except KeyboardInterrupt:
777 except KeyboardInterrupt:
645 self.stop_here = lambda frame: False
778 self.stop_here = lambda frame: False
646 self.do_quit("")
779 self.do_quit("")
647 sys.settrace(None)
780 sys.settrace(None)
648 self.quitting = False
781 self.quitting = False
649 raise
782 raise
650
783
651 def _cmdloop(self):
784 def _cmdloop(self):
652 while True:
785 while True:
653 try:
786 try:
654 # keyboard interrupts allow for an easy way to cancel
787 # keyboard interrupts allow for an easy way to cancel
655 # the current command, so allow them during interactive input
788 # the current command, so allow them during interactive input
656 self.allow_kbdint = True
789 self.allow_kbdint = True
657 self.cmdloop()
790 self.cmdloop()
658 self.allow_kbdint = False
791 self.allow_kbdint = False
659 break
792 break
660 except KeyboardInterrupt:
793 except KeyboardInterrupt:
661 self.message('--KeyboardInterrupt--')
794 self.message('--KeyboardInterrupt--')
662 raise
795 raise
663
796
664
797
665 def set_trace(frame=None):
798 def set_trace(frame=None):
666 """
799 """
667 Start debugging from `frame`.
800 Start debugging from `frame`.
668
801
669 If frame is not specified, debugging starts from caller's frame.
802 If frame is not specified, debugging starts from caller's frame.
670 """
803 """
671 Pdb().set_trace(frame or sys._getframe().f_back)
804 Pdb().set_trace(frame or sys._getframe().f_back)
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,651 +1,663 b''
1 """Implementation of basic magic functions."""
1 """Implementation of basic magic functions."""
2
2
3
3
4 import argparse
4 import argparse
5 from logging import error
5 from logging import error
6 import io
6 import io
7 from pprint import pformat
7 from pprint import pformat
8 import sys
8 import sys
9 from warnings import warn
9 from warnings import warn
10
10
11 from traitlets.utils.importstring import import_item
11 from traitlets.utils.importstring import import_item
12 from IPython.core import magic_arguments, page
12 from IPython.core import magic_arguments, page
13 from IPython.core.error import UsageError
13 from IPython.core.error import UsageError
14 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
14 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
15 from IPython.utils.text import format_screen, dedent, indent
15 from IPython.utils.text import format_screen, dedent, indent
16 from IPython.testing.skipdoctest import skip_doctest
16 from IPython.testing.skipdoctest import skip_doctest
17 from IPython.utils.ipstruct import Struct
17 from IPython.utils.ipstruct import Struct
18
18
19
19
20 class MagicsDisplay(object):
20 class MagicsDisplay(object):
21 def __init__(self, magics_manager, ignore=None):
21 def __init__(self, magics_manager, ignore=None):
22 self.ignore = ignore if ignore else []
22 self.ignore = ignore if ignore else []
23 self.magics_manager = magics_manager
23 self.magics_manager = magics_manager
24
24
25 def _lsmagic(self):
25 def _lsmagic(self):
26 """The main implementation of the %lsmagic"""
26 """The main implementation of the %lsmagic"""
27 mesc = magic_escapes['line']
27 mesc = magic_escapes['line']
28 cesc = magic_escapes['cell']
28 cesc = magic_escapes['cell']
29 mman = self.magics_manager
29 mman = self.magics_manager
30 magics = mman.lsmagic()
30 magics = mman.lsmagic()
31 out = ['Available line magics:',
31 out = ['Available line magics:',
32 mesc + (' '+mesc).join(sorted([m for m,v in magics['line'].items() if (v not in self.ignore)])),
32 mesc + (' '+mesc).join(sorted([m for m,v in magics['line'].items() if (v not in self.ignore)])),
33 '',
33 '',
34 'Available cell magics:',
34 'Available cell magics:',
35 cesc + (' '+cesc).join(sorted([m for m,v in magics['cell'].items() if (v not in self.ignore)])),
35 cesc + (' '+cesc).join(sorted([m for m,v in magics['cell'].items() if (v not in self.ignore)])),
36 '',
36 '',
37 mman.auto_status()]
37 mman.auto_status()]
38 return '\n'.join(out)
38 return '\n'.join(out)
39
39
40 def _repr_pretty_(self, p, cycle):
40 def _repr_pretty_(self, p, cycle):
41 p.text(self._lsmagic())
41 p.text(self._lsmagic())
42
42
43 def __str__(self):
43 def __str__(self):
44 return self._lsmagic()
44 return self._lsmagic()
45
45
46 def _jsonable(self):
46 def _jsonable(self):
47 """turn magics dict into jsonable dict of the same structure
47 """turn magics dict into jsonable dict of the same structure
48
48
49 replaces object instances with their class names as strings
49 replaces object instances with their class names as strings
50 """
50 """
51 magic_dict = {}
51 magic_dict = {}
52 mman = self.magics_manager
52 mman = self.magics_manager
53 magics = mman.lsmagic()
53 magics = mman.lsmagic()
54 for key, subdict in magics.items():
54 for key, subdict in magics.items():
55 d = {}
55 d = {}
56 magic_dict[key] = d
56 magic_dict[key] = d
57 for name, obj in subdict.items():
57 for name, obj in subdict.items():
58 try:
58 try:
59 classname = obj.__self__.__class__.__name__
59 classname = obj.__self__.__class__.__name__
60 except AttributeError:
60 except AttributeError:
61 classname = 'Other'
61 classname = 'Other'
62
62
63 d[name] = classname
63 d[name] = classname
64 return magic_dict
64 return magic_dict
65
65
66 def _repr_json_(self):
66 def _repr_json_(self):
67 return self._jsonable()
67 return self._jsonable()
68
68
69
69
70 @magics_class
70 @magics_class
71 class BasicMagics(Magics):
71 class BasicMagics(Magics):
72 """Magics that provide central IPython functionality.
72 """Magics that provide central IPython functionality.
73
73
74 These are various magics that don't fit into specific categories but that
74 These are various magics that don't fit into specific categories but that
75 are all part of the base 'IPython experience'."""
75 are all part of the base 'IPython experience'."""
76
76
77 @magic_arguments.magic_arguments()
77 @magic_arguments.magic_arguments()
78 @magic_arguments.argument(
78 @magic_arguments.argument(
79 '-l', '--line', action='store_true',
79 '-l', '--line', action='store_true',
80 help="""Create a line magic alias."""
80 help="""Create a line magic alias."""
81 )
81 )
82 @magic_arguments.argument(
82 @magic_arguments.argument(
83 '-c', '--cell', action='store_true',
83 '-c', '--cell', action='store_true',
84 help="""Create a cell magic alias."""
84 help="""Create a cell magic alias."""
85 )
85 )
86 @magic_arguments.argument(
86 @magic_arguments.argument(
87 'name',
87 'name',
88 help="""Name of the magic to be created."""
88 help="""Name of the magic to be created."""
89 )
89 )
90 @magic_arguments.argument(
90 @magic_arguments.argument(
91 'target',
91 'target',
92 help="""Name of the existing line or cell magic."""
92 help="""Name of the existing line or cell magic."""
93 )
93 )
94 @magic_arguments.argument(
94 @magic_arguments.argument(
95 '-p', '--params', default=None,
95 '-p', '--params', default=None,
96 help="""Parameters passed to the magic function."""
96 help="""Parameters passed to the magic function."""
97 )
97 )
98 @line_magic
98 @line_magic
99 def alias_magic(self, line=''):
99 def alias_magic(self, line=''):
100 """Create an alias for an existing line or cell magic.
100 """Create an alias for an existing line or cell magic.
101
101
102 Examples
102 Examples
103 --------
103 --------
104 ::
104 ::
105
105
106 In [1]: %alias_magic t timeit
106 In [1]: %alias_magic t timeit
107 Created `%t` as an alias for `%timeit`.
107 Created `%t` as an alias for `%timeit`.
108 Created `%%t` as an alias for `%%timeit`.
108 Created `%%t` as an alias for `%%timeit`.
109
109
110 In [2]: %t -n1 pass
110 In [2]: %t -n1 pass
111 1 loops, best of 3: 954 ns per loop
111 1 loops, best of 3: 954 ns per loop
112
112
113 In [3]: %%t -n1
113 In [3]: %%t -n1
114 ...: pass
114 ...: pass
115 ...:
115 ...:
116 1 loops, best of 3: 954 ns per loop
116 1 loops, best of 3: 954 ns per loop
117
117
118 In [4]: %alias_magic --cell whereami pwd
118 In [4]: %alias_magic --cell whereami pwd
119 UsageError: Cell magic function `%%pwd` not found.
119 UsageError: Cell magic function `%%pwd` not found.
120 In [5]: %alias_magic --line whereami pwd
120 In [5]: %alias_magic --line whereami pwd
121 Created `%whereami` as an alias for `%pwd`.
121 Created `%whereami` as an alias for `%pwd`.
122
122
123 In [6]: %whereami
123 In [6]: %whereami
124 Out[6]: u'/home/testuser'
124 Out[6]: u'/home/testuser'
125
125
126 In [7]: %alias_magic h history "-p -l 30" --line
126 In [7]: %alias_magic h history "-p -l 30" --line
127 Created `%h` as an alias for `%history -l 30`.
127 Created `%h` as an alias for `%history -l 30`.
128 """
128 """
129
129
130 args = magic_arguments.parse_argstring(self.alias_magic, line)
130 args = magic_arguments.parse_argstring(self.alias_magic, line)
131 shell = self.shell
131 shell = self.shell
132 mman = self.shell.magics_manager
132 mman = self.shell.magics_manager
133 escs = ''.join(magic_escapes.values())
133 escs = ''.join(magic_escapes.values())
134
134
135 target = args.target.lstrip(escs)
135 target = args.target.lstrip(escs)
136 name = args.name.lstrip(escs)
136 name = args.name.lstrip(escs)
137
137
138 params = args.params
138 params = args.params
139 if (params and
139 if (params and
140 ((params.startswith('"') and params.endswith('"'))
140 ((params.startswith('"') and params.endswith('"'))
141 or (params.startswith("'") and params.endswith("'")))):
141 or (params.startswith("'") and params.endswith("'")))):
142 params = params[1:-1]
142 params = params[1:-1]
143
143
144 # Find the requested magics.
144 # Find the requested magics.
145 m_line = shell.find_magic(target, 'line')
145 m_line = shell.find_magic(target, 'line')
146 m_cell = shell.find_magic(target, 'cell')
146 m_cell = shell.find_magic(target, 'cell')
147 if args.line and m_line is None:
147 if args.line and m_line is None:
148 raise UsageError('Line magic function `%s%s` not found.' %
148 raise UsageError('Line magic function `%s%s` not found.' %
149 (magic_escapes['line'], target))
149 (magic_escapes['line'], target))
150 if args.cell and m_cell is None:
150 if args.cell and m_cell is None:
151 raise UsageError('Cell magic function `%s%s` not found.' %
151 raise UsageError('Cell magic function `%s%s` not found.' %
152 (magic_escapes['cell'], target))
152 (magic_escapes['cell'], target))
153
153
154 # If --line and --cell are not specified, default to the ones
154 # If --line and --cell are not specified, default to the ones
155 # that are available.
155 # that are available.
156 if not args.line and not args.cell:
156 if not args.line and not args.cell:
157 if not m_line and not m_cell:
157 if not m_line and not m_cell:
158 raise UsageError(
158 raise UsageError(
159 'No line or cell magic with name `%s` found.' % target
159 'No line or cell magic with name `%s` found.' % target
160 )
160 )
161 args.line = bool(m_line)
161 args.line = bool(m_line)
162 args.cell = bool(m_cell)
162 args.cell = bool(m_cell)
163
163
164 params_str = "" if params is None else " " + params
164 params_str = "" if params is None else " " + params
165
165
166 if args.line:
166 if args.line:
167 mman.register_alias(name, target, 'line', params)
167 mman.register_alias(name, target, 'line', params)
168 print('Created `%s%s` as an alias for `%s%s%s`.' % (
168 print('Created `%s%s` as an alias for `%s%s%s`.' % (
169 magic_escapes['line'], name,
169 magic_escapes['line'], name,
170 magic_escapes['line'], target, params_str))
170 magic_escapes['line'], target, params_str))
171
171
172 if args.cell:
172 if args.cell:
173 mman.register_alias(name, target, 'cell', params)
173 mman.register_alias(name, target, 'cell', params)
174 print('Created `%s%s` as an alias for `%s%s%s`.' % (
174 print('Created `%s%s` as an alias for `%s%s%s`.' % (
175 magic_escapes['cell'], name,
175 magic_escapes['cell'], name,
176 magic_escapes['cell'], target, params_str))
176 magic_escapes['cell'], target, params_str))
177
177
178 @line_magic
178 @line_magic
179 def lsmagic(self, parameter_s=''):
179 def lsmagic(self, parameter_s=''):
180 """List currently available magic functions."""
180 """List currently available magic functions."""
181 return MagicsDisplay(self.shell.magics_manager, ignore=[])
181 return MagicsDisplay(self.shell.magics_manager, ignore=[])
182
182
183 def _magic_docs(self, brief=False, rest=False):
183 def _magic_docs(self, brief=False, rest=False):
184 """Return docstrings from magic functions."""
184 """Return docstrings from magic functions."""
185 mman = self.shell.magics_manager
185 mman = self.shell.magics_manager
186 docs = mman.lsmagic_docs(brief, missing='No documentation')
186 docs = mman.lsmagic_docs(brief, missing='No documentation')
187
187
188 if rest:
188 if rest:
189 format_string = '**%s%s**::\n\n%s\n\n'
189 format_string = '**%s%s**::\n\n%s\n\n'
190 else:
190 else:
191 format_string = '%s%s:\n%s\n'
191 format_string = '%s%s:\n%s\n'
192
192
193 return ''.join(
193 return ''.join(
194 [format_string % (magic_escapes['line'], fname,
194 [format_string % (magic_escapes['line'], fname,
195 indent(dedent(fndoc)))
195 indent(dedent(fndoc)))
196 for fname, fndoc in sorted(docs['line'].items())]
196 for fname, fndoc in sorted(docs['line'].items())]
197 +
197 +
198 [format_string % (magic_escapes['cell'], fname,
198 [format_string % (magic_escapes['cell'], fname,
199 indent(dedent(fndoc)))
199 indent(dedent(fndoc)))
200 for fname, fndoc in sorted(docs['cell'].items())]
200 for fname, fndoc in sorted(docs['cell'].items())]
201 )
201 )
202
202
203 @line_magic
203 @line_magic
204 def magic(self, parameter_s=''):
204 def magic(self, parameter_s=''):
205 """Print information about the magic function system.
205 """Print information about the magic function system.
206
206
207 Supported formats: -latex, -brief, -rest
207 Supported formats: -latex, -brief, -rest
208 """
208 """
209
209
210 mode = ''
210 mode = ''
211 try:
211 try:
212 mode = parameter_s.split()[0][1:]
212 mode = parameter_s.split()[0][1:]
213 except IndexError:
213 except IndexError:
214 pass
214 pass
215
215
216 brief = (mode == 'brief')
216 brief = (mode == 'brief')
217 rest = (mode == 'rest')
217 rest = (mode == 'rest')
218 magic_docs = self._magic_docs(brief, rest)
218 magic_docs = self._magic_docs(brief, rest)
219
219
220 if mode == 'latex':
220 if mode == 'latex':
221 print(self.format_latex(magic_docs))
221 print(self.format_latex(magic_docs))
222 return
222 return
223 else:
223 else:
224 magic_docs = format_screen(magic_docs)
224 magic_docs = format_screen(magic_docs)
225
225
226 out = ["""
226 out = ["""
227 IPython's 'magic' functions
227 IPython's 'magic' functions
228 ===========================
228 ===========================
229
229
230 The magic function system provides a series of functions which allow you to
230 The magic function system provides a series of functions which allow you to
231 control the behavior of IPython itself, plus a lot of system-type
231 control the behavior of IPython itself, plus a lot of system-type
232 features. There are two kinds of magics, line-oriented and cell-oriented.
232 features. There are two kinds of magics, line-oriented and cell-oriented.
233
233
234 Line magics are prefixed with the % character and work much like OS
234 Line magics are prefixed with the % character and work much like OS
235 command-line calls: they get as an argument the rest of the line, where
235 command-line calls: they get as an argument the rest of the line, where
236 arguments are passed without parentheses or quotes. For example, this will
236 arguments are passed without parentheses or quotes. For example, this will
237 time the given statement::
237 time the given statement::
238
238
239 %timeit range(1000)
239 %timeit range(1000)
240
240
241 Cell magics are prefixed with a double %%, and they are functions that get as
241 Cell magics are prefixed with a double %%, and they are functions that get as
242 an argument not only the rest of the line, but also the lines below it in a
242 an argument not only the rest of the line, but also the lines below it in a
243 separate argument. These magics are called with two arguments: the rest of the
243 separate argument. These magics are called with two arguments: the rest of the
244 call line and the body of the cell, consisting of the lines below the first.
244 call line and the body of the cell, consisting of the lines below the first.
245 For example::
245 For example::
246
246
247 %%timeit x = numpy.random.randn((100, 100))
247 %%timeit x = numpy.random.randn((100, 100))
248 numpy.linalg.svd(x)
248 numpy.linalg.svd(x)
249
249
250 will time the execution of the numpy svd routine, running the assignment of x
250 will time the execution of the numpy svd routine, running the assignment of x
251 as part of the setup phase, which is not timed.
251 as part of the setup phase, which is not timed.
252
252
253 In a line-oriented client (the terminal or Qt console IPython), starting a new
253 In a line-oriented client (the terminal or Qt console IPython), starting a new
254 input with %% will automatically enter cell mode, and IPython will continue
254 input with %% will automatically enter cell mode, and IPython will continue
255 reading input until a blank line is given. In the notebook, simply type the
255 reading input until a blank line is given. In the notebook, simply type the
256 whole cell as one entity, but keep in mind that the %% escape can only be at
256 whole cell as one entity, but keep in mind that the %% escape can only be at
257 the very start of the cell.
257 the very start of the cell.
258
258
259 NOTE: If you have 'automagic' enabled (via the command line option or with the
259 NOTE: If you have 'automagic' enabled (via the command line option or with the
260 %automagic function), you don't need to type in the % explicitly for line
260 %automagic function), you don't need to type in the % explicitly for line
261 magics; cell magics always require an explicit '%%' escape. By default,
261 magics; cell magics always require an explicit '%%' escape. By default,
262 IPython ships with automagic on, so you should only rarely need the % escape.
262 IPython ships with automagic on, so you should only rarely need the % escape.
263
263
264 Example: typing '%cd mydir' (without the quotes) changes your working directory
264 Example: typing '%cd mydir' (without the quotes) changes your working directory
265 to 'mydir', if it exists.
265 to 'mydir', if it exists.
266
266
267 For a list of the available magic functions, use %lsmagic. For a description
267 For a list of the available magic functions, use %lsmagic. For a description
268 of any of them, type %magic_name?, e.g. '%cd?'.
268 of any of them, type %magic_name?, e.g. '%cd?'.
269
269
270 Currently the magic system has the following functions:""",
270 Currently the magic system has the following functions:""",
271 magic_docs,
271 magic_docs,
272 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
272 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
273 str(self.lsmagic()),
273 str(self.lsmagic()),
274 ]
274 ]
275 page.page('\n'.join(out))
275 page.page('\n'.join(out))
276
276
277
277
278 @line_magic
278 @line_magic
279 def page(self, parameter_s=''):
279 def page(self, parameter_s=''):
280 """Pretty print the object and display it through a pager.
280 """Pretty print the object and display it through a pager.
281
281
282 %page [options] OBJECT
282 %page [options] OBJECT
283
283
284 If no object is given, use _ (last output).
284 If no object is given, use _ (last output).
285
285
286 Options:
286 Options:
287
287
288 -r: page str(object), don't pretty-print it."""
288 -r: page str(object), don't pretty-print it."""
289
289
290 # After a function contributed by Olivier Aubert, slightly modified.
290 # After a function contributed by Olivier Aubert, slightly modified.
291
291
292 # Process options/args
292 # Process options/args
293 opts, args = self.parse_options(parameter_s, 'r')
293 opts, args = self.parse_options(parameter_s, 'r')
294 raw = 'r' in opts
294 raw = 'r' in opts
295
295
296 oname = args and args or '_'
296 oname = args and args or '_'
297 info = self.shell._ofind(oname)
297 info = self.shell._ofind(oname)
298 if info['found']:
298 if info['found']:
299 txt = (raw and str or pformat)( info['obj'] )
299 txt = (raw and str or pformat)( info['obj'] )
300 page.page(txt)
300 page.page(txt)
301 else:
301 else:
302 print('Object `%s` not found' % oname)
302 print('Object `%s` not found' % oname)
303
303
304 @line_magic
304 @line_magic
305 def pprint(self, parameter_s=''):
305 def pprint(self, parameter_s=''):
306 """Toggle pretty printing on/off."""
306 """Toggle pretty printing on/off."""
307 ptformatter = self.shell.display_formatter.formatters['text/plain']
307 ptformatter = self.shell.display_formatter.formatters['text/plain']
308 ptformatter.pprint = bool(1 - ptformatter.pprint)
308 ptformatter.pprint = bool(1 - ptformatter.pprint)
309 print('Pretty printing has been turned',
309 print('Pretty printing has been turned',
310 ['OFF','ON'][ptformatter.pprint])
310 ['OFF','ON'][ptformatter.pprint])
311
311
312 @line_magic
312 @line_magic
313 def colors(self, parameter_s=''):
313 def colors(self, parameter_s=''):
314 """Switch color scheme for prompts, info system and exception handlers.
314 """Switch color scheme for prompts, info system and exception handlers.
315
315
316 Currently implemented schemes: NoColor, Linux, LightBG.
316 Currently implemented schemes: NoColor, Linux, LightBG.
317
317
318 Color scheme names are not case-sensitive.
318 Color scheme names are not case-sensitive.
319
319
320 Examples
320 Examples
321 --------
321 --------
322 To get a plain black and white terminal::
322 To get a plain black and white terminal::
323
323
324 %colors nocolor
324 %colors nocolor
325 """
325 """
326 def color_switch_err(name):
326 def color_switch_err(name):
327 warn('Error changing %s color schemes.\n%s' %
327 warn('Error changing %s color schemes.\n%s' %
328 (name, sys.exc_info()[1]), stacklevel=2)
328 (name, sys.exc_info()[1]), stacklevel=2)
329
329
330
330
331 new_scheme = parameter_s.strip()
331 new_scheme = parameter_s.strip()
332 if not new_scheme:
332 if not new_scheme:
333 raise UsageError(
333 raise UsageError(
334 "%colors: you must specify a color scheme. See '%colors?'")
334 "%colors: you must specify a color scheme. See '%colors?'")
335 # local shortcut
335 # local shortcut
336 shell = self.shell
336 shell = self.shell
337
337
338 # Set shell colour scheme
338 # Set shell colour scheme
339 try:
339 try:
340 shell.colors = new_scheme
340 shell.colors = new_scheme
341 shell.refresh_style()
341 shell.refresh_style()
342 except:
342 except:
343 color_switch_err('shell')
343 color_switch_err('shell')
344
344
345 # Set exception colors
345 # Set exception colors
346 try:
346 try:
347 shell.InteractiveTB.set_colors(scheme = new_scheme)
347 shell.InteractiveTB.set_colors(scheme = new_scheme)
348 shell.SyntaxTB.set_colors(scheme = new_scheme)
348 shell.SyntaxTB.set_colors(scheme = new_scheme)
349 except:
349 except:
350 color_switch_err('exception')
350 color_switch_err('exception')
351
351
352 # Set info (for 'object?') colors
352 # Set info (for 'object?') colors
353 if shell.color_info:
353 if shell.color_info:
354 try:
354 try:
355 shell.inspector.set_active_scheme(new_scheme)
355 shell.inspector.set_active_scheme(new_scheme)
356 except:
356 except:
357 color_switch_err('object inspector')
357 color_switch_err('object inspector')
358 else:
358 else:
359 shell.inspector.set_active_scheme('NoColor')
359 shell.inspector.set_active_scheme('NoColor')
360
360
361 @line_magic
361 @line_magic
362 def xmode(self, parameter_s=''):
362 def xmode(self, parameter_s=''):
363 """Switch modes for the exception handlers.
363 """Switch modes for the exception handlers.
364
364
365 Valid modes: Plain, Context, Verbose, and Minimal.
365 Valid modes: Plain, Context, Verbose, and Minimal.
366
366
367 If called without arguments, acts as a toggle."""
367 If called without arguments, acts as a toggle.
368
369 When in verbose mode the value --show (and --hide)
370 will respectively show (or hide) frames with ``__tracebackhide__ =
371 True`` value set.
372 """
368
373
369 def xmode_switch_err(name):
374 def xmode_switch_err(name):
370 warn('Error changing %s exception modes.\n%s' %
375 warn('Error changing %s exception modes.\n%s' %
371 (name,sys.exc_info()[1]))
376 (name,sys.exc_info()[1]))
372
377
373 shell = self.shell
378 shell = self.shell
379 if parameter_s.strip() == "--show":
380 shell.InteractiveTB.skip_hidden = False
381 return
382 if parameter_s.strip() == "--hide":
383 shell.InteractiveTB.skip_hidden = True
384 return
385
374 new_mode = parameter_s.strip().capitalize()
386 new_mode = parameter_s.strip().capitalize()
375 try:
387 try:
376 shell.InteractiveTB.set_mode(mode=new_mode)
388 shell.InteractiveTB.set_mode(mode=new_mode)
377 print('Exception reporting mode:',shell.InteractiveTB.mode)
389 print('Exception reporting mode:',shell.InteractiveTB.mode)
378 except:
390 except:
379 xmode_switch_err('user')
391 xmode_switch_err('user')
380
392
381 @line_magic
393 @line_magic
382 def quickref(self, arg):
394 def quickref(self, arg):
383 """ Show a quick reference sheet """
395 """ Show a quick reference sheet """
384 from IPython.core.usage import quick_reference
396 from IPython.core.usage import quick_reference
385 qr = quick_reference + self._magic_docs(brief=True)
397 qr = quick_reference + self._magic_docs(brief=True)
386 page.page(qr)
398 page.page(qr)
387
399
388 @line_magic
400 @line_magic
389 def doctest_mode(self, parameter_s=''):
401 def doctest_mode(self, parameter_s=''):
390 """Toggle doctest mode on and off.
402 """Toggle doctest mode on and off.
391
403
392 This mode is intended to make IPython behave as much as possible like a
404 This mode is intended to make IPython behave as much as possible like a
393 plain Python shell, from the perspective of how its prompts, exceptions
405 plain Python shell, from the perspective of how its prompts, exceptions
394 and output look. This makes it easy to copy and paste parts of a
406 and output look. This makes it easy to copy and paste parts of a
395 session into doctests. It does so by:
407 session into doctests. It does so by:
396
408
397 - Changing the prompts to the classic ``>>>`` ones.
409 - Changing the prompts to the classic ``>>>`` ones.
398 - Changing the exception reporting mode to 'Plain'.
410 - Changing the exception reporting mode to 'Plain'.
399 - Disabling pretty-printing of output.
411 - Disabling pretty-printing of output.
400
412
401 Note that IPython also supports the pasting of code snippets that have
413 Note that IPython also supports the pasting of code snippets that have
402 leading '>>>' and '...' prompts in them. This means that you can paste
414 leading '>>>' and '...' prompts in them. This means that you can paste
403 doctests from files or docstrings (even if they have leading
415 doctests from files or docstrings (even if they have leading
404 whitespace), and the code will execute correctly. You can then use
416 whitespace), and the code will execute correctly. You can then use
405 '%history -t' to see the translated history; this will give you the
417 '%history -t' to see the translated history; this will give you the
406 input after removal of all the leading prompts and whitespace, which
418 input after removal of all the leading prompts and whitespace, which
407 can be pasted back into an editor.
419 can be pasted back into an editor.
408
420
409 With these features, you can switch into this mode easily whenever you
421 With these features, you can switch into this mode easily whenever you
410 need to do testing and changes to doctests, without having to leave
422 need to do testing and changes to doctests, without having to leave
411 your existing IPython session.
423 your existing IPython session.
412 """
424 """
413
425
414 # Shorthands
426 # Shorthands
415 shell = self.shell
427 shell = self.shell
416 meta = shell.meta
428 meta = shell.meta
417 disp_formatter = self.shell.display_formatter
429 disp_formatter = self.shell.display_formatter
418 ptformatter = disp_formatter.formatters['text/plain']
430 ptformatter = disp_formatter.formatters['text/plain']
419 # dstore is a data store kept in the instance metadata bag to track any
431 # dstore is a data store kept in the instance metadata bag to track any
420 # changes we make, so we can undo them later.
432 # changes we make, so we can undo them later.
421 dstore = meta.setdefault('doctest_mode',Struct())
433 dstore = meta.setdefault('doctest_mode',Struct())
422 save_dstore = dstore.setdefault
434 save_dstore = dstore.setdefault
423
435
424 # save a few values we'll need to recover later
436 # save a few values we'll need to recover later
425 mode = save_dstore('mode',False)
437 mode = save_dstore('mode',False)
426 save_dstore('rc_pprint',ptformatter.pprint)
438 save_dstore('rc_pprint',ptformatter.pprint)
427 save_dstore('xmode',shell.InteractiveTB.mode)
439 save_dstore('xmode',shell.InteractiveTB.mode)
428 save_dstore('rc_separate_out',shell.separate_out)
440 save_dstore('rc_separate_out',shell.separate_out)
429 save_dstore('rc_separate_out2',shell.separate_out2)
441 save_dstore('rc_separate_out2',shell.separate_out2)
430 save_dstore('rc_separate_in',shell.separate_in)
442 save_dstore('rc_separate_in',shell.separate_in)
431 save_dstore('rc_active_types',disp_formatter.active_types)
443 save_dstore('rc_active_types',disp_formatter.active_types)
432
444
433 if not mode:
445 if not mode:
434 # turn on
446 # turn on
435
447
436 # Prompt separators like plain python
448 # Prompt separators like plain python
437 shell.separate_in = ''
449 shell.separate_in = ''
438 shell.separate_out = ''
450 shell.separate_out = ''
439 shell.separate_out2 = ''
451 shell.separate_out2 = ''
440
452
441
453
442 ptformatter.pprint = False
454 ptformatter.pprint = False
443 disp_formatter.active_types = ['text/plain']
455 disp_formatter.active_types = ['text/plain']
444
456
445 shell.magic('xmode Plain')
457 shell.magic('xmode Plain')
446 else:
458 else:
447 # turn off
459 # turn off
448 shell.separate_in = dstore.rc_separate_in
460 shell.separate_in = dstore.rc_separate_in
449
461
450 shell.separate_out = dstore.rc_separate_out
462 shell.separate_out = dstore.rc_separate_out
451 shell.separate_out2 = dstore.rc_separate_out2
463 shell.separate_out2 = dstore.rc_separate_out2
452
464
453 ptformatter.pprint = dstore.rc_pprint
465 ptformatter.pprint = dstore.rc_pprint
454 disp_formatter.active_types = dstore.rc_active_types
466 disp_formatter.active_types = dstore.rc_active_types
455
467
456 shell.magic('xmode ' + dstore.xmode)
468 shell.magic('xmode ' + dstore.xmode)
457
469
458 # mode here is the state before we switch; switch_doctest_mode takes
470 # mode here is the state before we switch; switch_doctest_mode takes
459 # the mode we're switching to.
471 # the mode we're switching to.
460 shell.switch_doctest_mode(not mode)
472 shell.switch_doctest_mode(not mode)
461
473
462 # Store new mode and inform
474 # Store new mode and inform
463 dstore.mode = bool(not mode)
475 dstore.mode = bool(not mode)
464 mode_label = ['OFF','ON'][dstore.mode]
476 mode_label = ['OFF','ON'][dstore.mode]
465 print('Doctest mode is:', mode_label)
477 print('Doctest mode is:', mode_label)
466
478
467 @line_magic
479 @line_magic
468 def gui(self, parameter_s=''):
480 def gui(self, parameter_s=''):
469 """Enable or disable IPython GUI event loop integration.
481 """Enable or disable IPython GUI event loop integration.
470
482
471 %gui [GUINAME]
483 %gui [GUINAME]
472
484
473 This magic replaces IPython's threaded shells that were activated
485 This magic replaces IPython's threaded shells that were activated
474 using the (pylab/wthread/etc.) command line flags. GUI toolkits
486 using the (pylab/wthread/etc.) command line flags. GUI toolkits
475 can now be enabled at runtime and keyboard
487 can now be enabled at runtime and keyboard
476 interrupts should work without any problems. The following toolkits
488 interrupts should work without any problems. The following toolkits
477 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
489 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
478
490
479 %gui wx # enable wxPython event loop integration
491 %gui wx # enable wxPython event loop integration
480 %gui qt4|qt # enable PyQt4 event loop integration
492 %gui qt4|qt # enable PyQt4 event loop integration
481 %gui qt5 # enable PyQt5 event loop integration
493 %gui qt5 # enable PyQt5 event loop integration
482 %gui gtk # enable PyGTK event loop integration
494 %gui gtk # enable PyGTK event loop integration
483 %gui gtk3 # enable Gtk3 event loop integration
495 %gui gtk3 # enable Gtk3 event loop integration
484 %gui tk # enable Tk event loop integration
496 %gui tk # enable Tk event loop integration
485 %gui osx # enable Cocoa event loop integration
497 %gui osx # enable Cocoa event loop integration
486 # (requires %matplotlib 1.1)
498 # (requires %matplotlib 1.1)
487 %gui # disable all event loop integration
499 %gui # disable all event loop integration
488
500
489 WARNING: after any of these has been called you can simply create
501 WARNING: after any of these has been called you can simply create
490 an application object, but DO NOT start the event loop yourself, as
502 an application object, but DO NOT start the event loop yourself, as
491 we have already handled that.
503 we have already handled that.
492 """
504 """
493 opts, arg = self.parse_options(parameter_s, '')
505 opts, arg = self.parse_options(parameter_s, '')
494 if arg=='': arg = None
506 if arg=='': arg = None
495 try:
507 try:
496 return self.shell.enable_gui(arg)
508 return self.shell.enable_gui(arg)
497 except Exception as e:
509 except Exception as e:
498 # print simple error message, rather than traceback if we can't
510 # print simple error message, rather than traceback if we can't
499 # hook up the GUI
511 # hook up the GUI
500 error(str(e))
512 error(str(e))
501
513
502 @skip_doctest
514 @skip_doctest
503 @line_magic
515 @line_magic
504 def precision(self, s=''):
516 def precision(self, s=''):
505 """Set floating point precision for pretty printing.
517 """Set floating point precision for pretty printing.
506
518
507 Can set either integer precision or a format string.
519 Can set either integer precision or a format string.
508
520
509 If numpy has been imported and precision is an int,
521 If numpy has been imported and precision is an int,
510 numpy display precision will also be set, via ``numpy.set_printoptions``.
522 numpy display precision will also be set, via ``numpy.set_printoptions``.
511
523
512 If no argument is given, defaults will be restored.
524 If no argument is given, defaults will be restored.
513
525
514 Examples
526 Examples
515 --------
527 --------
516 ::
528 ::
517
529
518 In [1]: from math import pi
530 In [1]: from math import pi
519
531
520 In [2]: %precision 3
532 In [2]: %precision 3
521 Out[2]: u'%.3f'
533 Out[2]: u'%.3f'
522
534
523 In [3]: pi
535 In [3]: pi
524 Out[3]: 3.142
536 Out[3]: 3.142
525
537
526 In [4]: %precision %i
538 In [4]: %precision %i
527 Out[4]: u'%i'
539 Out[4]: u'%i'
528
540
529 In [5]: pi
541 In [5]: pi
530 Out[5]: 3
542 Out[5]: 3
531
543
532 In [6]: %precision %e
544 In [6]: %precision %e
533 Out[6]: u'%e'
545 Out[6]: u'%e'
534
546
535 In [7]: pi**10
547 In [7]: pi**10
536 Out[7]: 9.364805e+04
548 Out[7]: 9.364805e+04
537
549
538 In [8]: %precision
550 In [8]: %precision
539 Out[8]: u'%r'
551 Out[8]: u'%r'
540
552
541 In [9]: pi**10
553 In [9]: pi**10
542 Out[9]: 93648.047476082982
554 Out[9]: 93648.047476082982
543 """
555 """
544 ptformatter = self.shell.display_formatter.formatters['text/plain']
556 ptformatter = self.shell.display_formatter.formatters['text/plain']
545 ptformatter.float_precision = s
557 ptformatter.float_precision = s
546 return ptformatter.float_format
558 return ptformatter.float_format
547
559
548 @magic_arguments.magic_arguments()
560 @magic_arguments.magic_arguments()
549 @magic_arguments.argument(
561 @magic_arguments.argument(
550 '-e', '--export', action='store_true', default=False,
562 '-e', '--export', action='store_true', default=False,
551 help=argparse.SUPPRESS
563 help=argparse.SUPPRESS
552 )
564 )
553 @magic_arguments.argument(
565 @magic_arguments.argument(
554 'filename', type=str,
566 'filename', type=str,
555 help='Notebook name or filename'
567 help='Notebook name or filename'
556 )
568 )
557 @line_magic
569 @line_magic
558 def notebook(self, s):
570 def notebook(self, s):
559 """Export and convert IPython notebooks.
571 """Export and convert IPython notebooks.
560
572
561 This function can export the current IPython history to a notebook file.
573 This function can export the current IPython history to a notebook file.
562 For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb".
574 For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb".
563
575
564 The -e or --export flag is deprecated in IPython 5.2, and will be
576 The -e or --export flag is deprecated in IPython 5.2, and will be
565 removed in the future.
577 removed in the future.
566 """
578 """
567 args = magic_arguments.parse_argstring(self.notebook, s)
579 args = magic_arguments.parse_argstring(self.notebook, s)
568
580
569 from nbformat import write, v4
581 from nbformat import write, v4
570
582
571 cells = []
583 cells = []
572 hist = list(self.shell.history_manager.get_range())
584 hist = list(self.shell.history_manager.get_range())
573 if(len(hist)<=1):
585 if(len(hist)<=1):
574 raise ValueError('History is empty, cannot export')
586 raise ValueError('History is empty, cannot export')
575 for session, execution_count, source in hist[:-1]:
587 for session, execution_count, source in hist[:-1]:
576 cells.append(v4.new_code_cell(
588 cells.append(v4.new_code_cell(
577 execution_count=execution_count,
589 execution_count=execution_count,
578 source=source
590 source=source
579 ))
591 ))
580 nb = v4.new_notebook(cells=cells)
592 nb = v4.new_notebook(cells=cells)
581 with io.open(args.filename, 'w', encoding='utf-8') as f:
593 with io.open(args.filename, 'w', encoding='utf-8') as f:
582 write(nb, f, version=4)
594 write(nb, f, version=4)
583
595
584 @magics_class
596 @magics_class
585 class AsyncMagics(BasicMagics):
597 class AsyncMagics(BasicMagics):
586
598
587 @line_magic
599 @line_magic
588 def autoawait(self, parameter_s):
600 def autoawait(self, parameter_s):
589 """
601 """
590 Allow to change the status of the autoawait option.
602 Allow to change the status of the autoawait option.
591
603
592 This allow you to set a specific asynchronous code runner.
604 This allow you to set a specific asynchronous code runner.
593
605
594 If no value is passed, print the currently used asynchronous integration
606 If no value is passed, print the currently used asynchronous integration
595 and whether it is activated.
607 and whether it is activated.
596
608
597 It can take a number of value evaluated in the following order:
609 It can take a number of value evaluated in the following order:
598
610
599 - False/false/off deactivate autoawait integration
611 - False/false/off deactivate autoawait integration
600 - True/true/on activate autoawait integration using configured default
612 - True/true/on activate autoawait integration using configured default
601 loop
613 loop
602 - asyncio/curio/trio activate autoawait integration and use integration
614 - asyncio/curio/trio activate autoawait integration and use integration
603 with said library.
615 with said library.
604
616
605 - `sync` turn on the pseudo-sync integration (mostly used for
617 - `sync` turn on the pseudo-sync integration (mostly used for
606 `IPython.embed()` which does not run IPython with a real eventloop and
618 `IPython.embed()` which does not run IPython with a real eventloop and
607 deactivate running asynchronous code. Turning on Asynchronous code with
619 deactivate running asynchronous code. Turning on Asynchronous code with
608 the pseudo sync loop is undefined behavior and may lead IPython to crash.
620 the pseudo sync loop is undefined behavior and may lead IPython to crash.
609
621
610 If the passed parameter does not match any of the above and is a python
622 If the passed parameter does not match any of the above and is a python
611 identifier, get said object from user namespace and set it as the
623 identifier, get said object from user namespace and set it as the
612 runner, and activate autoawait.
624 runner, and activate autoawait.
613
625
614 If the object is a fully qualified object name, attempt to import it and
626 If the object is a fully qualified object name, attempt to import it and
615 set it as the runner, and activate autoawait.
627 set it as the runner, and activate autoawait.
616
628
617
629
618 The exact behavior of autoawait is experimental and subject to change
630 The exact behavior of autoawait is experimental and subject to change
619 across version of IPython and Python.
631 across version of IPython and Python.
620 """
632 """
621
633
622 param = parameter_s.strip()
634 param = parameter_s.strip()
623 d = {True: "on", False: "off"}
635 d = {True: "on", False: "off"}
624
636
625 if not param:
637 if not param:
626 print("IPython autoawait is `{}`, and set to use `{}`".format(
638 print("IPython autoawait is `{}`, and set to use `{}`".format(
627 d[self.shell.autoawait],
639 d[self.shell.autoawait],
628 self.shell.loop_runner
640 self.shell.loop_runner
629 ))
641 ))
630 return None
642 return None
631
643
632 if param.lower() in ('false', 'off'):
644 if param.lower() in ('false', 'off'):
633 self.shell.autoawait = False
645 self.shell.autoawait = False
634 return None
646 return None
635 if param.lower() in ('true', 'on'):
647 if param.lower() in ('true', 'on'):
636 self.shell.autoawait = True
648 self.shell.autoawait = True
637 return None
649 return None
638
650
639 if param in self.shell.loop_runner_map:
651 if param in self.shell.loop_runner_map:
640 self.shell.loop_runner, self.shell.autoawait = self.shell.loop_runner_map[param]
652 self.shell.loop_runner, self.shell.autoawait = self.shell.loop_runner_map[param]
641 return None
653 return None
642
654
643 if param in self.shell.user_ns :
655 if param in self.shell.user_ns :
644 self.shell.loop_runner = self.shell.user_ns[param]
656 self.shell.loop_runner = self.shell.user_ns[param]
645 self.shell.autoawait = True
657 self.shell.autoawait = True
646 return None
658 return None
647
659
648 runner = import_item(param)
660 runner = import_item(param)
649
661
650 self.shell.loop_runner = runner
662 self.shell.loop_runner = runner
651 self.shell.autoawait = True
663 self.shell.autoawait = True
@@ -1,256 +1,326 b''
1 """Tests for debugging machinery.
1 """Tests for debugging machinery.
2 """
2 """
3
3
4 # Copyright (c) IPython Development Team.
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
5 # Distributed under the terms of the Modified BSD License.
6
6
7 import bdb
8 import builtins
9 import os
7 import signal
10 import signal
11 import subprocess
8 import sys
12 import sys
9 import time
13 import time
10 import warnings
14 import warnings
15 from subprocess import PIPE, CalledProcessError, check_output
11 from tempfile import NamedTemporaryFile
16 from tempfile import NamedTemporaryFile
12 from subprocess import check_output, CalledProcessError, PIPE
17 from textwrap import dedent
13 import subprocess
14 from unittest.mock import patch
18 from unittest.mock import patch
15 import builtins
16 import bdb
17
19
18 import nose.tools as nt
20 import nose.tools as nt
19
21
20 from IPython.core import debugger
22 from IPython.core import debugger
23 from IPython.testing import IPYTHON_TESTING_TIMEOUT_SCALE
24 from IPython.testing.decorators import skip_win32
21
25
22 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
23 # Helper classes, from CPython's Pdb test suite
27 # Helper classes, from CPython's Pdb test suite
24 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
25
29
26 class _FakeInput(object):
30 class _FakeInput(object):
27 """
31 """
28 A fake input stream for pdb's interactive debugger. Whenever a
32 A fake input stream for pdb's interactive debugger. Whenever a
29 line is read, print it (to simulate the user typing it), and then
33 line is read, print it (to simulate the user typing it), and then
30 return it. The set of lines to return is specified in the
34 return it. The set of lines to return is specified in the
31 constructor; they should not have trailing newlines.
35 constructor; they should not have trailing newlines.
32 """
36 """
33 def __init__(self, lines):
37 def __init__(self, lines):
34 self.lines = iter(lines)
38 self.lines = iter(lines)
35
39
36 def readline(self):
40 def readline(self):
37 line = next(self.lines)
41 line = next(self.lines)
38 print(line)
42 print(line)
39 return line+'\n'
43 return line+'\n'
40
44
41 class PdbTestInput(object):
45 class PdbTestInput(object):
42 """Context manager that makes testing Pdb in doctests easier."""
46 """Context manager that makes testing Pdb in doctests easier."""
43
47
44 def __init__(self, input):
48 def __init__(self, input):
45 self.input = input
49 self.input = input
46
50
47 def __enter__(self):
51 def __enter__(self):
48 self.real_stdin = sys.stdin
52 self.real_stdin = sys.stdin
49 sys.stdin = _FakeInput(self.input)
53 sys.stdin = _FakeInput(self.input)
50
54
51 def __exit__(self, *exc):
55 def __exit__(self, *exc):
52 sys.stdin = self.real_stdin
56 sys.stdin = self.real_stdin
53
57
54 #-----------------------------------------------------------------------------
58 #-----------------------------------------------------------------------------
55 # Tests
59 # Tests
56 #-----------------------------------------------------------------------------
60 #-----------------------------------------------------------------------------
57
61
58 def test_longer_repr():
62 def test_longer_repr():
59 try:
63 try:
60 from reprlib import repr as trepr # Py 3
64 from reprlib import repr as trepr # Py 3
61 except ImportError:
65 except ImportError:
62 from repr import repr as trepr # Py 2
66 from repr import repr as trepr # Py 2
63
67
64 a = '1234567890'* 7
68 a = '1234567890'* 7
65 ar = "'1234567890123456789012345678901234567890123456789012345678901234567890'"
69 ar = "'1234567890123456789012345678901234567890123456789012345678901234567890'"
66 a_trunc = "'123456789012...8901234567890'"
70 a_trunc = "'123456789012...8901234567890'"
67 nt.assert_equal(trepr(a), a_trunc)
71 nt.assert_equal(trepr(a), a_trunc)
68 # The creation of our tracer modifies the repr module's repr function
72 # The creation of our tracer modifies the repr module's repr function
69 # in-place, since that global is used directly by the stdlib's pdb module.
73 # in-place, since that global is used directly by the stdlib's pdb module.
70 with warnings.catch_warnings():
74 with warnings.catch_warnings():
71 warnings.simplefilter('ignore', DeprecationWarning)
75 warnings.simplefilter('ignore', DeprecationWarning)
72 debugger.Tracer()
76 debugger.Tracer()
73 nt.assert_equal(trepr(a), ar)
77 nt.assert_equal(trepr(a), ar)
74
78
75 def test_ipdb_magics():
79 def test_ipdb_magics():
76 '''Test calling some IPython magics from ipdb.
80 '''Test calling some IPython magics from ipdb.
77
81
78 First, set up some test functions and classes which we can inspect.
82 First, set up some test functions and classes which we can inspect.
79
83
80 >>> class ExampleClass(object):
84 >>> class ExampleClass(object):
81 ... """Docstring for ExampleClass."""
85 ... """Docstring for ExampleClass."""
82 ... def __init__(self):
86 ... def __init__(self):
83 ... """Docstring for ExampleClass.__init__"""
87 ... """Docstring for ExampleClass.__init__"""
84 ... pass
88 ... pass
85 ... def __str__(self):
89 ... def __str__(self):
86 ... return "ExampleClass()"
90 ... return "ExampleClass()"
87
91
88 >>> def example_function(x, y, z="hello"):
92 >>> def example_function(x, y, z="hello"):
89 ... """Docstring for example_function."""
93 ... """Docstring for example_function."""
90 ... pass
94 ... pass
91
95
92 >>> old_trace = sys.gettrace()
96 >>> old_trace = sys.gettrace()
93
97
94 Create a function which triggers ipdb.
98 Create a function which triggers ipdb.
95
99
96 >>> def trigger_ipdb():
100 >>> def trigger_ipdb():
97 ... a = ExampleClass()
101 ... a = ExampleClass()
98 ... debugger.Pdb().set_trace()
102 ... debugger.Pdb().set_trace()
99
103
100 >>> with PdbTestInput([
104 >>> with PdbTestInput([
101 ... 'pdef example_function',
105 ... 'pdef example_function',
102 ... 'pdoc ExampleClass',
106 ... 'pdoc ExampleClass',
103 ... 'up',
107 ... 'up',
104 ... 'down',
108 ... 'down',
105 ... 'list',
109 ... 'list',
106 ... 'pinfo a',
110 ... 'pinfo a',
107 ... 'll',
111 ... 'll',
108 ... 'continue',
112 ... 'continue',
109 ... ]):
113 ... ]):
110 ... trigger_ipdb()
114 ... trigger_ipdb()
111 --Return--
115 --Return--
112 None
116 None
113 > <doctest ...>(3)trigger_ipdb()
117 > <doctest ...>(3)trigger_ipdb()
114 1 def trigger_ipdb():
118 1 def trigger_ipdb():
115 2 a = ExampleClass()
119 2 a = ExampleClass()
116 ----> 3 debugger.Pdb().set_trace()
120 ----> 3 debugger.Pdb().set_trace()
117 <BLANKLINE>
121 <BLANKLINE>
118 ipdb> pdef example_function
122 ipdb> pdef example_function
119 example_function(x, y, z='hello')
123 example_function(x, y, z='hello')
120 ipdb> pdoc ExampleClass
124 ipdb> pdoc ExampleClass
121 Class docstring:
125 Class docstring:
122 Docstring for ExampleClass.
126 Docstring for ExampleClass.
123 Init docstring:
127 Init docstring:
124 Docstring for ExampleClass.__init__
128 Docstring for ExampleClass.__init__
125 ipdb> up
129 ipdb> up
126 > <doctest ...>(11)<module>()
130 > <doctest ...>(11)<module>()
127 7 'pinfo a',
131 7 'pinfo a',
128 8 'll',
132 8 'll',
129 9 'continue',
133 9 'continue',
130 10 ]):
134 10 ]):
131 ---> 11 trigger_ipdb()
135 ---> 11 trigger_ipdb()
132 <BLANKLINE>
136 <BLANKLINE>
133 ipdb> down
137 ipdb> down
134 None
138 None
135 > <doctest ...>(3)trigger_ipdb()
139 > <doctest ...>(3)trigger_ipdb()
136 1 def trigger_ipdb():
140 1 def trigger_ipdb():
137 2 a = ExampleClass()
141 2 a = ExampleClass()
138 ----> 3 debugger.Pdb().set_trace()
142 ----> 3 debugger.Pdb().set_trace()
139 <BLANKLINE>
143 <BLANKLINE>
140 ipdb> list
144 ipdb> list
141 1 def trigger_ipdb():
145 1 def trigger_ipdb():
142 2 a = ExampleClass()
146 2 a = ExampleClass()
143 ----> 3 debugger.Pdb().set_trace()
147 ----> 3 debugger.Pdb().set_trace()
144 <BLANKLINE>
148 <BLANKLINE>
145 ipdb> pinfo a
149 ipdb> pinfo a
146 Type: ExampleClass
150 Type: ExampleClass
147 String form: ExampleClass()
151 String form: ExampleClass()
148 Namespace: Local...
152 Namespace: Local...
149 Docstring: Docstring for ExampleClass.
153 Docstring: Docstring for ExampleClass.
150 Init docstring: Docstring for ExampleClass.__init__
154 Init docstring: Docstring for ExampleClass.__init__
151 ipdb> ll
155 ipdb> ll
152 1 def trigger_ipdb():
156 1 def trigger_ipdb():
153 2 a = ExampleClass()
157 2 a = ExampleClass()
154 ----> 3 debugger.Pdb().set_trace()
158 ----> 3 debugger.Pdb().set_trace()
155 <BLANKLINE>
159 <BLANKLINE>
156 ipdb> continue
160 ipdb> continue
157
161
158 Restore previous trace function, e.g. for coverage.py
162 Restore previous trace function, e.g. for coverage.py
159
163
160 >>> sys.settrace(old_trace)
164 >>> sys.settrace(old_trace)
161 '''
165 '''
162
166
163 def test_ipdb_magics2():
167 def test_ipdb_magics2():
164 '''Test ipdb with a very short function.
168 '''Test ipdb with a very short function.
165
169
166 >>> old_trace = sys.gettrace()
170 >>> old_trace = sys.gettrace()
167
171
168 >>> def bar():
172 >>> def bar():
169 ... pass
173 ... pass
170
174
171 Run ipdb.
175 Run ipdb.
172
176
173 >>> with PdbTestInput([
177 >>> with PdbTestInput([
174 ... 'continue',
178 ... 'continue',
175 ... ]):
179 ... ]):
176 ... debugger.Pdb().runcall(bar)
180 ... debugger.Pdb().runcall(bar)
177 > <doctest ...>(2)bar()
181 > <doctest ...>(2)bar()
178 1 def bar():
182 1 def bar():
179 ----> 2 pass
183 ----> 2 pass
180 <BLANKLINE>
184 <BLANKLINE>
181 ipdb> continue
185 ipdb> continue
182
186
183 Restore previous trace function, e.g. for coverage.py
187 Restore previous trace function, e.g. for coverage.py
184
188
185 >>> sys.settrace(old_trace)
189 >>> sys.settrace(old_trace)
186 '''
190 '''
187
191
188 def can_quit():
192 def can_quit():
189 '''Test that quit work in ipydb
193 '''Test that quit work in ipydb
190
194
191 >>> old_trace = sys.gettrace()
195 >>> old_trace = sys.gettrace()
192
196
193 >>> def bar():
197 >>> def bar():
194 ... pass
198 ... pass
195
199
196 >>> with PdbTestInput([
200 >>> with PdbTestInput([
197 ... 'quit',
201 ... 'quit',
198 ... ]):
202 ... ]):
199 ... debugger.Pdb().runcall(bar)
203 ... debugger.Pdb().runcall(bar)
200 > <doctest ...>(2)bar()
204 > <doctest ...>(2)bar()
201 1 def bar():
205 1 def bar():
202 ----> 2 pass
206 ----> 2 pass
203 <BLANKLINE>
207 <BLANKLINE>
204 ipdb> quit
208 ipdb> quit
205
209
206 Restore previous trace function, e.g. for coverage.py
210 Restore previous trace function, e.g. for coverage.py
207
211
208 >>> sys.settrace(old_trace)
212 >>> sys.settrace(old_trace)
209 '''
213 '''
210
214
211
215
212 def can_exit():
216 def can_exit():
213 '''Test that quit work in ipydb
217 '''Test that quit work in ipydb
214
218
215 >>> old_trace = sys.gettrace()
219 >>> old_trace = sys.gettrace()
216
220
217 >>> def bar():
221 >>> def bar():
218 ... pass
222 ... pass
219
223
220 >>> with PdbTestInput([
224 >>> with PdbTestInput([
221 ... 'exit',
225 ... 'exit',
222 ... ]):
226 ... ]):
223 ... debugger.Pdb().runcall(bar)
227 ... debugger.Pdb().runcall(bar)
224 > <doctest ...>(2)bar()
228 > <doctest ...>(2)bar()
225 1 def bar():
229 1 def bar():
226 ----> 2 pass
230 ----> 2 pass
227 <BLANKLINE>
231 <BLANKLINE>
228 ipdb> exit
232 ipdb> exit
229
233
230 Restore previous trace function, e.g. for coverage.py
234 Restore previous trace function, e.g. for coverage.py
231
235
232 >>> sys.settrace(old_trace)
236 >>> sys.settrace(old_trace)
233 '''
237 '''
234
238
235
239
236 def test_interruptible_core_debugger():
240 def test_interruptible_core_debugger():
237 """The debugger can be interrupted.
241 """The debugger can be interrupted.
238
242
239 The presumption is there is some mechanism that causes a KeyboardInterrupt
243 The presumption is there is some mechanism that causes a KeyboardInterrupt
240 (this is implemented in ipykernel). We want to ensure the
244 (this is implemented in ipykernel). We want to ensure the
241 KeyboardInterrupt cause debugging to cease.
245 KeyboardInterrupt cause debugging to cease.
242 """
246 """
243 def raising_input(msg="", called=[0]):
247 def raising_input(msg="", called=[0]):
244 called[0] += 1
248 called[0] += 1
245 if called[0] == 1:
249 if called[0] == 1:
246 raise KeyboardInterrupt()
250 raise KeyboardInterrupt()
247 else:
251 else:
248 raise AssertionError("input() should only be called once!")
252 raise AssertionError("input() should only be called once!")
249
253
250 with patch.object(builtins, "input", raising_input):
254 with patch.object(builtins, "input", raising_input):
251 debugger.InterruptiblePdb().set_trace()
255 debugger.InterruptiblePdb().set_trace()
252 # The way this test will fail is by set_trace() never exiting,
256 # The way this test will fail is by set_trace() never exiting,
253 # resulting in a timeout by the test runner. The alternative
257 # resulting in a timeout by the test runner. The alternative
254 # implementation would involve a subprocess, but that adds issues with
258 # implementation would involve a subprocess, but that adds issues with
255 # interrupting subprocesses that are rather complex, so it's simpler
259 # interrupting subprocesses that are rather complex, so it's simpler
256 # just to do it this way.
260 # just to do it this way.
261
262 @skip_win32
263 def test_xmode_skip():
264 """that xmode skip frames
265
266 Not as a doctest as pytest does not run doctests.
267 """
268 import pexpect
269 env = os.environ.copy()
270 env["IPY_TEST_SIMPLE_PROMPT"] = "1"
271
272 child = pexpect.spawn(
273 sys.executable, ["-m", "IPython", "--colors=nocolor"], env=env
274 )
275 child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE
276
277 child.expect("IPython")
278 child.expect("\n")
279 child.expect_exact("In [1]")
280
281 block = dedent(
282 """
283 def f():
284 __tracebackhide__ = True
285 g()
286
287 def g():
288 raise ValueError
289
290 f()
291 """
292 )
293
294 for line in block.splitlines():
295 child.sendline(line)
296 child.expect_exact(line)
297 child.expect_exact("skipping")
298
299 block = dedent(
300 """
301 def f():
302 __tracebackhide__ = True
303 g()
304
305 def g():
306 from IPython.core.debugger import set_trace
307 set_trace()
308
309 f()
310 """
311 )
312
313 for line in block.splitlines():
314 child.sendline(line)
315 child.expect_exact(line)
316
317 child.expect("ipdb>")
318 child.sendline("w")
319 child.expect("hidden")
320 child.expect("ipdb>")
321 child.sendline("skip_hidden false")
322 child.sendline("w")
323 child.expect("__traceba")
324 child.expect("ipdb>")
325
326 child.close()
@@ -1,1503 +1,1524 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Verbose and colourful traceback formatting.
3 Verbose and colourful traceback formatting.
4
4
5 **ColorTB**
5 **ColorTB**
6
6
7 I've always found it a bit hard to visually parse tracebacks in Python. The
7 I've always found it a bit hard to visually parse tracebacks in Python. The
8 ColorTB class is a solution to that problem. It colors the different parts of a
8 ColorTB class is a solution to that problem. It colors the different parts of a
9 traceback in a manner similar to what you would expect from a syntax-highlighting
9 traceback in a manner similar to what you would expect from a syntax-highlighting
10 text editor.
10 text editor.
11
11
12 Installation instructions for ColorTB::
12 Installation instructions for ColorTB::
13
13
14 import sys,ultratb
14 import sys,ultratb
15 sys.excepthook = ultratb.ColorTB()
15 sys.excepthook = ultratb.ColorTB()
16
16
17 **VerboseTB**
17 **VerboseTB**
18
18
19 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
19 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
20 of useful info when a traceback occurs. Ping originally had it spit out HTML
20 of useful info when a traceback occurs. Ping originally had it spit out HTML
21 and intended it for CGI programmers, but why should they have all the fun? I
21 and intended it for CGI programmers, but why should they have all the fun? I
22 altered it to spit out colored text to the terminal. It's a bit overwhelming,
22 altered it to spit out colored text to the terminal. It's a bit overwhelming,
23 but kind of neat, and maybe useful for long-running programs that you believe
23 but kind of neat, and maybe useful for long-running programs that you believe
24 are bug-free. If a crash *does* occur in that type of program you want details.
24 are bug-free. If a crash *does* occur in that type of program you want details.
25 Give it a shot--you'll love it or you'll hate it.
25 Give it a shot--you'll love it or you'll hate it.
26
26
27 .. note::
27 .. note::
28
28
29 The Verbose mode prints the variables currently visible where the exception
29 The Verbose mode prints the variables currently visible where the exception
30 happened (shortening their strings if too long). This can potentially be
30 happened (shortening their strings if too long). This can potentially be
31 very slow, if you happen to have a huge data structure whose string
31 very slow, if you happen to have a huge data structure whose string
32 representation is complex to compute. Your computer may appear to freeze for
32 representation is complex to compute. Your computer may appear to freeze for
33 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
33 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
34 with Ctrl-C (maybe hitting it more than once).
34 with Ctrl-C (maybe hitting it more than once).
35
35
36 If you encounter this kind of situation often, you may want to use the
36 If you encounter this kind of situation often, you may want to use the
37 Verbose_novars mode instead of the regular Verbose, which avoids formatting
37 Verbose_novars mode instead of the regular Verbose, which avoids formatting
38 variables (but otherwise includes the information and context given by
38 variables (but otherwise includes the information and context given by
39 Verbose).
39 Verbose).
40
40
41 .. note::
41 .. note::
42
42
43 The verbose mode print all variables in the stack, which means it can
43 The verbose mode print all variables in the stack, which means it can
44 potentially leak sensitive information like access keys, or unencrypted
44 potentially leak sensitive information like access keys, or unencrypted
45 password.
45 password.
46
46
47 Installation instructions for VerboseTB::
47 Installation instructions for VerboseTB::
48
48
49 import sys,ultratb
49 import sys,ultratb
50 sys.excepthook = ultratb.VerboseTB()
50 sys.excepthook = ultratb.VerboseTB()
51
51
52 Note: Much of the code in this module was lifted verbatim from the standard
52 Note: Much of the code in this module was lifted verbatim from the standard
53 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
53 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
54
54
55 Color schemes
55 Color schemes
56 -------------
56 -------------
57
57
58 The colors are defined in the class TBTools through the use of the
58 The colors are defined in the class TBTools through the use of the
59 ColorSchemeTable class. Currently the following exist:
59 ColorSchemeTable class. Currently the following exist:
60
60
61 - NoColor: allows all of this module to be used in any terminal (the color
61 - NoColor: allows all of this module to be used in any terminal (the color
62 escapes are just dummy blank strings).
62 escapes are just dummy blank strings).
63
63
64 - Linux: is meant to look good in a terminal like the Linux console (black
64 - Linux: is meant to look good in a terminal like the Linux console (black
65 or very dark background).
65 or very dark background).
66
66
67 - LightBG: similar to Linux but swaps dark/light colors to be more readable
67 - LightBG: similar to Linux but swaps dark/light colors to be more readable
68 in light background terminals.
68 in light background terminals.
69
69
70 - Neutral: a neutral color scheme that should be readable on both light and
70 - Neutral: a neutral color scheme that should be readable on both light and
71 dark background
71 dark background
72
72
73 You can implement other color schemes easily, the syntax is fairly
73 You can implement other color schemes easily, the syntax is fairly
74 self-explanatory. Please send back new schemes you develop to the author for
74 self-explanatory. Please send back new schemes you develop to the author for
75 possible inclusion in future releases.
75 possible inclusion in future releases.
76
76
77 Inheritance diagram:
77 Inheritance diagram:
78
78
79 .. inheritance-diagram:: IPython.core.ultratb
79 .. inheritance-diagram:: IPython.core.ultratb
80 :parts: 3
80 :parts: 3
81 """
81 """
82
82
83 #*****************************************************************************
83 #*****************************************************************************
84 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
84 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
85 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
85 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
86 #
86 #
87 # Distributed under the terms of the BSD License. The full license is in
87 # Distributed under the terms of the BSD License. The full license is in
88 # the file COPYING, distributed as part of this software.
88 # the file COPYING, distributed as part of this software.
89 #*****************************************************************************
89 #*****************************************************************************
90
90
91
91
92 import dis
92 import dis
93 import inspect
93 import inspect
94 import keyword
94 import keyword
95 import linecache
95 import linecache
96 import os
96 import os
97 import pydoc
97 import pydoc
98 import re
98 import re
99 import sys
99 import sys
100 import time
100 import time
101 import tokenize
101 import tokenize
102 import traceback
102 import traceback
103
103
104 from tokenize import generate_tokens
104 from tokenize import generate_tokens
105
105
106 # For purposes of monkeypatching inspect to fix a bug in it.
106 # For purposes of monkeypatching inspect to fix a bug in it.
107 from inspect import getsourcefile, getfile, getmodule, \
107 from inspect import getsourcefile, getfile, getmodule, \
108 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
108 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
109
109
110 # IPython's own modules
110 # IPython's own modules
111 from IPython import get_ipython
111 from IPython import get_ipython
112 from IPython.core import debugger
112 from IPython.core import debugger
113 from IPython.core.display_trap import DisplayTrap
113 from IPython.core.display_trap import DisplayTrap
114 from IPython.core.excolors import exception_colors
114 from IPython.core.excolors import exception_colors
115 from IPython.utils import PyColorize
115 from IPython.utils import PyColorize
116 from IPython.utils import path as util_path
116 from IPython.utils import path as util_path
117 from IPython.utils import py3compat
117 from IPython.utils import py3compat
118 from IPython.utils.data import uniq_stable
118 from IPython.utils.data import uniq_stable
119 from IPython.utils.terminal import get_terminal_size
119 from IPython.utils.terminal import get_terminal_size
120
120
121 from logging import info, error, debug
121 from logging import info, error, debug
122
122
123 from importlib.util import source_from_cache
123 from importlib.util import source_from_cache
124
124
125 import IPython.utils.colorable as colorable
125 import IPython.utils.colorable as colorable
126
126
127 # Globals
127 # Globals
128 # amount of space to put line numbers before verbose tracebacks
128 # amount of space to put line numbers before verbose tracebacks
129 INDENT_SIZE = 8
129 INDENT_SIZE = 8
130
130
131 # Default color scheme. This is used, for example, by the traceback
131 # Default color scheme. This is used, for example, by the traceback
132 # formatter. When running in an actual IPython instance, the user's rc.colors
132 # formatter. When running in an actual IPython instance, the user's rc.colors
133 # value is used, but having a module global makes this functionality available
133 # value is used, but having a module global makes this functionality available
134 # to users of ultratb who are NOT running inside ipython.
134 # to users of ultratb who are NOT running inside ipython.
135 DEFAULT_SCHEME = 'NoColor'
135 DEFAULT_SCHEME = 'NoColor'
136
136
137
137
138 # Number of frame above which we are likely to have a recursion and will
138 # Number of frame above which we are likely to have a recursion and will
139 # **attempt** to detect it. Made modifiable mostly to speedup test suite
139 # **attempt** to detect it. Made modifiable mostly to speedup test suite
140 # as detecting recursion is one of our slowest test
140 # as detecting recursion is one of our slowest test
141 _FRAME_RECURSION_LIMIT = 500
141 _FRAME_RECURSION_LIMIT = 500
142
142
143 # ---------------------------------------------------------------------------
143 # ---------------------------------------------------------------------------
144 # Code begins
144 # Code begins
145
145
146 # Utility functions
146 # Utility functions
147 def inspect_error():
147 def inspect_error():
148 """Print a message about internal inspect errors.
148 """Print a message about internal inspect errors.
149
149
150 These are unfortunately quite common."""
150 These are unfortunately quite common."""
151
151
152 error('Internal Python error in the inspect module.\n'
152 error('Internal Python error in the inspect module.\n'
153 'Below is the traceback from this internal error.\n')
153 'Below is the traceback from this internal error.\n')
154
154
155
155
156 # This function is a monkeypatch we apply to the Python inspect module. We have
156 # This function is a monkeypatch we apply to the Python inspect module. We have
157 # now found when it's needed (see discussion on issue gh-1456), and we have a
157 # now found when it's needed (see discussion on issue gh-1456), and we have a
158 # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
158 # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
159 # the monkeypatch is not applied. TK, Aug 2012.
159 # the monkeypatch is not applied. TK, Aug 2012.
160 def findsource(object):
160 def findsource(object):
161 """Return the entire source file and starting line number for an object.
161 """Return the entire source file and starting line number for an object.
162
162
163 The argument may be a module, class, method, function, traceback, frame,
163 The argument may be a module, class, method, function, traceback, frame,
164 or code object. The source code is returned as a list of all the lines
164 or code object. The source code is returned as a list of all the lines
165 in the file and the line number indexes a line in that list. An IOError
165 in the file and the line number indexes a line in that list. An IOError
166 is raised if the source code cannot be retrieved.
166 is raised if the source code cannot be retrieved.
167
167
168 FIXED version with which we monkeypatch the stdlib to work around a bug."""
168 FIXED version with which we monkeypatch the stdlib to work around a bug."""
169
169
170 file = getsourcefile(object) or getfile(object)
170 file = getsourcefile(object) or getfile(object)
171 # If the object is a frame, then trying to get the globals dict from its
171 # If the object is a frame, then trying to get the globals dict from its
172 # module won't work. Instead, the frame object itself has the globals
172 # module won't work. Instead, the frame object itself has the globals
173 # dictionary.
173 # dictionary.
174 globals_dict = None
174 globals_dict = None
175 if inspect.isframe(object):
175 if inspect.isframe(object):
176 # XXX: can this ever be false?
176 # XXX: can this ever be false?
177 globals_dict = object.f_globals
177 globals_dict = object.f_globals
178 else:
178 else:
179 module = getmodule(object, file)
179 module = getmodule(object, file)
180 if module:
180 if module:
181 globals_dict = module.__dict__
181 globals_dict = module.__dict__
182 lines = linecache.getlines(file, globals_dict)
182 lines = linecache.getlines(file, globals_dict)
183 if not lines:
183 if not lines:
184 raise IOError('could not get source code')
184 raise IOError('could not get source code')
185
185
186 if ismodule(object):
186 if ismodule(object):
187 return lines, 0
187 return lines, 0
188
188
189 if isclass(object):
189 if isclass(object):
190 name = object.__name__
190 name = object.__name__
191 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
191 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
192 # make some effort to find the best matching class definition:
192 # make some effort to find the best matching class definition:
193 # use the one with the least indentation, which is the one
193 # use the one with the least indentation, which is the one
194 # that's most probably not inside a function definition.
194 # that's most probably not inside a function definition.
195 candidates = []
195 candidates = []
196 for i, line in enumerate(lines):
196 for i, line in enumerate(lines):
197 match = pat.match(line)
197 match = pat.match(line)
198 if match:
198 if match:
199 # if it's at toplevel, it's already the best one
199 # if it's at toplevel, it's already the best one
200 if line[0] == 'c':
200 if line[0] == 'c':
201 return lines, i
201 return lines, i
202 # else add whitespace to candidate list
202 # else add whitespace to candidate list
203 candidates.append((match.group(1), i))
203 candidates.append((match.group(1), i))
204 if candidates:
204 if candidates:
205 # this will sort by whitespace, and by line number,
205 # this will sort by whitespace, and by line number,
206 # less whitespace first
206 # less whitespace first
207 candidates.sort()
207 candidates.sort()
208 return lines, candidates[0][1]
208 return lines, candidates[0][1]
209 else:
209 else:
210 raise IOError('could not find class definition')
210 raise IOError('could not find class definition')
211
211
212 if ismethod(object):
212 if ismethod(object):
213 object = object.__func__
213 object = object.__func__
214 if isfunction(object):
214 if isfunction(object):
215 object = object.__code__
215 object = object.__code__
216 if istraceback(object):
216 if istraceback(object):
217 object = object.tb_frame
217 object = object.tb_frame
218 if isframe(object):
218 if isframe(object):
219 object = object.f_code
219 object = object.f_code
220 if iscode(object):
220 if iscode(object):
221 if not hasattr(object, 'co_firstlineno'):
221 if not hasattr(object, 'co_firstlineno'):
222 raise IOError('could not find function definition')
222 raise IOError('could not find function definition')
223 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
223 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
224 pmatch = pat.match
224 pmatch = pat.match
225 # fperez - fix: sometimes, co_firstlineno can give a number larger than
225 # fperez - fix: sometimes, co_firstlineno can give a number larger than
226 # the length of lines, which causes an error. Safeguard against that.
226 # the length of lines, which causes an error. Safeguard against that.
227 lnum = min(object.co_firstlineno, len(lines)) - 1
227 lnum = min(object.co_firstlineno, len(lines)) - 1
228 while lnum > 0:
228 while lnum > 0:
229 if pmatch(lines[lnum]):
229 if pmatch(lines[lnum]):
230 break
230 break
231 lnum -= 1
231 lnum -= 1
232
232
233 return lines, lnum
233 return lines, lnum
234 raise IOError('could not find code object')
234 raise IOError('could not find code object')
235
235
236
236
237 # This is a patched version of inspect.getargs that applies the (unmerged)
237 # This is a patched version of inspect.getargs that applies the (unmerged)
238 # patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes
238 # patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes
239 # https://github.com/ipython/ipython/issues/8205 and
239 # https://github.com/ipython/ipython/issues/8205 and
240 # https://github.com/ipython/ipython/issues/8293
240 # https://github.com/ipython/ipython/issues/8293
241 def getargs(co):
241 def getargs(co):
242 """Get information about the arguments accepted by a code object.
242 """Get information about the arguments accepted by a code object.
243
243
244 Three things are returned: (args, varargs, varkw), where 'args' is
244 Three things are returned: (args, varargs, varkw), where 'args' is
245 a list of argument names (possibly containing nested lists), and
245 a list of argument names (possibly containing nested lists), and
246 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
246 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
247 if not iscode(co):
247 if not iscode(co):
248 raise TypeError('{!r} is not a code object'.format(co))
248 raise TypeError('{!r} is not a code object'.format(co))
249
249
250 nargs = co.co_argcount
250 nargs = co.co_argcount
251 names = co.co_varnames
251 names = co.co_varnames
252 args = list(names[:nargs])
252 args = list(names[:nargs])
253 step = 0
253 step = 0
254
254
255 # The following acrobatics are for anonymous (tuple) arguments.
255 # The following acrobatics are for anonymous (tuple) arguments.
256 for i in range(nargs):
256 for i in range(nargs):
257 if args[i][:1] in ('', '.'):
257 if args[i][:1] in ('', '.'):
258 stack, remain, count = [], [], []
258 stack, remain, count = [], [], []
259 while step < len(co.co_code):
259 while step < len(co.co_code):
260 op = ord(co.co_code[step])
260 op = ord(co.co_code[step])
261 step = step + 1
261 step = step + 1
262 if op >= dis.HAVE_ARGUMENT:
262 if op >= dis.HAVE_ARGUMENT:
263 opname = dis.opname[op]
263 opname = dis.opname[op]
264 value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256
264 value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256
265 step = step + 2
265 step = step + 2
266 if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
266 if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
267 remain.append(value)
267 remain.append(value)
268 count.append(value)
268 count.append(value)
269 elif opname in ('STORE_FAST', 'STORE_DEREF'):
269 elif opname in ('STORE_FAST', 'STORE_DEREF'):
270 if op in dis.haslocal:
270 if op in dis.haslocal:
271 stack.append(co.co_varnames[value])
271 stack.append(co.co_varnames[value])
272 elif op in dis.hasfree:
272 elif op in dis.hasfree:
273 stack.append((co.co_cellvars + co.co_freevars)[value])
273 stack.append((co.co_cellvars + co.co_freevars)[value])
274 # Special case for sublists of length 1: def foo((bar))
274 # Special case for sublists of length 1: def foo((bar))
275 # doesn't generate the UNPACK_TUPLE bytecode, so if
275 # doesn't generate the UNPACK_TUPLE bytecode, so if
276 # `remain` is empty here, we have such a sublist.
276 # `remain` is empty here, we have such a sublist.
277 if not remain:
277 if not remain:
278 stack[0] = [stack[0]]
278 stack[0] = [stack[0]]
279 break
279 break
280 else:
280 else:
281 remain[-1] = remain[-1] - 1
281 remain[-1] = remain[-1] - 1
282 while remain[-1] == 0:
282 while remain[-1] == 0:
283 remain.pop()
283 remain.pop()
284 size = count.pop()
284 size = count.pop()
285 stack[-size:] = [stack[-size:]]
285 stack[-size:] = [stack[-size:]]
286 if not remain:
286 if not remain:
287 break
287 break
288 remain[-1] = remain[-1] - 1
288 remain[-1] = remain[-1] - 1
289 if not remain:
289 if not remain:
290 break
290 break
291 args[i] = stack[0]
291 args[i] = stack[0]
292
292
293 varargs = None
293 varargs = None
294 if co.co_flags & inspect.CO_VARARGS:
294 if co.co_flags & inspect.CO_VARARGS:
295 varargs = co.co_varnames[nargs]
295 varargs = co.co_varnames[nargs]
296 nargs = nargs + 1
296 nargs = nargs + 1
297 varkw = None
297 varkw = None
298 if co.co_flags & inspect.CO_VARKEYWORDS:
298 if co.co_flags & inspect.CO_VARKEYWORDS:
299 varkw = co.co_varnames[nargs]
299 varkw = co.co_varnames[nargs]
300 return inspect.Arguments(args, varargs, varkw)
300 return inspect.Arguments(args, varargs, varkw)
301
301
302
302
303 # Monkeypatch inspect to apply our bugfix.
303 # Monkeypatch inspect to apply our bugfix.
304 def with_patch_inspect(f):
304 def with_patch_inspect(f):
305 """
305 """
306 Deprecated since IPython 6.0
306 Deprecated since IPython 6.0
307 decorator for monkeypatching inspect.findsource
307 decorator for monkeypatching inspect.findsource
308 """
308 """
309
309
310 def wrapped(*args, **kwargs):
310 def wrapped(*args, **kwargs):
311 save_findsource = inspect.findsource
311 save_findsource = inspect.findsource
312 save_getargs = inspect.getargs
312 save_getargs = inspect.getargs
313 inspect.findsource = findsource
313 inspect.findsource = findsource
314 inspect.getargs = getargs
314 inspect.getargs = getargs
315 try:
315 try:
316 return f(*args, **kwargs)
316 return f(*args, **kwargs)
317 finally:
317 finally:
318 inspect.findsource = save_findsource
318 inspect.findsource = save_findsource
319 inspect.getargs = save_getargs
319 inspect.getargs = save_getargs
320
320
321 return wrapped
321 return wrapped
322
322
323
323
324 def fix_frame_records_filenames(records):
324 def fix_frame_records_filenames(records):
325 """Try to fix the filenames in each record from inspect.getinnerframes().
325 """Try to fix the filenames in each record from inspect.getinnerframes().
326
326
327 Particularly, modules loaded from within zip files have useless filenames
327 Particularly, modules loaded from within zip files have useless filenames
328 attached to their code object, and inspect.getinnerframes() just uses it.
328 attached to their code object, and inspect.getinnerframes() just uses it.
329 """
329 """
330 fixed_records = []
330 fixed_records = []
331 for frame, filename, line_no, func_name, lines, index in records:
331 for frame, filename, line_no, func_name, lines, index in records:
332 # Look inside the frame's globals dictionary for __file__,
332 # Look inside the frame's globals dictionary for __file__,
333 # which should be better. However, keep Cython filenames since
333 # which should be better. However, keep Cython filenames since
334 # we prefer the source filenames over the compiled .so file.
334 # we prefer the source filenames over the compiled .so file.
335 if not filename.endswith(('.pyx', '.pxd', '.pxi')):
335 if not filename.endswith(('.pyx', '.pxd', '.pxi')):
336 better_fn = frame.f_globals.get('__file__', None)
336 better_fn = frame.f_globals.get('__file__', None)
337 if isinstance(better_fn, str):
337 if isinstance(better_fn, str):
338 # Check the type just in case someone did something weird with
338 # Check the type just in case someone did something weird with
339 # __file__. It might also be None if the error occurred during
339 # __file__. It might also be None if the error occurred during
340 # import.
340 # import.
341 filename = better_fn
341 filename = better_fn
342 fixed_records.append((frame, filename, line_no, func_name, lines, index))
342 fixed_records.append((frame, filename, line_no, func_name, lines, index))
343 return fixed_records
343 return fixed_records
344
344
345
345
346 @with_patch_inspect
346 @with_patch_inspect
347 def _fixed_getinnerframes(etb, context=1, tb_offset=0):
347 def _fixed_getinnerframes(etb, context=1, tb_offset=0):
348 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
348 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
349
349
350 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
350 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
351 # If the error is at the console, don't build any context, since it would
351 # If the error is at the console, don't build any context, since it would
352 # otherwise produce 5 blank lines printed out (there is no file at the
352 # otherwise produce 5 blank lines printed out (there is no file at the
353 # console)
353 # console)
354 rec_check = records[tb_offset:]
354 rec_check = records[tb_offset:]
355 try:
355 try:
356 rname = rec_check[0][1]
356 rname = rec_check[0][1]
357 if rname == '<ipython console>' or rname.endswith('<string>'):
357 if rname == '<ipython console>' or rname.endswith('<string>'):
358 return rec_check
358 return rec_check
359 except IndexError:
359 except IndexError:
360 pass
360 pass
361
361
362 aux = traceback.extract_tb(etb)
362 aux = traceback.extract_tb(etb)
363 assert len(records) == len(aux)
363 assert len(records) == len(aux)
364 for i, (file, lnum, _, _) in enumerate(aux):
364 for i, (file, lnum, _, _) in enumerate(aux):
365 maybeStart = lnum - 1 - context // 2
365 maybeStart = lnum - 1 - context // 2
366 start = max(maybeStart, 0)
366 start = max(maybeStart, 0)
367 end = start + context
367 end = start + context
368 lines = linecache.getlines(file)[start:end]
368 lines = linecache.getlines(file)[start:end]
369 buf = list(records[i])
369 buf = list(records[i])
370 buf[LNUM_POS] = lnum
370 buf[LNUM_POS] = lnum
371 buf[INDEX_POS] = lnum - 1 - start
371 buf[INDEX_POS] = lnum - 1 - start
372 buf[LINES_POS] = lines
372 buf[LINES_POS] = lines
373 records[i] = tuple(buf)
373 records[i] = tuple(buf)
374 return records[tb_offset:]
374 return records[tb_offset:]
375
375
376 # Helper function -- largely belongs to VerboseTB, but we need the same
376 # Helper function -- largely belongs to VerboseTB, but we need the same
377 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
377 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
378 # can be recognized properly by ipython.el's py-traceback-line-re
378 # can be recognized properly by ipython.el's py-traceback-line-re
379 # (SyntaxErrors have to be treated specially because they have no traceback)
379 # (SyntaxErrors have to be treated specially because they have no traceback)
380
380
381
381
382 def _format_traceback_lines(lnum, index, lines, Colors, lvals, _line_format):
382 def _format_traceback_lines(lnum, index, lines, Colors, lvals, _line_format):
383 """
383 """
384 Format tracebacks lines with pointing arrow, leading numbers...
384 Format tracebacks lines with pointing arrow, leading numbers...
385
385
386 Parameters
386 Parameters
387 ==========
387 ==========
388
388
389 lnum: int
389 lnum: int
390 index: int
390 index: int
391 lines: list[string]
391 lines: list[string]
392 Colors:
392 Colors:
393 ColorScheme used.
393 ColorScheme used.
394 lvals: bytes
394 lvals: bytes
395 Values of local variables, already colored, to inject just after the error line.
395 Values of local variables, already colored, to inject just after the error line.
396 _line_format: f (str) -> (str, bool)
396 _line_format: f (str) -> (str, bool)
397 return (colorized version of str, failure to do so)
397 return (colorized version of str, failure to do so)
398 """
398 """
399 numbers_width = INDENT_SIZE - 1
399 numbers_width = INDENT_SIZE - 1
400 res = []
400 res = []
401
401
402 for i,line in enumerate(lines, lnum-index):
402 for i,line in enumerate(lines, lnum-index):
403 line = py3compat.cast_unicode(line)
403 line = py3compat.cast_unicode(line)
404
404
405 new_line, err = _line_format(line, 'str')
405 new_line, err = _line_format(line, 'str')
406 if not err:
406 if not err:
407 line = new_line
407 line = new_line
408
408
409 if i == lnum:
409 if i == lnum:
410 # This is the line with the error
410 # This is the line with the error
411 pad = numbers_width - len(str(i))
411 pad = numbers_width - len(str(i))
412 num = '%s%s' % (debugger.make_arrow(pad), str(lnum))
412 num = '%s%s' % (debugger.make_arrow(pad), str(lnum))
413 line = '%s%s%s %s%s' % (Colors.linenoEm, num,
413 line = '%s%s%s %s%s' % (Colors.linenoEm, num,
414 Colors.line, line, Colors.Normal)
414 Colors.line, line, Colors.Normal)
415 else:
415 else:
416 num = '%*s' % (numbers_width, i)
416 num = '%*s' % (numbers_width, i)
417 line = '%s%s%s %s' % (Colors.lineno, num,
417 line = '%s%s%s %s' % (Colors.lineno, num,
418 Colors.Normal, line)
418 Colors.Normal, line)
419
419
420 res.append(line)
420 res.append(line)
421 if lvals and i == lnum:
421 if lvals and i == lnum:
422 res.append(lvals + '\n')
422 res.append(lvals + '\n')
423 return res
423 return res
424
424
425 def is_recursion_error(etype, value, records):
425 def is_recursion_error(etype, value, records):
426 try:
426 try:
427 # RecursionError is new in Python 3.5
427 # RecursionError is new in Python 3.5
428 recursion_error_type = RecursionError
428 recursion_error_type = RecursionError
429 except NameError:
429 except NameError:
430 recursion_error_type = RuntimeError
430 recursion_error_type = RuntimeError
431
431
432 # The default recursion limit is 1000, but some of that will be taken up
432 # The default recursion limit is 1000, but some of that will be taken up
433 # by stack frames in IPython itself. >500 frames probably indicates
433 # by stack frames in IPython itself. >500 frames probably indicates
434 # a recursion error.
434 # a recursion error.
435 return (etype is recursion_error_type) \
435 return (etype is recursion_error_type) \
436 and "recursion" in str(value).lower() \
436 and "recursion" in str(value).lower() \
437 and len(records) > _FRAME_RECURSION_LIMIT
437 and len(records) > _FRAME_RECURSION_LIMIT
438
438
439 def find_recursion(etype, value, records):
439 def find_recursion(etype, value, records):
440 """Identify the repeating stack frames from a RecursionError traceback
440 """Identify the repeating stack frames from a RecursionError traceback
441
441
442 'records' is a list as returned by VerboseTB.get_records()
442 'records' is a list as returned by VerboseTB.get_records()
443
443
444 Returns (last_unique, repeat_length)
444 Returns (last_unique, repeat_length)
445 """
445 """
446 # This involves a bit of guesswork - we want to show enough of the traceback
446 # This involves a bit of guesswork - we want to show enough of the traceback
447 # to indicate where the recursion is occurring. We guess that the innermost
447 # to indicate where the recursion is occurring. We guess that the innermost
448 # quarter of the traceback (250 frames by default) is repeats, and find the
448 # quarter of the traceback (250 frames by default) is repeats, and find the
449 # first frame (from in to out) that looks different.
449 # first frame (from in to out) that looks different.
450 if not is_recursion_error(etype, value, records):
450 if not is_recursion_error(etype, value, records):
451 return len(records), 0
451 return len(records), 0
452
452
453 # Select filename, lineno, func_name to track frames with
453 # Select filename, lineno, func_name to track frames with
454 records = [r[1:4] for r in records]
454 records = [r[1:4] for r in records]
455 inner_frames = records[-(len(records)//4):]
455 inner_frames = records[-(len(records)//4):]
456 frames_repeated = set(inner_frames)
456 frames_repeated = set(inner_frames)
457
457
458 last_seen_at = {}
458 last_seen_at = {}
459 longest_repeat = 0
459 longest_repeat = 0
460 i = len(records)
460 i = len(records)
461 for frame in reversed(records):
461 for frame in reversed(records):
462 i -= 1
462 i -= 1
463 if frame not in frames_repeated:
463 if frame not in frames_repeated:
464 last_unique = i
464 last_unique = i
465 break
465 break
466
466
467 if frame in last_seen_at:
467 if frame in last_seen_at:
468 distance = last_seen_at[frame] - i
468 distance = last_seen_at[frame] - i
469 longest_repeat = max(longest_repeat, distance)
469 longest_repeat = max(longest_repeat, distance)
470
470
471 last_seen_at[frame] = i
471 last_seen_at[frame] = i
472 else:
472 else:
473 last_unique = 0 # The whole traceback was recursion
473 last_unique = 0 # The whole traceback was recursion
474
474
475 return last_unique, longest_repeat
475 return last_unique, longest_repeat
476
476
477 #---------------------------------------------------------------------------
477 #---------------------------------------------------------------------------
478 # Module classes
478 # Module classes
479 class TBTools(colorable.Colorable):
479 class TBTools(colorable.Colorable):
480 """Basic tools used by all traceback printer classes."""
480 """Basic tools used by all traceback printer classes."""
481
481
482 # Number of frames to skip when reporting tracebacks
482 # Number of frames to skip when reporting tracebacks
483 tb_offset = 0
483 tb_offset = 0
484
484
485 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
485 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
486 # Whether to call the interactive pdb debugger after printing
486 # Whether to call the interactive pdb debugger after printing
487 # tracebacks or not
487 # tracebacks or not
488 super(TBTools, self).__init__(parent=parent, config=config)
488 super(TBTools, self).__init__(parent=parent, config=config)
489 self.call_pdb = call_pdb
489 self.call_pdb = call_pdb
490
490
491 # Output stream to write to. Note that we store the original value in
491 # Output stream to write to. Note that we store the original value in
492 # a private attribute and then make the public ostream a property, so
492 # a private attribute and then make the public ostream a property, so
493 # that we can delay accessing sys.stdout until runtime. The way
493 # that we can delay accessing sys.stdout until runtime. The way
494 # things are written now, the sys.stdout object is dynamically managed
494 # things are written now, the sys.stdout object is dynamically managed
495 # so a reference to it should NEVER be stored statically. This
495 # so a reference to it should NEVER be stored statically. This
496 # property approach confines this detail to a single location, and all
496 # property approach confines this detail to a single location, and all
497 # subclasses can simply access self.ostream for writing.
497 # subclasses can simply access self.ostream for writing.
498 self._ostream = ostream
498 self._ostream = ostream
499
499
500 # Create color table
500 # Create color table
501 self.color_scheme_table = exception_colors()
501 self.color_scheme_table = exception_colors()
502
502
503 self.set_colors(color_scheme)
503 self.set_colors(color_scheme)
504 self.old_scheme = color_scheme # save initial value for toggles
504 self.old_scheme = color_scheme # save initial value for toggles
505
505
506 if call_pdb:
506 if call_pdb:
507 self.pdb = debugger.Pdb()
507 self.pdb = debugger.Pdb()
508 else:
508 else:
509 self.pdb = None
509 self.pdb = None
510
510
511 def _get_ostream(self):
511 def _get_ostream(self):
512 """Output stream that exceptions are written to.
512 """Output stream that exceptions are written to.
513
513
514 Valid values are:
514 Valid values are:
515
515
516 - None: the default, which means that IPython will dynamically resolve
516 - None: the default, which means that IPython will dynamically resolve
517 to sys.stdout. This ensures compatibility with most tools, including
517 to sys.stdout. This ensures compatibility with most tools, including
518 Windows (where plain stdout doesn't recognize ANSI escapes).
518 Windows (where plain stdout doesn't recognize ANSI escapes).
519
519
520 - Any object with 'write' and 'flush' attributes.
520 - Any object with 'write' and 'flush' attributes.
521 """
521 """
522 return sys.stdout if self._ostream is None else self._ostream
522 return sys.stdout if self._ostream is None else self._ostream
523
523
524 def _set_ostream(self, val):
524 def _set_ostream(self, val):
525 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
525 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
526 self._ostream = val
526 self._ostream = val
527
527
528 ostream = property(_get_ostream, _set_ostream)
528 ostream = property(_get_ostream, _set_ostream)
529
529
530 def get_parts_of_chained_exception(self, evalue):
530 def get_parts_of_chained_exception(self, evalue):
531 def get_chained_exception(exception_value):
531 def get_chained_exception(exception_value):
532 cause = getattr(exception_value, '__cause__', None)
532 cause = getattr(exception_value, '__cause__', None)
533 if cause:
533 if cause:
534 return cause
534 return cause
535 if getattr(exception_value, '__suppress_context__', False):
535 if getattr(exception_value, '__suppress_context__', False):
536 return None
536 return None
537 return getattr(exception_value, '__context__', None)
537 return getattr(exception_value, '__context__', None)
538
538
539 chained_evalue = get_chained_exception(evalue)
539 chained_evalue = get_chained_exception(evalue)
540
540
541 if chained_evalue:
541 if chained_evalue:
542 return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
542 return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
543
543
544 def prepare_chained_exception_message(self, cause):
544 def prepare_chained_exception_message(self, cause):
545 direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
545 direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
546 exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
546 exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
547
547
548 if cause:
548 if cause:
549 message = [[direct_cause]]
549 message = [[direct_cause]]
550 else:
550 else:
551 message = [[exception_during_handling]]
551 message = [[exception_during_handling]]
552 return message
552 return message
553
553
554 def set_colors(self, *args, **kw):
554 def set_colors(self, *args, **kw):
555 """Shorthand access to the color table scheme selector method."""
555 """Shorthand access to the color table scheme selector method."""
556
556
557 # Set own color table
557 # Set own color table
558 self.color_scheme_table.set_active_scheme(*args, **kw)
558 self.color_scheme_table.set_active_scheme(*args, **kw)
559 # for convenience, set Colors to the active scheme
559 # for convenience, set Colors to the active scheme
560 self.Colors = self.color_scheme_table.active_colors
560 self.Colors = self.color_scheme_table.active_colors
561 # Also set colors of debugger
561 # Also set colors of debugger
562 if hasattr(self, 'pdb') and self.pdb is not None:
562 if hasattr(self, 'pdb') and self.pdb is not None:
563 self.pdb.set_colors(*args, **kw)
563 self.pdb.set_colors(*args, **kw)
564
564
565 def color_toggle(self):
565 def color_toggle(self):
566 """Toggle between the currently active color scheme and NoColor."""
566 """Toggle between the currently active color scheme and NoColor."""
567
567
568 if self.color_scheme_table.active_scheme_name == 'NoColor':
568 if self.color_scheme_table.active_scheme_name == 'NoColor':
569 self.color_scheme_table.set_active_scheme(self.old_scheme)
569 self.color_scheme_table.set_active_scheme(self.old_scheme)
570 self.Colors = self.color_scheme_table.active_colors
570 self.Colors = self.color_scheme_table.active_colors
571 else:
571 else:
572 self.old_scheme = self.color_scheme_table.active_scheme_name
572 self.old_scheme = self.color_scheme_table.active_scheme_name
573 self.color_scheme_table.set_active_scheme('NoColor')
573 self.color_scheme_table.set_active_scheme('NoColor')
574 self.Colors = self.color_scheme_table.active_colors
574 self.Colors = self.color_scheme_table.active_colors
575
575
576 def stb2text(self, stb):
576 def stb2text(self, stb):
577 """Convert a structured traceback (a list) to a string."""
577 """Convert a structured traceback (a list) to a string."""
578 return '\n'.join(stb)
578 return '\n'.join(stb)
579
579
580 def text(self, etype, value, tb, tb_offset=None, context=5):
580 def text(self, etype, value, tb, tb_offset=None, context=5):
581 """Return formatted traceback.
581 """Return formatted traceback.
582
582
583 Subclasses may override this if they add extra arguments.
583 Subclasses may override this if they add extra arguments.
584 """
584 """
585 tb_list = self.structured_traceback(etype, value, tb,
585 tb_list = self.structured_traceback(etype, value, tb,
586 tb_offset, context)
586 tb_offset, context)
587 return self.stb2text(tb_list)
587 return self.stb2text(tb_list)
588
588
589 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
589 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
590 context=5, mode=None):
590 context=5, mode=None):
591 """Return a list of traceback frames.
591 """Return a list of traceback frames.
592
592
593 Must be implemented by each class.
593 Must be implemented by each class.
594 """
594 """
595 raise NotImplementedError()
595 raise NotImplementedError()
596
596
597
597
598 #---------------------------------------------------------------------------
598 #---------------------------------------------------------------------------
599 class ListTB(TBTools):
599 class ListTB(TBTools):
600 """Print traceback information from a traceback list, with optional color.
600 """Print traceback information from a traceback list, with optional color.
601
601
602 Calling requires 3 arguments: (etype, evalue, elist)
602 Calling requires 3 arguments: (etype, evalue, elist)
603 as would be obtained by::
603 as would be obtained by::
604
604
605 etype, evalue, tb = sys.exc_info()
605 etype, evalue, tb = sys.exc_info()
606 if tb:
606 if tb:
607 elist = traceback.extract_tb(tb)
607 elist = traceback.extract_tb(tb)
608 else:
608 else:
609 elist = None
609 elist = None
610
610
611 It can thus be used by programs which need to process the traceback before
611 It can thus be used by programs which need to process the traceback before
612 printing (such as console replacements based on the code module from the
612 printing (such as console replacements based on the code module from the
613 standard library).
613 standard library).
614
614
615 Because they are meant to be called without a full traceback (only a
615 Because they are meant to be called without a full traceback (only a
616 list), instances of this class can't call the interactive pdb debugger."""
616 list), instances of this class can't call the interactive pdb debugger."""
617
617
618 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
618 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
619 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
619 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
620 ostream=ostream, parent=parent,config=config)
620 ostream=ostream, parent=parent,config=config)
621
621
622 def __call__(self, etype, value, elist):
622 def __call__(self, etype, value, elist):
623 self.ostream.flush()
623 self.ostream.flush()
624 self.ostream.write(self.text(etype, value, elist))
624 self.ostream.write(self.text(etype, value, elist))
625 self.ostream.write('\n')
625 self.ostream.write('\n')
626
626
627 def _extract_tb(self, tb):
627 def _extract_tb(self, tb):
628 if tb:
628 if tb:
629 return traceback.extract_tb(tb)
629 return traceback.extract_tb(tb)
630 else:
630 else:
631 return None
631 return None
632
632
633 def structured_traceback(self, etype, evalue, etb=None, tb_offset=None,
633 def structured_traceback(self, etype, evalue, etb=None, tb_offset=None,
634 context=5):
634 context=5):
635 """Return a color formatted string with the traceback info.
635 """Return a color formatted string with the traceback info.
636
636
637 Parameters
637 Parameters
638 ----------
638 ----------
639 etype : exception type
639 etype : exception type
640 Type of the exception raised.
640 Type of the exception raised.
641
641
642 evalue : object
642 evalue : object
643 Data stored in the exception
643 Data stored in the exception
644
644
645 etb : object
645 etb : object
646 If list: List of frames, see class docstring for details.
646 If list: List of frames, see class docstring for details.
647 If Traceback: Traceback of the exception.
647 If Traceback: Traceback of the exception.
648
648
649 tb_offset : int, optional
649 tb_offset : int, optional
650 Number of frames in the traceback to skip. If not given, the
650 Number of frames in the traceback to skip. If not given, the
651 instance evalue is used (set in constructor).
651 instance evalue is used (set in constructor).
652
652
653 context : int, optional
653 context : int, optional
654 Number of lines of context information to print.
654 Number of lines of context information to print.
655
655
656 Returns
656 Returns
657 -------
657 -------
658 String with formatted exception.
658 String with formatted exception.
659 """
659 """
660 # This is a workaround to get chained_exc_ids in recursive calls
660 # This is a workaround to get chained_exc_ids in recursive calls
661 # etb should not be a tuple if structured_traceback is not recursive
661 # etb should not be a tuple if structured_traceback is not recursive
662 if isinstance(etb, tuple):
662 if isinstance(etb, tuple):
663 etb, chained_exc_ids = etb
663 etb, chained_exc_ids = etb
664 else:
664 else:
665 chained_exc_ids = set()
665 chained_exc_ids = set()
666
666
667 if isinstance(etb, list):
667 if isinstance(etb, list):
668 elist = etb
668 elist = etb
669 elif etb is not None:
669 elif etb is not None:
670 elist = self._extract_tb(etb)
670 elist = self._extract_tb(etb)
671 else:
671 else:
672 elist = []
672 elist = []
673 tb_offset = self.tb_offset if tb_offset is None else tb_offset
673 tb_offset = self.tb_offset if tb_offset is None else tb_offset
674 Colors = self.Colors
674 Colors = self.Colors
675 out_list = []
675 out_list = []
676 if elist:
676 if elist:
677
677
678 if tb_offset and len(elist) > tb_offset:
678 if tb_offset and len(elist) > tb_offset:
679 elist = elist[tb_offset:]
679 elist = elist[tb_offset:]
680
680
681 out_list.append('Traceback %s(most recent call last)%s:' %
681 out_list.append('Traceback %s(most recent call last)%s:' %
682 (Colors.normalEm, Colors.Normal) + '\n')
682 (Colors.normalEm, Colors.Normal) + '\n')
683 out_list.extend(self._format_list(elist))
683 out_list.extend(self._format_list(elist))
684 # The exception info should be a single entry in the list.
684 # The exception info should be a single entry in the list.
685 lines = ''.join(self._format_exception_only(etype, evalue))
685 lines = ''.join(self._format_exception_only(etype, evalue))
686 out_list.append(lines)
686 out_list.append(lines)
687
687
688 exception = self.get_parts_of_chained_exception(evalue)
688 exception = self.get_parts_of_chained_exception(evalue)
689
689
690 if exception and not id(exception[1]) in chained_exc_ids:
690 if exception and not id(exception[1]) in chained_exc_ids:
691 chained_exception_message = self.prepare_chained_exception_message(
691 chained_exception_message = self.prepare_chained_exception_message(
692 evalue.__cause__)[0]
692 evalue.__cause__)[0]
693 etype, evalue, etb = exception
693 etype, evalue, etb = exception
694 # Trace exception to avoid infinite 'cause' loop
694 # Trace exception to avoid infinite 'cause' loop
695 chained_exc_ids.add(id(exception[1]))
695 chained_exc_ids.add(id(exception[1]))
696 chained_exceptions_tb_offset = 0
696 chained_exceptions_tb_offset = 0
697 out_list = (
697 out_list = (
698 self.structured_traceback(
698 self.structured_traceback(
699 etype, evalue, (etb, chained_exc_ids),
699 etype, evalue, (etb, chained_exc_ids),
700 chained_exceptions_tb_offset, context)
700 chained_exceptions_tb_offset, context)
701 + chained_exception_message
701 + chained_exception_message
702 + out_list)
702 + out_list)
703
703
704 return out_list
704 return out_list
705
705
706 def _format_list(self, extracted_list):
706 def _format_list(self, extracted_list):
707 """Format a list of traceback entry tuples for printing.
707 """Format a list of traceback entry tuples for printing.
708
708
709 Given a list of tuples as returned by extract_tb() or
709 Given a list of tuples as returned by extract_tb() or
710 extract_stack(), return a list of strings ready for printing.
710 extract_stack(), return a list of strings ready for printing.
711 Each string in the resulting list corresponds to the item with the
711 Each string in the resulting list corresponds to the item with the
712 same index in the argument list. Each string ends in a newline;
712 same index in the argument list. Each string ends in a newline;
713 the strings may contain internal newlines as well, for those items
713 the strings may contain internal newlines as well, for those items
714 whose source text line is not None.
714 whose source text line is not None.
715
715
716 Lifted almost verbatim from traceback.py
716 Lifted almost verbatim from traceback.py
717 """
717 """
718
718
719 Colors = self.Colors
719 Colors = self.Colors
720 list = []
720 list = []
721 for filename, lineno, name, line in extracted_list[:-1]:
721 for filename, lineno, name, line in extracted_list[:-1]:
722 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
722 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
723 (Colors.filename, filename, Colors.Normal,
723 (Colors.filename, filename, Colors.Normal,
724 Colors.lineno, lineno, Colors.Normal,
724 Colors.lineno, lineno, Colors.Normal,
725 Colors.name, name, Colors.Normal)
725 Colors.name, name, Colors.Normal)
726 if line:
726 if line:
727 item += ' %s\n' % line.strip()
727 item += ' %s\n' % line.strip()
728 list.append(item)
728 list.append(item)
729 # Emphasize the last entry
729 # Emphasize the last entry
730 filename, lineno, name, line = extracted_list[-1]
730 filename, lineno, name, line = extracted_list[-1]
731 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
731 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
732 (Colors.normalEm,
732 (Colors.normalEm,
733 Colors.filenameEm, filename, Colors.normalEm,
733 Colors.filenameEm, filename, Colors.normalEm,
734 Colors.linenoEm, lineno, Colors.normalEm,
734 Colors.linenoEm, lineno, Colors.normalEm,
735 Colors.nameEm, name, Colors.normalEm,
735 Colors.nameEm, name, Colors.normalEm,
736 Colors.Normal)
736 Colors.Normal)
737 if line:
737 if line:
738 item += '%s %s%s\n' % (Colors.line, line.strip(),
738 item += '%s %s%s\n' % (Colors.line, line.strip(),
739 Colors.Normal)
739 Colors.Normal)
740 list.append(item)
740 list.append(item)
741 return list
741 return list
742
742
743 def _format_exception_only(self, etype, value):
743 def _format_exception_only(self, etype, value):
744 """Format the exception part of a traceback.
744 """Format the exception part of a traceback.
745
745
746 The arguments are the exception type and value such as given by
746 The arguments are the exception type and value such as given by
747 sys.exc_info()[:2]. The return value is a list of strings, each ending
747 sys.exc_info()[:2]. The return value is a list of strings, each ending
748 in a newline. Normally, the list contains a single string; however,
748 in a newline. Normally, the list contains a single string; however,
749 for SyntaxError exceptions, it contains several lines that (when
749 for SyntaxError exceptions, it contains several lines that (when
750 printed) display detailed information about where the syntax error
750 printed) display detailed information about where the syntax error
751 occurred. The message indicating which exception occurred is the
751 occurred. The message indicating which exception occurred is the
752 always last string in the list.
752 always last string in the list.
753
753
754 Also lifted nearly verbatim from traceback.py
754 Also lifted nearly verbatim from traceback.py
755 """
755 """
756 have_filedata = False
756 have_filedata = False
757 Colors = self.Colors
757 Colors = self.Colors
758 list = []
758 list = []
759 stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
759 stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
760 if value is None:
760 if value is None:
761 # Not sure if this can still happen in Python 2.6 and above
761 # Not sure if this can still happen in Python 2.6 and above
762 list.append(stype + '\n')
762 list.append(stype + '\n')
763 else:
763 else:
764 if issubclass(etype, SyntaxError):
764 if issubclass(etype, SyntaxError):
765 have_filedata = True
765 have_filedata = True
766 if not value.filename: value.filename = "<string>"
766 if not value.filename: value.filename = "<string>"
767 if value.lineno:
767 if value.lineno:
768 lineno = value.lineno
768 lineno = value.lineno
769 textline = linecache.getline(value.filename, value.lineno)
769 textline = linecache.getline(value.filename, value.lineno)
770 else:
770 else:
771 lineno = 'unknown'
771 lineno = 'unknown'
772 textline = ''
772 textline = ''
773 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
773 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
774 (Colors.normalEm,
774 (Colors.normalEm,
775 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
775 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
776 Colors.linenoEm, lineno, Colors.Normal ))
776 Colors.linenoEm, lineno, Colors.Normal ))
777 if textline == '':
777 if textline == '':
778 textline = py3compat.cast_unicode(value.text, "utf-8")
778 textline = py3compat.cast_unicode(value.text, "utf-8")
779
779
780 if textline is not None:
780 if textline is not None:
781 i = 0
781 i = 0
782 while i < len(textline) and textline[i].isspace():
782 while i < len(textline) and textline[i].isspace():
783 i += 1
783 i += 1
784 list.append('%s %s%s\n' % (Colors.line,
784 list.append('%s %s%s\n' % (Colors.line,
785 textline.strip(),
785 textline.strip(),
786 Colors.Normal))
786 Colors.Normal))
787 if value.offset is not None:
787 if value.offset is not None:
788 s = ' '
788 s = ' '
789 for c in textline[i:value.offset - 1]:
789 for c in textline[i:value.offset - 1]:
790 if c.isspace():
790 if c.isspace():
791 s += c
791 s += c
792 else:
792 else:
793 s += ' '
793 s += ' '
794 list.append('%s%s^%s\n' % (Colors.caret, s,
794 list.append('%s%s^%s\n' % (Colors.caret, s,
795 Colors.Normal))
795 Colors.Normal))
796
796
797 try:
797 try:
798 s = value.msg
798 s = value.msg
799 except Exception:
799 except Exception:
800 s = self._some_str(value)
800 s = self._some_str(value)
801 if s:
801 if s:
802 list.append('%s%s:%s %s\n' % (stype, Colors.excName,
802 list.append('%s%s:%s %s\n' % (stype, Colors.excName,
803 Colors.Normal, s))
803 Colors.Normal, s))
804 else:
804 else:
805 list.append('%s\n' % stype)
805 list.append('%s\n' % stype)
806
806
807 # sync with user hooks
807 # sync with user hooks
808 if have_filedata:
808 if have_filedata:
809 ipinst = get_ipython()
809 ipinst = get_ipython()
810 if ipinst is not None:
810 if ipinst is not None:
811 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
811 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
812
812
813 return list
813 return list
814
814
815 def get_exception_only(self, etype, value):
815 def get_exception_only(self, etype, value):
816 """Only print the exception type and message, without a traceback.
816 """Only print the exception type and message, without a traceback.
817
817
818 Parameters
818 Parameters
819 ----------
819 ----------
820 etype : exception type
820 etype : exception type
821 value : exception value
821 value : exception value
822 """
822 """
823 return ListTB.structured_traceback(self, etype, value)
823 return ListTB.structured_traceback(self, etype, value)
824
824
825 def show_exception_only(self, etype, evalue):
825 def show_exception_only(self, etype, evalue):
826 """Only print the exception type and message, without a traceback.
826 """Only print the exception type and message, without a traceback.
827
827
828 Parameters
828 Parameters
829 ----------
829 ----------
830 etype : exception type
830 etype : exception type
831 value : exception value
831 value : exception value
832 """
832 """
833 # This method needs to use __call__ from *this* class, not the one from
833 # This method needs to use __call__ from *this* class, not the one from
834 # a subclass whose signature or behavior may be different
834 # a subclass whose signature or behavior may be different
835 ostream = self.ostream
835 ostream = self.ostream
836 ostream.flush()
836 ostream.flush()
837 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
837 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
838 ostream.flush()
838 ostream.flush()
839
839
840 def _some_str(self, value):
840 def _some_str(self, value):
841 # Lifted from traceback.py
841 # Lifted from traceback.py
842 try:
842 try:
843 return py3compat.cast_unicode(str(value))
843 return py3compat.cast_unicode(str(value))
844 except:
844 except:
845 return u'<unprintable %s object>' % type(value).__name__
845 return u'<unprintable %s object>' % type(value).__name__
846
846
847
847
848 #----------------------------------------------------------------------------
848 #----------------------------------------------------------------------------
849 class VerboseTB(TBTools):
849 class VerboseTB(TBTools):
850 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
850 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
851 of HTML. Requires inspect and pydoc. Crazy, man.
851 of HTML. Requires inspect and pydoc. Crazy, man.
852
852
853 Modified version which optionally strips the topmost entries from the
853 Modified version which optionally strips the topmost entries from the
854 traceback, to be used with alternate interpreters (because their own code
854 traceback, to be used with alternate interpreters (because their own code
855 would appear in the traceback)."""
855 would appear in the traceback)."""
856
856
857 def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
857 def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
858 tb_offset=0, long_header=False, include_vars=True,
858 tb_offset=0, long_header=False, include_vars=True,
859 check_cache=None, debugger_cls = None,
859 check_cache=None, debugger_cls = None,
860 parent=None, config=None):
860 parent=None, config=None):
861 """Specify traceback offset, headers and color scheme.
861 """Specify traceback offset, headers and color scheme.
862
862
863 Define how many frames to drop from the tracebacks. Calling it with
863 Define how many frames to drop from the tracebacks. Calling it with
864 tb_offset=1 allows use of this handler in interpreters which will have
864 tb_offset=1 allows use of this handler in interpreters which will have
865 their own code at the top of the traceback (VerboseTB will first
865 their own code at the top of the traceback (VerboseTB will first
866 remove that frame before printing the traceback info)."""
866 remove that frame before printing the traceback info)."""
867 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
867 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
868 ostream=ostream, parent=parent, config=config)
868 ostream=ostream, parent=parent, config=config)
869 self.tb_offset = tb_offset
869 self.tb_offset = tb_offset
870 self.long_header = long_header
870 self.long_header = long_header
871 self.include_vars = include_vars
871 self.include_vars = include_vars
872 # By default we use linecache.checkcache, but the user can provide a
872 # By default we use linecache.checkcache, but the user can provide a
873 # different check_cache implementation. This is used by the IPython
873 # different check_cache implementation. This is used by the IPython
874 # kernel to provide tracebacks for interactive code that is cached,
874 # kernel to provide tracebacks for interactive code that is cached,
875 # by a compiler instance that flushes the linecache but preserves its
875 # by a compiler instance that flushes the linecache but preserves its
876 # own code cache.
876 # own code cache.
877 if check_cache is None:
877 if check_cache is None:
878 check_cache = linecache.checkcache
878 check_cache = linecache.checkcache
879 self.check_cache = check_cache
879 self.check_cache = check_cache
880
880
881 self.debugger_cls = debugger_cls or debugger.Pdb
881 self.debugger_cls = debugger_cls or debugger.Pdb
882 self.skip_hidden = True
882
883
883 def format_records(self, records, last_unique, recursion_repeat):
884 def format_records(self, records, last_unique, recursion_repeat):
884 """Format the stack frames of the traceback"""
885 """Format the stack frames of the traceback"""
885 frames = []
886 frames = []
887
888 skipped = 0
886 for r in records[:last_unique+recursion_repeat+1]:
889 for r in records[:last_unique+recursion_repeat+1]:
887 #print '*** record:',file,lnum,func,lines,index # dbg
890 if self.skip_hidden:
891 if r[0].f_locals.get("__tracebackhide__", 0):
892 skipped += 1
893 continue
894 if skipped:
895 Colors = self.Colors # just a shorthand + quicker name lookup
896 ColorsNormal = Colors.Normal # used a lot
897 frames.append(
898 " %s[... skipping hidden %s frame]%s\n"
899 % (Colors.excName, skipped, ColorsNormal)
900 )
901 skipped = 0
902
888 frames.append(self.format_record(*r))
903 frames.append(self.format_record(*r))
904
905 if skipped:
906 Colors = self.Colors # just a shorthand + quicker name lookup
907 ColorsNormal = Colors.Normal # used a lot
908 frames.append(
909 " %s[... skipping hidden %s frame]%s\n"
910 % (Colors.excName, skipped, ColorsNormal)
911 )
889
912
890 if recursion_repeat:
913 if recursion_repeat:
891 frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat)
914 frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat)
892 frames.append(self.format_record(*records[last_unique+recursion_repeat+1]))
915 frames.append(self.format_record(*records[last_unique+recursion_repeat+1]))
893
916
894 return frames
917 return frames
895
918
896 def format_record(self, frame, file, lnum, func, lines, index):
919 def format_record(self, frame, file, lnum, func, lines, index):
897 """Format a single stack frame"""
920 """Format a single stack frame"""
898 Colors = self.Colors # just a shorthand + quicker name lookup
921 Colors = self.Colors # just a shorthand + quicker name lookup
899 ColorsNormal = Colors.Normal # used a lot
922 ColorsNormal = Colors.Normal # used a lot
900 col_scheme = self.color_scheme_table.active_scheme_name
923 col_scheme = self.color_scheme_table.active_scheme_name
901 indent = ' ' * INDENT_SIZE
924 indent = ' ' * INDENT_SIZE
902 em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
925 em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
903 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
926 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
904 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
927 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
905 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
928 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
906 ColorsNormal)
929 ColorsNormal)
907 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
930 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
908 (Colors.vName, Colors.valEm, ColorsNormal)
931 (Colors.vName, Colors.valEm, ColorsNormal)
909 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
932 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
910 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
933 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
911 Colors.vName, ColorsNormal)
934 Colors.vName, ColorsNormal)
912 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
935 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
913
936
914 if not file:
937 if not file:
915 file = '?'
938 file = '?'
916 elif file.startswith(str("<")) and file.endswith(str(">")):
939 elif file.startswith(str("<")) and file.endswith(str(">")):
917 # Not a real filename, no problem...
940 # Not a real filename, no problem...
918 pass
941 pass
919 elif not os.path.isabs(file):
942 elif not os.path.isabs(file):
920 # Try to make the filename absolute by trying all
943 # Try to make the filename absolute by trying all
921 # sys.path entries (which is also what linecache does)
944 # sys.path entries (which is also what linecache does)
922 for dirname in sys.path:
945 for dirname in sys.path:
923 try:
946 try:
924 fullname = os.path.join(dirname, file)
947 fullname = os.path.join(dirname, file)
925 if os.path.isfile(fullname):
948 if os.path.isfile(fullname):
926 file = os.path.abspath(fullname)
949 file = os.path.abspath(fullname)
927 break
950 break
928 except Exception:
951 except Exception:
929 # Just in case that sys.path contains very
952 # Just in case that sys.path contains very
930 # strange entries...
953 # strange entries...
931 pass
954 pass
932
955
933 file = py3compat.cast_unicode(file, util_path.fs_encoding)
956 file = py3compat.cast_unicode(file, util_path.fs_encoding)
934 link = tpl_link % util_path.compress_user(file)
957 link = tpl_link % util_path.compress_user(file)
935 args, varargs, varkw, locals_ = inspect.getargvalues(frame)
958 args, varargs, varkw, locals_ = inspect.getargvalues(frame)
936
959
937 if func == '?':
960 if func == '?':
938 call = ''
961 call = ''
939 elif func == '<module>':
962 elif func == '<module>':
940 call = tpl_call % (func, '')
963 call = tpl_call % (func, '')
941 else:
964 else:
942 # Decide whether to include variable details or not
965 # Decide whether to include variable details or not
943 var_repr = eqrepr if self.include_vars else nullrepr
966 var_repr = eqrepr if self.include_vars else nullrepr
944 try:
967 try:
945 call = tpl_call % (func, inspect.formatargvalues(args,
968 call = tpl_call % (func, inspect.formatargvalues(args,
946 varargs, varkw,
969 varargs, varkw,
947 locals_, formatvalue=var_repr))
970 locals_, formatvalue=var_repr))
948 except KeyError:
971 except KeyError:
949 # This happens in situations like errors inside generator
972 # This happens in situations like errors inside generator
950 # expressions, where local variables are listed in the
973 # expressions, where local variables are listed in the
951 # line, but can't be extracted from the frame. I'm not
974 # line, but can't be extracted from the frame. I'm not
952 # 100% sure this isn't actually a bug in inspect itself,
975 # 100% sure this isn't actually a bug in inspect itself,
953 # but since there's no info for us to compute with, the
976 # but since there's no info for us to compute with, the
954 # best we can do is report the failure and move on. Here
977 # best we can do is report the failure and move on. Here
955 # we must *not* call any traceback construction again,
978 # we must *not* call any traceback construction again,
956 # because that would mess up use of %debug later on. So we
979 # because that would mess up use of %debug later on. So we
957 # simply report the failure and move on. The only
980 # simply report the failure and move on. The only
958 # limitation will be that this frame won't have locals
981 # limitation will be that this frame won't have locals
959 # listed in the call signature. Quite subtle problem...
982 # listed in the call signature. Quite subtle problem...
960 # I can't think of a good way to validate this in a unit
983 # I can't think of a good way to validate this in a unit
961 # test, but running a script consisting of:
984 # test, but running a script consisting of:
962 # dict( (k,v.strip()) for (k,v) in range(10) )
985 # dict( (k,v.strip()) for (k,v) in range(10) )
963 # will illustrate the error, if this exception catch is
986 # will illustrate the error, if this exception catch is
964 # disabled.
987 # disabled.
965 call = tpl_call_fail % func
988 call = tpl_call_fail % func
966
989
967 # Don't attempt to tokenize binary files.
990 # Don't attempt to tokenize binary files.
968 if file.endswith(('.so', '.pyd', '.dll')):
991 if file.endswith(('.so', '.pyd', '.dll')):
969 return '%s %s\n' % (link, call)
992 return '%s %s\n' % (link, call)
970
993
971 elif file.endswith(('.pyc', '.pyo')):
994 elif file.endswith(('.pyc', '.pyo')):
972 # Look up the corresponding source file.
995 # Look up the corresponding source file.
973 try:
996 try:
974 file = source_from_cache(file)
997 file = source_from_cache(file)
975 except ValueError:
998 except ValueError:
976 # Failed to get the source file for some reason
999 # Failed to get the source file for some reason
977 # E.g. https://github.com/ipython/ipython/issues/9486
1000 # E.g. https://github.com/ipython/ipython/issues/9486
978 return '%s %s\n' % (link, call)
1001 return '%s %s\n' % (link, call)
979
1002
980 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
1003 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
981 line = getline(file, lnum[0])
1004 line = getline(file, lnum[0])
982 lnum[0] += 1
1005 lnum[0] += 1
983 return line
1006 return line
984
1007
985 # Build the list of names on this line of code where the exception
1008 # Build the list of names on this line of code where the exception
986 # occurred.
1009 # occurred.
987 try:
1010 try:
988 names = []
1011 names = []
989 name_cont = False
1012 name_cont = False
990
1013
991 for token_type, token, start, end, line in generate_tokens(linereader):
1014 for token_type, token, start, end, line in generate_tokens(linereader):
992 # build composite names
1015 # build composite names
993 if token_type == tokenize.NAME and token not in keyword.kwlist:
1016 if token_type == tokenize.NAME and token not in keyword.kwlist:
994 if name_cont:
1017 if name_cont:
995 # Continuation of a dotted name
1018 # Continuation of a dotted name
996 try:
1019 try:
997 names[-1].append(token)
1020 names[-1].append(token)
998 except IndexError:
1021 except IndexError:
999 names.append([token])
1022 names.append([token])
1000 name_cont = False
1023 name_cont = False
1001 else:
1024 else:
1002 # Regular new names. We append everything, the caller
1025 # Regular new names. We append everything, the caller
1003 # will be responsible for pruning the list later. It's
1026 # will be responsible for pruning the list later. It's
1004 # very tricky to try to prune as we go, b/c composite
1027 # very tricky to try to prune as we go, b/c composite
1005 # names can fool us. The pruning at the end is easy
1028 # names can fool us. The pruning at the end is easy
1006 # to do (or the caller can print a list with repeated
1029 # to do (or the caller can print a list with repeated
1007 # names if so desired.
1030 # names if so desired.
1008 names.append([token])
1031 names.append([token])
1009 elif token == '.':
1032 elif token == '.':
1010 name_cont = True
1033 name_cont = True
1011 elif token_type == tokenize.NEWLINE:
1034 elif token_type == tokenize.NEWLINE:
1012 break
1035 break
1013
1036
1014 except (IndexError, UnicodeDecodeError, SyntaxError):
1037 except (IndexError, UnicodeDecodeError, SyntaxError):
1015 # signals exit of tokenizer
1038 # signals exit of tokenizer
1016 # SyntaxError can occur if the file is not actually Python
1039 # SyntaxError can occur if the file is not actually Python
1017 # - see gh-6300
1040 # - see gh-6300
1018 pass
1041 pass
1019 except tokenize.TokenError as msg:
1042 except tokenize.TokenError as msg:
1020 # Tokenizing may fail for various reasons, many of which are
1043 # Tokenizing may fail for various reasons, many of which are
1021 # harmless. (A good example is when the line in question is the
1044 # harmless. (A good example is when the line in question is the
1022 # close of a triple-quoted string, cf gh-6864). We don't want to
1045 # close of a triple-quoted string, cf gh-6864). We don't want to
1023 # show this to users, but want make it available for debugging
1046 # show this to users, but want make it available for debugging
1024 # purposes.
1047 # purposes.
1025 _m = ("An unexpected error occurred while tokenizing input\n"
1048 _m = ("An unexpected error occurred while tokenizing input\n"
1026 "The following traceback may be corrupted or invalid\n"
1049 "The following traceback may be corrupted or invalid\n"
1027 "The error message is: %s\n" % msg)
1050 "The error message is: %s\n" % msg)
1028 debug(_m)
1051 debug(_m)
1029
1052
1030 # Join composite names (e.g. "dict.fromkeys")
1053 # Join composite names (e.g. "dict.fromkeys")
1031 names = ['.'.join(n) for n in names]
1054 names = ['.'.join(n) for n in names]
1032 # prune names list of duplicates, but keep the right order
1055 # prune names list of duplicates, but keep the right order
1033 unique_names = uniq_stable(names)
1056 unique_names = uniq_stable(names)
1034
1057
1035 # Start loop over vars
1058 # Start loop over vars
1036 lvals = ''
1059 lvals = ''
1037 lvals_list = []
1060 lvals_list = []
1038 if self.include_vars:
1061 if self.include_vars:
1039 for name_full in unique_names:
1062 for name_full in unique_names:
1040 name_base = name_full.split('.', 1)[0]
1063 name_base = name_full.split('.', 1)[0]
1041 if name_base in frame.f_code.co_varnames:
1064 if name_base in frame.f_code.co_varnames:
1042 if name_base in locals_:
1065 if name_base in locals_:
1043 try:
1066 try:
1044 value = repr(eval(name_full, locals_))
1067 value = repr(eval(name_full, locals_))
1045 except:
1068 except:
1046 value = undefined
1069 value = undefined
1047 else:
1070 else:
1048 value = undefined
1071 value = undefined
1049 name = tpl_local_var % name_full
1072 name = tpl_local_var % name_full
1050 else:
1073 else:
1051 if name_base in frame.f_globals:
1074 if name_base in frame.f_globals:
1052 try:
1075 try:
1053 value = repr(eval(name_full, frame.f_globals))
1076 value = repr(eval(name_full, frame.f_globals))
1054 except:
1077 except:
1055 value = undefined
1078 value = undefined
1056 else:
1079 else:
1057 value = undefined
1080 value = undefined
1058 name = tpl_global_var % name_full
1081 name = tpl_global_var % name_full
1059 lvals_list.append(tpl_name_val % (name, value))
1082 lvals_list.append(tpl_name_val % (name, value))
1060 if lvals_list:
1083 if lvals_list:
1061 lvals = '%s%s' % (indent, em_normal.join(lvals_list))
1084 lvals = '%s%s' % (indent, em_normal.join(lvals_list))
1062
1085
1063 level = '%s %s\n' % (link, call)
1086 level = '%s %s\n' % (link, call)
1064
1087
1065 if index is None:
1088 if index is None:
1066 return level
1089 return level
1067 else:
1090 else:
1068 _line_format = PyColorize.Parser(style=col_scheme, parent=self).format2
1091 _line_format = PyColorize.Parser(style=col_scheme, parent=self).format2
1069 return '%s%s' % (level, ''.join(
1092 return '%s%s' % (level, ''.join(
1070 _format_traceback_lines(lnum, index, lines, Colors, lvals,
1093 _format_traceback_lines(lnum, index, lines, Colors, lvals,
1071 _line_format)))
1094 _line_format)))
1072
1095
1073 def prepare_header(self, etype, long_version=False):
1096 def prepare_header(self, etype, long_version=False):
1074 colors = self.Colors # just a shorthand + quicker name lookup
1097 colors = self.Colors # just a shorthand + quicker name lookup
1075 colorsnormal = colors.Normal # used a lot
1098 colorsnormal = colors.Normal # used a lot
1076 exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
1099 exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
1077 width = min(75, get_terminal_size()[0])
1100 width = min(75, get_terminal_size()[0])
1078 if long_version:
1101 if long_version:
1079 # Header with the exception type, python version, and date
1102 # Header with the exception type, python version, and date
1080 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
1103 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
1081 date = time.ctime(time.time())
1104 date = time.ctime(time.time())
1082
1105
1083 head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
1106 head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
1084 exc, ' ' * (width - len(str(etype)) - len(pyver)),
1107 exc, ' ' * (width - len(str(etype)) - len(pyver)),
1085 pyver, date.rjust(width) )
1108 pyver, date.rjust(width) )
1086 head += "\nA problem occurred executing Python code. Here is the sequence of function" \
1109 head += "\nA problem occurred executing Python code. Here is the sequence of function" \
1087 "\ncalls leading up to the error, with the most recent (innermost) call last."
1110 "\ncalls leading up to the error, with the most recent (innermost) call last."
1088 else:
1111 else:
1089 # Simplified header
1112 # Simplified header
1090 head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
1113 head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
1091 rjust(width - len(str(etype))) )
1114 rjust(width - len(str(etype))) )
1092
1115
1093 return head
1116 return head
1094
1117
1095 def format_exception(self, etype, evalue):
1118 def format_exception(self, etype, evalue):
1096 colors = self.Colors # just a shorthand + quicker name lookup
1119 colors = self.Colors # just a shorthand + quicker name lookup
1097 colorsnormal = colors.Normal # used a lot
1120 colorsnormal = colors.Normal # used a lot
1098 # Get (safely) a string form of the exception info
1121 # Get (safely) a string form of the exception info
1099 try:
1122 try:
1100 etype_str, evalue_str = map(str, (etype, evalue))
1123 etype_str, evalue_str = map(str, (etype, evalue))
1101 except:
1124 except:
1102 # User exception is improperly defined.
1125 # User exception is improperly defined.
1103 etype, evalue = str, sys.exc_info()[:2]
1126 etype, evalue = str, sys.exc_info()[:2]
1104 etype_str, evalue_str = map(str, (etype, evalue))
1127 etype_str, evalue_str = map(str, (etype, evalue))
1105 # ... and format it
1128 # ... and format it
1106 return ['%s%s%s: %s' % (colors.excName, etype_str,
1129 return ['%s%s%s: %s' % (colors.excName, etype_str,
1107 colorsnormal, py3compat.cast_unicode(evalue_str))]
1130 colorsnormal, py3compat.cast_unicode(evalue_str))]
1108
1131
1109 def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
1132 def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
1110 """Formats the header, traceback and exception message for a single exception.
1133 """Formats the header, traceback and exception message for a single exception.
1111
1134
1112 This may be called multiple times by Python 3 exception chaining
1135 This may be called multiple times by Python 3 exception chaining
1113 (PEP 3134).
1136 (PEP 3134).
1114 """
1137 """
1115 # some locals
1138 # some locals
1116 orig_etype = etype
1139 orig_etype = etype
1117 try:
1140 try:
1118 etype = etype.__name__
1141 etype = etype.__name__
1119 except AttributeError:
1142 except AttributeError:
1120 pass
1143 pass
1121
1144
1122 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1145 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1123 head = self.prepare_header(etype, self.long_header)
1146 head = self.prepare_header(etype, self.long_header)
1124 records = self.get_records(etb, number_of_lines_of_context, tb_offset)
1147 records = self.get_records(etb, number_of_lines_of_context, tb_offset)
1125
1148
1126 if records is None:
1127 return ""
1128
1149
1129 last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
1150 last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
1130
1151
1131 frames = self.format_records(records, last_unique, recursion_repeat)
1152 frames = self.format_records(records, last_unique, recursion_repeat)
1132
1153
1133 formatted_exception = self.format_exception(etype, evalue)
1154 formatted_exception = self.format_exception(etype, evalue)
1134 if records:
1155 if records:
1135 filepath, lnum = records[-1][1:3]
1156 filepath, lnum = records[-1][1:3]
1136 filepath = os.path.abspath(filepath)
1157 filepath = os.path.abspath(filepath)
1137 ipinst = get_ipython()
1158 ipinst = get_ipython()
1138 if ipinst is not None:
1159 if ipinst is not None:
1139 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
1160 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
1140
1161
1141 return [[head] + frames + [''.join(formatted_exception[0])]]
1162 return [[head] + frames + [''.join(formatted_exception[0])]]
1142
1163
1143 def get_records(self, etb, number_of_lines_of_context, tb_offset):
1164 def get_records(self, etb, number_of_lines_of_context, tb_offset):
1144 try:
1165 try:
1145 # Try the default getinnerframes and Alex's: Alex's fixes some
1166 # Try the default getinnerframes and Alex's: Alex's fixes some
1146 # problems, but it generates empty tracebacks for console errors
1167 # problems, but it generates empty tracebacks for console errors
1147 # (5 blanks lines) where none should be returned.
1168 # (5 blanks lines) where none should be returned.
1148 return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
1169 return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
1149 except UnicodeDecodeError:
1170 except UnicodeDecodeError:
1150 # This can occur if a file's encoding magic comment is wrong.
1171 # This can occur if a file's encoding magic comment is wrong.
1151 # I can't see a way to recover without duplicating a bunch of code
1172 # I can't see a way to recover without duplicating a bunch of code
1152 # from the stdlib traceback module. --TK
1173 # from the stdlib traceback module. --TK
1153 error('\nUnicodeDecodeError while processing traceback.\n')
1174 error('\nUnicodeDecodeError while processing traceback.\n')
1154 return None
1175 return None
1155 except:
1176 except:
1156 # FIXME: I've been getting many crash reports from python 2.3
1177 # FIXME: I've been getting many crash reports from python 2.3
1157 # users, traceable to inspect.py. If I can find a small test-case
1178 # users, traceable to inspect.py. If I can find a small test-case
1158 # to reproduce this, I should either write a better workaround or
1179 # to reproduce this, I should either write a better workaround or
1159 # file a bug report against inspect (if that's the real problem).
1180 # file a bug report against inspect (if that's the real problem).
1160 # So far, I haven't been able to find an isolated example to
1181 # So far, I haven't been able to find an isolated example to
1161 # reproduce the problem.
1182 # reproduce the problem.
1162 inspect_error()
1183 inspect_error()
1163 traceback.print_exc(file=self.ostream)
1184 traceback.print_exc(file=self.ostream)
1164 info('\nUnfortunately, your original traceback can not be constructed.\n')
1185 info('\nUnfortunately, your original traceback can not be constructed.\n')
1165 return None
1186 return None
1166
1187
1167 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
1188 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
1168 number_of_lines_of_context=5):
1189 number_of_lines_of_context=5):
1169 """Return a nice text document describing the traceback."""
1190 """Return a nice text document describing the traceback."""
1170
1191
1171 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
1192 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
1172 tb_offset)
1193 tb_offset)
1173
1194
1174 colors = self.Colors # just a shorthand + quicker name lookup
1195 colors = self.Colors # just a shorthand + quicker name lookup
1175 colorsnormal = colors.Normal # used a lot
1196 colorsnormal = colors.Normal # used a lot
1176 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
1197 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
1177 structured_traceback_parts = [head]
1198 structured_traceback_parts = [head]
1178 chained_exceptions_tb_offset = 0
1199 chained_exceptions_tb_offset = 0
1179 lines_of_context = 3
1200 lines_of_context = 3
1180 formatted_exceptions = formatted_exception
1201 formatted_exceptions = formatted_exception
1181 exception = self.get_parts_of_chained_exception(evalue)
1202 exception = self.get_parts_of_chained_exception(evalue)
1182 if exception:
1203 if exception:
1183 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1204 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1184 etype, evalue, etb = exception
1205 etype, evalue, etb = exception
1185 else:
1206 else:
1186 evalue = None
1207 evalue = None
1187 chained_exc_ids = set()
1208 chained_exc_ids = set()
1188 while evalue:
1209 while evalue:
1189 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
1210 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
1190 chained_exceptions_tb_offset)
1211 chained_exceptions_tb_offset)
1191 exception = self.get_parts_of_chained_exception(evalue)
1212 exception = self.get_parts_of_chained_exception(evalue)
1192
1213
1193 if exception and not id(exception[1]) in chained_exc_ids:
1214 if exception and not id(exception[1]) in chained_exc_ids:
1194 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
1215 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
1195 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1216 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1196 etype, evalue, etb = exception
1217 etype, evalue, etb = exception
1197 else:
1218 else:
1198 evalue = None
1219 evalue = None
1199
1220
1200 # we want to see exceptions in a reversed order:
1221 # we want to see exceptions in a reversed order:
1201 # the first exception should be on top
1222 # the first exception should be on top
1202 for formatted_exception in reversed(formatted_exceptions):
1223 for formatted_exception in reversed(formatted_exceptions):
1203 structured_traceback_parts += formatted_exception
1224 structured_traceback_parts += formatted_exception
1204
1225
1205 return structured_traceback_parts
1226 return structured_traceback_parts
1206
1227
1207 def debugger(self, force=False):
1228 def debugger(self, force=False):
1208 """Call up the pdb debugger if desired, always clean up the tb
1229 """Call up the pdb debugger if desired, always clean up the tb
1209 reference.
1230 reference.
1210
1231
1211 Keywords:
1232 Keywords:
1212
1233
1213 - force(False): by default, this routine checks the instance call_pdb
1234 - force(False): by default, this routine checks the instance call_pdb
1214 flag and does not actually invoke the debugger if the flag is false.
1235 flag and does not actually invoke the debugger if the flag is false.
1215 The 'force' option forces the debugger to activate even if the flag
1236 The 'force' option forces the debugger to activate even if the flag
1216 is false.
1237 is false.
1217
1238
1218 If the call_pdb flag is set, the pdb interactive debugger is
1239 If the call_pdb flag is set, the pdb interactive debugger is
1219 invoked. In all cases, the self.tb reference to the current traceback
1240 invoked. In all cases, the self.tb reference to the current traceback
1220 is deleted to prevent lingering references which hamper memory
1241 is deleted to prevent lingering references which hamper memory
1221 management.
1242 management.
1222
1243
1223 Note that each call to pdb() does an 'import readline', so if your app
1244 Note that each call to pdb() does an 'import readline', so if your app
1224 requires a special setup for the readline completers, you'll have to
1245 requires a special setup for the readline completers, you'll have to
1225 fix that by hand after invoking the exception handler."""
1246 fix that by hand after invoking the exception handler."""
1226
1247
1227 if force or self.call_pdb:
1248 if force or self.call_pdb:
1228 if self.pdb is None:
1249 if self.pdb is None:
1229 self.pdb = self.debugger_cls()
1250 self.pdb = self.debugger_cls()
1230 # the system displayhook may have changed, restore the original
1251 # the system displayhook may have changed, restore the original
1231 # for pdb
1252 # for pdb
1232 display_trap = DisplayTrap(hook=sys.__displayhook__)
1253 display_trap = DisplayTrap(hook=sys.__displayhook__)
1233 with display_trap:
1254 with display_trap:
1234 self.pdb.reset()
1255 self.pdb.reset()
1235 # Find the right frame so we don't pop up inside ipython itself
1256 # Find the right frame so we don't pop up inside ipython itself
1236 if hasattr(self, 'tb') and self.tb is not None:
1257 if hasattr(self, 'tb') and self.tb is not None:
1237 etb = self.tb
1258 etb = self.tb
1238 else:
1259 else:
1239 etb = self.tb = sys.last_traceback
1260 etb = self.tb = sys.last_traceback
1240 while self.tb is not None and self.tb.tb_next is not None:
1261 while self.tb is not None and self.tb.tb_next is not None:
1241 self.tb = self.tb.tb_next
1262 self.tb = self.tb.tb_next
1242 if etb and etb.tb_next:
1263 if etb and etb.tb_next:
1243 etb = etb.tb_next
1264 etb = etb.tb_next
1244 self.pdb.botframe = etb.tb_frame
1265 self.pdb.botframe = etb.tb_frame
1245 self.pdb.interaction(None, etb)
1266 self.pdb.interaction(None, etb)
1246
1267
1247 if hasattr(self, 'tb'):
1268 if hasattr(self, 'tb'):
1248 del self.tb
1269 del self.tb
1249
1270
1250 def handler(self, info=None):
1271 def handler(self, info=None):
1251 (etype, evalue, etb) = info or sys.exc_info()
1272 (etype, evalue, etb) = info or sys.exc_info()
1252 self.tb = etb
1273 self.tb = etb
1253 ostream = self.ostream
1274 ostream = self.ostream
1254 ostream.flush()
1275 ostream.flush()
1255 ostream.write(self.text(etype, evalue, etb))
1276 ostream.write(self.text(etype, evalue, etb))
1256 ostream.write('\n')
1277 ostream.write('\n')
1257 ostream.flush()
1278 ostream.flush()
1258
1279
1259 # Changed so an instance can just be called as VerboseTB_inst() and print
1280 # Changed so an instance can just be called as VerboseTB_inst() and print
1260 # out the right info on its own.
1281 # out the right info on its own.
1261 def __call__(self, etype=None, evalue=None, etb=None):
1282 def __call__(self, etype=None, evalue=None, etb=None):
1262 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1283 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1263 if etb is None:
1284 if etb is None:
1264 self.handler()
1285 self.handler()
1265 else:
1286 else:
1266 self.handler((etype, evalue, etb))
1287 self.handler((etype, evalue, etb))
1267 try:
1288 try:
1268 self.debugger()
1289 self.debugger()
1269 except KeyboardInterrupt:
1290 except KeyboardInterrupt:
1270 print("\nKeyboardInterrupt")
1291 print("\nKeyboardInterrupt")
1271
1292
1272
1293
1273 #----------------------------------------------------------------------------
1294 #----------------------------------------------------------------------------
1274 class FormattedTB(VerboseTB, ListTB):
1295 class FormattedTB(VerboseTB, ListTB):
1275 """Subclass ListTB but allow calling with a traceback.
1296 """Subclass ListTB but allow calling with a traceback.
1276
1297
1277 It can thus be used as a sys.excepthook for Python > 2.1.
1298 It can thus be used as a sys.excepthook for Python > 2.1.
1278
1299
1279 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1300 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1280
1301
1281 Allows a tb_offset to be specified. This is useful for situations where
1302 Allows a tb_offset to be specified. This is useful for situations where
1282 one needs to remove a number of topmost frames from the traceback (such as
1303 one needs to remove a number of topmost frames from the traceback (such as
1283 occurs with python programs that themselves execute other python code,
1304 occurs with python programs that themselves execute other python code,
1284 like Python shells). """
1305 like Python shells). """
1285
1306
1286 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1307 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1287 ostream=None,
1308 ostream=None,
1288 tb_offset=0, long_header=False, include_vars=False,
1309 tb_offset=0, long_header=False, include_vars=False,
1289 check_cache=None, debugger_cls=None,
1310 check_cache=None, debugger_cls=None,
1290 parent=None, config=None):
1311 parent=None, config=None):
1291
1312
1292 # NEVER change the order of this list. Put new modes at the end:
1313 # NEVER change the order of this list. Put new modes at the end:
1293 self.valid_modes = ['Plain', 'Context', 'Verbose', 'Minimal']
1314 self.valid_modes = ['Plain', 'Context', 'Verbose', 'Minimal']
1294 self.verbose_modes = self.valid_modes[1:3]
1315 self.verbose_modes = self.valid_modes[1:3]
1295
1316
1296 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1317 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1297 ostream=ostream, tb_offset=tb_offset,
1318 ostream=ostream, tb_offset=tb_offset,
1298 long_header=long_header, include_vars=include_vars,
1319 long_header=long_header, include_vars=include_vars,
1299 check_cache=check_cache, debugger_cls=debugger_cls,
1320 check_cache=check_cache, debugger_cls=debugger_cls,
1300 parent=parent, config=config)
1321 parent=parent, config=config)
1301
1322
1302 # Different types of tracebacks are joined with different separators to
1323 # Different types of tracebacks are joined with different separators to
1303 # form a single string. They are taken from this dict
1324 # form a single string. They are taken from this dict
1304 self._join_chars = dict(Plain='', Context='\n', Verbose='\n',
1325 self._join_chars = dict(Plain='', Context='\n', Verbose='\n',
1305 Minimal='')
1326 Minimal='')
1306 # set_mode also sets the tb_join_char attribute
1327 # set_mode also sets the tb_join_char attribute
1307 self.set_mode(mode)
1328 self.set_mode(mode)
1308
1329
1309 def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
1330 def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
1310 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1331 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1311 mode = self.mode
1332 mode = self.mode
1312 if mode in self.verbose_modes:
1333 if mode in self.verbose_modes:
1313 # Verbose modes need a full traceback
1334 # Verbose modes need a full traceback
1314 return VerboseTB.structured_traceback(
1335 return VerboseTB.structured_traceback(
1315 self, etype, value, tb, tb_offset, number_of_lines_of_context
1336 self, etype, value, tb, tb_offset, number_of_lines_of_context
1316 )
1337 )
1317 elif mode == 'Minimal':
1338 elif mode == 'Minimal':
1318 return ListTB.get_exception_only(self, etype, value)
1339 return ListTB.get_exception_only(self, etype, value)
1319 else:
1340 else:
1320 # We must check the source cache because otherwise we can print
1341 # We must check the source cache because otherwise we can print
1321 # out-of-date source code.
1342 # out-of-date source code.
1322 self.check_cache()
1343 self.check_cache()
1323 # Now we can extract and format the exception
1344 # Now we can extract and format the exception
1324 return ListTB.structured_traceback(
1345 return ListTB.structured_traceback(
1325 self, etype, value, tb, tb_offset, number_of_lines_of_context
1346 self, etype, value, tb, tb_offset, number_of_lines_of_context
1326 )
1347 )
1327
1348
1328 def stb2text(self, stb):
1349 def stb2text(self, stb):
1329 """Convert a structured traceback (a list) to a string."""
1350 """Convert a structured traceback (a list) to a string."""
1330 return self.tb_join_char.join(stb)
1351 return self.tb_join_char.join(stb)
1331
1352
1332
1353
1333 def set_mode(self, mode=None):
1354 def set_mode(self, mode=None):
1334 """Switch to the desired mode.
1355 """Switch to the desired mode.
1335
1356
1336 If mode is not specified, cycles through the available modes."""
1357 If mode is not specified, cycles through the available modes."""
1337
1358
1338 if not mode:
1359 if not mode:
1339 new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
1360 new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
1340 len(self.valid_modes)
1361 len(self.valid_modes)
1341 self.mode = self.valid_modes[new_idx]
1362 self.mode = self.valid_modes[new_idx]
1342 elif mode not in self.valid_modes:
1363 elif mode not in self.valid_modes:
1343 raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
1364 raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
1344 'Valid modes: ' + str(self.valid_modes))
1365 'Valid modes: ' + str(self.valid_modes))
1345 else:
1366 else:
1346 self.mode = mode
1367 self.mode = mode
1347 # include variable details only in 'Verbose' mode
1368 # include variable details only in 'Verbose' mode
1348 self.include_vars = (self.mode == self.valid_modes[2])
1369 self.include_vars = (self.mode == self.valid_modes[2])
1349 # Set the join character for generating text tracebacks
1370 # Set the join character for generating text tracebacks
1350 self.tb_join_char = self._join_chars[self.mode]
1371 self.tb_join_char = self._join_chars[self.mode]
1351
1372
1352 # some convenient shortcuts
1373 # some convenient shortcuts
1353 def plain(self):
1374 def plain(self):
1354 self.set_mode(self.valid_modes[0])
1375 self.set_mode(self.valid_modes[0])
1355
1376
1356 def context(self):
1377 def context(self):
1357 self.set_mode(self.valid_modes[1])
1378 self.set_mode(self.valid_modes[1])
1358
1379
1359 def verbose(self):
1380 def verbose(self):
1360 self.set_mode(self.valid_modes[2])
1381 self.set_mode(self.valid_modes[2])
1361
1382
1362 def minimal(self):
1383 def minimal(self):
1363 self.set_mode(self.valid_modes[3])
1384 self.set_mode(self.valid_modes[3])
1364
1385
1365
1386
1366 #----------------------------------------------------------------------------
1387 #----------------------------------------------------------------------------
1367 class AutoFormattedTB(FormattedTB):
1388 class AutoFormattedTB(FormattedTB):
1368 """A traceback printer which can be called on the fly.
1389 """A traceback printer which can be called on the fly.
1369
1390
1370 It will find out about exceptions by itself.
1391 It will find out about exceptions by itself.
1371
1392
1372 A brief example::
1393 A brief example::
1373
1394
1374 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1395 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1375 try:
1396 try:
1376 ...
1397 ...
1377 except:
1398 except:
1378 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1399 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1379 """
1400 """
1380
1401
1381 def __call__(self, etype=None, evalue=None, etb=None,
1402 def __call__(self, etype=None, evalue=None, etb=None,
1382 out=None, tb_offset=None):
1403 out=None, tb_offset=None):
1383 """Print out a formatted exception traceback.
1404 """Print out a formatted exception traceback.
1384
1405
1385 Optional arguments:
1406 Optional arguments:
1386 - out: an open file-like object to direct output to.
1407 - out: an open file-like object to direct output to.
1387
1408
1388 - tb_offset: the number of frames to skip over in the stack, on a
1409 - tb_offset: the number of frames to skip over in the stack, on a
1389 per-call basis (this overrides temporarily the instance's tb_offset
1410 per-call basis (this overrides temporarily the instance's tb_offset
1390 given at initialization time. """
1411 given at initialization time. """
1391
1412
1392 if out is None:
1413 if out is None:
1393 out = self.ostream
1414 out = self.ostream
1394 out.flush()
1415 out.flush()
1395 out.write(self.text(etype, evalue, etb, tb_offset))
1416 out.write(self.text(etype, evalue, etb, tb_offset))
1396 out.write('\n')
1417 out.write('\n')
1397 out.flush()
1418 out.flush()
1398 # FIXME: we should remove the auto pdb behavior from here and leave
1419 # FIXME: we should remove the auto pdb behavior from here and leave
1399 # that to the clients.
1420 # that to the clients.
1400 try:
1421 try:
1401 self.debugger()
1422 self.debugger()
1402 except KeyboardInterrupt:
1423 except KeyboardInterrupt:
1403 print("\nKeyboardInterrupt")
1424 print("\nKeyboardInterrupt")
1404
1425
1405 def structured_traceback(self, etype=None, value=None, tb=None,
1426 def structured_traceback(self, etype=None, value=None, tb=None,
1406 tb_offset=None, number_of_lines_of_context=5):
1427 tb_offset=None, number_of_lines_of_context=5):
1407 if etype is None:
1428 if etype is None:
1408 etype, value, tb = sys.exc_info()
1429 etype, value, tb = sys.exc_info()
1409 if isinstance(tb, tuple):
1430 if isinstance(tb, tuple):
1410 # tb is a tuple if this is a chained exception.
1431 # tb is a tuple if this is a chained exception.
1411 self.tb = tb[0]
1432 self.tb = tb[0]
1412 else:
1433 else:
1413 self.tb = tb
1434 self.tb = tb
1414 return FormattedTB.structured_traceback(
1435 return FormattedTB.structured_traceback(
1415 self, etype, value, tb, tb_offset, number_of_lines_of_context)
1436 self, etype, value, tb, tb_offset, number_of_lines_of_context)
1416
1437
1417
1438
1418 #---------------------------------------------------------------------------
1439 #---------------------------------------------------------------------------
1419
1440
1420 # A simple class to preserve Nathan's original functionality.
1441 # A simple class to preserve Nathan's original functionality.
1421 class ColorTB(FormattedTB):
1442 class ColorTB(FormattedTB):
1422 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1443 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1423
1444
1424 def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
1445 def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
1425 FormattedTB.__init__(self, color_scheme=color_scheme,
1446 FormattedTB.__init__(self, color_scheme=color_scheme,
1426 call_pdb=call_pdb, **kwargs)
1447 call_pdb=call_pdb, **kwargs)
1427
1448
1428
1449
1429 class SyntaxTB(ListTB):
1450 class SyntaxTB(ListTB):
1430 """Extension which holds some state: the last exception value"""
1451 """Extension which holds some state: the last exception value"""
1431
1452
1432 def __init__(self, color_scheme='NoColor', parent=None, config=None):
1453 def __init__(self, color_scheme='NoColor', parent=None, config=None):
1433 ListTB.__init__(self, color_scheme, parent=parent, config=config)
1454 ListTB.__init__(self, color_scheme, parent=parent, config=config)
1434 self.last_syntax_error = None
1455 self.last_syntax_error = None
1435
1456
1436 def __call__(self, etype, value, elist):
1457 def __call__(self, etype, value, elist):
1437 self.last_syntax_error = value
1458 self.last_syntax_error = value
1438
1459
1439 ListTB.__call__(self, etype, value, elist)
1460 ListTB.__call__(self, etype, value, elist)
1440
1461
1441 def structured_traceback(self, etype, value, elist, tb_offset=None,
1462 def structured_traceback(self, etype, value, elist, tb_offset=None,
1442 context=5):
1463 context=5):
1443 # If the source file has been edited, the line in the syntax error can
1464 # If the source file has been edited, the line in the syntax error can
1444 # be wrong (retrieved from an outdated cache). This replaces it with
1465 # be wrong (retrieved from an outdated cache). This replaces it with
1445 # the current value.
1466 # the current value.
1446 if isinstance(value, SyntaxError) \
1467 if isinstance(value, SyntaxError) \
1447 and isinstance(value.filename, str) \
1468 and isinstance(value.filename, str) \
1448 and isinstance(value.lineno, int):
1469 and isinstance(value.lineno, int):
1449 linecache.checkcache(value.filename)
1470 linecache.checkcache(value.filename)
1450 newtext = linecache.getline(value.filename, value.lineno)
1471 newtext = linecache.getline(value.filename, value.lineno)
1451 if newtext:
1472 if newtext:
1452 value.text = newtext
1473 value.text = newtext
1453 self.last_syntax_error = value
1474 self.last_syntax_error = value
1454 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1475 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1455 tb_offset=tb_offset, context=context)
1476 tb_offset=tb_offset, context=context)
1456
1477
1457 def clear_err_state(self):
1478 def clear_err_state(self):
1458 """Return the current error state and clear it"""
1479 """Return the current error state and clear it"""
1459 e = self.last_syntax_error
1480 e = self.last_syntax_error
1460 self.last_syntax_error = None
1481 self.last_syntax_error = None
1461 return e
1482 return e
1462
1483
1463 def stb2text(self, stb):
1484 def stb2text(self, stb):
1464 """Convert a structured traceback (a list) to a string."""
1485 """Convert a structured traceback (a list) to a string."""
1465 return ''.join(stb)
1486 return ''.join(stb)
1466
1487
1467
1488
1468 # some internal-use functions
1489 # some internal-use functions
1469 def text_repr(value):
1490 def text_repr(value):
1470 """Hopefully pretty robust repr equivalent."""
1491 """Hopefully pretty robust repr equivalent."""
1471 # this is pretty horrible but should always return *something*
1492 # this is pretty horrible but should always return *something*
1472 try:
1493 try:
1473 return pydoc.text.repr(value)
1494 return pydoc.text.repr(value)
1474 except KeyboardInterrupt:
1495 except KeyboardInterrupt:
1475 raise
1496 raise
1476 except:
1497 except:
1477 try:
1498 try:
1478 return repr(value)
1499 return repr(value)
1479 except KeyboardInterrupt:
1500 except KeyboardInterrupt:
1480 raise
1501 raise
1481 except:
1502 except:
1482 try:
1503 try:
1483 # all still in an except block so we catch
1504 # all still in an except block so we catch
1484 # getattr raising
1505 # getattr raising
1485 name = getattr(value, '__name__', None)
1506 name = getattr(value, '__name__', None)
1486 if name:
1507 if name:
1487 # ick, recursion
1508 # ick, recursion
1488 return text_repr(name)
1509 return text_repr(name)
1489 klass = getattr(value, '__class__', None)
1510 klass = getattr(value, '__class__', None)
1490 if klass:
1511 if klass:
1491 return '%s instance' % text_repr(klass)
1512 return '%s instance' % text_repr(klass)
1492 except KeyboardInterrupt:
1513 except KeyboardInterrupt:
1493 raise
1514 raise
1494 except:
1515 except:
1495 return 'UNRECOVERABLE REPR FAILURE'
1516 return 'UNRECOVERABLE REPR FAILURE'
1496
1517
1497
1518
1498 def eqrepr(value, repr=text_repr):
1519 def eqrepr(value, repr=text_repr):
1499 return '=%s' % repr(value)
1520 return '=%s' % repr(value)
1500
1521
1501
1522
1502 def nullrepr(value, repr=text_repr):
1523 def nullrepr(value, repr=text_repr):
1503 return ''
1524 return ''
@@ -1,141 +1,151 b''
1 import asyncio
1 import asyncio
2 import signal
2 import signal
3 import sys
3 import sys
4 import threading
4 import threading
5
5
6 from IPython.core.debugger import Pdb
6 from IPython.core.debugger import Pdb
7
7
8 from IPython.core.completer import IPCompleter
8 from IPython.core.completer import IPCompleter
9 from .ptutils import IPythonPTCompleter
9 from .ptutils import IPythonPTCompleter
10 from .shortcuts import create_ipython_shortcuts, suspend_to_bg, cursor_in_leading_ws
10 from .shortcuts import create_ipython_shortcuts, suspend_to_bg, cursor_in_leading_ws
11
11
12 from prompt_toolkit.enums import DEFAULT_BUFFER
12 from prompt_toolkit.enums import DEFAULT_BUFFER
13 from prompt_toolkit.filters import (Condition, has_focus, has_selection,
13 from prompt_toolkit.filters import (Condition, has_focus, has_selection,
14 vi_insert_mode, emacs_insert_mode)
14 vi_insert_mode, emacs_insert_mode)
15 from prompt_toolkit.key_binding import KeyBindings
15 from prompt_toolkit.key_binding import KeyBindings
16 from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
16 from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
17 from pygments.token import Token
17 from pygments.token import Token
18 from prompt_toolkit.shortcuts.prompt import PromptSession
18 from prompt_toolkit.shortcuts.prompt import PromptSession
19 from prompt_toolkit.enums import EditingMode
19 from prompt_toolkit.enums import EditingMode
20 from prompt_toolkit.formatted_text import PygmentsTokens
20 from prompt_toolkit.formatted_text import PygmentsTokens
21
21
22 from prompt_toolkit import __version__ as ptk_version
22 from prompt_toolkit import __version__ as ptk_version
23 PTK3 = ptk_version.startswith('3.')
23 PTK3 = ptk_version.startswith('3.')
24
24
25
25
26 class TerminalPdb(Pdb):
26 class TerminalPdb(Pdb):
27 """Standalone IPython debugger."""
27 """Standalone IPython debugger."""
28
28
29 def __init__(self, *args, **kwargs):
29 def __init__(self, *args, **kwargs):
30 Pdb.__init__(self, *args, **kwargs)
30 Pdb.__init__(self, *args, **kwargs)
31 self._ptcomp = None
31 self._ptcomp = None
32 self.pt_init()
32 self.pt_init()
33
33
34 def pt_init(self):
34 def pt_init(self):
35 def get_prompt_tokens():
35 def get_prompt_tokens():
36 return [(Token.Prompt, self.prompt)]
36 return [(Token.Prompt, self.prompt)]
37
37
38 if self._ptcomp is None:
38 if self._ptcomp is None:
39 compl = IPCompleter(shell=self.shell,
39 compl = IPCompleter(shell=self.shell,
40 namespace={},
40 namespace={},
41 global_namespace={},
41 global_namespace={},
42 parent=self.shell,
42 parent=self.shell,
43 )
43 )
44 # add a completer for all the do_ methods
45 methods_names = [m[3:] for m in dir(self) if m.startswith("do_")]
46
47 def gen_comp(self, text):
48 return [m for m in methods_names if m.startswith(text)]
49 import types
50 newcomp = types.MethodType(gen_comp, compl)
51 compl.custom_matchers.insert(0, newcomp)
52 # end add completer.
53
44 self._ptcomp = IPythonPTCompleter(compl)
54 self._ptcomp = IPythonPTCompleter(compl)
45
55
46 options = dict(
56 options = dict(
47 message=(lambda: PygmentsTokens(get_prompt_tokens())),
57 message=(lambda: PygmentsTokens(get_prompt_tokens())),
48 editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()),
58 editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()),
49 key_bindings=create_ipython_shortcuts(self.shell),
59 key_bindings=create_ipython_shortcuts(self.shell),
50 history=self.shell.debugger_history,
60 history=self.shell.debugger_history,
51 completer=self._ptcomp,
61 completer=self._ptcomp,
52 enable_history_search=True,
62 enable_history_search=True,
53 mouse_support=self.shell.mouse_support,
63 mouse_support=self.shell.mouse_support,
54 complete_style=self.shell.pt_complete_style,
64 complete_style=self.shell.pt_complete_style,
55 style=self.shell.style,
65 style=self.shell.style,
56 color_depth=self.shell.color_depth,
66 color_depth=self.shell.color_depth,
57 )
67 )
58
68
59 if not PTK3:
69 if not PTK3:
60 options['inputhook'] = self.shell.inputhook
70 options['inputhook'] = self.shell.inputhook
61 self.pt_loop = asyncio.new_event_loop()
71 self.pt_loop = asyncio.new_event_loop()
62 self.pt_app = PromptSession(**options)
72 self.pt_app = PromptSession(**options)
63
73
64 def cmdloop(self, intro=None):
74 def cmdloop(self, intro=None):
65 """Repeatedly issue a prompt, accept input, parse an initial prefix
75 """Repeatedly issue a prompt, accept input, parse an initial prefix
66 off the received input, and dispatch to action methods, passing them
76 off the received input, and dispatch to action methods, passing them
67 the remainder of the line as argument.
77 the remainder of the line as argument.
68
78
69 override the same methods from cmd.Cmd to provide prompt toolkit replacement.
79 override the same methods from cmd.Cmd to provide prompt toolkit replacement.
70 """
80 """
71 if not self.use_rawinput:
81 if not self.use_rawinput:
72 raise ValueError('Sorry ipdb does not support use_rawinput=False')
82 raise ValueError('Sorry ipdb does not support use_rawinput=False')
73
83
74 # In order to make sure that prompt, which uses asyncio doesn't
84 # In order to make sure that prompt, which uses asyncio doesn't
75 # interfere with applications in which it's used, we always run the
85 # interfere with applications in which it's used, we always run the
76 # prompt itself in a different thread (we can't start an event loop
86 # prompt itself in a different thread (we can't start an event loop
77 # within an event loop). This new thread won't have any event loop
87 # within an event loop). This new thread won't have any event loop
78 # running, and here we run our prompt-loop.
88 # running, and here we run our prompt-loop.
79
89
80 self.preloop()
90 self.preloop()
81
91
82 try:
92 try:
83 if intro is not None:
93 if intro is not None:
84 self.intro = intro
94 self.intro = intro
85 if self.intro:
95 if self.intro:
86 self.stdout.write(str(self.intro)+"\n")
96 self.stdout.write(str(self.intro)+"\n")
87 stop = None
97 stop = None
88 while not stop:
98 while not stop:
89 if self.cmdqueue:
99 if self.cmdqueue:
90 line = self.cmdqueue.pop(0)
100 line = self.cmdqueue.pop(0)
91 else:
101 else:
92 self._ptcomp.ipy_completer.namespace = self.curframe_locals
102 self._ptcomp.ipy_completer.namespace = self.curframe_locals
93 self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals
103 self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals
94
104
95 # Run the prompt in a different thread.
105 # Run the prompt in a different thread.
96 line = ''
106 line = ''
97 keyboard_interrupt = False
107 keyboard_interrupt = False
98
108
99 def in_thread():
109 def in_thread():
100 nonlocal line, keyboard_interrupt
110 nonlocal line, keyboard_interrupt
101 try:
111 try:
102 line = self.pt_app.prompt()
112 line = self.pt_app.prompt()
103 except EOFError:
113 except EOFError:
104 line = 'EOF'
114 line = 'EOF'
105 except KeyboardInterrupt:
115 except KeyboardInterrupt:
106 keyboard_interrupt = True
116 keyboard_interrupt = True
107
117
108 th = threading.Thread(target=in_thread)
118 th = threading.Thread(target=in_thread)
109 th.start()
119 th.start()
110 th.join()
120 th.join()
111
121
112 if keyboard_interrupt:
122 if keyboard_interrupt:
113 raise KeyboardInterrupt
123 raise KeyboardInterrupt
114
124
115 line = self.precmd(line)
125 line = self.precmd(line)
116 stop = self.onecmd(line)
126 stop = self.onecmd(line)
117 stop = self.postcmd(stop, line)
127 stop = self.postcmd(stop, line)
118 self.postloop()
128 self.postloop()
119 except Exception:
129 except Exception:
120 raise
130 raise
121
131
122
132
123 def set_trace(frame=None):
133 def set_trace(frame=None):
124 """
134 """
125 Start debugging from `frame`.
135 Start debugging from `frame`.
126
136
127 If frame is not specified, debugging starts from caller's frame.
137 If frame is not specified, debugging starts from caller's frame.
128 """
138 """
129 TerminalPdb().set_trace(frame or sys._getframe().f_back)
139 TerminalPdb().set_trace(frame or sys._getframe().f_back)
130
140
131
141
132 if __name__ == '__main__':
142 if __name__ == '__main__':
133 import pdb
143 import pdb
134 # IPython.core.debugger.Pdb.trace_dispatch shall not catch
144 # IPython.core.debugger.Pdb.trace_dispatch shall not catch
135 # bdb.BdbQuit. When started through __main__ and an exception
145 # bdb.BdbQuit. When started through __main__ and an exception
136 # happened after hitting "c", this is needed in order to
146 # happened after hitting "c", this is needed in order to
137 # be able to quit the debugging session (see #9950).
147 # be able to quit the debugging session (see #9950).
138 old_trace_dispatch = pdb.Pdb.trace_dispatch
148 old_trace_dispatch = pdb.Pdb.trace_dispatch
139 pdb.Pdb = TerminalPdb
149 pdb.Pdb = TerminalPdb
140 pdb.Pdb.trace_dispatch = old_trace_dispatch
150 pdb.Pdb.trace_dispatch = old_trace_dispatch
141 pdb.main()
151 pdb.main()
@@ -1,38 +1,31 b''
1 build: false
1 build: false
2 matrix:
2 matrix:
3 fast_finish: true # immediately finish build once one of the jobs fails.
3 fast_finish: true # immediately finish build once one of the jobs fails.
4
4
5 environment:
5 environment:
6 matrix:
6 matrix:
7 - PYTHON: "C:\\Python36"
8 PYTHON_VERSION: "3.6.x"
9 PYTHON_ARCH: "32"
10
11 - PYTHON: "C:\\Python36-x64"
12 PYTHON_VERSION: "3.6.x"
13 PYTHON_ARCH: "64"
14
7
15 - PYTHON: "C:\\Python37-x64"
8 - PYTHON: "C:\\Python37-x64"
16 PYTHON_VERSION: "3.7.x"
9 PYTHON_VERSION: "3.7.x"
17 PYTHON_ARCH: "64"
10 PYTHON_ARCH: "64"
18
11
19 - PYTHON: "C:\\Python38"
12 - PYTHON: "C:\\Python38"
20 PYTHON_VERSION: "3.8.x"
13 PYTHON_VERSION: "3.8.x"
21 PYTHON_ARCH: "32"
14 PYTHON_ARCH: "32"
22
15
23 - PYTHON: "C:\\Python38-x64"
16 - PYTHON: "C:\\Python38-x64"
24 PYTHON_VERSION: "3.8.x"
17 PYTHON_VERSION: "3.8.x"
25 PYTHON_ARCH: "64"
18 PYTHON_ARCH: "64"
26
19
27 init:
20 init:
28 - "ECHO %PYTHON% %PYTHON_VERSION% %PYTHON_ARCH%"
21 - "ECHO %PYTHON% %PYTHON_VERSION% %PYTHON_ARCH%"
29
22
30 install:
23 install:
31 - "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%"
24 - "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%"
32 - "%CMD_IN_ENV% python -m pip install --upgrade setuptools pip"
25 - "%CMD_IN_ENV% python -m pip install --upgrade setuptools pip"
33 - "%CMD_IN_ENV% pip install nose coverage"
26 - "%CMD_IN_ENV% pip install nose coverage"
34 - "%CMD_IN_ENV% pip install .[test]"
27 - "%CMD_IN_ENV% pip install .[test]"
35 - "%CMD_IN_ENV% mkdir results"
28 - "%CMD_IN_ENV% mkdir results"
36 - "%CMD_IN_ENV% cd results"
29 - "%CMD_IN_ENV% cd results"
37 test_script:
30 test_script:
38 - "%CMD_IN_ENV% iptest --coverage xml"
31 - "%CMD_IN_ENV% iptest --coverage xml"
General Comments 0
You need to be logged in to leave comments. Login now