##// END OF EJS Templates
Do not capture BdbQuit....
Matthias Bussonnier -
Show More
@@ -1,637 +1,631 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 http://www.python.org/2.2.3/license.html"""
16 http://www.python.org/2.2.3/license.html"""
17
17
18 #*****************************************************************************
18 #*****************************************************************************
19 #
19 #
20 # This file is licensed under the PSF license.
20 # This file is licensed under the PSF license.
21 #
21 #
22 # Copyright (C) 2001 Python Software Foundation, www.python.org
22 # Copyright (C) 2001 Python Software Foundation, www.python.org
23 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
23 # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu>
24 #
24 #
25 #
25 #
26 #*****************************************************************************
26 #*****************************************************************************
27 from __future__ import print_function
27 from __future__ import print_function
28
28
29 import bdb
29 import bdb
30 import functools
30 import functools
31 import inspect
31 import inspect
32 import sys
32 import sys
33 import warnings
33 import warnings
34
34
35 from IPython import get_ipython
35 from IPython import get_ipython
36 from IPython.utils import PyColorize, ulinecache
36 from IPython.utils import PyColorize, ulinecache
37 from IPython.utils import coloransi, py3compat
37 from IPython.utils import coloransi, py3compat
38 from IPython.core.excolors import exception_colors
38 from IPython.core.excolors import exception_colors
39 from IPython.testing.skipdoctest import skip_doctest
39 from IPython.testing.skipdoctest import skip_doctest
40
40
41
41
42 prompt = 'ipdb> '
42 prompt = 'ipdb> '
43
43
44 #We have to check this directly from sys.argv, config struct not yet available
44 #We have to check this directly from sys.argv, config struct not yet available
45 from pdb import Pdb as OldPdb
45 from pdb import Pdb as OldPdb
46
46
47 # Allow the set_trace code to operate outside of an ipython instance, even if
47 # Allow the set_trace code to operate outside of an ipython instance, even if
48 # it does so with some limitations. The rest of this support is implemented in
48 # it does so with some limitations. The rest of this support is implemented in
49 # the Tracer constructor.
49 # the Tracer constructor.
50
50
51 def make_arrow(pad):
51 def make_arrow(pad):
52 """generate the leading arrow in front of traceback or debugger"""
52 """generate the leading arrow in front of traceback or debugger"""
53 if pad >= 2:
53 if pad >= 2:
54 return '-'*(pad-2) + '> '
54 return '-'*(pad-2) + '> '
55 elif pad == 1:
55 elif pad == 1:
56 return '>'
56 return '>'
57 return ''
57 return ''
58
58
59
59
60 def BdbQuit_excepthook(et, ev, tb, excepthook=None):
60 def BdbQuit_excepthook(et, ev, tb, excepthook=None):
61 """Exception hook which handles `BdbQuit` exceptions.
61 """Exception hook which handles `BdbQuit` exceptions.
62
62
63 All other exceptions are processed using the `excepthook`
63 All other exceptions are processed using the `excepthook`
64 parameter.
64 parameter.
65 """
65 """
66 warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1",
66 warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1",
67 DeprecationWarning)
67 DeprecationWarning)
68 if et==bdb.BdbQuit:
68 if et==bdb.BdbQuit:
69 print('Exiting Debugger.')
69 print('Exiting Debugger.')
70 elif excepthook is not None:
70 elif excepthook is not None:
71 excepthook(et, ev, tb)
71 excepthook(et, ev, tb)
72 else:
72 else:
73 # Backwards compatibility. Raise deprecation warning?
73 # Backwards compatibility. Raise deprecation warning?
74 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
74 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
75
75
76
76
77 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
77 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
78 warnings.warn(
78 warnings.warn(
79 "`BdbQuit_IPython_excepthook` is deprecated since version 5.1",
79 "`BdbQuit_IPython_excepthook` is deprecated since version 5.1",
80 DeprecationWarning)
80 DeprecationWarning)
81 print('Exiting Debugger.')
81 print('Exiting Debugger.')
82
82
83
83
84 class Tracer(object):
84 class Tracer(object):
85 """
85 """
86 DEPRECATED
86 DEPRECATED
87
87
88 Class for local debugging, similar to pdb.set_trace.
88 Class for local debugging, similar to pdb.set_trace.
89
89
90 Instances of this class, when called, behave like pdb.set_trace, but
90 Instances of this class, when called, behave like pdb.set_trace, but
91 providing IPython's enhanced capabilities.
91 providing IPython's enhanced capabilities.
92
92
93 This is implemented as a class which must be initialized in your own code
93 This is implemented as a class which must be initialized in your own code
94 and not as a standalone function because we need to detect at runtime
94 and not as a standalone function because we need to detect at runtime
95 whether IPython is already active or not. That detection is done in the
95 whether IPython is already active or not. That detection is done in the
96 constructor, ensuring that this code plays nicely with a running IPython,
96 constructor, ensuring that this code plays nicely with a running IPython,
97 while functioning acceptably (though with limitations) if outside of it.
97 while functioning acceptably (though with limitations) if outside of it.
98 """
98 """
99
99
100 @skip_doctest
100 @skip_doctest
101 def __init__(self, colors=None):
101 def __init__(self, colors=None):
102 """
102 """
103 DEPRECATED
103 DEPRECATED
104
104
105 Create a local debugger instance.
105 Create a local debugger instance.
106
106
107 Parameters
107 Parameters
108 ----------
108 ----------
109
109
110 colors : str, optional
110 colors : str, optional
111 The name of the color scheme to use, it must be one of IPython's
111 The name of the color scheme to use, it must be one of IPython's
112 valid color schemes. If not given, the function will default to
112 valid color schemes. If not given, the function will default to
113 the current IPython scheme when running inside IPython, and to
113 the current IPython scheme when running inside IPython, and to
114 'NoColor' otherwise.
114 'NoColor' otherwise.
115
115
116 Examples
116 Examples
117 --------
117 --------
118 ::
118 ::
119
119
120 from IPython.core.debugger import Tracer; debug_here = Tracer()
120 from IPython.core.debugger import Tracer; debug_here = Tracer()
121
121
122 Later in your code::
122 Later in your code::
123
123
124 debug_here() # -> will open up the debugger at that point.
124 debug_here() # -> will open up the debugger at that point.
125
125
126 Once the debugger activates, you can use all of its regular commands to
126 Once the debugger activates, you can use all of its regular commands to
127 step through code, set breakpoints, etc. See the pdb documentation
127 step through code, set breakpoints, etc. See the pdb documentation
128 from the Python standard library for usage details.
128 from the Python standard library for usage details.
129 """
129 """
130 warnings.warn("`Tracer` is deprecated since version 5.1, directly use "
130 warnings.warn("`Tracer` is deprecated since version 5.1, directly use "
131 "`IPython.core.debugger.Pdb.set_trace()`",
131 "`IPython.core.debugger.Pdb.set_trace()`",
132 DeprecationWarning)
132 DeprecationWarning)
133
133
134 ip = get_ipython()
134 ip = get_ipython()
135 if ip is None:
135 if ip is None:
136 # Outside of ipython, we set our own exception hook manually
136 # Outside of ipython, we set our own exception hook manually
137 sys.excepthook = functools.partial(BdbQuit_excepthook,
137 sys.excepthook = functools.partial(BdbQuit_excepthook,
138 excepthook=sys.excepthook)
138 excepthook=sys.excepthook)
139 def_colors = 'NoColor'
139 def_colors = 'NoColor'
140 else:
140 else:
141 # In ipython, we use its custom exception handler mechanism
141 # In ipython, we use its custom exception handler mechanism
142 def_colors = ip.colors
142 def_colors = ip.colors
143 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
143 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
144
144
145 if colors is None:
145 if colors is None:
146 colors = def_colors
146 colors = def_colors
147
147
148 # The stdlib debugger internally uses a modified repr from the `repr`
148 # The stdlib debugger internally uses a modified repr from the `repr`
149 # module, that limits the length of printed strings to a hardcoded
149 # module, that limits the length of printed strings to a hardcoded
150 # limit of 30 characters. That much trimming is too aggressive, let's
150 # limit of 30 characters. That much trimming is too aggressive, let's
151 # at least raise that limit to 80 chars, which should be enough for
151 # at least raise that limit to 80 chars, which should be enough for
152 # most interactive uses.
152 # most interactive uses.
153 try:
153 try:
154 try:
154 try:
155 from reprlib import aRepr # Py 3
155 from reprlib import aRepr # Py 3
156 except ImportError:
156 except ImportError:
157 from repr import aRepr # Py 2
157 from repr import aRepr # Py 2
158 aRepr.maxstring = 80
158 aRepr.maxstring = 80
159 except:
159 except:
160 # This is only a user-facing convenience, so any error we encounter
160 # This is only a user-facing convenience, so any error we encounter
161 # here can be warned about but can be otherwise ignored. These
161 # here can be warned about but can be otherwise ignored. These
162 # printouts will tell us about problems if this API changes
162 # printouts will tell us about problems if this API changes
163 import traceback
163 import traceback
164 traceback.print_exc()
164 traceback.print_exc()
165
165
166 self.debugger = Pdb(colors)
166 self.debugger = Pdb(colors)
167
167
168 def __call__(self):
168 def __call__(self):
169 """Starts an interactive debugger at the point where called.
169 """Starts an interactive debugger at the point where called.
170
170
171 This is similar to the pdb.set_trace() function from the std lib, but
171 This is similar to the pdb.set_trace() function from the std lib, but
172 using IPython's enhanced debugger."""
172 using IPython's enhanced debugger."""
173
173
174 self.debugger.set_trace(sys._getframe().f_back)
174 self.debugger.set_trace(sys._getframe().f_back)
175
175
176
176
177 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
177 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
178 """Make new_fn have old_fn's doc string. This is particularly useful
178 """Make new_fn have old_fn's doc string. This is particularly useful
179 for the ``do_...`` commands that hook into the help system.
179 for the ``do_...`` commands that hook into the help system.
180 Adapted from from a comp.lang.python posting
180 Adapted from from a comp.lang.python posting
181 by Duncan Booth."""
181 by Duncan Booth."""
182 def wrapper(*args, **kw):
182 def wrapper(*args, **kw):
183 return new_fn(*args, **kw)
183 return new_fn(*args, **kw)
184 if old_fn.__doc__:
184 if old_fn.__doc__:
185 wrapper.__doc__ = old_fn.__doc__ + additional_text
185 wrapper.__doc__ = old_fn.__doc__ + additional_text
186 return wrapper
186 return wrapper
187
187
188
188
189 def _file_lines(fname):
189 def _file_lines(fname):
190 """Return the contents of a named file as a list of lines.
190 """Return the contents of a named file as a list of lines.
191
191
192 This function never raises an IOError exception: if the file can't be
192 This function never raises an IOError exception: if the file can't be
193 read, it simply returns an empty list."""
193 read, it simply returns an empty list."""
194
194
195 try:
195 try:
196 outfile = open(fname)
196 outfile = open(fname)
197 except IOError:
197 except IOError:
198 return []
198 return []
199 else:
199 else:
200 out = outfile.readlines()
200 out = outfile.readlines()
201 outfile.close()
201 outfile.close()
202 return out
202 return out
203
203
204
204
205 class Pdb(OldPdb, object):
205 class Pdb(OldPdb, object):
206 """Modified Pdb class, does not load readline.
206 """Modified Pdb class, does not load readline.
207
207
208 for a standalone version that uses prompt_toolkit, see
208 for a standalone version that uses prompt_toolkit, see
209 `IPython.terminal.debugger.TerminalPdb` and
209 `IPython.terminal.debugger.TerminalPdb` and
210 `IPython.terminal.debugger.set_trace()`
210 `IPython.terminal.debugger.set_trace()`
211 """
211 """
212
212
213 def __init__(self, color_scheme=None, completekey=None,
213 def __init__(self, color_scheme=None, completekey=None,
214 stdin=None, stdout=None, context=5):
214 stdin=None, stdout=None, context=5):
215
215
216 # Parent constructor:
216 # Parent constructor:
217 try:
217 try:
218 self.context = int(context)
218 self.context = int(context)
219 if self.context <= 0:
219 if self.context <= 0:
220 raise ValueError("Context must be a positive integer")
220 raise ValueError("Context must be a positive integer")
221 except (TypeError, ValueError):
221 except (TypeError, ValueError):
222 raise ValueError("Context must be a positive integer")
222 raise ValueError("Context must be a positive integer")
223
223
224 OldPdb.__init__(self, completekey, stdin, stdout)
224 OldPdb.__init__(self, completekey, stdin, stdout)
225
225
226 # IPython changes...
226 # IPython changes...
227 self.shell = get_ipython()
227 self.shell = get_ipython()
228
228
229 if self.shell is None:
229 if self.shell is None:
230 save_main = sys.modules['__main__']
230 save_main = sys.modules['__main__']
231 # No IPython instance running, we must create one
231 # No IPython instance running, we must create one
232 from IPython.terminal.interactiveshell import \
232 from IPython.terminal.interactiveshell import \
233 TerminalInteractiveShell
233 TerminalInteractiveShell
234 self.shell = TerminalInteractiveShell.instance()
234 self.shell = TerminalInteractiveShell.instance()
235 # needed by any code which calls __import__("__main__") after
235 # needed by any code which calls __import__("__main__") after
236 # the debugger was entered. See also #9941.
236 # the debugger was entered. See also #9941.
237 sys.modules['__main__'] = save_main
237 sys.modules['__main__'] = save_main
238
238
239 if color_scheme is not None:
239 if color_scheme is not None:
240 warnings.warn(
240 warnings.warn(
241 "The `color_scheme` argument is deprecated since version 5.1",
241 "The `color_scheme` argument is deprecated since version 5.1",
242 DeprecationWarning, stacklevel=2)
242 DeprecationWarning, stacklevel=2)
243 else:
243 else:
244 color_scheme = self.shell.colors
244 color_scheme = self.shell.colors
245
245
246 self.aliases = {}
246 self.aliases = {}
247
247
248 # Create color table: we copy the default one from the traceback
248 # Create color table: we copy the default one from the traceback
249 # module and add a few attributes needed for debugging
249 # module and add a few attributes needed for debugging
250 self.color_scheme_table = exception_colors()
250 self.color_scheme_table = exception_colors()
251
251
252 # shorthands
252 # shorthands
253 C = coloransi.TermColors
253 C = coloransi.TermColors
254 cst = self.color_scheme_table
254 cst = self.color_scheme_table
255
255
256 cst['NoColor'].colors.prompt = C.NoColor
256 cst['NoColor'].colors.prompt = C.NoColor
257 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
257 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
258 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
258 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
259
259
260 cst['Linux'].colors.prompt = C.Green
260 cst['Linux'].colors.prompt = C.Green
261 cst['Linux'].colors.breakpoint_enabled = C.LightRed
261 cst['Linux'].colors.breakpoint_enabled = C.LightRed
262 cst['Linux'].colors.breakpoint_disabled = C.Red
262 cst['Linux'].colors.breakpoint_disabled = C.Red
263
263
264 cst['LightBG'].colors.prompt = C.Blue
264 cst['LightBG'].colors.prompt = C.Blue
265 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
265 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
266 cst['LightBG'].colors.breakpoint_disabled = C.Red
266 cst['LightBG'].colors.breakpoint_disabled = C.Red
267
267
268 cst['Neutral'].colors.prompt = C.Blue
268 cst['Neutral'].colors.prompt = C.Blue
269 cst['Neutral'].colors.breakpoint_enabled = C.LightRed
269 cst['Neutral'].colors.breakpoint_enabled = C.LightRed
270 cst['Neutral'].colors.breakpoint_disabled = C.Red
270 cst['Neutral'].colors.breakpoint_disabled = C.Red
271
271
272
272
273 # Add a python parser so we can syntax highlight source while
273 # Add a python parser so we can syntax highlight source while
274 # debugging.
274 # debugging.
275 self.parser = PyColorize.Parser(style=color_scheme)
275 self.parser = PyColorize.Parser(style=color_scheme)
276 self.set_colors(color_scheme)
276 self.set_colors(color_scheme)
277
277
278 # Set the prompt - the default prompt is '(Pdb)'
278 # Set the prompt - the default prompt is '(Pdb)'
279 self.prompt = prompt
279 self.prompt = prompt
280
280
281 def set_colors(self, scheme):
281 def set_colors(self, scheme):
282 """Shorthand access to the color table scheme selector method."""
282 """Shorthand access to the color table scheme selector method."""
283 self.color_scheme_table.set_active_scheme(scheme)
283 self.color_scheme_table.set_active_scheme(scheme)
284 self.parser.style = scheme
284 self.parser.style = scheme
285
285
286 def trace_dispatch(self, frame, event, arg):
287 try:
288 return super(Pdb, self).trace_dispatch(frame, event, arg)
289 except bdb.BdbQuit:
290 pass
291
292 def interaction(self, frame, traceback):
286 def interaction(self, frame, traceback):
293 try:
287 try:
294 OldPdb.interaction(self, frame, traceback)
288 OldPdb.interaction(self, frame, traceback)
295 except KeyboardInterrupt:
289 except KeyboardInterrupt:
296 sys.stdout.write('\n' + self.shell.get_exception_only())
290 sys.stdout.write('\n' + self.shell.get_exception_only())
297
291
298 def parseline(self, line):
292 def parseline(self, line):
299 if line.startswith("!!"):
293 if line.startswith("!!"):
300 # Force standard behavior.
294 # Force standard behavior.
301 return super(Pdb, self).parseline(line[2:])
295 return super(Pdb, self).parseline(line[2:])
302 # "Smart command mode" from pdb++: don't execute commands if a variable
296 # "Smart command mode" from pdb++: don't execute commands if a variable
303 # with the same name exists.
297 # with the same name exists.
304 cmd, arg, newline = super(Pdb, self).parseline(line)
298 cmd, arg, newline = super(Pdb, self).parseline(line)
305 # Fix for #9611: Do not trigger smart command if the command is `exit`
299 # Fix for #9611: Do not trigger smart command if the command is `exit`
306 # or `quit` and it would resolve to their *global* value (the
300 # or `quit` and it would resolve to their *global* value (the
307 # `ExitAutocall` object). Just checking that it is not present in the
301 # `ExitAutocall` object). Just checking that it is not present in the
308 # locals dict is not enough as locals and globals match at the
302 # locals dict is not enough as locals and globals match at the
309 # toplevel.
303 # toplevel.
310 if ((cmd in self.curframe.f_locals or cmd in self.curframe.f_globals)
304 if ((cmd in self.curframe.f_locals or cmd in self.curframe.f_globals)
311 and not (cmd in ["exit", "quit"]
305 and not (cmd in ["exit", "quit"]
312 and (self.curframe.f_locals is self.curframe.f_globals
306 and (self.curframe.f_locals is self.curframe.f_globals
313 or cmd not in self.curframe.f_locals))):
307 or cmd not in self.curframe.f_locals))):
314 return super(Pdb, self).parseline("!" + line)
308 return super(Pdb, self).parseline("!" + line)
315 return super(Pdb, self).parseline(line)
309 return super(Pdb, self).parseline(line)
316
310
317 def new_do_up(self, arg):
311 def new_do_up(self, arg):
318 OldPdb.do_up(self, arg)
312 OldPdb.do_up(self, arg)
319 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
313 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
320
314
321 def new_do_down(self, arg):
315 def new_do_down(self, arg):
322 OldPdb.do_down(self, arg)
316 OldPdb.do_down(self, arg)
323
317
324 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
318 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
325
319
326 def new_do_frame(self, arg):
320 def new_do_frame(self, arg):
327 OldPdb.do_frame(self, arg)
321 OldPdb.do_frame(self, arg)
328
322
329 def new_do_quit(self, arg):
323 def new_do_quit(self, arg):
330
324
331 if hasattr(self, 'old_all_completions'):
325 if hasattr(self, 'old_all_completions'):
332 self.shell.Completer.all_completions=self.old_all_completions
326 self.shell.Completer.all_completions=self.old_all_completions
333
327
334 return OldPdb.do_quit(self, arg)
328 return OldPdb.do_quit(self, arg)
335
329
336 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
330 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
337
331
338 def new_do_restart(self, arg):
332 def new_do_restart(self, arg):
339 """Restart command. In the context of ipython this is exactly the same
333 """Restart command. In the context of ipython this is exactly the same
340 thing as 'quit'."""
334 thing as 'quit'."""
341 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
335 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
342 return self.do_quit(arg)
336 return self.do_quit(arg)
343
337
344 def print_stack_trace(self, context=None):
338 def print_stack_trace(self, context=None):
345 if context is None:
339 if context is None:
346 context = self.context
340 context = self.context
347 try:
341 try:
348 context=int(context)
342 context=int(context)
349 if context <= 0:
343 if context <= 0:
350 raise ValueError("Context must be a positive integer")
344 raise ValueError("Context must be a positive integer")
351 except (TypeError, ValueError):
345 except (TypeError, ValueError):
352 raise ValueError("Context must be a positive integer")
346 raise ValueError("Context must be a positive integer")
353 try:
347 try:
354 for frame_lineno in self.stack:
348 for frame_lineno in self.stack:
355 self.print_stack_entry(frame_lineno, context=context)
349 self.print_stack_entry(frame_lineno, context=context)
356 except KeyboardInterrupt:
350 except KeyboardInterrupt:
357 pass
351 pass
358
352
359 def print_stack_entry(self,frame_lineno, prompt_prefix='\n-> ',
353 def print_stack_entry(self,frame_lineno, prompt_prefix='\n-> ',
360 context=None):
354 context=None):
361 if context is None:
355 if context is None:
362 context = self.context
356 context = self.context
363 try:
357 try:
364 context=int(context)
358 context=int(context)
365 if context <= 0:
359 if context <= 0:
366 raise ValueError("Context must be a positive integer")
360 raise ValueError("Context must be a positive integer")
367 except (TypeError, ValueError):
361 except (TypeError, ValueError):
368 raise ValueError("Context must be a positive integer")
362 raise ValueError("Context must be a positive integer")
369 print(self.format_stack_entry(frame_lineno, '', context))
363 print(self.format_stack_entry(frame_lineno, '', context))
370
364
371 # vds: >>
365 # vds: >>
372 frame, lineno = frame_lineno
366 frame, lineno = frame_lineno
373 filename = frame.f_code.co_filename
367 filename = frame.f_code.co_filename
374 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
368 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
375 # vds: <<
369 # vds: <<
376
370
377 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
371 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
378 if context is None:
372 if context is None:
379 context = self.context
373 context = self.context
380 try:
374 try:
381 context=int(context)
375 context=int(context)
382 if context <= 0:
376 if context <= 0:
383 print("Context must be a positive integer")
377 print("Context must be a positive integer")
384 except (TypeError, ValueError):
378 except (TypeError, ValueError):
385 print("Context must be a positive integer")
379 print("Context must be a positive integer")
386 try:
380 try:
387 import reprlib # Py 3
381 import reprlib # Py 3
388 except ImportError:
382 except ImportError:
389 import repr as reprlib # Py 2
383 import repr as reprlib # Py 2
390
384
391 ret = []
385 ret = []
392
386
393 Colors = self.color_scheme_table.active_colors
387 Colors = self.color_scheme_table.active_colors
394 ColorsNormal = Colors.Normal
388 ColorsNormal = Colors.Normal
395 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
389 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
396 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
390 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
397 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
391 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
398 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
392 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
399 ColorsNormal)
393 ColorsNormal)
400
394
401 frame, lineno = frame_lineno
395 frame, lineno = frame_lineno
402
396
403 return_value = ''
397 return_value = ''
404 if '__return__' in frame.f_locals:
398 if '__return__' in frame.f_locals:
405 rv = frame.f_locals['__return__']
399 rv = frame.f_locals['__return__']
406 #return_value += '->'
400 #return_value += '->'
407 return_value += reprlib.repr(rv) + '\n'
401 return_value += reprlib.repr(rv) + '\n'
408 ret.append(return_value)
402 ret.append(return_value)
409
403
410 #s = filename + '(' + `lineno` + ')'
404 #s = filename + '(' + `lineno` + ')'
411 filename = self.canonic(frame.f_code.co_filename)
405 filename = self.canonic(frame.f_code.co_filename)
412 link = tpl_link % py3compat.cast_unicode(filename)
406 link = tpl_link % py3compat.cast_unicode(filename)
413
407
414 if frame.f_code.co_name:
408 if frame.f_code.co_name:
415 func = frame.f_code.co_name
409 func = frame.f_code.co_name
416 else:
410 else:
417 func = "<lambda>"
411 func = "<lambda>"
418
412
419 call = ''
413 call = ''
420 if func != '?':
414 if func != '?':
421 if '__args__' in frame.f_locals:
415 if '__args__' in frame.f_locals:
422 args = reprlib.repr(frame.f_locals['__args__'])
416 args = reprlib.repr(frame.f_locals['__args__'])
423 else:
417 else:
424 args = '()'
418 args = '()'
425 call = tpl_call % (func, args)
419 call = tpl_call % (func, args)
426
420
427 # The level info should be generated in the same format pdb uses, to
421 # The level info should be generated in the same format pdb uses, to
428 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
422 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
429 if frame is self.curframe:
423 if frame is self.curframe:
430 ret.append('> ')
424 ret.append('> ')
431 else:
425 else:
432 ret.append(' ')
426 ret.append(' ')
433 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
427 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
434
428
435 start = lineno - 1 - context//2
429 start = lineno - 1 - context//2
436 lines = ulinecache.getlines(filename)
430 lines = ulinecache.getlines(filename)
437 start = min(start, len(lines) - context)
431 start = min(start, len(lines) - context)
438 start = max(start, 0)
432 start = max(start, 0)
439 lines = lines[start : start + context]
433 lines = lines[start : start + context]
440
434
441 for i,line in enumerate(lines):
435 for i,line in enumerate(lines):
442 show_arrow = (start + 1 + i == lineno)
436 show_arrow = (start + 1 + i == lineno)
443 linetpl = (frame is self.curframe or show_arrow) \
437 linetpl = (frame is self.curframe or show_arrow) \
444 and tpl_line_em \
438 and tpl_line_em \
445 or tpl_line
439 or tpl_line
446 ret.append(self.__format_line(linetpl, filename,
440 ret.append(self.__format_line(linetpl, filename,
447 start + 1 + i, line,
441 start + 1 + i, line,
448 arrow = show_arrow) )
442 arrow = show_arrow) )
449 return ''.join(ret)
443 return ''.join(ret)
450
444
451 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
445 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
452 bp_mark = ""
446 bp_mark = ""
453 bp_mark_color = ""
447 bp_mark_color = ""
454
448
455 new_line, err = self.parser.format2(line, 'str')
449 new_line, err = self.parser.format2(line, 'str')
456 if not err:
450 if not err:
457 line = new_line
451 line = new_line
458
452
459 bp = None
453 bp = None
460 if lineno in self.get_file_breaks(filename):
454 if lineno in self.get_file_breaks(filename):
461 bps = self.get_breaks(filename, lineno)
455 bps = self.get_breaks(filename, lineno)
462 bp = bps[-1]
456 bp = bps[-1]
463
457
464 if bp:
458 if bp:
465 Colors = self.color_scheme_table.active_colors
459 Colors = self.color_scheme_table.active_colors
466 bp_mark = str(bp.number)
460 bp_mark = str(bp.number)
467 bp_mark_color = Colors.breakpoint_enabled
461 bp_mark_color = Colors.breakpoint_enabled
468 if not bp.enabled:
462 if not bp.enabled:
469 bp_mark_color = Colors.breakpoint_disabled
463 bp_mark_color = Colors.breakpoint_disabled
470
464
471 numbers_width = 7
465 numbers_width = 7
472 if arrow:
466 if arrow:
473 # This is the line with the error
467 # This is the line with the error
474 pad = numbers_width - len(str(lineno)) - len(bp_mark)
468 pad = numbers_width - len(str(lineno)) - len(bp_mark)
475 num = '%s%s' % (make_arrow(pad), str(lineno))
469 num = '%s%s' % (make_arrow(pad), str(lineno))
476 else:
470 else:
477 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
471 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
478
472
479 return tpl_line % (bp_mark_color + bp_mark, num, line)
473 return tpl_line % (bp_mark_color + bp_mark, num, line)
480
474
481
475
482 def print_list_lines(self, filename, first, last):
476 def print_list_lines(self, filename, first, last):
483 """The printing (as opposed to the parsing part of a 'list'
477 """The printing (as opposed to the parsing part of a 'list'
484 command."""
478 command."""
485 try:
479 try:
486 Colors = self.color_scheme_table.active_colors
480 Colors = self.color_scheme_table.active_colors
487 ColorsNormal = Colors.Normal
481 ColorsNormal = Colors.Normal
488 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
482 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
489 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
483 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
490 src = []
484 src = []
491 if filename == "<string>" and hasattr(self, "_exec_filename"):
485 if filename == "<string>" and hasattr(self, "_exec_filename"):
492 filename = self._exec_filename
486 filename = self._exec_filename
493
487
494 for lineno in range(first, last+1):
488 for lineno in range(first, last+1):
495 line = ulinecache.getline(filename, lineno)
489 line = ulinecache.getline(filename, lineno)
496 if not line:
490 if not line:
497 break
491 break
498
492
499 if lineno == self.curframe.f_lineno:
493 if lineno == self.curframe.f_lineno:
500 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
494 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
501 else:
495 else:
502 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
496 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
503
497
504 src.append(line)
498 src.append(line)
505 self.lineno = lineno
499 self.lineno = lineno
506
500
507 print(''.join(src))
501 print(''.join(src))
508
502
509 except KeyboardInterrupt:
503 except KeyboardInterrupt:
510 pass
504 pass
511
505
512 def do_list(self, arg):
506 def do_list(self, arg):
513 self.lastcmd = 'list'
507 self.lastcmd = 'list'
514 last = None
508 last = None
515 if arg:
509 if arg:
516 try:
510 try:
517 x = eval(arg, {}, {})
511 x = eval(arg, {}, {})
518 if type(x) == type(()):
512 if type(x) == type(()):
519 first, last = x
513 first, last = x
520 first = int(first)
514 first = int(first)
521 last = int(last)
515 last = int(last)
522 if last < first:
516 if last < first:
523 # Assume it's a count
517 # Assume it's a count
524 last = first + last
518 last = first + last
525 else:
519 else:
526 first = max(1, int(x) - 5)
520 first = max(1, int(x) - 5)
527 except:
521 except:
528 print('*** Error in argument:', repr(arg))
522 print('*** Error in argument:', repr(arg))
529 return
523 return
530 elif self.lineno is None:
524 elif self.lineno is None:
531 first = max(1, self.curframe.f_lineno - 5)
525 first = max(1, self.curframe.f_lineno - 5)
532 else:
526 else:
533 first = self.lineno + 1
527 first = self.lineno + 1
534 if last is None:
528 if last is None:
535 last = first + 10
529 last = first + 10
536 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
530 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
537
531
538 # vds: >>
532 # vds: >>
539 lineno = first
533 lineno = first
540 filename = self.curframe.f_code.co_filename
534 filename = self.curframe.f_code.co_filename
541 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
535 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
542 # vds: <<
536 # vds: <<
543
537
544 do_l = do_list
538 do_l = do_list
545
539
546 def getsourcelines(self, obj):
540 def getsourcelines(self, obj):
547 lines, lineno = inspect.findsource(obj)
541 lines, lineno = inspect.findsource(obj)
548 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
542 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
549 # must be a module frame: do not try to cut a block out of it
543 # must be a module frame: do not try to cut a block out of it
550 return lines, 1
544 return lines, 1
551 elif inspect.ismodule(obj):
545 elif inspect.ismodule(obj):
552 return lines, 1
546 return lines, 1
553 return inspect.getblock(lines[lineno:]), lineno+1
547 return inspect.getblock(lines[lineno:]), lineno+1
554
548
555 def do_longlist(self, arg):
549 def do_longlist(self, arg):
556 self.lastcmd = 'longlist'
550 self.lastcmd = 'longlist'
557 try:
551 try:
558 lines, lineno = self.getsourcelines(self.curframe)
552 lines, lineno = self.getsourcelines(self.curframe)
559 except OSError as err:
553 except OSError as err:
560 self.error(err)
554 self.error(err)
561 return
555 return
562 last = lineno + len(lines)
556 last = lineno + len(lines)
563 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
557 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
564 do_ll = do_longlist
558 do_ll = do_longlist
565
559
566 def do_pdef(self, arg):
560 def do_pdef(self, arg):
567 """Print the call signature for any callable object.
561 """Print the call signature for any callable object.
568
562
569 The debugger interface to %pdef"""
563 The debugger interface to %pdef"""
570 namespaces = [('Locals', self.curframe.f_locals),
564 namespaces = [('Locals', self.curframe.f_locals),
571 ('Globals', self.curframe.f_globals)]
565 ('Globals', self.curframe.f_globals)]
572 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
566 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
573
567
574 def do_pdoc(self, arg):
568 def do_pdoc(self, arg):
575 """Print the docstring for an object.
569 """Print the docstring for an object.
576
570
577 The debugger interface to %pdoc."""
571 The debugger interface to %pdoc."""
578 namespaces = [('Locals', self.curframe.f_locals),
572 namespaces = [('Locals', self.curframe.f_locals),
579 ('Globals', self.curframe.f_globals)]
573 ('Globals', self.curframe.f_globals)]
580 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
574 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
581
575
582 def do_pfile(self, arg):
576 def do_pfile(self, arg):
583 """Print (or run through pager) the file where an object is defined.
577 """Print (or run through pager) the file where an object is defined.
584
578
585 The debugger interface to %pfile.
579 The debugger interface to %pfile.
586 """
580 """
587 namespaces = [('Locals', self.curframe.f_locals),
581 namespaces = [('Locals', self.curframe.f_locals),
588 ('Globals', self.curframe.f_globals)]
582 ('Globals', self.curframe.f_globals)]
589 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
583 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
590
584
591 def do_pinfo(self, arg):
585 def do_pinfo(self, arg):
592 """Provide detailed information about an object.
586 """Provide detailed information about an object.
593
587
594 The debugger interface to %pinfo, i.e., obj?."""
588 The debugger interface to %pinfo, i.e., obj?."""
595 namespaces = [('Locals', self.curframe.f_locals),
589 namespaces = [('Locals', self.curframe.f_locals),
596 ('Globals', self.curframe.f_globals)]
590 ('Globals', self.curframe.f_globals)]
597 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
591 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
598
592
599 def do_pinfo2(self, arg):
593 def do_pinfo2(self, arg):
600 """Provide extra detailed information about an object.
594 """Provide extra detailed information about an object.
601
595
602 The debugger interface to %pinfo2, i.e., obj??."""
596 The debugger interface to %pinfo2, i.e., obj??."""
603 namespaces = [('Locals', self.curframe.f_locals),
597 namespaces = [('Locals', self.curframe.f_locals),
604 ('Globals', self.curframe.f_globals)]
598 ('Globals', self.curframe.f_globals)]
605 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
599 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
606
600
607 def do_psource(self, arg):
601 def do_psource(self, arg):
608 """Print (or run through pager) the source code for an object."""
602 """Print (or run through pager) the source code for an object."""
609 namespaces = [('Locals', self.curframe.f_locals),
603 namespaces = [('Locals', self.curframe.f_locals),
610 ('Globals', self.curframe.f_globals)]
604 ('Globals', self.curframe.f_globals)]
611 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
605 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
612
606
613 if sys.version_info > (3, ):
607 if sys.version_info > (3, ):
614 def do_where(self, arg):
608 def do_where(self, arg):
615 """w(here)
609 """w(here)
616 Print a stack trace, with the most recent frame at the bottom.
610 Print a stack trace, with the most recent frame at the bottom.
617 An arrow indicates the "current frame", which determines the
611 An arrow indicates the "current frame", which determines the
618 context of most commands. 'bt' is an alias for this command.
612 context of most commands. 'bt' is an alias for this command.
619
613
620 Take a number as argument as an (optional) number of context line to
614 Take a number as argument as an (optional) number of context line to
621 print"""
615 print"""
622 if arg:
616 if arg:
623 context = int(arg)
617 context = int(arg)
624 self.print_stack_trace(context)
618 self.print_stack_trace(context)
625 else:
619 else:
626 self.print_stack_trace()
620 self.print_stack_trace()
627
621
628 do_w = do_where
622 do_w = do_where
629
623
630
624
631 def set_trace(frame=None):
625 def set_trace(frame=None):
632 """
626 """
633 Start debugging from `frame`.
627 Start debugging from `frame`.
634
628
635 If frame is not specified, debugging starts from caller's frame.
629 If frame is not specified, debugging starts from caller's frame.
636 """
630 """
637 Pdb().set_trace(frame or sys._getframe().f_back)
631 Pdb().set_trace(frame or sys._getframe().f_back)
@@ -1,200 +1,207 b''
1 ============
1 ============
2 5.x Series
2 5.x Series
3 ============
3 ============
4
4
5
6 IPython 5.2
7 ===========
8
9 * restore IPython's debugger to raise on quit. :ghpull:`10009`
10
11
5 IPython 5.1
12 IPython 5.1
6 ===========
13 ===========
7
14
8 * Broken ``%timeit`` on Python2 due to the use of ``__qualname__``. :ghpull:`9804`
15 * Broken ``%timeit`` on Python2 due to the use of ``__qualname__``. :ghpull:`9804`
9 * Restore ``%gui qt`` to create and return a ``QApplication`` if necessary. :ghpull:`9789`
16 * Restore ``%gui qt`` to create and return a ``QApplication`` if necessary. :ghpull:`9789`
10 * Don't set terminal title by default. :ghpull:`9801`
17 * Don't set terminal title by default. :ghpull:`9801`
11 * Preserve indentation when inserting newlines with ``Ctrl-O``. :ghpull:`9770`
18 * Preserve indentation when inserting newlines with ``Ctrl-O``. :ghpull:`9770`
12 * Restore completion in debugger. :ghpull:`9785`
19 * Restore completion in debugger. :ghpull:`9785`
13 * Deprecate ``IPython.core.debugger.Tracer()`` in favor of simpler, newer, APIs. :ghpull:`9731`
20 * Deprecate ``IPython.core.debugger.Tracer()`` in favor of simpler, newer, APIs. :ghpull:`9731`
14 * Restore ``NoOpContext`` context manager removed by mistake, and add `DeprecationWarning`. :ghpull:`9765`
21 * Restore ``NoOpContext`` context manager removed by mistake, and add `DeprecationWarning`. :ghpull:`9765`
15 * Add option allowing ``Prompt_toolkit`` to use 24bits colors. :ghpull:`9736`
22 * Add option allowing ``Prompt_toolkit`` to use 24bits colors. :ghpull:`9736`
16 * Fix for closing interactive matplotlib windows on OS X. :ghpull:`9854`
23 * Fix for closing interactive matplotlib windows on OS X. :ghpull:`9854`
17 * An embedded interactive shell instance can be used more than once. :ghpull:`9843`
24 * An embedded interactive shell instance can be used more than once. :ghpull:`9843`
18 * More robust check for whether IPython is in a terminal. :ghpull:`9833`
25 * More robust check for whether IPython is in a terminal. :ghpull:`9833`
19 * Better pretty-printing of dicts on PyPy. :ghpull:`9827`
26 * Better pretty-printing of dicts on PyPy. :ghpull:`9827`
20 * Some coloured output now looks better on dark background command prompts in Windows.
27 * Some coloured output now looks better on dark background command prompts in Windows.
21 :ghpull:`9838`
28 :ghpull:`9838`
22 * Improved tab completion of paths on Windows . :ghpull:`9826`
29 * Improved tab completion of paths on Windows . :ghpull:`9826`
23 * Fix tkinter event loop integration on Python 2 with ``future`` installed. :ghpull:`9824`
30 * Fix tkinter event loop integration on Python 2 with ``future`` installed. :ghpull:`9824`
24 * Restore ``Ctrl-\`` as a shortcut to quit IPython.
31 * Restore ``Ctrl-\`` as a shortcut to quit IPython.
25 * Make ``get_ipython()`` accessible when modules are imported by startup files. :ghpull:`9818`
32 * Make ``get_ipython()`` accessible when modules are imported by startup files. :ghpull:`9818`
26 * Add support for running directories containing a ``__main__.py`` file with the
33 * Add support for running directories containing a ``__main__.py`` file with the
27 ``ipython`` command. :ghpull:`9813`
34 ``ipython`` command. :ghpull:`9813`
28
35
29
36
30 True Color feature
37 True Color feature
31 ------------------
38 ------------------
32
39
33 ``prompt_toolkit`` uses pygments styles for syntax highlighting. By default, the
40 ``prompt_toolkit`` uses pygments styles for syntax highlighting. By default, the
34 colors specified in the style are approximated using a standard 256-color
41 colors specified in the style are approximated using a standard 256-color
35 palette. ``prompt_toolkit`` also supports 24bit, a.k.a. "true", a.k.a. 16-million
42 palette. ``prompt_toolkit`` also supports 24bit, a.k.a. "true", a.k.a. 16-million
36 color escape sequences which enable compatible terminals to display the exact
43 color escape sequences which enable compatible terminals to display the exact
37 colors specified instead of an approximation. This true_color option exposes
44 colors specified instead of an approximation. This true_color option exposes
38 that capability in prompt_toolkit to the IPython shell.
45 that capability in prompt_toolkit to the IPython shell.
39
46
40 Here is a good source for the current state of true color support in various
47 Here is a good source for the current state of true color support in various
41 terminal emulators and software projects: https://gist.github.com/XVilka/8346728
48 terminal emulators and software projects: https://gist.github.com/XVilka/8346728
42
49
43
50
44
51
45 IPython 5.0
52 IPython 5.0
46 ===========
53 ===========
47
54
48 Released July 7, 2016
55 Released July 7, 2016
49
56
50 New terminal interface
57 New terminal interface
51 ----------------------
58 ----------------------
52
59
53 IPython 5 features a major upgrade to the terminal interface, bringing live
60 IPython 5 features a major upgrade to the terminal interface, bringing live
54 syntax highlighting as you type, proper multiline editing and multiline paste,
61 syntax highlighting as you type, proper multiline editing and multiline paste,
55 and tab completions that don't clutter up your history.
62 and tab completions that don't clutter up your history.
56
63
57 .. image:: ../_images/ptshell_features.png
64 .. image:: ../_images/ptshell_features.png
58 :alt: New terminal interface features
65 :alt: New terminal interface features
59 :align: center
66 :align: center
60 :target: ../_images/ptshell_features.png
67 :target: ../_images/ptshell_features.png
61
68
62 These features are provided by the Python library `prompt_toolkit
69 These features are provided by the Python library `prompt_toolkit
63 <http://python-prompt-toolkit.readthedocs.io/en/stable/>`__, which replaces
70 <http://python-prompt-toolkit.readthedocs.io/en/stable/>`__, which replaces
64 ``readline`` throughout our terminal interface.
71 ``readline`` throughout our terminal interface.
65
72
66 Relying on this pure-Python, cross platform module also makes it simpler to
73 Relying on this pure-Python, cross platform module also makes it simpler to
67 install IPython. We have removed dependencies on ``pyreadline`` for Windows and
74 install IPython. We have removed dependencies on ``pyreadline`` for Windows and
68 ``gnureadline`` for Mac.
75 ``gnureadline`` for Mac.
69
76
70 Backwards incompatible changes
77 Backwards incompatible changes
71 ------------------------------
78 ------------------------------
72
79
73 - The ``%install_ext`` magic function, deprecated since 4.0, has now been deleted.
80 - The ``%install_ext`` magic function, deprecated since 4.0, has now been deleted.
74 You can distribute and install extensions as packages on PyPI.
81 You can distribute and install extensions as packages on PyPI.
75 - Callbacks registered while an event is being handled will now only be called
82 - Callbacks registered while an event is being handled will now only be called
76 for subsequent events; previously they could be called for the current event.
83 for subsequent events; previously they could be called for the current event.
77 Similarly, callbacks removed while handling an event *will* always get that
84 Similarly, callbacks removed while handling an event *will* always get that
78 event. See :ghissue:`9447` and :ghpull:`9453`.
85 event. See :ghissue:`9447` and :ghpull:`9453`.
79 - Integration with pydb has been removed since pydb development has been stopped
86 - Integration with pydb has been removed since pydb development has been stopped
80 since 2012, and pydb is not installable from PyPI.
87 since 2012, and pydb is not installable from PyPI.
81 - The ``autoedit_syntax`` option has apparently been broken for many years.
88 - The ``autoedit_syntax`` option has apparently been broken for many years.
82 It has been removed.
89 It has been removed.
83
90
84 New terminal interface
91 New terminal interface
85 ~~~~~~~~~~~~~~~~~~~~~~
92 ~~~~~~~~~~~~~~~~~~~~~~
86
93
87 The overhaul of the terminal interface will probably cause a range of minor
94 The overhaul of the terminal interface will probably cause a range of minor
88 issues for existing users.
95 issues for existing users.
89 This is inevitable for such a significant change, and we've done our best to
96 This is inevitable for such a significant change, and we've done our best to
90 minimise these issues.
97 minimise these issues.
91 Some changes that we're aware of, with suggestions on how to handle them:
98 Some changes that we're aware of, with suggestions on how to handle them:
92
99
93 IPython no longer uses readline configuration (``~/.inputrc``). We hope that
100 IPython no longer uses readline configuration (``~/.inputrc``). We hope that
94 the functionality you want (e.g. vi input mode) will be available by configuring
101 the functionality you want (e.g. vi input mode) will be available by configuring
95 IPython directly (see :doc:`/config/options/terminal`).
102 IPython directly (see :doc:`/config/options/terminal`).
96 If something's missing, please file an issue.
103 If something's missing, please file an issue.
97
104
98 The ``PromptManager`` class has been removed, and the prompt machinery simplified.
105 The ``PromptManager`` class has been removed, and the prompt machinery simplified.
99 See :ref:`custom_prompts` to customise prompts with the new machinery.
106 See :ref:`custom_prompts` to customise prompts with the new machinery.
100
107
101 :mod:`IPython.core.debugger` now provides a plainer interface.
108 :mod:`IPython.core.debugger` now provides a plainer interface.
102 :mod:`IPython.terminal.debugger` contains the terminal debugger using
109 :mod:`IPython.terminal.debugger` contains the terminal debugger using
103 prompt_toolkit.
110 prompt_toolkit.
104
111
105 There are new options to configure the colours used in syntax highlighting.
112 There are new options to configure the colours used in syntax highlighting.
106 We have tried to integrate them with our classic ``--colors`` option and
113 We have tried to integrate them with our classic ``--colors`` option and
107 ``%colors`` magic, but there's a mismatch in possibilities, so some configurations
114 ``%colors`` magic, but there's a mismatch in possibilities, so some configurations
108 may produce unexpected results. See :ref:`termcolour` for more information.
115 may produce unexpected results. See :ref:`termcolour` for more information.
109
116
110 The new interface is not compatible with Emacs 'inferior-shell' feature. To
117 The new interface is not compatible with Emacs 'inferior-shell' feature. To
111 continue using this, add the ``--simple-prompt`` flag to the command Emacs
118 continue using this, add the ``--simple-prompt`` flag to the command Emacs
112 runs. This flag disables most IPython features, relying on Emacs to provide
119 runs. This flag disables most IPython features, relying on Emacs to provide
113 things like tab completion.
120 things like tab completion.
114
121
115 Provisional Changes
122 Provisional Changes
116 -------------------
123 -------------------
117
124
118 Provisional changes are experimental functionality that may, or may not, make
125 Provisional changes are experimental functionality that may, or may not, make
119 it into a future version of IPython, and which API may change without warnings.
126 it into a future version of IPython, and which API may change without warnings.
120 Activating these features and using these API are at your own risk, and may have
127 Activating these features and using these API are at your own risk, and may have
121 security implication for your system, especially if used with the Jupyter notebook,
128 security implication for your system, especially if used with the Jupyter notebook,
122
129
123 When running via the Jupyter notebook interfaces, or other compatible client,
130 When running via the Jupyter notebook interfaces, or other compatible client,
124 you can enable rich documentation experimental functionality:
131 you can enable rich documentation experimental functionality:
125
132
126 When the ``docrepr`` package is installed setting the boolean flag
133 When the ``docrepr`` package is installed setting the boolean flag
127 ``InteractiveShell.sphinxify_docstring`` to ``True``, will process the various
134 ``InteractiveShell.sphinxify_docstring`` to ``True``, will process the various
128 object through sphinx before displaying them (see the ``docrepr`` package
135 object through sphinx before displaying them (see the ``docrepr`` package
129 documentation for more information.
136 documentation for more information.
130
137
131 You need to also enable the IPython pager display rich HTML representation
138 You need to also enable the IPython pager display rich HTML representation
132 using the ``InteractiveShell.enable_html_pager`` boolean configuration option.
139 using the ``InteractiveShell.enable_html_pager`` boolean configuration option.
133 As usual you can set these configuration options globally in your configuration
140 As usual you can set these configuration options globally in your configuration
134 files, alternatively you can turn them on dynamically using the following
141 files, alternatively you can turn them on dynamically using the following
135 snippet:
142 snippet:
136
143
137 .. code-block:: python
144 .. code-block:: python
138
145
139 ip = get_ipython()
146 ip = get_ipython()
140 ip.sphinxify_docstring = True
147 ip.sphinxify_docstring = True
141 ip.enable_html_pager = True
148 ip.enable_html_pager = True
142
149
143
150
144 You can test the effect of various combinations of the above configuration in
151 You can test the effect of various combinations of the above configuration in
145 the Jupyter notebook, with things example like :
152 the Jupyter notebook, with things example like :
146
153
147 .. code-block:: ipython
154 .. code-block:: ipython
148
155
149 import numpy as np
156 import numpy as np
150 np.histogram?
157 np.histogram?
151
158
152
159
153 This is part of an effort to make Documentation in Python richer and provide in
160 This is part of an effort to make Documentation in Python richer and provide in
154 the long term if possible dynamic examples that can contain math, images,
161 the long term if possible dynamic examples that can contain math, images,
155 widgets... As stated above this is nightly experimental feature with a lot of
162 widgets... As stated above this is nightly experimental feature with a lot of
156 (fun) problem to solve. We would be happy to get your feedback and expertise on
163 (fun) problem to solve. We would be happy to get your feedback and expertise on
157 it.
164 it.
158
165
159
166
160
167
161 Deprecated Features
168 Deprecated Features
162 -------------------
169 -------------------
163
170
164 Some deprecated features are listed in this section. Don't forget to enable
171 Some deprecated features are listed in this section. Don't forget to enable
165 ``DeprecationWarning`` as an error if you are using IPython in a Continuous
172 ``DeprecationWarning`` as an error if you are using IPython in a Continuous
166 Integration setup or in your testing in general:
173 Integration setup or in your testing in general:
167
174
168 .. code-block:: python
175 .. code-block:: python
169
176
170 import warnings
177 import warnings
171 warnings.filterwarnings('error', '.*', DeprecationWarning, module='yourmodule.*')
178 warnings.filterwarnings('error', '.*', DeprecationWarning, module='yourmodule.*')
172
179
173
180
174 - ``hooks.fix_error_editor`` seems unused and is pending deprecation.
181 - ``hooks.fix_error_editor`` seems unused and is pending deprecation.
175 - `IPython/core/excolors.py:ExceptionColors` is deprecated.
182 - `IPython/core/excolors.py:ExceptionColors` is deprecated.
176 - `IPython.core.InteractiveShell:write()` is deprecated; use `sys.stdout` instead.
183 - `IPython.core.InteractiveShell:write()` is deprecated; use `sys.stdout` instead.
177 - `IPython.core.InteractiveShell:write_err()` is deprecated; use `sys.stderr` instead.
184 - `IPython.core.InteractiveShell:write_err()` is deprecated; use `sys.stderr` instead.
178 - The `formatter` keyword argument to `Inspector.info` in `IPython.core.oinspec` has no effect.
185 - The `formatter` keyword argument to `Inspector.info` in `IPython.core.oinspec` has no effect.
179 - The `global_ns` keyword argument of IPython Embed was deprecated, and has no effect. Use `module` keyword argument instead.
186 - The `global_ns` keyword argument of IPython Embed was deprecated, and has no effect. Use `module` keyword argument instead.
180
187
181
188
182 Known Issues:
189 Known Issues:
183 -------------
190 -------------
184
191
185 - ``<Esc>`` Key does not dismiss the completer and does not clear the current
192 - ``<Esc>`` Key does not dismiss the completer and does not clear the current
186 buffer. This is an on purpose modification due to current technical
193 buffer. This is an on purpose modification due to current technical
187 limitation. Cf :ghpull:`9572`. Escape the control character which is used
194 limitation. Cf :ghpull:`9572`. Escape the control character which is used
188 for other shortcut, and there is no practical way to distinguish. Use Ctr-G
195 for other shortcut, and there is no practical way to distinguish. Use Ctr-G
189 or Ctrl-C as an alternative.
196 or Ctrl-C as an alternative.
190
197
191 - Cannot use ``Shift-Enter`` and ``Ctrl-Enter`` to submit code in terminal. cf
198 - Cannot use ``Shift-Enter`` and ``Ctrl-Enter`` to submit code in terminal. cf
192 :ghissue:`9587` and :ghissue:`9401`. In terminal there is no practical way to
199 :ghissue:`9587` and :ghissue:`9401`. In terminal there is no practical way to
193 distinguish these key sequences from a normal new line return.
200 distinguish these key sequences from a normal new line return.
194
201
195 - ``PageUp`` and ``pageDown`` do not move through completion menu.
202 - ``PageUp`` and ``pageDown`` do not move through completion menu.
196
203
197 - Color styles might not adapt to terminal emulator themes. This will need new
204 - Color styles might not adapt to terminal emulator themes. This will need new
198 version of Pygments to be released, and can be mitigated with custom themes.
205 version of Pygments to be released, and can be mitigated with custom themes.
199
206
200
207
General Comments 0
You need to be logged in to leave comments. Login now