Show More
@@ -1,847 +1,847 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 | self.skip_hidden = True | |
284 |
|
284 | |||
285 | def set_colors(self, scheme): |
|
285 | def set_colors(self, scheme): | |
286 | """Shorthand access to the color table scheme selector method.""" |
|
286 | """Shorthand access to the color table scheme selector method.""" | |
287 | self.color_scheme_table.set_active_scheme(scheme) |
|
287 | self.color_scheme_table.set_active_scheme(scheme) | |
288 | self.parser.style = scheme |
|
288 | self.parser.style = scheme | |
289 |
|
289 | |||
290 | def set_trace(self, frame=None): |
|
290 | def set_trace(self, frame=None): | |
291 | if frame is None: |
|
291 | if frame is None: | |
292 | frame = sys._getframe().f_back |
|
292 | frame = sys._getframe().f_back | |
293 | self.initial_frame = frame |
|
293 | self.initial_frame = frame | |
294 | return super().set_trace(frame) |
|
294 | return super().set_trace(frame) | |
295 |
|
295 | |||
296 | def hidden_frames(self, stack): |
|
296 | def hidden_frames(self, stack): | |
297 | """ |
|
297 | """ | |
298 | Given an index in the stack return wether it should be skipped. |
|
298 | Given an index in the stack return wether it should be skipped. | |
299 |
|
299 | |||
300 | This is used in up/down and where to skip frames. |
|
300 | This is used in up/down and where to skip frames. | |
301 | """ |
|
301 | """ | |
302 | # The f_locals dictionary is updated from the actual frame |
|
302 | # The f_locals dictionary is updated from the actual frame | |
303 | # locals whenever the .f_locals accessor is called, so we |
|
303 | # locals whenever the .f_locals accessor is called, so we | |
304 | # avoid calling it here to preserve self.curframe_locals. |
|
304 | # avoid calling it here to preserve self.curframe_locals. | |
305 | # Futhermore, there is no good reason to hide the current frame. |
|
305 | # Futhermore, there is no good reason to hide the current frame. | |
306 | ip_hide = [ |
|
306 | ip_hide = [ | |
307 | False |
|
307 | False | |
308 | if s[0] in (self.curframe, getattr(self, "initial_frame", None)) |
|
308 | if s[0] in (self.curframe, getattr(self, "initial_frame", None)) | |
309 | else s[0].f_locals.get("__tracebackhide__", False) |
|
309 | else s[0].f_locals.get("__tracebackhide__", False) | |
310 | for s in stack |
|
310 | for s in stack | |
311 | ] |
|
311 | ] | |
312 | ip_start = [i for i, s in enumerate(ip_hide) if s == "__ipython_bottom__"] |
|
312 | ip_start = [i for i, s in enumerate(ip_hide) if s == "__ipython_bottom__"] | |
313 | if ip_start: |
|
313 | if ip_start: | |
314 | ip_hide = [h if i > ip_start[0] else True for (i, h) in enumerate(ip_hide)] |
|
314 | ip_hide = [h if i > ip_start[0] else True for (i, h) in enumerate(ip_hide)] | |
315 | return ip_hide |
|
315 | return ip_hide | |
316 |
|
316 | |||
317 | def interaction(self, frame, traceback): |
|
317 | def interaction(self, frame, traceback): | |
318 | try: |
|
318 | try: | |
319 | OldPdb.interaction(self, frame, traceback) |
|
319 | OldPdb.interaction(self, frame, traceback) | |
320 | except KeyboardInterrupt: |
|
320 | except KeyboardInterrupt: | |
321 | self.stdout.write("\n" + self.shell.get_exception_only()) |
|
321 | self.stdout.write("\n" + self.shell.get_exception_only()) | |
322 |
|
322 | |||
323 | def new_do_frame(self, arg): |
|
323 | def new_do_frame(self, arg): | |
324 | OldPdb.do_frame(self, arg) |
|
324 | OldPdb.do_frame(self, arg) | |
325 |
|
325 | |||
326 | def new_do_quit(self, arg): |
|
326 | def new_do_quit(self, arg): | |
327 |
|
327 | |||
328 | if hasattr(self, 'old_all_completions'): |
|
328 | if hasattr(self, 'old_all_completions'): | |
329 | self.shell.Completer.all_completions=self.old_all_completions |
|
329 | self.shell.Completer.all_completions=self.old_all_completions | |
330 |
|
330 | |||
331 | return OldPdb.do_quit(self, arg) |
|
331 | return OldPdb.do_quit(self, arg) | |
332 |
|
332 | |||
333 | do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit) |
|
333 | do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit) | |
334 |
|
334 | |||
335 | def new_do_restart(self, arg): |
|
335 | def new_do_restart(self, arg): | |
336 | """Restart command. In the context of ipython this is exactly the same |
|
336 | """Restart command. In the context of ipython this is exactly the same | |
337 | thing as 'quit'.""" |
|
337 | thing as 'quit'.""" | |
338 | self.msg("Restart doesn't make sense here. Using 'quit' instead.") |
|
338 | self.msg("Restart doesn't make sense here. Using 'quit' instead.") | |
339 | return self.do_quit(arg) |
|
339 | return self.do_quit(arg) | |
340 |
|
340 | |||
341 | def print_stack_trace(self, context=None): |
|
341 | def print_stack_trace(self, context=None): | |
342 | Colors = self.color_scheme_table.active_colors |
|
342 | Colors = self.color_scheme_table.active_colors | |
343 | ColorsNormal = Colors.Normal |
|
343 | ColorsNormal = Colors.Normal | |
344 | if context is None: |
|
344 | if context is None: | |
345 | context = self.context |
|
345 | context = self.context | |
346 | try: |
|
346 | try: | |
347 | context=int(context) |
|
347 | context=int(context) | |
348 | if context <= 0: |
|
348 | if context <= 0: | |
349 | raise ValueError("Context must be a positive integer") |
|
349 | raise ValueError("Context must be a positive integer") | |
350 | except (TypeError, ValueError): |
|
350 | except (TypeError, ValueError): | |
351 | raise ValueError("Context must be a positive integer") |
|
351 | raise ValueError("Context must be a positive integer") | |
352 | try: |
|
352 | try: | |
353 | skipped = 0 |
|
353 | skipped = 0 | |
354 | for hidden, frame_lineno in zip(self.hidden_frames(self.stack), self.stack): |
|
354 | for hidden, frame_lineno in zip(self.hidden_frames(self.stack), self.stack): | |
355 | if hidden and self.skip_hidden: |
|
355 | if hidden and self.skip_hidden: | |
356 | skipped += 1 |
|
356 | skipped += 1 | |
357 | continue |
|
357 | continue | |
358 | if skipped: |
|
358 | if skipped: | |
359 | print( |
|
359 | print( | |
360 | f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n" |
|
360 | f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n" | |
361 | ) |
|
361 | ) | |
362 | skipped = 0 |
|
362 | skipped = 0 | |
363 | self.print_stack_entry(frame_lineno, context=context) |
|
363 | self.print_stack_entry(frame_lineno, context=context) | |
364 | if skipped: |
|
364 | if skipped: | |
365 | print( |
|
365 | print( | |
366 | f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n" |
|
366 | f"{Colors.excName} [... skipping {skipped} hidden frame(s)]{ColorsNormal}\n" | |
367 | ) |
|
367 | ) | |
368 | except KeyboardInterrupt: |
|
368 | except KeyboardInterrupt: | |
369 | pass |
|
369 | pass | |
370 |
|
370 | |||
371 | def print_stack_entry(self, frame_lineno, prompt_prefix='\n-> ', |
|
371 | def print_stack_entry(self, frame_lineno, prompt_prefix='\n-> ', | |
372 | context=None): |
|
372 | context=None): | |
373 | if context is None: |
|
373 | if context is None: | |
374 | context = self.context |
|
374 | context = self.context | |
375 | try: |
|
375 | try: | |
376 | context=int(context) |
|
376 | context=int(context) | |
377 | if context <= 0: |
|
377 | if context <= 0: | |
378 | raise ValueError("Context must be a positive integer") |
|
378 | raise ValueError("Context must be a positive integer") | |
379 | except (TypeError, ValueError): |
|
379 | except (TypeError, ValueError): | |
380 | raise ValueError("Context must be a positive integer") |
|
380 | raise ValueError("Context must be a positive integer") | |
381 | print(self.format_stack_entry(frame_lineno, '', context), file=self.stdout) |
|
381 | print(self.format_stack_entry(frame_lineno, '', context), file=self.stdout) | |
382 |
|
382 | |||
383 | # vds: >> |
|
383 | # vds: >> | |
384 | frame, lineno = frame_lineno |
|
384 | frame, lineno = frame_lineno | |
385 | filename = frame.f_code.co_filename |
|
385 | filename = frame.f_code.co_filename | |
386 | self.shell.hooks.synchronize_with_editor(filename, lineno, 0) |
|
386 | self.shell.hooks.synchronize_with_editor(filename, lineno, 0) | |
387 | # vds: << |
|
387 | # vds: << | |
388 |
|
388 | |||
389 | def format_stack_entry(self, frame_lineno, lprefix=': ', context=None): |
|
389 | def format_stack_entry(self, frame_lineno, lprefix=': ', context=None): | |
390 | if context is None: |
|
390 | if context is None: | |
391 | context = self.context |
|
391 | context = self.context | |
392 | try: |
|
392 | try: | |
393 | context=int(context) |
|
393 | context=int(context) | |
394 | if context <= 0: |
|
394 | if context <= 0: | |
395 | print("Context must be a positive integer", file=self.stdout) |
|
395 | print("Context must be a positive integer", file=self.stdout) | |
396 | except (TypeError, ValueError): |
|
396 | except (TypeError, ValueError): | |
397 | print("Context must be a positive integer", file=self.stdout) |
|
397 | print("Context must be a positive integer", file=self.stdout) | |
398 | try: |
|
398 | try: | |
399 | import reprlib # Py 3 |
|
399 | import reprlib # Py 3 | |
400 | except ImportError: |
|
400 | except ImportError: | |
401 | import repr as reprlib # Py 2 |
|
401 | import repr as reprlib # Py 2 | |
402 |
|
402 | |||
403 | ret = [] |
|
403 | ret = [] | |
404 |
|
404 | |||
405 | Colors = self.color_scheme_table.active_colors |
|
405 | Colors = self.color_scheme_table.active_colors | |
406 | ColorsNormal = Colors.Normal |
|
406 | ColorsNormal = Colors.Normal | |
407 | tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal) |
|
407 | tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal) | |
408 | tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal) |
|
408 | tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal) | |
409 | tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) |
|
409 | tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) | |
410 | tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, |
|
410 | tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, | |
411 | ColorsNormal) |
|
411 | ColorsNormal) | |
412 |
|
412 | |||
413 | frame, lineno = frame_lineno |
|
413 | frame, lineno = frame_lineno | |
414 |
|
414 | |||
415 | return_value = '' |
|
415 | return_value = '' | |
416 | if '__return__' in frame.f_locals: |
|
416 | if '__return__' in frame.f_locals: | |
417 | rv = frame.f_locals['__return__'] |
|
417 | rv = frame.f_locals['__return__'] | |
418 | #return_value += '->' |
|
418 | #return_value += '->' | |
419 | return_value += reprlib.repr(rv) + '\n' |
|
419 | return_value += reprlib.repr(rv) + '\n' | |
420 | ret.append(return_value) |
|
420 | ret.append(return_value) | |
421 |
|
421 | |||
422 | #s = filename + '(' + `lineno` + ')' |
|
422 | #s = filename + '(' + `lineno` + ')' | |
423 | filename = self.canonic(frame.f_code.co_filename) |
|
423 | filename = self.canonic(frame.f_code.co_filename) | |
424 | link = tpl_link % py3compat.cast_unicode(filename) |
|
424 | link = tpl_link % py3compat.cast_unicode(filename) | |
425 |
|
425 | |||
426 | if frame.f_code.co_name: |
|
426 | if frame.f_code.co_name: | |
427 | func = frame.f_code.co_name |
|
427 | func = frame.f_code.co_name | |
428 | else: |
|
428 | else: | |
429 | func = "<lambda>" |
|
429 | func = "<lambda>" | |
430 |
|
430 | |||
431 | call = '' |
|
431 | call = '' | |
432 | if func != '?': |
|
432 | if func != '?': | |
433 | if '__args__' in frame.f_locals: |
|
433 | if '__args__' in frame.f_locals: | |
434 | args = reprlib.repr(frame.f_locals['__args__']) |
|
434 | args = reprlib.repr(frame.f_locals['__args__']) | |
435 | else: |
|
435 | else: | |
436 | args = '()' |
|
436 | args = '()' | |
437 | call = tpl_call % (func, args) |
|
437 | call = tpl_call % (func, args) | |
438 |
|
438 | |||
439 | # The level info should be generated in the same format pdb uses, to |
|
439 | # The level info should be generated in the same format pdb uses, to | |
440 | # avoid breaking the pdbtrack functionality of python-mode in *emacs. |
|
440 | # avoid breaking the pdbtrack functionality of python-mode in *emacs. | |
441 | if frame is self.curframe: |
|
441 | if frame is self.curframe: | |
442 | ret.append('> ') |
|
442 | ret.append('> ') | |
443 | else: |
|
443 | else: | |
444 | ret.append(' ') |
|
444 | ret.append(' ') | |
445 | ret.append(u'%s(%s)%s\n' % (link,lineno,call)) |
|
445 | ret.append(u'%s(%s)%s\n' % (link,lineno,call)) | |
446 |
|
446 | |||
447 | start = lineno - 1 - context//2 |
|
447 | start = lineno - 1 - context//2 | |
448 | lines = linecache.getlines(filename) |
|
448 | lines = linecache.getlines(filename) | |
449 | start = min(start, len(lines) - context) |
|
449 | start = min(start, len(lines) - context) | |
450 | start = max(start, 0) |
|
450 | start = max(start, 0) | |
451 | lines = lines[start : start + context] |
|
451 | lines = lines[start : start + context] | |
452 |
|
452 | |||
453 | for i,line in enumerate(lines): |
|
453 | for i,line in enumerate(lines): | |
454 | show_arrow = (start + 1 + i == lineno) |
|
454 | show_arrow = (start + 1 + i == lineno) | |
455 | linetpl = (frame is self.curframe or show_arrow) \ |
|
455 | linetpl = (frame is self.curframe or show_arrow) \ | |
456 | and tpl_line_em \ |
|
456 | and tpl_line_em \ | |
457 | or tpl_line |
|
457 | or tpl_line | |
458 | ret.append(self.__format_line(linetpl, filename, |
|
458 | ret.append(self.__format_line(linetpl, filename, | |
459 | start + 1 + i, line, |
|
459 | start + 1 + i, line, | |
460 | arrow = show_arrow) ) |
|
460 | arrow = show_arrow) ) | |
461 | return ''.join(ret) |
|
461 | return ''.join(ret) | |
462 |
|
462 | |||
463 | def __format_line(self, tpl_line, filename, lineno, line, arrow = False): |
|
463 | def __format_line(self, tpl_line, filename, lineno, line, arrow = False): | |
464 | bp_mark = "" |
|
464 | bp_mark = "" | |
465 | bp_mark_color = "" |
|
465 | bp_mark_color = "" | |
466 |
|
466 | |||
467 | new_line, err = self.parser.format2(line, 'str') |
|
467 | new_line, err = self.parser.format2(line, 'str') | |
468 | if not err: |
|
468 | if not err: | |
469 | line = new_line |
|
469 | line = new_line | |
470 |
|
470 | |||
471 | bp = None |
|
471 | bp = None | |
472 | if lineno in self.get_file_breaks(filename): |
|
472 | if lineno in self.get_file_breaks(filename): | |
473 | bps = self.get_breaks(filename, lineno) |
|
473 | bps = self.get_breaks(filename, lineno) | |
474 | bp = bps[-1] |
|
474 | bp = bps[-1] | |
475 |
|
475 | |||
476 | if bp: |
|
476 | if bp: | |
477 | Colors = self.color_scheme_table.active_colors |
|
477 | Colors = self.color_scheme_table.active_colors | |
478 | bp_mark = str(bp.number) |
|
478 | bp_mark = str(bp.number) | |
479 | bp_mark_color = Colors.breakpoint_enabled |
|
479 | bp_mark_color = Colors.breakpoint_enabled | |
480 | if not bp.enabled: |
|
480 | if not bp.enabled: | |
481 | bp_mark_color = Colors.breakpoint_disabled |
|
481 | bp_mark_color = Colors.breakpoint_disabled | |
482 |
|
482 | |||
483 | numbers_width = 7 |
|
483 | numbers_width = 7 | |
484 | if arrow: |
|
484 | if arrow: | |
485 | # This is the line with the error |
|
485 | # This is the line with the error | |
486 | pad = numbers_width - len(str(lineno)) - len(bp_mark) |
|
486 | pad = numbers_width - len(str(lineno)) - len(bp_mark) | |
487 | num = '%s%s' % (make_arrow(pad), str(lineno)) |
|
487 | num = '%s%s' % (make_arrow(pad), str(lineno)) | |
488 | else: |
|
488 | else: | |
489 | num = '%*s' % (numbers_width - len(bp_mark), str(lineno)) |
|
489 | num = '%*s' % (numbers_width - len(bp_mark), str(lineno)) | |
490 |
|
490 | |||
491 | return tpl_line % (bp_mark_color + bp_mark, num, line) |
|
491 | return tpl_line % (bp_mark_color + bp_mark, num, line) | |
492 |
|
492 | |||
493 |
|
493 | |||
494 | def print_list_lines(self, filename, first, last): |
|
494 | def print_list_lines(self, filename, first, last): | |
495 | """The printing (as opposed to the parsing part of a 'list' |
|
495 | """The printing (as opposed to the parsing part of a 'list' | |
496 | command.""" |
|
496 | command.""" | |
497 | try: |
|
497 | try: | |
498 | Colors = self.color_scheme_table.active_colors |
|
498 | Colors = self.color_scheme_table.active_colors | |
499 | ColorsNormal = Colors.Normal |
|
499 | ColorsNormal = Colors.Normal | |
500 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) |
|
500 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) | |
501 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal) |
|
501 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal) | |
502 | src = [] |
|
502 | src = [] | |
503 | if filename == "<string>" and hasattr(self, "_exec_filename"): |
|
503 | if filename == "<string>" and hasattr(self, "_exec_filename"): | |
504 | filename = self._exec_filename |
|
504 | filename = self._exec_filename | |
505 |
|
505 | |||
506 | for lineno in range(first, last+1): |
|
506 | for lineno in range(first, last+1): | |
507 | line = linecache.getline(filename, lineno) |
|
507 | line = linecache.getline(filename, lineno) | |
508 | if not line: |
|
508 | if not line: | |
509 | break |
|
509 | break | |
510 |
|
510 | |||
511 | if lineno == self.curframe.f_lineno: |
|
511 | if lineno == self.curframe.f_lineno: | |
512 | line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True) |
|
512 | line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True) | |
513 | else: |
|
513 | else: | |
514 | line = self.__format_line(tpl_line, filename, lineno, line, arrow = False) |
|
514 | line = self.__format_line(tpl_line, filename, lineno, line, arrow = False) | |
515 |
|
515 | |||
516 | src.append(line) |
|
516 | src.append(line) | |
517 | self.lineno = lineno |
|
517 | self.lineno = lineno | |
518 |
|
518 | |||
519 | print(''.join(src), file=self.stdout) |
|
519 | print(''.join(src), file=self.stdout) | |
520 |
|
520 | |||
521 | except KeyboardInterrupt: |
|
521 | except KeyboardInterrupt: | |
522 | pass |
|
522 | pass | |
523 |
|
523 | |||
524 | def do_skip_hidden(self, arg): |
|
524 | def do_skip_hidden(self, arg): | |
525 | """ |
|
525 | """ | |
526 | Change whether or not we should skip frames with the |
|
526 | Change whether or not we should skip frames with the | |
527 | __tracebackhide__ attribute. |
|
527 | __tracebackhide__ attribute. | |
528 | """ |
|
528 | """ | |
529 | if arg.strip().lower() in ("true", "yes"): |
|
529 | if arg.strip().lower() in ("true", "yes"): | |
530 | self.skip_hidden = True |
|
530 | self.skip_hidden = True | |
531 | elif arg.strip().lower() in ("false", "no"): |
|
531 | elif arg.strip().lower() in ("false", "no"): | |
532 | self.skip_hidden = False |
|
532 | self.skip_hidden = False | |
533 |
|
533 | |||
534 | def do_list(self, arg): |
|
534 | def do_list(self, arg): | |
535 | """Print lines of code from the current stack frame |
|
535 | """Print lines of code from the current stack frame | |
536 | """ |
|
536 | """ | |
537 | self.lastcmd = 'list' |
|
537 | self.lastcmd = 'list' | |
538 | last = None |
|
538 | last = None | |
539 | if arg: |
|
539 | if arg: | |
540 | try: |
|
540 | try: | |
541 | x = eval(arg, {}, {}) |
|
541 | x = eval(arg, {}, {}) | |
542 | if type(x) == type(()): |
|
542 | if type(x) == type(()): | |
543 | first, last = x |
|
543 | first, last = x | |
544 | first = int(first) |
|
544 | first = int(first) | |
545 | last = int(last) |
|
545 | last = int(last) | |
546 | if last < first: |
|
546 | if last < first: | |
547 | # Assume it's a count |
|
547 | # Assume it's a count | |
548 | last = first + last |
|
548 | last = first + last | |
549 | else: |
|
549 | else: | |
550 | first = max(1, int(x) - 5) |
|
550 | first = max(1, int(x) - 5) | |
551 | except: |
|
551 | except: | |
552 | print('*** Error in argument:', repr(arg), file=self.stdout) |
|
552 | print('*** Error in argument:', repr(arg), file=self.stdout) | |
553 | return |
|
553 | return | |
554 | elif self.lineno is None: |
|
554 | elif self.lineno is None: | |
555 | first = max(1, self.curframe.f_lineno - 5) |
|
555 | first = max(1, self.curframe.f_lineno - 5) | |
556 | else: |
|
556 | else: | |
557 | first = self.lineno + 1 |
|
557 | first = self.lineno + 1 | |
558 | if last is None: |
|
558 | if last is None: | |
559 | last = first + 10 |
|
559 | last = first + 10 | |
560 | self.print_list_lines(self.curframe.f_code.co_filename, first, last) |
|
560 | self.print_list_lines(self.curframe.f_code.co_filename, first, last) | |
561 |
|
561 | |||
562 | # vds: >> |
|
562 | # vds: >> | |
563 | lineno = first |
|
563 | lineno = first | |
564 | filename = self.curframe.f_code.co_filename |
|
564 | filename = self.curframe.f_code.co_filename | |
565 | self.shell.hooks.synchronize_with_editor(filename, lineno, 0) |
|
565 | self.shell.hooks.synchronize_with_editor(filename, lineno, 0) | |
566 | # vds: << |
|
566 | # vds: << | |
567 |
|
567 | |||
568 | do_l = do_list |
|
568 | do_l = do_list | |
569 |
|
569 | |||
570 | def getsourcelines(self, obj): |
|
570 | def getsourcelines(self, obj): | |
571 | lines, lineno = inspect.findsource(obj) |
|
571 | lines, lineno = inspect.findsource(obj) | |
572 | if inspect.isframe(obj) and obj.f_globals is obj.f_locals: |
|
572 | if inspect.isframe(obj) and obj.f_globals is obj.f_locals: | |
573 | # must be a module frame: do not try to cut a block out of it |
|
573 | # must be a module frame: do not try to cut a block out of it | |
574 | return lines, 1 |
|
574 | return lines, 1 | |
575 | elif inspect.ismodule(obj): |
|
575 | elif inspect.ismodule(obj): | |
576 | return lines, 1 |
|
576 | return lines, 1 | |
577 | return inspect.getblock(lines[lineno:]), lineno+1 |
|
577 | return inspect.getblock(lines[lineno:]), lineno+1 | |
578 |
|
578 | |||
579 | def do_longlist(self, arg): |
|
579 | def do_longlist(self, arg): | |
580 | """Print lines of code from the current stack frame. |
|
580 | """Print lines of code from the current stack frame. | |
581 |
|
581 | |||
582 | Shows more lines than 'list' does. |
|
582 | Shows more lines than 'list' does. | |
583 | """ |
|
583 | """ | |
584 | self.lastcmd = 'longlist' |
|
584 | self.lastcmd = 'longlist' | |
585 | try: |
|
585 | try: | |
586 | lines, lineno = self.getsourcelines(self.curframe) |
|
586 | lines, lineno = self.getsourcelines(self.curframe) | |
587 | except OSError as err: |
|
587 | except OSError as err: | |
588 | self.error(err) |
|
588 | self.error(err) | |
589 | return |
|
589 | return | |
590 | last = lineno + len(lines) |
|
590 | last = lineno + len(lines) | |
591 | self.print_list_lines(self.curframe.f_code.co_filename, lineno, last) |
|
591 | self.print_list_lines(self.curframe.f_code.co_filename, lineno, last) | |
592 | do_ll = do_longlist |
|
592 | do_ll = do_longlist | |
593 |
|
593 | |||
594 | def do_debug(self, arg): |
|
594 | def do_debug(self, arg): | |
595 | """debug code |
|
595 | """debug code | |
596 | Enter a recursive debugger that steps through the code |
|
596 | Enter a recursive debugger that steps through the code | |
597 | argument (which is an arbitrary expression or statement to be |
|
597 | argument (which is an arbitrary expression or statement to be | |
598 | executed in the current environment). |
|
598 | executed in the current environment). | |
599 | """ |
|
599 | """ | |
600 | trace_function = sys.gettrace() |
|
600 | trace_function = sys.gettrace() | |
601 | sys.settrace(None) |
|
601 | sys.settrace(None) | |
602 | globals = self.curframe.f_globals |
|
602 | globals = self.curframe.f_globals | |
603 | locals = self.curframe_locals |
|
603 | locals = self.curframe_locals | |
604 | p = self.__class__(completekey=self.completekey, |
|
604 | p = self.__class__(completekey=self.completekey, | |
605 | stdin=self.stdin, stdout=self.stdout) |
|
605 | stdin=self.stdin, stdout=self.stdout) | |
606 | p.use_rawinput = self.use_rawinput |
|
606 | p.use_rawinput = self.use_rawinput | |
607 | p.prompt = "(%s) " % self.prompt.strip() |
|
607 | p.prompt = "(%s) " % self.prompt.strip() | |
608 | self.message("ENTERING RECURSIVE DEBUGGER") |
|
608 | self.message("ENTERING RECURSIVE DEBUGGER") | |
609 | sys.call_tracing(p.run, (arg, globals, locals)) |
|
609 | sys.call_tracing(p.run, (arg, globals, locals)) | |
610 | self.message("LEAVING RECURSIVE DEBUGGER") |
|
610 | self.message("LEAVING RECURSIVE DEBUGGER") | |
611 | sys.settrace(trace_function) |
|
611 | sys.settrace(trace_function) | |
612 | self.lastcmd = p.lastcmd |
|
612 | self.lastcmd = p.lastcmd | |
613 |
|
613 | |||
614 | def do_pdef(self, arg): |
|
614 | def do_pdef(self, arg): | |
615 | """Print the call signature for any callable object. |
|
615 | """Print the call signature for any callable object. | |
616 |
|
616 | |||
617 | The debugger interface to %pdef""" |
|
617 | The debugger interface to %pdef""" | |
618 | namespaces = [ |
|
618 | namespaces = [ | |
619 | ("Locals", self.curframe_locals), |
|
619 | ("Locals", self.curframe_locals), | |
620 | ("Globals", self.curframe.f_globals), |
|
620 | ("Globals", self.curframe.f_globals), | |
621 | ] |
|
621 | ] | |
622 | self.shell.find_line_magic("pdef")(arg, namespaces=namespaces) |
|
622 | self.shell.find_line_magic("pdef")(arg, namespaces=namespaces) | |
623 |
|
623 | |||
624 | def do_pdoc(self, arg): |
|
624 | def do_pdoc(self, arg): | |
625 | """Print the docstring for an object. |
|
625 | """Print the docstring for an object. | |
626 |
|
626 | |||
627 | The debugger interface to %pdoc.""" |
|
627 | The debugger interface to %pdoc.""" | |
628 | namespaces = [ |
|
628 | namespaces = [ | |
629 | ("Locals", self.curframe_locals), |
|
629 | ("Locals", self.curframe_locals), | |
630 | ("Globals", self.curframe.f_globals), |
|
630 | ("Globals", self.curframe.f_globals), | |
631 | ] |
|
631 | ] | |
632 | self.shell.find_line_magic("pdoc")(arg, namespaces=namespaces) |
|
632 | self.shell.find_line_magic("pdoc")(arg, namespaces=namespaces) | |
633 |
|
633 | |||
634 | def do_pfile(self, arg): |
|
634 | def do_pfile(self, arg): | |
635 | """Print (or run through pager) the file where an object is defined. |
|
635 | """Print (or run through pager) the file where an object is defined. | |
636 |
|
636 | |||
637 | The debugger interface to %pfile. |
|
637 | The debugger interface to %pfile. | |
638 | """ |
|
638 | """ | |
639 | namespaces = [ |
|
639 | namespaces = [ | |
640 | ("Locals", self.curframe_locals), |
|
640 | ("Locals", self.curframe_locals), | |
641 | ("Globals", self.curframe.f_globals), |
|
641 | ("Globals", self.curframe.f_globals), | |
642 | ] |
|
642 | ] | |
643 | self.shell.find_line_magic("pfile")(arg, namespaces=namespaces) |
|
643 | self.shell.find_line_magic("pfile")(arg, namespaces=namespaces) | |
644 |
|
644 | |||
645 | def do_pinfo(self, arg): |
|
645 | def do_pinfo(self, arg): | |
646 | """Provide detailed information about an object. |
|
646 | """Provide detailed information about an object. | |
647 |
|
647 | |||
648 | The debugger interface to %pinfo, i.e., obj?.""" |
|
648 | The debugger interface to %pinfo, i.e., obj?.""" | |
649 | namespaces = [ |
|
649 | namespaces = [ | |
650 | ("Locals", self.curframe_locals), |
|
650 | ("Locals", self.curframe_locals), | |
651 | ("Globals", self.curframe.f_globals), |
|
651 | ("Globals", self.curframe.f_globals), | |
652 | ] |
|
652 | ] | |
653 | self.shell.find_line_magic("pinfo")(arg, namespaces=namespaces) |
|
653 | self.shell.find_line_magic("pinfo")(arg, namespaces=namespaces) | |
654 |
|
654 | |||
655 | def do_pinfo2(self, arg): |
|
655 | def do_pinfo2(self, arg): | |
656 | """Provide extra detailed information about an object. |
|
656 | """Provide extra detailed information about an object. | |
657 |
|
657 | |||
658 | The debugger interface to %pinfo2, i.e., obj??.""" |
|
658 | The debugger interface to %pinfo2, i.e., obj??.""" | |
659 | namespaces = [ |
|
659 | namespaces = [ | |
660 | ("Locals", self.curframe_locals), |
|
660 | ("Locals", self.curframe_locals), | |
661 | ("Globals", self.curframe.f_globals), |
|
661 | ("Globals", self.curframe.f_globals), | |
662 | ] |
|
662 | ] | |
663 | self.shell.find_line_magic("pinfo2")(arg, namespaces=namespaces) |
|
663 | self.shell.find_line_magic("pinfo2")(arg, namespaces=namespaces) | |
664 |
|
664 | |||
665 | def do_psource(self, arg): |
|
665 | def do_psource(self, arg): | |
666 | """Print (or run through pager) the source code for an object.""" |
|
666 | """Print (or run through pager) the source code for an object.""" | |
667 | namespaces = [ |
|
667 | namespaces = [ | |
668 | ("Locals", self.curframe_locals), |
|
668 | ("Locals", self.curframe_locals), | |
669 | ("Globals", self.curframe.f_globals), |
|
669 | ("Globals", self.curframe.f_globals), | |
670 | ] |
|
670 | ] | |
671 | self.shell.find_line_magic("psource")(arg, namespaces=namespaces) |
|
671 | self.shell.find_line_magic("psource")(arg, namespaces=namespaces) | |
672 |
|
672 | |||
673 | def do_where(self, arg): |
|
673 | def do_where(self, arg): | |
674 | """w(here) |
|
674 | """w(here) | |
675 | Print a stack trace, with the most recent frame at the bottom. |
|
675 | Print a stack trace, with the most recent frame at the bottom. | |
676 | An arrow indicates the "current frame", which determines the |
|
676 | An arrow indicates the "current frame", which determines the | |
677 | context of most commands. 'bt' is an alias for this command. |
|
677 | context of most commands. 'bt' is an alias for this command. | |
678 |
|
678 | |||
679 | Take a number as argument as an (optional) number of context line to |
|
679 | Take a number as argument as an (optional) number of context line to | |
680 | print""" |
|
680 | print""" | |
681 | if arg: |
|
681 | if arg: | |
682 | try: |
|
682 | try: | |
683 | context = int(arg) |
|
683 | context = int(arg) | |
684 | except ValueError as err: |
|
684 | except ValueError as err: | |
685 | self.error(err) |
|
685 | self.error(err) | |
686 | return |
|
686 | return | |
687 | self.print_stack_trace(context) |
|
687 | self.print_stack_trace(context) | |
688 | else: |
|
688 | else: | |
689 | self.print_stack_trace() |
|
689 | self.print_stack_trace() | |
690 |
|
690 | |||
691 | do_w = do_where |
|
691 | do_w = do_where | |
692 |
|
692 | |||
693 | def stop_here(self, frame): |
|
693 | def stop_here(self, frame): | |
694 | """Check if pdb should stop here""" |
|
694 | """Check if pdb should stop here""" | |
695 | if not super().stop_here(frame): |
|
695 | if not super().stop_here(frame): | |
696 | return False |
|
696 | return False | |
697 | if self.skip_hidden and frame.f_locals.get("__tracebackhide__", False): |
|
697 | if self.skip_hidden and frame.f_locals.get("__tracebackhide__", False): | |
698 | if self._wait_for_mainpyfile: |
|
698 | if self._wait_for_mainpyfile: | |
699 | return False |
|
699 | return False | |
700 | Colors = self.color_scheme_table.active_colors |
|
700 | Colors = self.color_scheme_table.active_colors | |
701 | ColorsNormal = Colors.Normal |
|
701 | ColorsNormal = Colors.Normal | |
702 | print(f"{Colors.excName} [... skipped 1 hidden frame]{ColorsNormal}\n") |
|
702 | print(f"{Colors.excName} [... skipped 1 hidden frame]{ColorsNormal}\n") | |
703 | return False |
|
703 | return False | |
704 | return True |
|
704 | return True | |
705 |
|
705 | |||
706 | def do_up(self, arg): |
|
706 | def do_up(self, arg): | |
707 | """u(p) [count] |
|
707 | """u(p) [count] | |
708 | Move the current frame count (default one) levels up in the |
|
708 | Move the current frame count (default one) levels up in the | |
709 | stack trace (to an older frame). |
|
709 | stack trace (to an older frame). | |
710 |
|
710 | |||
711 | Will skip hidden frames. |
|
711 | Will skip hidden frames. | |
712 | """ |
|
712 | """ | |
713 | ## modified version of upstream that skips |
|
713 | ## modified version of upstream that skips | |
714 | # frames with __tracebackide__ |
|
714 | # frames with __tracebackide__ | |
715 | if self.curindex == 0: |
|
715 | if self.curindex == 0: | |
716 | self.error("Oldest frame") |
|
716 | self.error("Oldest frame") | |
717 | return |
|
717 | return | |
718 | try: |
|
718 | try: | |
719 | count = int(arg or 1) |
|
719 | count = int(arg or 1) | |
720 | except ValueError: |
|
720 | except ValueError: | |
721 | self.error("Invalid frame count (%s)" % arg) |
|
721 | self.error("Invalid frame count (%s)" % arg) | |
722 | return |
|
722 | return | |
723 | skipped = 0 |
|
723 | skipped = 0 | |
724 | if count < 0: |
|
724 | if count < 0: | |
725 | _newframe = 0 |
|
725 | _newframe = 0 | |
726 | else: |
|
726 | else: | |
727 | _newindex = self.curindex |
|
727 | _newindex = self.curindex | |
728 | counter = 0 |
|
728 | counter = 0 | |
729 | hidden_frames = self.hidden_frames(self.stack) |
|
729 | hidden_frames = self.hidden_frames(self.stack) | |
730 | for i in range(self.curindex - 1, -1, -1): |
|
730 | for i in range(self.curindex - 1, -1, -1): | |
731 | frame = self.stack[i][0] |
|
731 | frame = self.stack[i][0] | |
732 | if hidden_frames[i] and self.skip_hidden: |
|
732 | if hidden_frames[i] and self.skip_hidden: | |
733 | skipped += 1 |
|
733 | skipped += 1 | |
734 | continue |
|
734 | continue | |
735 | counter += 1 |
|
735 | counter += 1 | |
736 | if counter >= count: |
|
736 | if counter >= count: | |
737 | break |
|
737 | break | |
738 | else: |
|
738 | else: | |
739 | # if no break occured. |
|
739 | # if no break occured. | |
740 | self.error("all frames above hidden") |
|
740 | self.error("all frames above hidden") | |
741 | return |
|
741 | return | |
742 |
|
742 | |||
743 | Colors = self.color_scheme_table.active_colors |
|
743 | Colors = self.color_scheme_table.active_colors | |
744 | ColorsNormal = Colors.Normal |
|
744 | ColorsNormal = Colors.Normal | |
745 | _newframe = i |
|
745 | _newframe = i | |
746 | self._select_frame(_newframe) |
|
746 | self._select_frame(_newframe) | |
747 | if skipped: |
|
747 | if skipped: | |
748 | print( |
|
748 | print( | |
749 | f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n" |
|
749 | f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n" | |
750 | ) |
|
750 | ) | |
751 |
|
751 | |||
752 | def do_down(self, arg): |
|
752 | def do_down(self, arg): | |
753 | """d(own) [count] |
|
753 | """d(own) [count] | |
754 | Move the current frame count (default one) levels down in the |
|
754 | Move the current frame count (default one) levels down in the | |
755 | stack trace (to a newer frame). |
|
755 | stack trace (to a newer frame). | |
756 |
|
756 | |||
757 | Will skip hidden frames. |
|
757 | Will skip hidden frames. | |
758 | """ |
|
758 | """ | |
759 | if self.curindex + 1 == len(self.stack): |
|
759 | if self.curindex + 1 == len(self.stack): | |
760 | self.error("Newest frame") |
|
760 | self.error("Newest frame") | |
761 | return |
|
761 | return | |
762 | try: |
|
762 | try: | |
763 | count = int(arg or 1) |
|
763 | count = int(arg or 1) | |
764 | except ValueError: |
|
764 | except ValueError: | |
765 | self.error("Invalid frame count (%s)" % arg) |
|
765 | self.error("Invalid frame count (%s)" % arg) | |
766 | return |
|
766 | return | |
767 | if count < 0: |
|
767 | if count < 0: | |
768 | _newframe = len(self.stack) - 1 |
|
768 | _newframe = len(self.stack) - 1 | |
769 | else: |
|
769 | else: | |
770 | _newindex = self.curindex |
|
770 | _newindex = self.curindex | |
771 | counter = 0 |
|
771 | counter = 0 | |
772 | skipped = 0 |
|
772 | skipped = 0 | |
773 | hidden_frames = self.hidden_frames(self.stack) |
|
773 | hidden_frames = self.hidden_frames(self.stack) | |
774 | for i in range(self.curindex + 1, len(self.stack)): |
|
774 | for i in range(self.curindex + 1, len(self.stack)): | |
775 | frame = self.stack[i][0] |
|
775 | frame = self.stack[i][0] | |
776 | if hidden_frames[i] and self.skip_hidden: |
|
776 | if hidden_frames[i] and self.skip_hidden: | |
777 | skipped += 1 |
|
777 | skipped += 1 | |
778 | continue |
|
778 | continue | |
779 | counter += 1 |
|
779 | counter += 1 | |
780 | if counter >= count: |
|
780 | if counter >= count: | |
781 | break |
|
781 | break | |
782 | else: |
|
782 | else: | |
783 | self.error("all frames bellow hidden") |
|
783 | self.error("all frames bellow hidden") | |
784 | return |
|
784 | return | |
785 |
|
785 | |||
786 | Colors = self.color_scheme_table.active_colors |
|
786 | Colors = self.color_scheme_table.active_colors | |
787 | ColorsNormal = Colors.Normal |
|
787 | ColorsNormal = Colors.Normal | |
788 | if skipped: |
|
788 | if skipped: | |
789 | print( |
|
789 | print( | |
790 | f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n" |
|
790 | f"{Colors.excName} [... skipped {skipped} hidden frame(s)]{ColorsNormal}\n" | |
791 | ) |
|
791 | ) | |
792 | _newframe = i |
|
792 | _newframe = i | |
793 |
|
793 | |||
794 | self._select_frame(_newframe) |
|
794 | self._select_frame(_newframe) | |
795 |
|
795 | |||
796 | do_d = do_down |
|
796 | do_d = do_down | |
797 | do_u = do_up |
|
797 | do_u = do_up | |
798 |
|
798 | |||
799 | def do_context(self, context): |
|
799 | def do_context(self, context): | |
800 | """context number_of_lines |
|
800 | """context number_of_lines | |
801 | Set the number of lines of source code to show when displaying |
|
801 | Set the number of lines of source code to show when displaying | |
802 | stacktrace information. |
|
802 | stacktrace information. | |
803 | """ |
|
803 | """ | |
804 | try: |
|
804 | try: | |
805 | new_context = int(context) |
|
805 | new_context = int(context) | |
806 | if new_context <= 0: |
|
806 | if new_context <= 0: | |
807 | raise ValueError() |
|
807 | raise ValueError() | |
|
808 | self.context = new_context | |||
808 | except ValueError: |
|
809 | except ValueError: | |
809 | self.error("The 'context' command requires a positive integer argument.") |
|
810 | self.error("The 'context' command requires a positive integer argument.") | |
810 | self.context = new_context |
|
|||
811 |
|
811 | |||
812 |
|
812 | |||
813 | class InterruptiblePdb(Pdb): |
|
813 | class InterruptiblePdb(Pdb): | |
814 | """Version of debugger where KeyboardInterrupt exits the debugger altogether.""" |
|
814 | """Version of debugger where KeyboardInterrupt exits the debugger altogether.""" | |
815 |
|
815 | |||
816 | def cmdloop(self): |
|
816 | def cmdloop(self): | |
817 | """Wrap cmdloop() such that KeyboardInterrupt stops the debugger.""" |
|
817 | """Wrap cmdloop() such that KeyboardInterrupt stops the debugger.""" | |
818 | try: |
|
818 | try: | |
819 | return OldPdb.cmdloop(self) |
|
819 | return OldPdb.cmdloop(self) | |
820 | except KeyboardInterrupt: |
|
820 | except KeyboardInterrupt: | |
821 | self.stop_here = lambda frame: False |
|
821 | self.stop_here = lambda frame: False | |
822 | self.do_quit("") |
|
822 | self.do_quit("") | |
823 | sys.settrace(None) |
|
823 | sys.settrace(None) | |
824 | self.quitting = False |
|
824 | self.quitting = False | |
825 | raise |
|
825 | raise | |
826 |
|
826 | |||
827 | def _cmdloop(self): |
|
827 | def _cmdloop(self): | |
828 | while True: |
|
828 | while True: | |
829 | try: |
|
829 | try: | |
830 | # keyboard interrupts allow for an easy way to cancel |
|
830 | # keyboard interrupts allow for an easy way to cancel | |
831 | # the current command, so allow them during interactive input |
|
831 | # the current command, so allow them during interactive input | |
832 | self.allow_kbdint = True |
|
832 | self.allow_kbdint = True | |
833 | self.cmdloop() |
|
833 | self.cmdloop() | |
834 | self.allow_kbdint = False |
|
834 | self.allow_kbdint = False | |
835 | break |
|
835 | break | |
836 | except KeyboardInterrupt: |
|
836 | except KeyboardInterrupt: | |
837 | self.message('--KeyboardInterrupt--') |
|
837 | self.message('--KeyboardInterrupt--') | |
838 | raise |
|
838 | raise | |
839 |
|
839 | |||
840 |
|
840 | |||
841 | def set_trace(frame=None): |
|
841 | def set_trace(frame=None): | |
842 | """ |
|
842 | """ | |
843 | Start debugging from `frame`. |
|
843 | Start debugging from `frame`. | |
844 |
|
844 | |||
845 | If frame is not specified, debugging starts from caller's frame. |
|
845 | If frame is not specified, debugging starts from caller's frame. | |
846 | """ |
|
846 | """ | |
847 | Pdb().set_trace(frame or sys._getframe().f_back) |
|
847 | Pdb().set_trace(frame or sys._getframe().f_back) |
General Comments 0
You need to be logged in to leave comments.
Login now