##// END OF EJS Templates
Start refactoring handling of color....
Matthias Bussonnier -
Show More
@@ -1,636 +1,637 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)
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 self.set_colors(color_scheme)
273
272
274 # Add a python parser so we can syntax highlight source while
273 # Add a python parser so we can syntax highlight source while
275 # debugging.
274 # debugging.
276 self.parser = PyColorize.Parser()
275 self.parser = PyColorize.Parser(style=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
285
285 def trace_dispatch(self, frame, event, arg):
286 def trace_dispatch(self, frame, event, arg):
286 try:
287 try:
287 return super(Pdb, self).trace_dispatch(frame, event, arg)
288 return super(Pdb, self).trace_dispatch(frame, event, arg)
288 except bdb.BdbQuit:
289 except bdb.BdbQuit:
289 pass
290 pass
290
291
291 def interaction(self, frame, traceback):
292 def interaction(self, frame, traceback):
292 try:
293 try:
293 OldPdb.interaction(self, frame, traceback)
294 OldPdb.interaction(self, frame, traceback)
294 except KeyboardInterrupt:
295 except KeyboardInterrupt:
295 sys.stdout.write('\n' + self.shell.get_exception_only())
296 sys.stdout.write('\n' + self.shell.get_exception_only())
296
297
297 def parseline(self, line):
298 def parseline(self, line):
298 if line.startswith("!!"):
299 if line.startswith("!!"):
299 # Force standard behavior.
300 # Force standard behavior.
300 return super(Pdb, self).parseline(line[2:])
301 return super(Pdb, self).parseline(line[2:])
301 # "Smart command mode" from pdb++: don't execute commands if a variable
302 # "Smart command mode" from pdb++: don't execute commands if a variable
302 # with the same name exists.
303 # with the same name exists.
303 cmd, arg, newline = super(Pdb, self).parseline(line)
304 cmd, arg, newline = super(Pdb, self).parseline(line)
304 # Fix for #9611: Do not trigger smart command if the command is `exit`
305 # Fix for #9611: Do not trigger smart command if the command is `exit`
305 # or `quit` and it would resolve to their *global* value (the
306 # or `quit` and it would resolve to their *global* value (the
306 # `ExitAutocall` object). Just checking that it is not present in the
307 # `ExitAutocall` object). Just checking that it is not present in the
307 # locals dict is not enough as locals and globals match at the
308 # locals dict is not enough as locals and globals match at the
308 # toplevel.
309 # toplevel.
309 if ((cmd in self.curframe.f_locals or cmd in self.curframe.f_globals)
310 if ((cmd in self.curframe.f_locals or cmd in self.curframe.f_globals)
310 and not (cmd in ["exit", "quit"]
311 and not (cmd in ["exit", "quit"]
311 and (self.curframe.f_locals is self.curframe.f_globals
312 and (self.curframe.f_locals is self.curframe.f_globals
312 or cmd not in self.curframe.f_locals))):
313 or cmd not in self.curframe.f_locals))):
313 return super(Pdb, self).parseline("!" + line)
314 return super(Pdb, self).parseline("!" + line)
314 return super(Pdb, self).parseline(line)
315 return super(Pdb, self).parseline(line)
315
316
316 def new_do_up(self, arg):
317 def new_do_up(self, arg):
317 OldPdb.do_up(self, arg)
318 OldPdb.do_up(self, arg)
318 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
319 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
319
320
320 def new_do_down(self, arg):
321 def new_do_down(self, arg):
321 OldPdb.do_down(self, arg)
322 OldPdb.do_down(self, arg)
322
323
323 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
324 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
324
325
325 def new_do_frame(self, arg):
326 def new_do_frame(self, arg):
326 OldPdb.do_frame(self, arg)
327 OldPdb.do_frame(self, arg)
327
328
328 def new_do_quit(self, arg):
329 def new_do_quit(self, arg):
329
330
330 if hasattr(self, 'old_all_completions'):
331 if hasattr(self, 'old_all_completions'):
331 self.shell.Completer.all_completions=self.old_all_completions
332 self.shell.Completer.all_completions=self.old_all_completions
332
333
333 return OldPdb.do_quit(self, arg)
334 return OldPdb.do_quit(self, arg)
334
335
335 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
336 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
336
337
337 def new_do_restart(self, arg):
338 def new_do_restart(self, arg):
338 """Restart command. In the context of ipython this is exactly the same
339 """Restart command. In the context of ipython this is exactly the same
339 thing as 'quit'."""
340 thing as 'quit'."""
340 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
341 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
341 return self.do_quit(arg)
342 return self.do_quit(arg)
342
343
343 def print_stack_trace(self, context=None):
344 def print_stack_trace(self, context=None):
344 if context is None:
345 if context is None:
345 context = self.context
346 context = self.context
346 try:
347 try:
347 context=int(context)
348 context=int(context)
348 if context <= 0:
349 if context <= 0:
349 raise ValueError("Context must be a positive integer")
350 raise ValueError("Context must be a positive integer")
350 except (TypeError, ValueError):
351 except (TypeError, ValueError):
351 raise ValueError("Context must be a positive integer")
352 raise ValueError("Context must be a positive integer")
352 try:
353 try:
353 for frame_lineno in self.stack:
354 for frame_lineno in self.stack:
354 self.print_stack_entry(frame_lineno, context=context)
355 self.print_stack_entry(frame_lineno, context=context)
355 except KeyboardInterrupt:
356 except KeyboardInterrupt:
356 pass
357 pass
357
358
358 def print_stack_entry(self,frame_lineno, prompt_prefix='\n-> ',
359 def print_stack_entry(self,frame_lineno, prompt_prefix='\n-> ',
359 context=None):
360 context=None):
360 if context is None:
361 if context is None:
361 context = self.context
362 context = self.context
362 try:
363 try:
363 context=int(context)
364 context=int(context)
364 if context <= 0:
365 if context <= 0:
365 raise ValueError("Context must be a positive integer")
366 raise ValueError("Context must be a positive integer")
366 except (TypeError, ValueError):
367 except (TypeError, ValueError):
367 raise ValueError("Context must be a positive integer")
368 raise ValueError("Context must be a positive integer")
368 print(self.format_stack_entry(frame_lineno, '', context))
369 print(self.format_stack_entry(frame_lineno, '', context))
369
370
370 # vds: >>
371 # vds: >>
371 frame, lineno = frame_lineno
372 frame, lineno = frame_lineno
372 filename = frame.f_code.co_filename
373 filename = frame.f_code.co_filename
373 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
374 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
374 # vds: <<
375 # vds: <<
375
376
376 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
377 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
377 if context is None:
378 if context is None:
378 context = self.context
379 context = self.context
379 try:
380 try:
380 context=int(context)
381 context=int(context)
381 if context <= 0:
382 if context <= 0:
382 print("Context must be a positive integer")
383 print("Context must be a positive integer")
383 except (TypeError, ValueError):
384 except (TypeError, ValueError):
384 print("Context must be a positive integer")
385 print("Context must be a positive integer")
385 try:
386 try:
386 import reprlib # Py 3
387 import reprlib # Py 3
387 except ImportError:
388 except ImportError:
388 import repr as reprlib # Py 2
389 import repr as reprlib # Py 2
389
390
390 ret = []
391 ret = []
391
392
392 Colors = self.color_scheme_table.active_colors
393 Colors = self.color_scheme_table.active_colors
393 ColorsNormal = Colors.Normal
394 ColorsNormal = Colors.Normal
394 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
395 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
395 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
396 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
396 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
397 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
397 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
398 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
398 ColorsNormal)
399 ColorsNormal)
399
400
400 frame, lineno = frame_lineno
401 frame, lineno = frame_lineno
401
402
402 return_value = ''
403 return_value = ''
403 if '__return__' in frame.f_locals:
404 if '__return__' in frame.f_locals:
404 rv = frame.f_locals['__return__']
405 rv = frame.f_locals['__return__']
405 #return_value += '->'
406 #return_value += '->'
406 return_value += reprlib.repr(rv) + '\n'
407 return_value += reprlib.repr(rv) + '\n'
407 ret.append(return_value)
408 ret.append(return_value)
408
409
409 #s = filename + '(' + `lineno` + ')'
410 #s = filename + '(' + `lineno` + ')'
410 filename = self.canonic(frame.f_code.co_filename)
411 filename = self.canonic(frame.f_code.co_filename)
411 link = tpl_link % py3compat.cast_unicode(filename)
412 link = tpl_link % py3compat.cast_unicode(filename)
412
413
413 if frame.f_code.co_name:
414 if frame.f_code.co_name:
414 func = frame.f_code.co_name
415 func = frame.f_code.co_name
415 else:
416 else:
416 func = "<lambda>"
417 func = "<lambda>"
417
418
418 call = ''
419 call = ''
419 if func != '?':
420 if func != '?':
420 if '__args__' in frame.f_locals:
421 if '__args__' in frame.f_locals:
421 args = reprlib.repr(frame.f_locals['__args__'])
422 args = reprlib.repr(frame.f_locals['__args__'])
422 else:
423 else:
423 args = '()'
424 args = '()'
424 call = tpl_call % (func, args)
425 call = tpl_call % (func, args)
425
426
426 # The level info should be generated in the same format pdb uses, to
427 # The level info should be generated in the same format pdb uses, to
427 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
428 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
428 if frame is self.curframe:
429 if frame is self.curframe:
429 ret.append('> ')
430 ret.append('> ')
430 else:
431 else:
431 ret.append(' ')
432 ret.append(' ')
432 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
433 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
433
434
434 start = lineno - 1 - context//2
435 start = lineno - 1 - context//2
435 lines = ulinecache.getlines(filename)
436 lines = ulinecache.getlines(filename)
436 start = min(start, len(lines) - context)
437 start = min(start, len(lines) - context)
437 start = max(start, 0)
438 start = max(start, 0)
438 lines = lines[start : start + context]
439 lines = lines[start : start + context]
439
440
440 for i,line in enumerate(lines):
441 for i,line in enumerate(lines):
441 show_arrow = (start + 1 + i == lineno)
442 show_arrow = (start + 1 + i == lineno)
442 linetpl = (frame is self.curframe or show_arrow) \
443 linetpl = (frame is self.curframe or show_arrow) \
443 and tpl_line_em \
444 and tpl_line_em \
444 or tpl_line
445 or tpl_line
445 ret.append(self.__format_line(linetpl, filename,
446 ret.append(self.__format_line(linetpl, filename,
446 start + 1 + i, line,
447 start + 1 + i, line,
447 arrow = show_arrow) )
448 arrow = show_arrow) )
448 return ''.join(ret)
449 return ''.join(ret)
449
450
450 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
451 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
451 bp_mark = ""
452 bp_mark = ""
452 bp_mark_color = ""
453 bp_mark_color = ""
453
454
454 scheme = self.color_scheme_table.active_scheme_name
455 new_line, err = self.parser.format2(line, 'str')
455 new_line, err = self.parser.format2(line, 'str', scheme)
456 if not err:
456 if not err: line = new_line
457 line = new_line
457
458
458 bp = None
459 bp = None
459 if lineno in self.get_file_breaks(filename):
460 if lineno in self.get_file_breaks(filename):
460 bps = self.get_breaks(filename, lineno)
461 bps = self.get_breaks(filename, lineno)
461 bp = bps[-1]
462 bp = bps[-1]
462
463
463 if bp:
464 if bp:
464 Colors = self.color_scheme_table.active_colors
465 Colors = self.color_scheme_table.active_colors
465 bp_mark = str(bp.number)
466 bp_mark = str(bp.number)
466 bp_mark_color = Colors.breakpoint_enabled
467 bp_mark_color = Colors.breakpoint_enabled
467 if not bp.enabled:
468 if not bp.enabled:
468 bp_mark_color = Colors.breakpoint_disabled
469 bp_mark_color = Colors.breakpoint_disabled
469
470
470 numbers_width = 7
471 numbers_width = 7
471 if arrow:
472 if arrow:
472 # This is the line with the error
473 # This is the line with the error
473 pad = numbers_width - len(str(lineno)) - len(bp_mark)
474 pad = numbers_width - len(str(lineno)) - len(bp_mark)
474 num = '%s%s' % (make_arrow(pad), str(lineno))
475 num = '%s%s' % (make_arrow(pad), str(lineno))
475 else:
476 else:
476 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
477 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
477
478
478 return tpl_line % (bp_mark_color + bp_mark, num, line)
479 return tpl_line % (bp_mark_color + bp_mark, num, line)
479
480
480
481
481 def print_list_lines(self, filename, first, last):
482 def print_list_lines(self, filename, first, last):
482 """The printing (as opposed to the parsing part of a 'list'
483 """The printing (as opposed to the parsing part of a 'list'
483 command."""
484 command."""
484 try:
485 try:
485 Colors = self.color_scheme_table.active_colors
486 Colors = self.color_scheme_table.active_colors
486 ColorsNormal = Colors.Normal
487 ColorsNormal = Colors.Normal
487 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
488 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
488 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
489 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
489 src = []
490 src = []
490 if filename == "<string>" and hasattr(self, "_exec_filename"):
491 if filename == "<string>" and hasattr(self, "_exec_filename"):
491 filename = self._exec_filename
492 filename = self._exec_filename
492
493
493 for lineno in range(first, last+1):
494 for lineno in range(first, last+1):
494 line = ulinecache.getline(filename, lineno)
495 line = ulinecache.getline(filename, lineno)
495 if not line:
496 if not line:
496 break
497 break
497
498
498 if lineno == self.curframe.f_lineno:
499 if lineno == self.curframe.f_lineno:
499 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
500 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
500 else:
501 else:
501 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
502 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
502
503
503 src.append(line)
504 src.append(line)
504 self.lineno = lineno
505 self.lineno = lineno
505
506
506 print(''.join(src))
507 print(''.join(src))
507
508
508 except KeyboardInterrupt:
509 except KeyboardInterrupt:
509 pass
510 pass
510
511
511 def do_list(self, arg):
512 def do_list(self, arg):
512 self.lastcmd = 'list'
513 self.lastcmd = 'list'
513 last = None
514 last = None
514 if arg:
515 if arg:
515 try:
516 try:
516 x = eval(arg, {}, {})
517 x = eval(arg, {}, {})
517 if type(x) == type(()):
518 if type(x) == type(()):
518 first, last = x
519 first, last = x
519 first = int(first)
520 first = int(first)
520 last = int(last)
521 last = int(last)
521 if last < first:
522 if last < first:
522 # Assume it's a count
523 # Assume it's a count
523 last = first + last
524 last = first + last
524 else:
525 else:
525 first = max(1, int(x) - 5)
526 first = max(1, int(x) - 5)
526 except:
527 except:
527 print('*** Error in argument:', repr(arg))
528 print('*** Error in argument:', repr(arg))
528 return
529 return
529 elif self.lineno is None:
530 elif self.lineno is None:
530 first = max(1, self.curframe.f_lineno - 5)
531 first = max(1, self.curframe.f_lineno - 5)
531 else:
532 else:
532 first = self.lineno + 1
533 first = self.lineno + 1
533 if last is None:
534 if last is None:
534 last = first + 10
535 last = first + 10
535 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
536 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
536
537
537 # vds: >>
538 # vds: >>
538 lineno = first
539 lineno = first
539 filename = self.curframe.f_code.co_filename
540 filename = self.curframe.f_code.co_filename
540 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
541 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
541 # vds: <<
542 # vds: <<
542
543
543 do_l = do_list
544 do_l = do_list
544
545
545 def getsourcelines(self, obj):
546 def getsourcelines(self, obj):
546 lines, lineno = inspect.findsource(obj)
547 lines, lineno = inspect.findsource(obj)
547 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
548 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
548 # must be a module frame: do not try to cut a block out of it
549 # must be a module frame: do not try to cut a block out of it
549 return lines, 1
550 return lines, 1
550 elif inspect.ismodule(obj):
551 elif inspect.ismodule(obj):
551 return lines, 1
552 return lines, 1
552 return inspect.getblock(lines[lineno:]), lineno+1
553 return inspect.getblock(lines[lineno:]), lineno+1
553
554
554 def do_longlist(self, arg):
555 def do_longlist(self, arg):
555 self.lastcmd = 'longlist'
556 self.lastcmd = 'longlist'
556 try:
557 try:
557 lines, lineno = self.getsourcelines(self.curframe)
558 lines, lineno = self.getsourcelines(self.curframe)
558 except OSError as err:
559 except OSError as err:
559 self.error(err)
560 self.error(err)
560 return
561 return
561 last = lineno + len(lines)
562 last = lineno + len(lines)
562 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
563 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
563 do_ll = do_longlist
564 do_ll = do_longlist
564
565
565 def do_pdef(self, arg):
566 def do_pdef(self, arg):
566 """Print the call signature for any callable object.
567 """Print the call signature for any callable object.
567
568
568 The debugger interface to %pdef"""
569 The debugger interface to %pdef"""
569 namespaces = [('Locals', self.curframe.f_locals),
570 namespaces = [('Locals', self.curframe.f_locals),
570 ('Globals', self.curframe.f_globals)]
571 ('Globals', self.curframe.f_globals)]
571 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
572 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
572
573
573 def do_pdoc(self, arg):
574 def do_pdoc(self, arg):
574 """Print the docstring for an object.
575 """Print the docstring for an object.
575
576
576 The debugger interface to %pdoc."""
577 The debugger interface to %pdoc."""
577 namespaces = [('Locals', self.curframe.f_locals),
578 namespaces = [('Locals', self.curframe.f_locals),
578 ('Globals', self.curframe.f_globals)]
579 ('Globals', self.curframe.f_globals)]
579 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
580 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
580
581
581 def do_pfile(self, arg):
582 def do_pfile(self, arg):
582 """Print (or run through pager) the file where an object is defined.
583 """Print (or run through pager) the file where an object is defined.
583
584
584 The debugger interface to %pfile.
585 The debugger interface to %pfile.
585 """
586 """
586 namespaces = [('Locals', self.curframe.f_locals),
587 namespaces = [('Locals', self.curframe.f_locals),
587 ('Globals', self.curframe.f_globals)]
588 ('Globals', self.curframe.f_globals)]
588 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
589 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
589
590
590 def do_pinfo(self, arg):
591 def do_pinfo(self, arg):
591 """Provide detailed information about an object.
592 """Provide detailed information about an object.
592
593
593 The debugger interface to %pinfo, i.e., obj?."""
594 The debugger interface to %pinfo, i.e., obj?."""
594 namespaces = [('Locals', self.curframe.f_locals),
595 namespaces = [('Locals', self.curframe.f_locals),
595 ('Globals', self.curframe.f_globals)]
596 ('Globals', self.curframe.f_globals)]
596 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
597 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
597
598
598 def do_pinfo2(self, arg):
599 def do_pinfo2(self, arg):
599 """Provide extra detailed information about an object.
600 """Provide extra detailed information about an object.
600
601
601 The debugger interface to %pinfo2, i.e., obj??."""
602 The debugger interface to %pinfo2, i.e., obj??."""
602 namespaces = [('Locals', self.curframe.f_locals),
603 namespaces = [('Locals', self.curframe.f_locals),
603 ('Globals', self.curframe.f_globals)]
604 ('Globals', self.curframe.f_globals)]
604 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
605 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
605
606
606 def do_psource(self, arg):
607 def do_psource(self, arg):
607 """Print (or run through pager) the source code for an object."""
608 """Print (or run through pager) the source code for an object."""
608 namespaces = [('Locals', self.curframe.f_locals),
609 namespaces = [('Locals', self.curframe.f_locals),
609 ('Globals', self.curframe.f_globals)]
610 ('Globals', self.curframe.f_globals)]
610 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
611 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
611
612
612 if sys.version_info > (3, ):
613 if sys.version_info > (3, ):
613 def do_where(self, arg):
614 def do_where(self, arg):
614 """w(here)
615 """w(here)
615 Print a stack trace, with the most recent frame at the bottom.
616 Print a stack trace, with the most recent frame at the bottom.
616 An arrow indicates the "current frame", which determines the
617 An arrow indicates the "current frame", which determines the
617 context of most commands. 'bt' is an alias for this command.
618 context of most commands. 'bt' is an alias for this command.
618
619
619 Take a number as argument as an (optional) number of context line to
620 Take a number as argument as an (optional) number of context line to
620 print"""
621 print"""
621 if arg:
622 if arg:
622 context = int(arg)
623 context = int(arg)
623 self.print_stack_trace(context)
624 self.print_stack_trace(context)
624 else:
625 else:
625 self.print_stack_trace()
626 self.print_stack_trace()
626
627
627 do_w = do_where
628 do_w = do_where
628
629
629
630
630 def set_trace(frame=None):
631 def set_trace(frame=None):
631 """
632 """
632 Start debugging from `frame`.
633 Start debugging from `frame`.
633
634
634 If frame is not specified, debugging starts from caller's frame.
635 If frame is not specified, debugging starts from caller's frame.
635 """
636 """
636 Pdb().set_trace(frame or sys._getframe().f_back)
637 Pdb().set_trace(frame or sys._getframe().f_back)
@@ -1,3230 +1,3229 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 from __future__ import absolute_import, print_function
13 from __future__ import absolute_import, print_function
14
14
15 import __future__
15 import __future__
16 import abc
16 import abc
17 import ast
17 import ast
18 import atexit
18 import atexit
19 import functools
19 import functools
20 import os
20 import os
21 import re
21 import re
22 import runpy
22 import runpy
23 import sys
23 import sys
24 import tempfile
24 import tempfile
25 import traceback
25 import traceback
26 import types
26 import types
27 import subprocess
27 import subprocess
28 import warnings
28 import warnings
29 from io import open as io_open
29 from io import open as io_open
30
30
31 from pickleshare import PickleShareDB
31 from pickleshare import PickleShareDB
32
32
33 from traitlets.config.configurable import SingletonConfigurable
33 from traitlets.config.configurable import SingletonConfigurable
34 from IPython.core import oinspect
34 from IPython.core import oinspect
35 from IPython.core import magic
35 from IPython.core import magic
36 from IPython.core import page
36 from IPython.core import page
37 from IPython.core import prefilter
37 from IPython.core import prefilter
38 from IPython.core import shadowns
38 from IPython.core import shadowns
39 from IPython.core import ultratb
39 from IPython.core import ultratb
40 from IPython.core.alias import Alias, AliasManager
40 from IPython.core.alias import Alias, AliasManager
41 from IPython.core.autocall import ExitAutocall
41 from IPython.core.autocall import ExitAutocall
42 from IPython.core.builtin_trap import BuiltinTrap
42 from IPython.core.builtin_trap import BuiltinTrap
43 from IPython.core.events import EventManager, available_events
43 from IPython.core.events import EventManager, available_events
44 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
44 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
45 from IPython.core.debugger import Pdb
45 from IPython.core.debugger import Pdb
46 from IPython.core.display_trap import DisplayTrap
46 from IPython.core.display_trap import DisplayTrap
47 from IPython.core.displayhook import DisplayHook
47 from IPython.core.displayhook import DisplayHook
48 from IPython.core.displaypub import DisplayPublisher
48 from IPython.core.displaypub import DisplayPublisher
49 from IPython.core.error import InputRejected, UsageError
49 from IPython.core.error import InputRejected, UsageError
50 from IPython.core.extensions import ExtensionManager
50 from IPython.core.extensions import ExtensionManager
51 from IPython.core.formatters import DisplayFormatter
51 from IPython.core.formatters import DisplayFormatter
52 from IPython.core.history import HistoryManager
52 from IPython.core.history import HistoryManager
53 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
53 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
54 from IPython.core.logger import Logger
54 from IPython.core.logger import Logger
55 from IPython.core.macro import Macro
55 from IPython.core.macro import Macro
56 from IPython.core.payload import PayloadManager
56 from IPython.core.payload import PayloadManager
57 from IPython.core.prefilter import PrefilterManager
57 from IPython.core.prefilter import PrefilterManager
58 from IPython.core.profiledir import ProfileDir
58 from IPython.core.profiledir import ProfileDir
59 from IPython.core.usage import default_banner
59 from IPython.core.usage import default_banner
60 from IPython.testing.skipdoctest import skip_doctest_py2, skip_doctest
60 from IPython.testing.skipdoctest import skip_doctest_py2, skip_doctest
61 from IPython.utils import PyColorize
61 from IPython.utils import PyColorize
62 from IPython.utils import io
62 from IPython.utils import io
63 from IPython.utils import py3compat
63 from IPython.utils import py3compat
64 from IPython.utils import openpy
64 from IPython.utils import openpy
65 from IPython.utils.decorators import undoc
65 from IPython.utils.decorators import undoc
66 from IPython.utils.io import ask_yes_no
66 from IPython.utils.io import ask_yes_no
67 from IPython.utils.ipstruct import Struct
67 from IPython.utils.ipstruct import Struct
68 from IPython.paths import get_ipython_dir
68 from IPython.paths import get_ipython_dir
69 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
69 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
70 from IPython.utils.process import system, getoutput
70 from IPython.utils.process import system, getoutput
71 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
71 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
72 with_metaclass, iteritems)
72 with_metaclass, iteritems)
73 from IPython.utils.strdispatch import StrDispatch
73 from IPython.utils.strdispatch import StrDispatch
74 from IPython.utils.syspathcontext import prepended_to_syspath
74 from IPython.utils.syspathcontext import prepended_to_syspath
75 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
75 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
76 from IPython.utils.tempdir import TemporaryDirectory
76 from IPython.utils.tempdir import TemporaryDirectory
77 from traitlets import (
77 from traitlets import (
78 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
78 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
79 observe, default,
79 observe, default,
80 )
80 )
81 from warnings import warn
81 from warnings import warn
82 from logging import error
82 from logging import error
83 import IPython.core.hooks
83 import IPython.core.hooks
84
84
85 # NoOpContext is deprecated, but ipykernel imports it from here.
85 # NoOpContext is deprecated, but ipykernel imports it from here.
86 # See https://github.com/ipython/ipykernel/issues/157
86 # See https://github.com/ipython/ipykernel/issues/157
87 from IPython.utils.contexts import NoOpContext
87 from IPython.utils.contexts import NoOpContext
88
88
89 try:
89 try:
90 import docrepr.sphinxify as sphx
90 import docrepr.sphinxify as sphx
91
91
92 def sphinxify(doc):
92 def sphinxify(doc):
93 with TemporaryDirectory() as dirname:
93 with TemporaryDirectory() as dirname:
94 return {
94 return {
95 'text/html': sphx.sphinxify(doc, dirname),
95 'text/html': sphx.sphinxify(doc, dirname),
96 'text/plain': doc
96 'text/plain': doc
97 }
97 }
98 except ImportError:
98 except ImportError:
99 sphinxify = None
99 sphinxify = None
100
100
101
101
102 class ProvisionalWarning(DeprecationWarning):
102 class ProvisionalWarning(DeprecationWarning):
103 """
103 """
104 Warning class for unstable features
104 Warning class for unstable features
105 """
105 """
106 pass
106 pass
107
107
108 #-----------------------------------------------------------------------------
108 #-----------------------------------------------------------------------------
109 # Globals
109 # Globals
110 #-----------------------------------------------------------------------------
110 #-----------------------------------------------------------------------------
111
111
112 # compiled regexps for autoindent management
112 # compiled regexps for autoindent management
113 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
113 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
114
114
115 #-----------------------------------------------------------------------------
115 #-----------------------------------------------------------------------------
116 # Utilities
116 # Utilities
117 #-----------------------------------------------------------------------------
117 #-----------------------------------------------------------------------------
118
118
119 @undoc
119 @undoc
120 def softspace(file, newvalue):
120 def softspace(file, newvalue):
121 """Copied from code.py, to remove the dependency"""
121 """Copied from code.py, to remove the dependency"""
122
122
123 oldvalue = 0
123 oldvalue = 0
124 try:
124 try:
125 oldvalue = file.softspace
125 oldvalue = file.softspace
126 except AttributeError:
126 except AttributeError:
127 pass
127 pass
128 try:
128 try:
129 file.softspace = newvalue
129 file.softspace = newvalue
130 except (AttributeError, TypeError):
130 except (AttributeError, TypeError):
131 # "attribute-less object" or "read-only attributes"
131 # "attribute-less object" or "read-only attributes"
132 pass
132 pass
133 return oldvalue
133 return oldvalue
134
134
135 @undoc
135 @undoc
136 def no_op(*a, **kw): pass
136 def no_op(*a, **kw): pass
137
137
138
138
139 class SpaceInInput(Exception): pass
139 class SpaceInInput(Exception): pass
140
140
141
141
142 def get_default_colors():
142 def get_default_colors():
143 "DEPRECATED"
143 "DEPRECATED"
144 warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
144 warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
145 DeprecationWarning, stacklevel=2)
145 DeprecationWarning, stacklevel=2)
146 return 'Neutral'
146 return 'Neutral'
147
147
148
148
149 class SeparateUnicode(Unicode):
149 class SeparateUnicode(Unicode):
150 r"""A Unicode subclass to validate separate_in, separate_out, etc.
150 r"""A Unicode subclass to validate separate_in, separate_out, etc.
151
151
152 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
152 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
153 """
153 """
154
154
155 def validate(self, obj, value):
155 def validate(self, obj, value):
156 if value == '0': value = ''
156 if value == '0': value = ''
157 value = value.replace('\\n','\n')
157 value = value.replace('\\n','\n')
158 return super(SeparateUnicode, self).validate(obj, value)
158 return super(SeparateUnicode, self).validate(obj, value)
159
159
160
160
161 @undoc
161 @undoc
162 class DummyMod(object):
162 class DummyMod(object):
163 """A dummy module used for IPython's interactive module when
163 """A dummy module used for IPython's interactive module when
164 a namespace must be assigned to the module's __dict__."""
164 a namespace must be assigned to the module's __dict__."""
165 pass
165 pass
166
166
167
167
168 class ExecutionResult(object):
168 class ExecutionResult(object):
169 """The result of a call to :meth:`InteractiveShell.run_cell`
169 """The result of a call to :meth:`InteractiveShell.run_cell`
170
170
171 Stores information about what took place.
171 Stores information about what took place.
172 """
172 """
173 execution_count = None
173 execution_count = None
174 error_before_exec = None
174 error_before_exec = None
175 error_in_exec = None
175 error_in_exec = None
176 result = None
176 result = None
177
177
178 @property
178 @property
179 def success(self):
179 def success(self):
180 return (self.error_before_exec is None) and (self.error_in_exec is None)
180 return (self.error_before_exec is None) and (self.error_in_exec is None)
181
181
182 def raise_error(self):
182 def raise_error(self):
183 """Reraises error if `success` is `False`, otherwise does nothing"""
183 """Reraises error if `success` is `False`, otherwise does nothing"""
184 if self.error_before_exec is not None:
184 if self.error_before_exec is not None:
185 raise self.error_before_exec
185 raise self.error_before_exec
186 if self.error_in_exec is not None:
186 if self.error_in_exec is not None:
187 raise self.error_in_exec
187 raise self.error_in_exec
188
188
189 def __repr__(self):
189 def __repr__(self):
190 if sys.version_info > (3,):
190 if sys.version_info > (3,):
191 name = self.__class__.__qualname__
191 name = self.__class__.__qualname__
192 else:
192 else:
193 name = self.__class__.__name__
193 name = self.__class__.__name__
194 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
194 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
195 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
195 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
196
196
197
197
198 class InteractiveShell(SingletonConfigurable):
198 class InteractiveShell(SingletonConfigurable):
199 """An enhanced, interactive shell for Python."""
199 """An enhanced, interactive shell for Python."""
200
200
201 _instance = None
201 _instance = None
202
202
203 ast_transformers = List([], help=
203 ast_transformers = List([], help=
204 """
204 """
205 A list of ast.NodeTransformer subclass instances, which will be applied
205 A list of ast.NodeTransformer subclass instances, which will be applied
206 to user input before code is run.
206 to user input before code is run.
207 """
207 """
208 ).tag(config=True)
208 ).tag(config=True)
209
209
210 autocall = Enum((0,1,2), default_value=0, help=
210 autocall = Enum((0,1,2), default_value=0, help=
211 """
211 """
212 Make IPython automatically call any callable object even if you didn't
212 Make IPython automatically call any callable object even if you didn't
213 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
213 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
214 automatically. The value can be '0' to disable the feature, '1' for
214 automatically. The value can be '0' to disable the feature, '1' for
215 'smart' autocall, where it is not applied if there are no more
215 'smart' autocall, where it is not applied if there are no more
216 arguments on the line, and '2' for 'full' autocall, where all callable
216 arguments on the line, and '2' for 'full' autocall, where all callable
217 objects are automatically called (even if no arguments are present).
217 objects are automatically called (even if no arguments are present).
218 """
218 """
219 ).tag(config=True)
219 ).tag(config=True)
220 # TODO: remove all autoindent logic and put into frontends.
220 # TODO: remove all autoindent logic and put into frontends.
221 # We can't do this yet because even runlines uses the autoindent.
221 # We can't do this yet because even runlines uses the autoindent.
222 autoindent = Bool(True, help=
222 autoindent = Bool(True, help=
223 """
223 """
224 Autoindent IPython code entered interactively.
224 Autoindent IPython code entered interactively.
225 """
225 """
226 ).tag(config=True)
226 ).tag(config=True)
227
227
228 automagic = Bool(True, help=
228 automagic = Bool(True, help=
229 """
229 """
230 Enable magic commands to be called without the leading %.
230 Enable magic commands to be called without the leading %.
231 """
231 """
232 ).tag(config=True)
232 ).tag(config=True)
233
233
234 banner1 = Unicode(default_banner,
234 banner1 = Unicode(default_banner,
235 help="""The part of the banner to be printed before the profile"""
235 help="""The part of the banner to be printed before the profile"""
236 ).tag(config=True)
236 ).tag(config=True)
237 banner2 = Unicode('',
237 banner2 = Unicode('',
238 help="""The part of the banner to be printed after the profile"""
238 help="""The part of the banner to be printed after the profile"""
239 ).tag(config=True)
239 ).tag(config=True)
240
240
241 cache_size = Integer(1000, help=
241 cache_size = Integer(1000, help=
242 """
242 """
243 Set the size of the output cache. The default is 1000, you can
243 Set the size of the output cache. The default is 1000, you can
244 change it permanently in your config file. Setting it to 0 completely
244 change it permanently in your config file. Setting it to 0 completely
245 disables the caching system, and the minimum value accepted is 20 (if
245 disables the caching system, and the minimum value accepted is 20 (if
246 you provide a value less than 20, it is reset to 0 and a warning is
246 you provide a value less than 20, it is reset to 0 and a warning is
247 issued). This limit is defined because otherwise you'll spend more
247 issued). This limit is defined because otherwise you'll spend more
248 time re-flushing a too small cache than working
248 time re-flushing a too small cache than working
249 """
249 """
250 ).tag(config=True)
250 ).tag(config=True)
251 color_info = Bool(True, help=
251 color_info = Bool(True, help=
252 """
252 """
253 Use colors for displaying information about objects. Because this
253 Use colors for displaying information about objects. Because this
254 information is passed through a pager (like 'less'), and some pagers
254 information is passed through a pager (like 'less'), and some pagers
255 get confused with color codes, this capability can be turned off.
255 get confused with color codes, this capability can be turned off.
256 """
256 """
257 ).tag(config=True)
257 ).tag(config=True)
258 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
258 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
259 default_value='Neutral',
259 default_value='Neutral',
260 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
260 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
261 ).tag(config=True)
261 ).tag(config=True)
262 debug = Bool(False).tag(config=True)
262 debug = Bool(False).tag(config=True)
263 disable_failing_post_execute = Bool(False,
263 disable_failing_post_execute = Bool(False,
264 help="Don't call post-execute functions that have failed in the past."
264 help="Don't call post-execute functions that have failed in the past."
265 ).tag(config=True)
265 ).tag(config=True)
266 display_formatter = Instance(DisplayFormatter, allow_none=True)
266 display_formatter = Instance(DisplayFormatter, allow_none=True)
267 displayhook_class = Type(DisplayHook)
267 displayhook_class = Type(DisplayHook)
268 display_pub_class = Type(DisplayPublisher)
268 display_pub_class = Type(DisplayPublisher)
269
269
270 sphinxify_docstring = Bool(False, help=
270 sphinxify_docstring = Bool(False, help=
271 """
271 """
272 Enables rich html representation of docstrings. (This requires the
272 Enables rich html representation of docstrings. (This requires the
273 docrepr module).
273 docrepr module).
274 """).tag(config=True)
274 """).tag(config=True)
275
275
276 @observe("sphinxify_docstring")
276 @observe("sphinxify_docstring")
277 def _sphinxify_docstring_changed(self, change):
277 def _sphinxify_docstring_changed(self, change):
278 if change['new']:
278 if change['new']:
279 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
279 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
280
280
281 enable_html_pager = Bool(False, help=
281 enable_html_pager = Bool(False, help=
282 """
282 """
283 (Provisional API) enables html representation in mime bundles sent
283 (Provisional API) enables html representation in mime bundles sent
284 to pagers.
284 to pagers.
285 """).tag(config=True)
285 """).tag(config=True)
286
286
287 @observe("enable_html_pager")
287 @observe("enable_html_pager")
288 def _enable_html_pager_changed(self, change):
288 def _enable_html_pager_changed(self, change):
289 if change['new']:
289 if change['new']:
290 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
290 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
291
291
292 data_pub_class = None
292 data_pub_class = None
293
293
294 exit_now = Bool(False)
294 exit_now = Bool(False)
295 exiter = Instance(ExitAutocall)
295 exiter = Instance(ExitAutocall)
296 @default('exiter')
296 @default('exiter')
297 def _exiter_default(self):
297 def _exiter_default(self):
298 return ExitAutocall(self)
298 return ExitAutocall(self)
299 # Monotonically increasing execution counter
299 # Monotonically increasing execution counter
300 execution_count = Integer(1)
300 execution_count = Integer(1)
301 filename = Unicode("<ipython console>")
301 filename = Unicode("<ipython console>")
302 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
302 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
303
303
304 # Input splitter, to transform input line by line and detect when a block
304 # Input splitter, to transform input line by line and detect when a block
305 # is ready to be executed.
305 # is ready to be executed.
306 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
306 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
307 (), {'line_input_checker': True})
307 (), {'line_input_checker': True})
308
308
309 # This InputSplitter instance is used to transform completed cells before
309 # This InputSplitter instance is used to transform completed cells before
310 # running them. It allows cell magics to contain blank lines.
310 # running them. It allows cell magics to contain blank lines.
311 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
311 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
312 (), {'line_input_checker': False})
312 (), {'line_input_checker': False})
313
313
314 logstart = Bool(False, help=
314 logstart = Bool(False, help=
315 """
315 """
316 Start logging to the default log file in overwrite mode.
316 Start logging to the default log file in overwrite mode.
317 Use `logappend` to specify a log file to **append** logs to.
317 Use `logappend` to specify a log file to **append** logs to.
318 """
318 """
319 ).tag(config=True)
319 ).tag(config=True)
320 logfile = Unicode('', help=
320 logfile = Unicode('', help=
321 """
321 """
322 The name of the logfile to use.
322 The name of the logfile to use.
323 """
323 """
324 ).tag(config=True)
324 ).tag(config=True)
325 logappend = Unicode('', help=
325 logappend = Unicode('', help=
326 """
326 """
327 Start logging to the given file in append mode.
327 Start logging to the given file in append mode.
328 Use `logfile` to specify a log file to **overwrite** logs to.
328 Use `logfile` to specify a log file to **overwrite** logs to.
329 """
329 """
330 ).tag(config=True)
330 ).tag(config=True)
331 object_info_string_level = Enum((0,1,2), default_value=0,
331 object_info_string_level = Enum((0,1,2), default_value=0,
332 ).tag(config=True)
332 ).tag(config=True)
333 pdb = Bool(False, help=
333 pdb = Bool(False, help=
334 """
334 """
335 Automatically call the pdb debugger after every exception.
335 Automatically call the pdb debugger after every exception.
336 """
336 """
337 ).tag(config=True)
337 ).tag(config=True)
338 display_page = Bool(False,
338 display_page = Bool(False,
339 help="""If True, anything that would be passed to the pager
339 help="""If True, anything that would be passed to the pager
340 will be displayed as regular output instead."""
340 will be displayed as regular output instead."""
341 ).tag(config=True)
341 ).tag(config=True)
342
342
343 # deprecated prompt traits:
343 # deprecated prompt traits:
344
344
345 prompt_in1 = Unicode('In [\\#]: ',
345 prompt_in1 = Unicode('In [\\#]: ',
346 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
346 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
347 ).tag(config=True)
347 ).tag(config=True)
348 prompt_in2 = Unicode(' .\\D.: ',
348 prompt_in2 = Unicode(' .\\D.: ',
349 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
349 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
350 ).tag(config=True)
350 ).tag(config=True)
351 prompt_out = Unicode('Out[\\#]: ',
351 prompt_out = Unicode('Out[\\#]: ',
352 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
352 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
353 ).tag(config=True)
353 ).tag(config=True)
354 prompts_pad_left = Bool(True,
354 prompts_pad_left = Bool(True,
355 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
355 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
356 ).tag(config=True)
356 ).tag(config=True)
357
357
358 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
358 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
359 def _prompt_trait_changed(self, change):
359 def _prompt_trait_changed(self, change):
360 name = change['name']
360 name = change['name']
361 warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format(
361 warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format(
362 name=name)
362 name=name)
363 )
363 )
364 # protect against weird cases where self.config may not exist:
364 # protect against weird cases where self.config may not exist:
365
365
366 show_rewritten_input = Bool(True,
366 show_rewritten_input = Bool(True,
367 help="Show rewritten input, e.g. for autocall."
367 help="Show rewritten input, e.g. for autocall."
368 ).tag(config=True)
368 ).tag(config=True)
369
369
370 quiet = Bool(False).tag(config=True)
370 quiet = Bool(False).tag(config=True)
371
371
372 history_length = Integer(10000,
372 history_length = Integer(10000,
373 help='Total length of command history'
373 help='Total length of command history'
374 ).tag(config=True)
374 ).tag(config=True)
375
375
376 history_load_length = Integer(1000, help=
376 history_load_length = Integer(1000, help=
377 """
377 """
378 The number of saved history entries to be loaded
378 The number of saved history entries to be loaded
379 into the history buffer at startup.
379 into the history buffer at startup.
380 """
380 """
381 ).tag(config=True)
381 ).tag(config=True)
382
382
383 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
383 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
384 default_value='last_expr',
384 default_value='last_expr',
385 help="""
385 help="""
386 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
386 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
387 run interactively (displaying output from expressions)."""
387 run interactively (displaying output from expressions)."""
388 ).tag(config=True)
388 ).tag(config=True)
389
389
390 # TODO: this part of prompt management should be moved to the frontends.
390 # TODO: this part of prompt management should be moved to the frontends.
391 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
391 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
392 separate_in = SeparateUnicode('\n').tag(config=True)
392 separate_in = SeparateUnicode('\n').tag(config=True)
393 separate_out = SeparateUnicode('').tag(config=True)
393 separate_out = SeparateUnicode('').tag(config=True)
394 separate_out2 = SeparateUnicode('').tag(config=True)
394 separate_out2 = SeparateUnicode('').tag(config=True)
395 wildcards_case_sensitive = Bool(True).tag(config=True)
395 wildcards_case_sensitive = Bool(True).tag(config=True)
396 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
396 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
397 default_value='Context').tag(config=True)
397 default_value='Context').tag(config=True)
398
398
399 # Subcomponents of InteractiveShell
399 # Subcomponents of InteractiveShell
400 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
400 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
401 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
401 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
402 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
402 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
403 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
403 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
404 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
404 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
405 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
405 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
406 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
406 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
407 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
407 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
408
408
409 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
409 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
410 @property
410 @property
411 def profile(self):
411 def profile(self):
412 if self.profile_dir is not None:
412 if self.profile_dir is not None:
413 name = os.path.basename(self.profile_dir.location)
413 name = os.path.basename(self.profile_dir.location)
414 return name.replace('profile_','')
414 return name.replace('profile_','')
415
415
416
416
417 # Private interface
417 # Private interface
418 _post_execute = Dict()
418 _post_execute = Dict()
419
419
420 # Tracks any GUI loop loaded for pylab
420 # Tracks any GUI loop loaded for pylab
421 pylab_gui_select = None
421 pylab_gui_select = None
422
422
423 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
423 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
424
424
425 def __init__(self, ipython_dir=None, profile_dir=None,
425 def __init__(self, ipython_dir=None, profile_dir=None,
426 user_module=None, user_ns=None,
426 user_module=None, user_ns=None,
427 custom_exceptions=((), None), **kwargs):
427 custom_exceptions=((), None), **kwargs):
428
428
429 # This is where traits with a config_key argument are updated
429 # This is where traits with a config_key argument are updated
430 # from the values on config.
430 # from the values on config.
431 super(InteractiveShell, self).__init__(**kwargs)
431 super(InteractiveShell, self).__init__(**kwargs)
432 if 'PromptManager' in self.config:
432 if 'PromptManager' in self.config:
433 warn('As of IPython 5.0 `PromptManager` config will have no effect'
433 warn('As of IPython 5.0 `PromptManager` config will have no effect'
434 ' and has been replaced by TerminalInteractiveShell.prompts_class')
434 ' and has been replaced by TerminalInteractiveShell.prompts_class')
435 self.configurables = [self]
435 self.configurables = [self]
436
436
437 # These are relatively independent and stateless
437 # These are relatively independent and stateless
438 self.init_ipython_dir(ipython_dir)
438 self.init_ipython_dir(ipython_dir)
439 self.init_profile_dir(profile_dir)
439 self.init_profile_dir(profile_dir)
440 self.init_instance_attrs()
440 self.init_instance_attrs()
441 self.init_environment()
441 self.init_environment()
442
442
443 # Check if we're in a virtualenv, and set up sys.path.
443 # Check if we're in a virtualenv, and set up sys.path.
444 self.init_virtualenv()
444 self.init_virtualenv()
445
445
446 # Create namespaces (user_ns, user_global_ns, etc.)
446 # Create namespaces (user_ns, user_global_ns, etc.)
447 self.init_create_namespaces(user_module, user_ns)
447 self.init_create_namespaces(user_module, user_ns)
448 # This has to be done after init_create_namespaces because it uses
448 # This has to be done after init_create_namespaces because it uses
449 # something in self.user_ns, but before init_sys_modules, which
449 # something in self.user_ns, but before init_sys_modules, which
450 # is the first thing to modify sys.
450 # is the first thing to modify sys.
451 # TODO: When we override sys.stdout and sys.stderr before this class
451 # TODO: When we override sys.stdout and sys.stderr before this class
452 # is created, we are saving the overridden ones here. Not sure if this
452 # is created, we are saving the overridden ones here. Not sure if this
453 # is what we want to do.
453 # is what we want to do.
454 self.save_sys_module_state()
454 self.save_sys_module_state()
455 self.init_sys_modules()
455 self.init_sys_modules()
456
456
457 # While we're trying to have each part of the code directly access what
457 # While we're trying to have each part of the code directly access what
458 # it needs without keeping redundant references to objects, we have too
458 # it needs without keeping redundant references to objects, we have too
459 # much legacy code that expects ip.db to exist.
459 # much legacy code that expects ip.db to exist.
460 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
460 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
461
461
462 self.init_history()
462 self.init_history()
463 self.init_encoding()
463 self.init_encoding()
464 self.init_prefilter()
464 self.init_prefilter()
465
465
466 self.init_syntax_highlighting()
466 self.init_syntax_highlighting()
467 self.init_hooks()
467 self.init_hooks()
468 self.init_events()
468 self.init_events()
469 self.init_pushd_popd_magic()
469 self.init_pushd_popd_magic()
470 self.init_user_ns()
470 self.init_user_ns()
471 self.init_logger()
471 self.init_logger()
472 self.init_builtins()
472 self.init_builtins()
473
473
474 # The following was in post_config_initialization
474 # The following was in post_config_initialization
475 self.init_inspector()
475 self.init_inspector()
476 if py3compat.PY3:
476 self.raw_input_original = input
477 self.raw_input_original = input
478 else:
479 self.raw_input_original = raw_input
480 self.init_completer()
477 self.init_completer()
481 # TODO: init_io() needs to happen before init_traceback handlers
478 # TODO: init_io() needs to happen before init_traceback handlers
482 # because the traceback handlers hardcode the stdout/stderr streams.
479 # because the traceback handlers hardcode the stdout/stderr streams.
483 # This logic in in debugger.Pdb and should eventually be changed.
480 # This logic in in debugger.Pdb and should eventually be changed.
484 self.init_io()
481 self.init_io()
485 self.init_traceback_handlers(custom_exceptions)
482 self.init_traceback_handlers(custom_exceptions)
486 self.init_prompts()
483 self.init_prompts()
487 self.init_display_formatter()
484 self.init_display_formatter()
488 self.init_display_pub()
485 self.init_display_pub()
489 self.init_data_pub()
486 self.init_data_pub()
490 self.init_displayhook()
487 self.init_displayhook()
491 self.init_magics()
488 self.init_magics()
492 self.init_alias()
489 self.init_alias()
493 self.init_logstart()
490 self.init_logstart()
494 self.init_pdb()
491 self.init_pdb()
495 self.init_extension_manager()
492 self.init_extension_manager()
496 self.init_payload()
493 self.init_payload()
497 self.init_deprecation_warnings()
494 self.init_deprecation_warnings()
498 self.hooks.late_startup_hook()
495 self.hooks.late_startup_hook()
499 self.events.trigger('shell_initialized', self)
496 self.events.trigger('shell_initialized', self)
500 atexit.register(self.atexit_operations)
497 atexit.register(self.atexit_operations)
501
498
502 def get_ipython(self):
499 def get_ipython(self):
503 """Return the currently running IPython instance."""
500 """Return the currently running IPython instance."""
504 return self
501 return self
505
502
506 #-------------------------------------------------------------------------
503 #-------------------------------------------------------------------------
507 # Trait changed handlers
504 # Trait changed handlers
508 #-------------------------------------------------------------------------
505 #-------------------------------------------------------------------------
509 @observe('ipython_dir')
506 @observe('ipython_dir')
510 def _ipython_dir_changed(self, change):
507 def _ipython_dir_changed(self, change):
511 ensure_dir_exists(change['new'])
508 ensure_dir_exists(change['new'])
512
509
513 def set_autoindent(self,value=None):
510 def set_autoindent(self,value=None):
514 """Set the autoindent flag.
511 """Set the autoindent flag.
515
512
516 If called with no arguments, it acts as a toggle."""
513 If called with no arguments, it acts as a toggle."""
517 if value is None:
514 if value is None:
518 self.autoindent = not self.autoindent
515 self.autoindent = not self.autoindent
519 else:
516 else:
520 self.autoindent = value
517 self.autoindent = value
521
518
522 #-------------------------------------------------------------------------
519 #-------------------------------------------------------------------------
523 # init_* methods called by __init__
520 # init_* methods called by __init__
524 #-------------------------------------------------------------------------
521 #-------------------------------------------------------------------------
525
522
526 def init_ipython_dir(self, ipython_dir):
523 def init_ipython_dir(self, ipython_dir):
527 if ipython_dir is not None:
524 if ipython_dir is not None:
528 self.ipython_dir = ipython_dir
525 self.ipython_dir = ipython_dir
529 return
526 return
530
527
531 self.ipython_dir = get_ipython_dir()
528 self.ipython_dir = get_ipython_dir()
532
529
533 def init_profile_dir(self, profile_dir):
530 def init_profile_dir(self, profile_dir):
534 if profile_dir is not None:
531 if profile_dir is not None:
535 self.profile_dir = profile_dir
532 self.profile_dir = profile_dir
536 return
533 return
537 self.profile_dir =\
534 self.profile_dir =\
538 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
535 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
539
536
540 def init_instance_attrs(self):
537 def init_instance_attrs(self):
541 self.more = False
538 self.more = False
542
539
543 # command compiler
540 # command compiler
544 self.compile = CachingCompiler()
541 self.compile = CachingCompiler()
545
542
546 # Make an empty namespace, which extension writers can rely on both
543 # Make an empty namespace, which extension writers can rely on both
547 # existing and NEVER being used by ipython itself. This gives them a
544 # existing and NEVER being used by ipython itself. This gives them a
548 # convenient location for storing additional information and state
545 # convenient location for storing additional information and state
549 # their extensions may require, without fear of collisions with other
546 # their extensions may require, without fear of collisions with other
550 # ipython names that may develop later.
547 # ipython names that may develop later.
551 self.meta = Struct()
548 self.meta = Struct()
552
549
553 # Temporary files used for various purposes. Deleted at exit.
550 # Temporary files used for various purposes. Deleted at exit.
554 self.tempfiles = []
551 self.tempfiles = []
555 self.tempdirs = []
552 self.tempdirs = []
556
553
557 # keep track of where we started running (mainly for crash post-mortem)
554 # keep track of where we started running (mainly for crash post-mortem)
558 # This is not being used anywhere currently.
555 # This is not being used anywhere currently.
559 self.starting_dir = py3compat.getcwd()
556 self.starting_dir = py3compat.getcwd()
560
557
561 # Indentation management
558 # Indentation management
562 self.indent_current_nsp = 0
559 self.indent_current_nsp = 0
563
560
564 # Dict to track post-execution functions that have been registered
561 # Dict to track post-execution functions that have been registered
565 self._post_execute = {}
562 self._post_execute = {}
566
563
567 def init_environment(self):
564 def init_environment(self):
568 """Any changes we need to make to the user's environment."""
565 """Any changes we need to make to the user's environment."""
569 pass
566 pass
570
567
571 def init_encoding(self):
568 def init_encoding(self):
572 # Get system encoding at startup time. Certain terminals (like Emacs
569 # Get system encoding at startup time. Certain terminals (like Emacs
573 # under Win32 have it set to None, and we need to have a known valid
570 # under Win32 have it set to None, and we need to have a known valid
574 # encoding to use in the raw_input() method
571 # encoding to use in the raw_input() method
575 try:
572 try:
576 self.stdin_encoding = sys.stdin.encoding or 'ascii'
573 self.stdin_encoding = sys.stdin.encoding or 'ascii'
577 except AttributeError:
574 except AttributeError:
578 self.stdin_encoding = 'ascii'
575 self.stdin_encoding = 'ascii'
579
576
580 def init_syntax_highlighting(self):
577
578 @observe('colors')
579 def init_syntax_highlighting(self, changes=None):
581 # Python source parser/formatter for syntax highlighting
580 # Python source parser/formatter for syntax highlighting
582 pyformat = PyColorize.Parser().format
581 pyformat = PyColorize.Parser(style=self.colors).format
583 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
582 self.pycolorize = lambda src: pyformat(src,'str')
584
583
585 def refresh_style(self):
584 def refresh_style(self):
586 # No-op here, used in subclass
585 # No-op here, used in subclass
587 pass
586 pass
588
587
589 def init_pushd_popd_magic(self):
588 def init_pushd_popd_magic(self):
590 # for pushd/popd management
589 # for pushd/popd management
591 self.home_dir = get_home_dir()
590 self.home_dir = get_home_dir()
592
591
593 self.dir_stack = []
592 self.dir_stack = []
594
593
595 def init_logger(self):
594 def init_logger(self):
596 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
595 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
597 logmode='rotate')
596 logmode='rotate')
598
597
599 def init_logstart(self):
598 def init_logstart(self):
600 """Initialize logging in case it was requested at the command line.
599 """Initialize logging in case it was requested at the command line.
601 """
600 """
602 if self.logappend:
601 if self.logappend:
603 self.magic('logstart %s append' % self.logappend)
602 self.magic('logstart %s append' % self.logappend)
604 elif self.logfile:
603 elif self.logfile:
605 self.magic('logstart %s' % self.logfile)
604 self.magic('logstart %s' % self.logfile)
606 elif self.logstart:
605 elif self.logstart:
607 self.magic('logstart')
606 self.magic('logstart')
608
607
609 def init_deprecation_warnings(self):
608 def init_deprecation_warnings(self):
610 """
609 """
611 register default filter for deprecation warning.
610 register default filter for deprecation warning.
612
611
613 This will allow deprecation warning of function used interactively to show
612 This will allow deprecation warning of function used interactively to show
614 warning to users, and still hide deprecation warning from libraries import.
613 warning to users, and still hide deprecation warning from libraries import.
615 """
614 """
616 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
615 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
617
616
618 def init_builtins(self):
617 def init_builtins(self):
619 # A single, static flag that we set to True. Its presence indicates
618 # A single, static flag that we set to True. Its presence indicates
620 # that an IPython shell has been created, and we make no attempts at
619 # that an IPython shell has been created, and we make no attempts at
621 # removing on exit or representing the existence of more than one
620 # removing on exit or representing the existence of more than one
622 # IPython at a time.
621 # IPython at a time.
623 builtin_mod.__dict__['__IPYTHON__'] = True
622 builtin_mod.__dict__['__IPYTHON__'] = True
624
623
625 self.builtin_trap = BuiltinTrap(shell=self)
624 self.builtin_trap = BuiltinTrap(shell=self)
626
625
627 def init_inspector(self):
626 def init_inspector(self):
628 # Object inspector
627 # Object inspector
629 self.inspector = oinspect.Inspector(oinspect.InspectColors,
628 self.inspector = oinspect.Inspector(oinspect.InspectColors,
630 PyColorize.ANSICodeColors,
629 PyColorize.ANSICodeColors,
631 'NoColor',
630 'NoColor',
632 self.object_info_string_level)
631 self.object_info_string_level)
633
632
634 def init_io(self):
633 def init_io(self):
635 # This will just use sys.stdout and sys.stderr. If you want to
634 # This will just use sys.stdout and sys.stderr. If you want to
636 # override sys.stdout and sys.stderr themselves, you need to do that
635 # override sys.stdout and sys.stderr themselves, you need to do that
637 # *before* instantiating this class, because io holds onto
636 # *before* instantiating this class, because io holds onto
638 # references to the underlying streams.
637 # references to the underlying streams.
639 # io.std* are deprecated, but don't show our own deprecation warnings
638 # io.std* are deprecated, but don't show our own deprecation warnings
640 # during initialization of the deprecated API.
639 # during initialization of the deprecated API.
641 with warnings.catch_warnings():
640 with warnings.catch_warnings():
642 warnings.simplefilter('ignore', DeprecationWarning)
641 warnings.simplefilter('ignore', DeprecationWarning)
643 io.stdout = io.IOStream(sys.stdout)
642 io.stdout = io.IOStream(sys.stdout)
644 io.stderr = io.IOStream(sys.stderr)
643 io.stderr = io.IOStream(sys.stderr)
645
644
646 def init_prompts(self):
645 def init_prompts(self):
647 # Set system prompts, so that scripts can decide if they are running
646 # Set system prompts, so that scripts can decide if they are running
648 # interactively.
647 # interactively.
649 sys.ps1 = 'In : '
648 sys.ps1 = 'In : '
650 sys.ps2 = '...: '
649 sys.ps2 = '...: '
651 sys.ps3 = 'Out: '
650 sys.ps3 = 'Out: '
652
651
653 def init_display_formatter(self):
652 def init_display_formatter(self):
654 self.display_formatter = DisplayFormatter(parent=self)
653 self.display_formatter = DisplayFormatter(parent=self)
655 self.configurables.append(self.display_formatter)
654 self.configurables.append(self.display_formatter)
656
655
657 def init_display_pub(self):
656 def init_display_pub(self):
658 self.display_pub = self.display_pub_class(parent=self)
657 self.display_pub = self.display_pub_class(parent=self)
659 self.configurables.append(self.display_pub)
658 self.configurables.append(self.display_pub)
660
659
661 def init_data_pub(self):
660 def init_data_pub(self):
662 if not self.data_pub_class:
661 if not self.data_pub_class:
663 self.data_pub = None
662 self.data_pub = None
664 return
663 return
665 self.data_pub = self.data_pub_class(parent=self)
664 self.data_pub = self.data_pub_class(parent=self)
666 self.configurables.append(self.data_pub)
665 self.configurables.append(self.data_pub)
667
666
668 def init_displayhook(self):
667 def init_displayhook(self):
669 # Initialize displayhook, set in/out prompts and printing system
668 # Initialize displayhook, set in/out prompts and printing system
670 self.displayhook = self.displayhook_class(
669 self.displayhook = self.displayhook_class(
671 parent=self,
670 parent=self,
672 shell=self,
671 shell=self,
673 cache_size=self.cache_size,
672 cache_size=self.cache_size,
674 )
673 )
675 self.configurables.append(self.displayhook)
674 self.configurables.append(self.displayhook)
676 # This is a context manager that installs/revmoes the displayhook at
675 # This is a context manager that installs/revmoes the displayhook at
677 # the appropriate time.
676 # the appropriate time.
678 self.display_trap = DisplayTrap(hook=self.displayhook)
677 self.display_trap = DisplayTrap(hook=self.displayhook)
679
678
680 def init_virtualenv(self):
679 def init_virtualenv(self):
681 """Add a virtualenv to sys.path so the user can import modules from it.
680 """Add a virtualenv to sys.path so the user can import modules from it.
682 This isn't perfect: it doesn't use the Python interpreter with which the
681 This isn't perfect: it doesn't use the Python interpreter with which the
683 virtualenv was built, and it ignores the --no-site-packages option. A
682 virtualenv was built, and it ignores the --no-site-packages option. A
684 warning will appear suggesting the user installs IPython in the
683 warning will appear suggesting the user installs IPython in the
685 virtualenv, but for many cases, it probably works well enough.
684 virtualenv, but for many cases, it probably works well enough.
686
685
687 Adapted from code snippets online.
686 Adapted from code snippets online.
688
687
689 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
688 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
690 """
689 """
691 if 'VIRTUAL_ENV' not in os.environ:
690 if 'VIRTUAL_ENV' not in os.environ:
692 # Not in a virtualenv
691 # Not in a virtualenv
693 return
692 return
694
693
695 # venv detection:
694 # venv detection:
696 # stdlib venv may symlink sys.executable, so we can't use realpath.
695 # stdlib venv may symlink sys.executable, so we can't use realpath.
697 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
696 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
698 # So we just check every item in the symlink tree (generally <= 3)
697 # So we just check every item in the symlink tree (generally <= 3)
699 p = os.path.normcase(sys.executable)
698 p = os.path.normcase(sys.executable)
700 paths = [p]
699 paths = [p]
701 while os.path.islink(p):
700 while os.path.islink(p):
702 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
701 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
703 paths.append(p)
702 paths.append(p)
704 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
703 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
705 if any(p.startswith(p_venv) for p in paths):
704 if any(p.startswith(p_venv) for p in paths):
706 # Running properly in the virtualenv, don't need to do anything
705 # Running properly in the virtualenv, don't need to do anything
707 return
706 return
708
707
709 warn("Attempting to work in a virtualenv. If you encounter problems, please "
708 warn("Attempting to work in a virtualenv. If you encounter problems, please "
710 "install IPython inside the virtualenv.")
709 "install IPython inside the virtualenv.")
711 if sys.platform == "win32":
710 if sys.platform == "win32":
712 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
711 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
713 else:
712 else:
714 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
713 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
715 'python%d.%d' % sys.version_info[:2], 'site-packages')
714 'python%d.%d' % sys.version_info[:2], 'site-packages')
716
715
717 import site
716 import site
718 sys.path.insert(0, virtual_env)
717 sys.path.insert(0, virtual_env)
719 site.addsitedir(virtual_env)
718 site.addsitedir(virtual_env)
720
719
721 #-------------------------------------------------------------------------
720 #-------------------------------------------------------------------------
722 # Things related to injections into the sys module
721 # Things related to injections into the sys module
723 #-------------------------------------------------------------------------
722 #-------------------------------------------------------------------------
724
723
725 def save_sys_module_state(self):
724 def save_sys_module_state(self):
726 """Save the state of hooks in the sys module.
725 """Save the state of hooks in the sys module.
727
726
728 This has to be called after self.user_module is created.
727 This has to be called after self.user_module is created.
729 """
728 """
730 self._orig_sys_module_state = {'stdin': sys.stdin,
729 self._orig_sys_module_state = {'stdin': sys.stdin,
731 'stdout': sys.stdout,
730 'stdout': sys.stdout,
732 'stderr': sys.stderr,
731 'stderr': sys.stderr,
733 'excepthook': sys.excepthook}
732 'excepthook': sys.excepthook}
734 self._orig_sys_modules_main_name = self.user_module.__name__
733 self._orig_sys_modules_main_name = self.user_module.__name__
735 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
734 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
736
735
737 def restore_sys_module_state(self):
736 def restore_sys_module_state(self):
738 """Restore the state of the sys module."""
737 """Restore the state of the sys module."""
739 try:
738 try:
740 for k, v in iteritems(self._orig_sys_module_state):
739 for k, v in iteritems(self._orig_sys_module_state):
741 setattr(sys, k, v)
740 setattr(sys, k, v)
742 except AttributeError:
741 except AttributeError:
743 pass
742 pass
744 # Reset what what done in self.init_sys_modules
743 # Reset what what done in self.init_sys_modules
745 if self._orig_sys_modules_main_mod is not None:
744 if self._orig_sys_modules_main_mod is not None:
746 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
745 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
747
746
748 #-------------------------------------------------------------------------
747 #-------------------------------------------------------------------------
749 # Things related to the banner
748 # Things related to the banner
750 #-------------------------------------------------------------------------
749 #-------------------------------------------------------------------------
751
750
752 @property
751 @property
753 def banner(self):
752 def banner(self):
754 banner = self.banner1
753 banner = self.banner1
755 if self.profile and self.profile != 'default':
754 if self.profile and self.profile != 'default':
756 banner += '\nIPython profile: %s\n' % self.profile
755 banner += '\nIPython profile: %s\n' % self.profile
757 if self.banner2:
756 if self.banner2:
758 banner += '\n' + self.banner2
757 banner += '\n' + self.banner2
759 return banner
758 return banner
760
759
761 def show_banner(self, banner=None):
760 def show_banner(self, banner=None):
762 if banner is None:
761 if banner is None:
763 banner = self.banner
762 banner = self.banner
764 sys.stdout.write(banner)
763 sys.stdout.write(banner)
765
764
766 #-------------------------------------------------------------------------
765 #-------------------------------------------------------------------------
767 # Things related to hooks
766 # Things related to hooks
768 #-------------------------------------------------------------------------
767 #-------------------------------------------------------------------------
769
768
770 def init_hooks(self):
769 def init_hooks(self):
771 # hooks holds pointers used for user-side customizations
770 # hooks holds pointers used for user-side customizations
772 self.hooks = Struct()
771 self.hooks = Struct()
773
772
774 self.strdispatchers = {}
773 self.strdispatchers = {}
775
774
776 # Set all default hooks, defined in the IPython.hooks module.
775 # Set all default hooks, defined in the IPython.hooks module.
777 hooks = IPython.core.hooks
776 hooks = IPython.core.hooks
778 for hook_name in hooks.__all__:
777 for hook_name in hooks.__all__:
779 # default hooks have priority 100, i.e. low; user hooks should have
778 # default hooks have priority 100, i.e. low; user hooks should have
780 # 0-100 priority
779 # 0-100 priority
781 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
780 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
782
781
783 if self.display_page:
782 if self.display_page:
784 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
783 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
785
784
786 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
785 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
787 _warn_deprecated=True):
786 _warn_deprecated=True):
788 """set_hook(name,hook) -> sets an internal IPython hook.
787 """set_hook(name,hook) -> sets an internal IPython hook.
789
788
790 IPython exposes some of its internal API as user-modifiable hooks. By
789 IPython exposes some of its internal API as user-modifiable hooks. By
791 adding your function to one of these hooks, you can modify IPython's
790 adding your function to one of these hooks, you can modify IPython's
792 behavior to call at runtime your own routines."""
791 behavior to call at runtime your own routines."""
793
792
794 # At some point in the future, this should validate the hook before it
793 # At some point in the future, this should validate the hook before it
795 # accepts it. Probably at least check that the hook takes the number
794 # accepts it. Probably at least check that the hook takes the number
796 # of args it's supposed to.
795 # of args it's supposed to.
797
796
798 f = types.MethodType(hook,self)
797 f = types.MethodType(hook,self)
799
798
800 # check if the hook is for strdispatcher first
799 # check if the hook is for strdispatcher first
801 if str_key is not None:
800 if str_key is not None:
802 sdp = self.strdispatchers.get(name, StrDispatch())
801 sdp = self.strdispatchers.get(name, StrDispatch())
803 sdp.add_s(str_key, f, priority )
802 sdp.add_s(str_key, f, priority )
804 self.strdispatchers[name] = sdp
803 self.strdispatchers[name] = sdp
805 return
804 return
806 if re_key is not None:
805 if re_key is not None:
807 sdp = self.strdispatchers.get(name, StrDispatch())
806 sdp = self.strdispatchers.get(name, StrDispatch())
808 sdp.add_re(re.compile(re_key), f, priority )
807 sdp.add_re(re.compile(re_key), f, priority )
809 self.strdispatchers[name] = sdp
808 self.strdispatchers[name] = sdp
810 return
809 return
811
810
812 dp = getattr(self.hooks, name, None)
811 dp = getattr(self.hooks, name, None)
813 if name not in IPython.core.hooks.__all__:
812 if name not in IPython.core.hooks.__all__:
814 print("Warning! Hook '%s' is not one of %s" % \
813 print("Warning! Hook '%s' is not one of %s" % \
815 (name, IPython.core.hooks.__all__ ))
814 (name, IPython.core.hooks.__all__ ))
816
815
817 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
816 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
818 alternative = IPython.core.hooks.deprecated[name]
817 alternative = IPython.core.hooks.deprecated[name]
819 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
818 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
820
819
821 if not dp:
820 if not dp:
822 dp = IPython.core.hooks.CommandChainDispatcher()
821 dp = IPython.core.hooks.CommandChainDispatcher()
823
822
824 try:
823 try:
825 dp.add(f,priority)
824 dp.add(f,priority)
826 except AttributeError:
825 except AttributeError:
827 # it was not commandchain, plain old func - replace
826 # it was not commandchain, plain old func - replace
828 dp = f
827 dp = f
829
828
830 setattr(self.hooks,name, dp)
829 setattr(self.hooks,name, dp)
831
830
832 #-------------------------------------------------------------------------
831 #-------------------------------------------------------------------------
833 # Things related to events
832 # Things related to events
834 #-------------------------------------------------------------------------
833 #-------------------------------------------------------------------------
835
834
836 def init_events(self):
835 def init_events(self):
837 self.events = EventManager(self, available_events)
836 self.events = EventManager(self, available_events)
838
837
839 self.events.register("pre_execute", self._clear_warning_registry)
838 self.events.register("pre_execute", self._clear_warning_registry)
840
839
841 def register_post_execute(self, func):
840 def register_post_execute(self, func):
842 """DEPRECATED: Use ip.events.register('post_run_cell', func)
841 """DEPRECATED: Use ip.events.register('post_run_cell', func)
843
842
844 Register a function for calling after code execution.
843 Register a function for calling after code execution.
845 """
844 """
846 warn("ip.register_post_execute is deprecated, use "
845 warn("ip.register_post_execute is deprecated, use "
847 "ip.events.register('post_run_cell', func) instead.")
846 "ip.events.register('post_run_cell', func) instead.")
848 self.events.register('post_run_cell', func)
847 self.events.register('post_run_cell', func)
849
848
850 def _clear_warning_registry(self):
849 def _clear_warning_registry(self):
851 # clear the warning registry, so that different code blocks with
850 # clear the warning registry, so that different code blocks with
852 # overlapping line number ranges don't cause spurious suppression of
851 # overlapping line number ranges don't cause spurious suppression of
853 # warnings (see gh-6611 for details)
852 # warnings (see gh-6611 for details)
854 if "__warningregistry__" in self.user_global_ns:
853 if "__warningregistry__" in self.user_global_ns:
855 del self.user_global_ns["__warningregistry__"]
854 del self.user_global_ns["__warningregistry__"]
856
855
857 #-------------------------------------------------------------------------
856 #-------------------------------------------------------------------------
858 # Things related to the "main" module
857 # Things related to the "main" module
859 #-------------------------------------------------------------------------
858 #-------------------------------------------------------------------------
860
859
861 def new_main_mod(self, filename, modname):
860 def new_main_mod(self, filename, modname):
862 """Return a new 'main' module object for user code execution.
861 """Return a new 'main' module object for user code execution.
863
862
864 ``filename`` should be the path of the script which will be run in the
863 ``filename`` should be the path of the script which will be run in the
865 module. Requests with the same filename will get the same module, with
864 module. Requests with the same filename will get the same module, with
866 its namespace cleared.
865 its namespace cleared.
867
866
868 ``modname`` should be the module name - normally either '__main__' or
867 ``modname`` should be the module name - normally either '__main__' or
869 the basename of the file without the extension.
868 the basename of the file without the extension.
870
869
871 When scripts are executed via %run, we must keep a reference to their
870 When scripts are executed via %run, we must keep a reference to their
872 __main__ module around so that Python doesn't
871 __main__ module around so that Python doesn't
873 clear it, rendering references to module globals useless.
872 clear it, rendering references to module globals useless.
874
873
875 This method keeps said reference in a private dict, keyed by the
874 This method keeps said reference in a private dict, keyed by the
876 absolute path of the script. This way, for multiple executions of the
875 absolute path of the script. This way, for multiple executions of the
877 same script we only keep one copy of the namespace (the last one),
876 same script we only keep one copy of the namespace (the last one),
878 thus preventing memory leaks from old references while allowing the
877 thus preventing memory leaks from old references while allowing the
879 objects from the last execution to be accessible.
878 objects from the last execution to be accessible.
880 """
879 """
881 filename = os.path.abspath(filename)
880 filename = os.path.abspath(filename)
882 try:
881 try:
883 main_mod = self._main_mod_cache[filename]
882 main_mod = self._main_mod_cache[filename]
884 except KeyError:
883 except KeyError:
885 main_mod = self._main_mod_cache[filename] = types.ModuleType(
884 main_mod = self._main_mod_cache[filename] = types.ModuleType(
886 py3compat.cast_bytes_py2(modname),
885 py3compat.cast_bytes_py2(modname),
887 doc="Module created for script run in IPython")
886 doc="Module created for script run in IPython")
888 else:
887 else:
889 main_mod.__dict__.clear()
888 main_mod.__dict__.clear()
890 main_mod.__name__ = modname
889 main_mod.__name__ = modname
891
890
892 main_mod.__file__ = filename
891 main_mod.__file__ = filename
893 # It seems pydoc (and perhaps others) needs any module instance to
892 # It seems pydoc (and perhaps others) needs any module instance to
894 # implement a __nonzero__ method
893 # implement a __nonzero__ method
895 main_mod.__nonzero__ = lambda : True
894 main_mod.__nonzero__ = lambda : True
896
895
897 return main_mod
896 return main_mod
898
897
899 def clear_main_mod_cache(self):
898 def clear_main_mod_cache(self):
900 """Clear the cache of main modules.
899 """Clear the cache of main modules.
901
900
902 Mainly for use by utilities like %reset.
901 Mainly for use by utilities like %reset.
903
902
904 Examples
903 Examples
905 --------
904 --------
906
905
907 In [15]: import IPython
906 In [15]: import IPython
908
907
909 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
908 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
910
909
911 In [17]: len(_ip._main_mod_cache) > 0
910 In [17]: len(_ip._main_mod_cache) > 0
912 Out[17]: True
911 Out[17]: True
913
912
914 In [18]: _ip.clear_main_mod_cache()
913 In [18]: _ip.clear_main_mod_cache()
915
914
916 In [19]: len(_ip._main_mod_cache) == 0
915 In [19]: len(_ip._main_mod_cache) == 0
917 Out[19]: True
916 Out[19]: True
918 """
917 """
919 self._main_mod_cache.clear()
918 self._main_mod_cache.clear()
920
919
921 #-------------------------------------------------------------------------
920 #-------------------------------------------------------------------------
922 # Things related to debugging
921 # Things related to debugging
923 #-------------------------------------------------------------------------
922 #-------------------------------------------------------------------------
924
923
925 def init_pdb(self):
924 def init_pdb(self):
926 # Set calling of pdb on exceptions
925 # Set calling of pdb on exceptions
927 # self.call_pdb is a property
926 # self.call_pdb is a property
928 self.call_pdb = self.pdb
927 self.call_pdb = self.pdb
929
928
930 def _get_call_pdb(self):
929 def _get_call_pdb(self):
931 return self._call_pdb
930 return self._call_pdb
932
931
933 def _set_call_pdb(self,val):
932 def _set_call_pdb(self,val):
934
933
935 if val not in (0,1,False,True):
934 if val not in (0,1,False,True):
936 raise ValueError('new call_pdb value must be boolean')
935 raise ValueError('new call_pdb value must be boolean')
937
936
938 # store value in instance
937 # store value in instance
939 self._call_pdb = val
938 self._call_pdb = val
940
939
941 # notify the actual exception handlers
940 # notify the actual exception handlers
942 self.InteractiveTB.call_pdb = val
941 self.InteractiveTB.call_pdb = val
943
942
944 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
943 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
945 'Control auto-activation of pdb at exceptions')
944 'Control auto-activation of pdb at exceptions')
946
945
947 def debugger(self,force=False):
946 def debugger(self,force=False):
948 """Call the pdb debugger.
947 """Call the pdb debugger.
949
948
950 Keywords:
949 Keywords:
951
950
952 - force(False): by default, this routine checks the instance call_pdb
951 - force(False): by default, this routine checks the instance call_pdb
953 flag and does not actually invoke the debugger if the flag is false.
952 flag and does not actually invoke the debugger if the flag is false.
954 The 'force' option forces the debugger to activate even if the flag
953 The 'force' option forces the debugger to activate even if the flag
955 is false.
954 is false.
956 """
955 """
957
956
958 if not (force or self.call_pdb):
957 if not (force or self.call_pdb):
959 return
958 return
960
959
961 if not hasattr(sys,'last_traceback'):
960 if not hasattr(sys,'last_traceback'):
962 error('No traceback has been produced, nothing to debug.')
961 error('No traceback has been produced, nothing to debug.')
963 return
962 return
964
963
965 self.InteractiveTB.debugger(force=True)
964 self.InteractiveTB.debugger(force=True)
966
965
967 #-------------------------------------------------------------------------
966 #-------------------------------------------------------------------------
968 # Things related to IPython's various namespaces
967 # Things related to IPython's various namespaces
969 #-------------------------------------------------------------------------
968 #-------------------------------------------------------------------------
970 default_user_namespaces = True
969 default_user_namespaces = True
971
970
972 def init_create_namespaces(self, user_module=None, user_ns=None):
971 def init_create_namespaces(self, user_module=None, user_ns=None):
973 # Create the namespace where the user will operate. user_ns is
972 # Create the namespace where the user will operate. user_ns is
974 # normally the only one used, and it is passed to the exec calls as
973 # normally the only one used, and it is passed to the exec calls as
975 # the locals argument. But we do carry a user_global_ns namespace
974 # the locals argument. But we do carry a user_global_ns namespace
976 # given as the exec 'globals' argument, This is useful in embedding
975 # given as the exec 'globals' argument, This is useful in embedding
977 # situations where the ipython shell opens in a context where the
976 # situations where the ipython shell opens in a context where the
978 # distinction between locals and globals is meaningful. For
977 # distinction between locals and globals is meaningful. For
979 # non-embedded contexts, it is just the same object as the user_ns dict.
978 # non-embedded contexts, it is just the same object as the user_ns dict.
980
979
981 # FIXME. For some strange reason, __builtins__ is showing up at user
980 # FIXME. For some strange reason, __builtins__ is showing up at user
982 # level as a dict instead of a module. This is a manual fix, but I
981 # level as a dict instead of a module. This is a manual fix, but I
983 # should really track down where the problem is coming from. Alex
982 # should really track down where the problem is coming from. Alex
984 # Schmolck reported this problem first.
983 # Schmolck reported this problem first.
985
984
986 # A useful post by Alex Martelli on this topic:
985 # A useful post by Alex Martelli on this topic:
987 # Re: inconsistent value from __builtins__
986 # Re: inconsistent value from __builtins__
988 # Von: Alex Martelli <aleaxit@yahoo.com>
987 # Von: Alex Martelli <aleaxit@yahoo.com>
989 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
988 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
990 # Gruppen: comp.lang.python
989 # Gruppen: comp.lang.python
991
990
992 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
991 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
993 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
992 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
994 # > <type 'dict'>
993 # > <type 'dict'>
995 # > >>> print type(__builtins__)
994 # > >>> print type(__builtins__)
996 # > <type 'module'>
995 # > <type 'module'>
997 # > Is this difference in return value intentional?
996 # > Is this difference in return value intentional?
998
997
999 # Well, it's documented that '__builtins__' can be either a dictionary
998 # Well, it's documented that '__builtins__' can be either a dictionary
1000 # or a module, and it's been that way for a long time. Whether it's
999 # or a module, and it's been that way for a long time. Whether it's
1001 # intentional (or sensible), I don't know. In any case, the idea is
1000 # intentional (or sensible), I don't know. In any case, the idea is
1002 # that if you need to access the built-in namespace directly, you
1001 # that if you need to access the built-in namespace directly, you
1003 # should start with "import __builtin__" (note, no 's') which will
1002 # should start with "import __builtin__" (note, no 's') which will
1004 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1003 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1005
1004
1006 # These routines return a properly built module and dict as needed by
1005 # These routines return a properly built module and dict as needed by
1007 # the rest of the code, and can also be used by extension writers to
1006 # the rest of the code, and can also be used by extension writers to
1008 # generate properly initialized namespaces.
1007 # generate properly initialized namespaces.
1009 if (user_ns is not None) or (user_module is not None):
1008 if (user_ns is not None) or (user_module is not None):
1010 self.default_user_namespaces = False
1009 self.default_user_namespaces = False
1011 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1010 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1012
1011
1013 # A record of hidden variables we have added to the user namespace, so
1012 # A record of hidden variables we have added to the user namespace, so
1014 # we can list later only variables defined in actual interactive use.
1013 # we can list later only variables defined in actual interactive use.
1015 self.user_ns_hidden = {}
1014 self.user_ns_hidden = {}
1016
1015
1017 # Now that FakeModule produces a real module, we've run into a nasty
1016 # Now that FakeModule produces a real module, we've run into a nasty
1018 # problem: after script execution (via %run), the module where the user
1017 # problem: after script execution (via %run), the module where the user
1019 # code ran is deleted. Now that this object is a true module (needed
1018 # code ran is deleted. Now that this object is a true module (needed
1020 # so doctest and other tools work correctly), the Python module
1019 # so doctest and other tools work correctly), the Python module
1021 # teardown mechanism runs over it, and sets to None every variable
1020 # teardown mechanism runs over it, and sets to None every variable
1022 # present in that module. Top-level references to objects from the
1021 # present in that module. Top-level references to objects from the
1023 # script survive, because the user_ns is updated with them. However,
1022 # script survive, because the user_ns is updated with them. However,
1024 # calling functions defined in the script that use other things from
1023 # calling functions defined in the script that use other things from
1025 # the script will fail, because the function's closure had references
1024 # the script will fail, because the function's closure had references
1026 # to the original objects, which are now all None. So we must protect
1025 # to the original objects, which are now all None. So we must protect
1027 # these modules from deletion by keeping a cache.
1026 # these modules from deletion by keeping a cache.
1028 #
1027 #
1029 # To avoid keeping stale modules around (we only need the one from the
1028 # To avoid keeping stale modules around (we only need the one from the
1030 # last run), we use a dict keyed with the full path to the script, so
1029 # last run), we use a dict keyed with the full path to the script, so
1031 # only the last version of the module is held in the cache. Note,
1030 # only the last version of the module is held in the cache. Note,
1032 # however, that we must cache the module *namespace contents* (their
1031 # however, that we must cache the module *namespace contents* (their
1033 # __dict__). Because if we try to cache the actual modules, old ones
1032 # __dict__). Because if we try to cache the actual modules, old ones
1034 # (uncached) could be destroyed while still holding references (such as
1033 # (uncached) could be destroyed while still holding references (such as
1035 # those held by GUI objects that tend to be long-lived)>
1034 # those held by GUI objects that tend to be long-lived)>
1036 #
1035 #
1037 # The %reset command will flush this cache. See the cache_main_mod()
1036 # The %reset command will flush this cache. See the cache_main_mod()
1038 # and clear_main_mod_cache() methods for details on use.
1037 # and clear_main_mod_cache() methods for details on use.
1039
1038
1040 # This is the cache used for 'main' namespaces
1039 # This is the cache used for 'main' namespaces
1041 self._main_mod_cache = {}
1040 self._main_mod_cache = {}
1042
1041
1043 # A table holding all the namespaces IPython deals with, so that
1042 # A table holding all the namespaces IPython deals with, so that
1044 # introspection facilities can search easily.
1043 # introspection facilities can search easily.
1045 self.ns_table = {'user_global':self.user_module.__dict__,
1044 self.ns_table = {'user_global':self.user_module.__dict__,
1046 'user_local':self.user_ns,
1045 'user_local':self.user_ns,
1047 'builtin':builtin_mod.__dict__
1046 'builtin':builtin_mod.__dict__
1048 }
1047 }
1049
1048
1050 @property
1049 @property
1051 def user_global_ns(self):
1050 def user_global_ns(self):
1052 return self.user_module.__dict__
1051 return self.user_module.__dict__
1053
1052
1054 def prepare_user_module(self, user_module=None, user_ns=None):
1053 def prepare_user_module(self, user_module=None, user_ns=None):
1055 """Prepare the module and namespace in which user code will be run.
1054 """Prepare the module and namespace in which user code will be run.
1056
1055
1057 When IPython is started normally, both parameters are None: a new module
1056 When IPython is started normally, both parameters are None: a new module
1058 is created automatically, and its __dict__ used as the namespace.
1057 is created automatically, and its __dict__ used as the namespace.
1059
1058
1060 If only user_module is provided, its __dict__ is used as the namespace.
1059 If only user_module is provided, its __dict__ is used as the namespace.
1061 If only user_ns is provided, a dummy module is created, and user_ns
1060 If only user_ns is provided, a dummy module is created, and user_ns
1062 becomes the global namespace. If both are provided (as they may be
1061 becomes the global namespace. If both are provided (as they may be
1063 when embedding), user_ns is the local namespace, and user_module
1062 when embedding), user_ns is the local namespace, and user_module
1064 provides the global namespace.
1063 provides the global namespace.
1065
1064
1066 Parameters
1065 Parameters
1067 ----------
1066 ----------
1068 user_module : module, optional
1067 user_module : module, optional
1069 The current user module in which IPython is being run. If None,
1068 The current user module in which IPython is being run. If None,
1070 a clean module will be created.
1069 a clean module will be created.
1071 user_ns : dict, optional
1070 user_ns : dict, optional
1072 A namespace in which to run interactive commands.
1071 A namespace in which to run interactive commands.
1073
1072
1074 Returns
1073 Returns
1075 -------
1074 -------
1076 A tuple of user_module and user_ns, each properly initialised.
1075 A tuple of user_module and user_ns, each properly initialised.
1077 """
1076 """
1078 if user_module is None and user_ns is not None:
1077 if user_module is None and user_ns is not None:
1079 user_ns.setdefault("__name__", "__main__")
1078 user_ns.setdefault("__name__", "__main__")
1080 user_module = DummyMod()
1079 user_module = DummyMod()
1081 user_module.__dict__ = user_ns
1080 user_module.__dict__ = user_ns
1082
1081
1083 if user_module is None:
1082 if user_module is None:
1084 user_module = types.ModuleType("__main__",
1083 user_module = types.ModuleType("__main__",
1085 doc="Automatically created module for IPython interactive environment")
1084 doc="Automatically created module for IPython interactive environment")
1086
1085
1087 # We must ensure that __builtin__ (without the final 's') is always
1086 # We must ensure that __builtin__ (without the final 's') is always
1088 # available and pointing to the __builtin__ *module*. For more details:
1087 # available and pointing to the __builtin__ *module*. For more details:
1089 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1088 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1090 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1089 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1091 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1090 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1092
1091
1093 if user_ns is None:
1092 if user_ns is None:
1094 user_ns = user_module.__dict__
1093 user_ns = user_module.__dict__
1095
1094
1096 return user_module, user_ns
1095 return user_module, user_ns
1097
1096
1098 def init_sys_modules(self):
1097 def init_sys_modules(self):
1099 # We need to insert into sys.modules something that looks like a
1098 # We need to insert into sys.modules something that looks like a
1100 # module but which accesses the IPython namespace, for shelve and
1099 # module but which accesses the IPython namespace, for shelve and
1101 # pickle to work interactively. Normally they rely on getting
1100 # pickle to work interactively. Normally they rely on getting
1102 # everything out of __main__, but for embedding purposes each IPython
1101 # everything out of __main__, but for embedding purposes each IPython
1103 # instance has its own private namespace, so we can't go shoving
1102 # instance has its own private namespace, so we can't go shoving
1104 # everything into __main__.
1103 # everything into __main__.
1105
1104
1106 # note, however, that we should only do this for non-embedded
1105 # note, however, that we should only do this for non-embedded
1107 # ipythons, which really mimic the __main__.__dict__ with their own
1106 # ipythons, which really mimic the __main__.__dict__ with their own
1108 # namespace. Embedded instances, on the other hand, should not do
1107 # namespace. Embedded instances, on the other hand, should not do
1109 # this because they need to manage the user local/global namespaces
1108 # this because they need to manage the user local/global namespaces
1110 # only, but they live within a 'normal' __main__ (meaning, they
1109 # only, but they live within a 'normal' __main__ (meaning, they
1111 # shouldn't overtake the execution environment of the script they're
1110 # shouldn't overtake the execution environment of the script they're
1112 # embedded in).
1111 # embedded in).
1113
1112
1114 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1113 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1115 main_name = self.user_module.__name__
1114 main_name = self.user_module.__name__
1116 sys.modules[main_name] = self.user_module
1115 sys.modules[main_name] = self.user_module
1117
1116
1118 def init_user_ns(self):
1117 def init_user_ns(self):
1119 """Initialize all user-visible namespaces to their minimum defaults.
1118 """Initialize all user-visible namespaces to their minimum defaults.
1120
1119
1121 Certain history lists are also initialized here, as they effectively
1120 Certain history lists are also initialized here, as they effectively
1122 act as user namespaces.
1121 act as user namespaces.
1123
1122
1124 Notes
1123 Notes
1125 -----
1124 -----
1126 All data structures here are only filled in, they are NOT reset by this
1125 All data structures here are only filled in, they are NOT reset by this
1127 method. If they were not empty before, data will simply be added to
1126 method. If they were not empty before, data will simply be added to
1128 therm.
1127 therm.
1129 """
1128 """
1130 # This function works in two parts: first we put a few things in
1129 # This function works in two parts: first we put a few things in
1131 # user_ns, and we sync that contents into user_ns_hidden so that these
1130 # user_ns, and we sync that contents into user_ns_hidden so that these
1132 # initial variables aren't shown by %who. After the sync, we add the
1131 # initial variables aren't shown by %who. After the sync, we add the
1133 # rest of what we *do* want the user to see with %who even on a new
1132 # rest of what we *do* want the user to see with %who even on a new
1134 # session (probably nothing, so they really only see their own stuff)
1133 # session (probably nothing, so they really only see their own stuff)
1135
1134
1136 # The user dict must *always* have a __builtin__ reference to the
1135 # The user dict must *always* have a __builtin__ reference to the
1137 # Python standard __builtin__ namespace, which must be imported.
1136 # Python standard __builtin__ namespace, which must be imported.
1138 # This is so that certain operations in prompt evaluation can be
1137 # This is so that certain operations in prompt evaluation can be
1139 # reliably executed with builtins. Note that we can NOT use
1138 # reliably executed with builtins. Note that we can NOT use
1140 # __builtins__ (note the 's'), because that can either be a dict or a
1139 # __builtins__ (note the 's'), because that can either be a dict or a
1141 # module, and can even mutate at runtime, depending on the context
1140 # module, and can even mutate at runtime, depending on the context
1142 # (Python makes no guarantees on it). In contrast, __builtin__ is
1141 # (Python makes no guarantees on it). In contrast, __builtin__ is
1143 # always a module object, though it must be explicitly imported.
1142 # always a module object, though it must be explicitly imported.
1144
1143
1145 # For more details:
1144 # For more details:
1146 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1145 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1147 ns = dict()
1146 ns = dict()
1148
1147
1149 # make global variables for user access to the histories
1148 # make global variables for user access to the histories
1150 ns['_ih'] = self.history_manager.input_hist_parsed
1149 ns['_ih'] = self.history_manager.input_hist_parsed
1151 ns['_oh'] = self.history_manager.output_hist
1150 ns['_oh'] = self.history_manager.output_hist
1152 ns['_dh'] = self.history_manager.dir_hist
1151 ns['_dh'] = self.history_manager.dir_hist
1153
1152
1154 ns['_sh'] = shadowns
1153 ns['_sh'] = shadowns
1155
1154
1156 # user aliases to input and output histories. These shouldn't show up
1155 # user aliases to input and output histories. These shouldn't show up
1157 # in %who, as they can have very large reprs.
1156 # in %who, as they can have very large reprs.
1158 ns['In'] = self.history_manager.input_hist_parsed
1157 ns['In'] = self.history_manager.input_hist_parsed
1159 ns['Out'] = self.history_manager.output_hist
1158 ns['Out'] = self.history_manager.output_hist
1160
1159
1161 # Store myself as the public api!!!
1160 # Store myself as the public api!!!
1162 ns['get_ipython'] = self.get_ipython
1161 ns['get_ipython'] = self.get_ipython
1163
1162
1164 ns['exit'] = self.exiter
1163 ns['exit'] = self.exiter
1165 ns['quit'] = self.exiter
1164 ns['quit'] = self.exiter
1166
1165
1167 # Sync what we've added so far to user_ns_hidden so these aren't seen
1166 # Sync what we've added so far to user_ns_hidden so these aren't seen
1168 # by %who
1167 # by %who
1169 self.user_ns_hidden.update(ns)
1168 self.user_ns_hidden.update(ns)
1170
1169
1171 # Anything put into ns now would show up in %who. Think twice before
1170 # Anything put into ns now would show up in %who. Think twice before
1172 # putting anything here, as we really want %who to show the user their
1171 # putting anything here, as we really want %who to show the user their
1173 # stuff, not our variables.
1172 # stuff, not our variables.
1174
1173
1175 # Finally, update the real user's namespace
1174 # Finally, update the real user's namespace
1176 self.user_ns.update(ns)
1175 self.user_ns.update(ns)
1177
1176
1178 @property
1177 @property
1179 def all_ns_refs(self):
1178 def all_ns_refs(self):
1180 """Get a list of references to all the namespace dictionaries in which
1179 """Get a list of references to all the namespace dictionaries in which
1181 IPython might store a user-created object.
1180 IPython might store a user-created object.
1182
1181
1183 Note that this does not include the displayhook, which also caches
1182 Note that this does not include the displayhook, which also caches
1184 objects from the output."""
1183 objects from the output."""
1185 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1184 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1186 [m.__dict__ for m in self._main_mod_cache.values()]
1185 [m.__dict__ for m in self._main_mod_cache.values()]
1187
1186
1188 def reset(self, new_session=True):
1187 def reset(self, new_session=True):
1189 """Clear all internal namespaces, and attempt to release references to
1188 """Clear all internal namespaces, and attempt to release references to
1190 user objects.
1189 user objects.
1191
1190
1192 If new_session is True, a new history session will be opened.
1191 If new_session is True, a new history session will be opened.
1193 """
1192 """
1194 # Clear histories
1193 # Clear histories
1195 self.history_manager.reset(new_session)
1194 self.history_manager.reset(new_session)
1196 # Reset counter used to index all histories
1195 # Reset counter used to index all histories
1197 if new_session:
1196 if new_session:
1198 self.execution_count = 1
1197 self.execution_count = 1
1199
1198
1200 # Flush cached output items
1199 # Flush cached output items
1201 if self.displayhook.do_full_cache:
1200 if self.displayhook.do_full_cache:
1202 self.displayhook.flush()
1201 self.displayhook.flush()
1203
1202
1204 # The main execution namespaces must be cleared very carefully,
1203 # The main execution namespaces must be cleared very carefully,
1205 # skipping the deletion of the builtin-related keys, because doing so
1204 # skipping the deletion of the builtin-related keys, because doing so
1206 # would cause errors in many object's __del__ methods.
1205 # would cause errors in many object's __del__ methods.
1207 if self.user_ns is not self.user_global_ns:
1206 if self.user_ns is not self.user_global_ns:
1208 self.user_ns.clear()
1207 self.user_ns.clear()
1209 ns = self.user_global_ns
1208 ns = self.user_global_ns
1210 drop_keys = set(ns.keys())
1209 drop_keys = set(ns.keys())
1211 drop_keys.discard('__builtin__')
1210 drop_keys.discard('__builtin__')
1212 drop_keys.discard('__builtins__')
1211 drop_keys.discard('__builtins__')
1213 drop_keys.discard('__name__')
1212 drop_keys.discard('__name__')
1214 for k in drop_keys:
1213 for k in drop_keys:
1215 del ns[k]
1214 del ns[k]
1216
1215
1217 self.user_ns_hidden.clear()
1216 self.user_ns_hidden.clear()
1218
1217
1219 # Restore the user namespaces to minimal usability
1218 # Restore the user namespaces to minimal usability
1220 self.init_user_ns()
1219 self.init_user_ns()
1221
1220
1222 # Restore the default and user aliases
1221 # Restore the default and user aliases
1223 self.alias_manager.clear_aliases()
1222 self.alias_manager.clear_aliases()
1224 self.alias_manager.init_aliases()
1223 self.alias_manager.init_aliases()
1225
1224
1226 # Flush the private list of module references kept for script
1225 # Flush the private list of module references kept for script
1227 # execution protection
1226 # execution protection
1228 self.clear_main_mod_cache()
1227 self.clear_main_mod_cache()
1229
1228
1230 def del_var(self, varname, by_name=False):
1229 def del_var(self, varname, by_name=False):
1231 """Delete a variable from the various namespaces, so that, as
1230 """Delete a variable from the various namespaces, so that, as
1232 far as possible, we're not keeping any hidden references to it.
1231 far as possible, we're not keeping any hidden references to it.
1233
1232
1234 Parameters
1233 Parameters
1235 ----------
1234 ----------
1236 varname : str
1235 varname : str
1237 The name of the variable to delete.
1236 The name of the variable to delete.
1238 by_name : bool
1237 by_name : bool
1239 If True, delete variables with the given name in each
1238 If True, delete variables with the given name in each
1240 namespace. If False (default), find the variable in the user
1239 namespace. If False (default), find the variable in the user
1241 namespace, and delete references to it.
1240 namespace, and delete references to it.
1242 """
1241 """
1243 if varname in ('__builtin__', '__builtins__'):
1242 if varname in ('__builtin__', '__builtins__'):
1244 raise ValueError("Refusing to delete %s" % varname)
1243 raise ValueError("Refusing to delete %s" % varname)
1245
1244
1246 ns_refs = self.all_ns_refs
1245 ns_refs = self.all_ns_refs
1247
1246
1248 if by_name: # Delete by name
1247 if by_name: # Delete by name
1249 for ns in ns_refs:
1248 for ns in ns_refs:
1250 try:
1249 try:
1251 del ns[varname]
1250 del ns[varname]
1252 except KeyError:
1251 except KeyError:
1253 pass
1252 pass
1254 else: # Delete by object
1253 else: # Delete by object
1255 try:
1254 try:
1256 obj = self.user_ns[varname]
1255 obj = self.user_ns[varname]
1257 except KeyError:
1256 except KeyError:
1258 raise NameError("name '%s' is not defined" % varname)
1257 raise NameError("name '%s' is not defined" % varname)
1259 # Also check in output history
1258 # Also check in output history
1260 ns_refs.append(self.history_manager.output_hist)
1259 ns_refs.append(self.history_manager.output_hist)
1261 for ns in ns_refs:
1260 for ns in ns_refs:
1262 to_delete = [n for n, o in iteritems(ns) if o is obj]
1261 to_delete = [n for n, o in iteritems(ns) if o is obj]
1263 for name in to_delete:
1262 for name in to_delete:
1264 del ns[name]
1263 del ns[name]
1265
1264
1266 # displayhook keeps extra references, but not in a dictionary
1265 # displayhook keeps extra references, but not in a dictionary
1267 for name in ('_', '__', '___'):
1266 for name in ('_', '__', '___'):
1268 if getattr(self.displayhook, name) is obj:
1267 if getattr(self.displayhook, name) is obj:
1269 setattr(self.displayhook, name, None)
1268 setattr(self.displayhook, name, None)
1270
1269
1271 def reset_selective(self, regex=None):
1270 def reset_selective(self, regex=None):
1272 """Clear selective variables from internal namespaces based on a
1271 """Clear selective variables from internal namespaces based on a
1273 specified regular expression.
1272 specified regular expression.
1274
1273
1275 Parameters
1274 Parameters
1276 ----------
1275 ----------
1277 regex : string or compiled pattern, optional
1276 regex : string or compiled pattern, optional
1278 A regular expression pattern that will be used in searching
1277 A regular expression pattern that will be used in searching
1279 variable names in the users namespaces.
1278 variable names in the users namespaces.
1280 """
1279 """
1281 if regex is not None:
1280 if regex is not None:
1282 try:
1281 try:
1283 m = re.compile(regex)
1282 m = re.compile(regex)
1284 except TypeError:
1283 except TypeError:
1285 raise TypeError('regex must be a string or compiled pattern')
1284 raise TypeError('regex must be a string or compiled pattern')
1286 # Search for keys in each namespace that match the given regex
1285 # Search for keys in each namespace that match the given regex
1287 # If a match is found, delete the key/value pair.
1286 # If a match is found, delete the key/value pair.
1288 for ns in self.all_ns_refs:
1287 for ns in self.all_ns_refs:
1289 for var in ns:
1288 for var in ns:
1290 if m.search(var):
1289 if m.search(var):
1291 del ns[var]
1290 del ns[var]
1292
1291
1293 def push(self, variables, interactive=True):
1292 def push(self, variables, interactive=True):
1294 """Inject a group of variables into the IPython user namespace.
1293 """Inject a group of variables into the IPython user namespace.
1295
1294
1296 Parameters
1295 Parameters
1297 ----------
1296 ----------
1298 variables : dict, str or list/tuple of str
1297 variables : dict, str or list/tuple of str
1299 The variables to inject into the user's namespace. If a dict, a
1298 The variables to inject into the user's namespace. If a dict, a
1300 simple update is done. If a str, the string is assumed to have
1299 simple update is done. If a str, the string is assumed to have
1301 variable names separated by spaces. A list/tuple of str can also
1300 variable names separated by spaces. A list/tuple of str can also
1302 be used to give the variable names. If just the variable names are
1301 be used to give the variable names. If just the variable names are
1303 give (list/tuple/str) then the variable values looked up in the
1302 give (list/tuple/str) then the variable values looked up in the
1304 callers frame.
1303 callers frame.
1305 interactive : bool
1304 interactive : bool
1306 If True (default), the variables will be listed with the ``who``
1305 If True (default), the variables will be listed with the ``who``
1307 magic.
1306 magic.
1308 """
1307 """
1309 vdict = None
1308 vdict = None
1310
1309
1311 # We need a dict of name/value pairs to do namespace updates.
1310 # We need a dict of name/value pairs to do namespace updates.
1312 if isinstance(variables, dict):
1311 if isinstance(variables, dict):
1313 vdict = variables
1312 vdict = variables
1314 elif isinstance(variables, string_types+(list, tuple)):
1313 elif isinstance(variables, string_types+(list, tuple)):
1315 if isinstance(variables, string_types):
1314 if isinstance(variables, string_types):
1316 vlist = variables.split()
1315 vlist = variables.split()
1317 else:
1316 else:
1318 vlist = variables
1317 vlist = variables
1319 vdict = {}
1318 vdict = {}
1320 cf = sys._getframe(1)
1319 cf = sys._getframe(1)
1321 for name in vlist:
1320 for name in vlist:
1322 try:
1321 try:
1323 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1322 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1324 except:
1323 except:
1325 print('Could not get variable %s from %s' %
1324 print('Could not get variable %s from %s' %
1326 (name,cf.f_code.co_name))
1325 (name,cf.f_code.co_name))
1327 else:
1326 else:
1328 raise ValueError('variables must be a dict/str/list/tuple')
1327 raise ValueError('variables must be a dict/str/list/tuple')
1329
1328
1330 # Propagate variables to user namespace
1329 # Propagate variables to user namespace
1331 self.user_ns.update(vdict)
1330 self.user_ns.update(vdict)
1332
1331
1333 # And configure interactive visibility
1332 # And configure interactive visibility
1334 user_ns_hidden = self.user_ns_hidden
1333 user_ns_hidden = self.user_ns_hidden
1335 if interactive:
1334 if interactive:
1336 for name in vdict:
1335 for name in vdict:
1337 user_ns_hidden.pop(name, None)
1336 user_ns_hidden.pop(name, None)
1338 else:
1337 else:
1339 user_ns_hidden.update(vdict)
1338 user_ns_hidden.update(vdict)
1340
1339
1341 def drop_by_id(self, variables):
1340 def drop_by_id(self, variables):
1342 """Remove a dict of variables from the user namespace, if they are the
1341 """Remove a dict of variables from the user namespace, if they are the
1343 same as the values in the dictionary.
1342 same as the values in the dictionary.
1344
1343
1345 This is intended for use by extensions: variables that they've added can
1344 This is intended for use by extensions: variables that they've added can
1346 be taken back out if they are unloaded, without removing any that the
1345 be taken back out if they are unloaded, without removing any that the
1347 user has overwritten.
1346 user has overwritten.
1348
1347
1349 Parameters
1348 Parameters
1350 ----------
1349 ----------
1351 variables : dict
1350 variables : dict
1352 A dictionary mapping object names (as strings) to the objects.
1351 A dictionary mapping object names (as strings) to the objects.
1353 """
1352 """
1354 for name, obj in iteritems(variables):
1353 for name, obj in iteritems(variables):
1355 if name in self.user_ns and self.user_ns[name] is obj:
1354 if name in self.user_ns and self.user_ns[name] is obj:
1356 del self.user_ns[name]
1355 del self.user_ns[name]
1357 self.user_ns_hidden.pop(name, None)
1356 self.user_ns_hidden.pop(name, None)
1358
1357
1359 #-------------------------------------------------------------------------
1358 #-------------------------------------------------------------------------
1360 # Things related to object introspection
1359 # Things related to object introspection
1361 #-------------------------------------------------------------------------
1360 #-------------------------------------------------------------------------
1362
1361
1363 def _ofind(self, oname, namespaces=None):
1362 def _ofind(self, oname, namespaces=None):
1364 """Find an object in the available namespaces.
1363 """Find an object in the available namespaces.
1365
1364
1366 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1365 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1367
1366
1368 Has special code to detect magic functions.
1367 Has special code to detect magic functions.
1369 """
1368 """
1370 oname = oname.strip()
1369 oname = oname.strip()
1371 #print '1- oname: <%r>' % oname # dbg
1370 #print '1- oname: <%r>' % oname # dbg
1372 if not oname.startswith(ESC_MAGIC) and \
1371 if not oname.startswith(ESC_MAGIC) and \
1373 not oname.startswith(ESC_MAGIC2) and \
1372 not oname.startswith(ESC_MAGIC2) and \
1374 not py3compat.isidentifier(oname, dotted=True):
1373 not py3compat.isidentifier(oname, dotted=True):
1375 return dict(found=False)
1374 return dict(found=False)
1376
1375
1377 if namespaces is None:
1376 if namespaces is None:
1378 # Namespaces to search in:
1377 # Namespaces to search in:
1379 # Put them in a list. The order is important so that we
1378 # Put them in a list. The order is important so that we
1380 # find things in the same order that Python finds them.
1379 # find things in the same order that Python finds them.
1381 namespaces = [ ('Interactive', self.user_ns),
1380 namespaces = [ ('Interactive', self.user_ns),
1382 ('Interactive (global)', self.user_global_ns),
1381 ('Interactive (global)', self.user_global_ns),
1383 ('Python builtin', builtin_mod.__dict__),
1382 ('Python builtin', builtin_mod.__dict__),
1384 ]
1383 ]
1385
1384
1386 # initialize results to 'null'
1385 # initialize results to 'null'
1387 found = False; obj = None; ospace = None;
1386 found = False; obj = None; ospace = None;
1388 ismagic = False; isalias = False; parent = None
1387 ismagic = False; isalias = False; parent = None
1389
1388
1390 # We need to special-case 'print', which as of python2.6 registers as a
1389 # We need to special-case 'print', which as of python2.6 registers as a
1391 # function but should only be treated as one if print_function was
1390 # function but should only be treated as one if print_function was
1392 # loaded with a future import. In this case, just bail.
1391 # loaded with a future import. In this case, just bail.
1393 if (oname == 'print' and not py3compat.PY3 and not \
1392 if (oname == 'print' and not py3compat.PY3 and not \
1394 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1393 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1395 return {'found':found, 'obj':obj, 'namespace':ospace,
1394 return {'found':found, 'obj':obj, 'namespace':ospace,
1396 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1395 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1397
1396
1398 # Look for the given name by splitting it in parts. If the head is
1397 # Look for the given name by splitting it in parts. If the head is
1399 # found, then we look for all the remaining parts as members, and only
1398 # found, then we look for all the remaining parts as members, and only
1400 # declare success if we can find them all.
1399 # declare success if we can find them all.
1401 oname_parts = oname.split('.')
1400 oname_parts = oname.split('.')
1402 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1401 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1403 for nsname,ns in namespaces:
1402 for nsname,ns in namespaces:
1404 try:
1403 try:
1405 obj = ns[oname_head]
1404 obj = ns[oname_head]
1406 except KeyError:
1405 except KeyError:
1407 continue
1406 continue
1408 else:
1407 else:
1409 #print 'oname_rest:', oname_rest # dbg
1408 #print 'oname_rest:', oname_rest # dbg
1410 for idx, part in enumerate(oname_rest):
1409 for idx, part in enumerate(oname_rest):
1411 try:
1410 try:
1412 parent = obj
1411 parent = obj
1413 # The last part is looked up in a special way to avoid
1412 # The last part is looked up in a special way to avoid
1414 # descriptor invocation as it may raise or have side
1413 # descriptor invocation as it may raise or have side
1415 # effects.
1414 # effects.
1416 if idx == len(oname_rest) - 1:
1415 if idx == len(oname_rest) - 1:
1417 obj = self._getattr_property(obj, part)
1416 obj = self._getattr_property(obj, part)
1418 else:
1417 else:
1419 obj = getattr(obj, part)
1418 obj = getattr(obj, part)
1420 except:
1419 except:
1421 # Blanket except b/c some badly implemented objects
1420 # Blanket except b/c some badly implemented objects
1422 # allow __getattr__ to raise exceptions other than
1421 # allow __getattr__ to raise exceptions other than
1423 # AttributeError, which then crashes IPython.
1422 # AttributeError, which then crashes IPython.
1424 break
1423 break
1425 else:
1424 else:
1426 # If we finish the for loop (no break), we got all members
1425 # If we finish the for loop (no break), we got all members
1427 found = True
1426 found = True
1428 ospace = nsname
1427 ospace = nsname
1429 break # namespace loop
1428 break # namespace loop
1430
1429
1431 # Try to see if it's magic
1430 # Try to see if it's magic
1432 if not found:
1431 if not found:
1433 obj = None
1432 obj = None
1434 if oname.startswith(ESC_MAGIC2):
1433 if oname.startswith(ESC_MAGIC2):
1435 oname = oname.lstrip(ESC_MAGIC2)
1434 oname = oname.lstrip(ESC_MAGIC2)
1436 obj = self.find_cell_magic(oname)
1435 obj = self.find_cell_magic(oname)
1437 elif oname.startswith(ESC_MAGIC):
1436 elif oname.startswith(ESC_MAGIC):
1438 oname = oname.lstrip(ESC_MAGIC)
1437 oname = oname.lstrip(ESC_MAGIC)
1439 obj = self.find_line_magic(oname)
1438 obj = self.find_line_magic(oname)
1440 else:
1439 else:
1441 # search without prefix, so run? will find %run?
1440 # search without prefix, so run? will find %run?
1442 obj = self.find_line_magic(oname)
1441 obj = self.find_line_magic(oname)
1443 if obj is None:
1442 if obj is None:
1444 obj = self.find_cell_magic(oname)
1443 obj = self.find_cell_magic(oname)
1445 if obj is not None:
1444 if obj is not None:
1446 found = True
1445 found = True
1447 ospace = 'IPython internal'
1446 ospace = 'IPython internal'
1448 ismagic = True
1447 ismagic = True
1449 isalias = isinstance(obj, Alias)
1448 isalias = isinstance(obj, Alias)
1450
1449
1451 # Last try: special-case some literals like '', [], {}, etc:
1450 # Last try: special-case some literals like '', [], {}, etc:
1452 if not found and oname_head in ["''",'""','[]','{}','()']:
1451 if not found and oname_head in ["''",'""','[]','{}','()']:
1453 obj = eval(oname_head)
1452 obj = eval(oname_head)
1454 found = True
1453 found = True
1455 ospace = 'Interactive'
1454 ospace = 'Interactive'
1456
1455
1457 return {'found':found, 'obj':obj, 'namespace':ospace,
1456 return {'found':found, 'obj':obj, 'namespace':ospace,
1458 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1457 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1459
1458
1460 @staticmethod
1459 @staticmethod
1461 def _getattr_property(obj, attrname):
1460 def _getattr_property(obj, attrname):
1462 """Property-aware getattr to use in object finding.
1461 """Property-aware getattr to use in object finding.
1463
1462
1464 If attrname represents a property, return it unevaluated (in case it has
1463 If attrname represents a property, return it unevaluated (in case it has
1465 side effects or raises an error.
1464 side effects or raises an error.
1466
1465
1467 """
1466 """
1468 if not isinstance(obj, type):
1467 if not isinstance(obj, type):
1469 try:
1468 try:
1470 # `getattr(type(obj), attrname)` is not guaranteed to return
1469 # `getattr(type(obj), attrname)` is not guaranteed to return
1471 # `obj`, but does so for property:
1470 # `obj`, but does so for property:
1472 #
1471 #
1473 # property.__get__(self, None, cls) -> self
1472 # property.__get__(self, None, cls) -> self
1474 #
1473 #
1475 # The universal alternative is to traverse the mro manually
1474 # The universal alternative is to traverse the mro manually
1476 # searching for attrname in class dicts.
1475 # searching for attrname in class dicts.
1477 attr = getattr(type(obj), attrname)
1476 attr = getattr(type(obj), attrname)
1478 except AttributeError:
1477 except AttributeError:
1479 pass
1478 pass
1480 else:
1479 else:
1481 # This relies on the fact that data descriptors (with both
1480 # This relies on the fact that data descriptors (with both
1482 # __get__ & __set__ magic methods) take precedence over
1481 # __get__ & __set__ magic methods) take precedence over
1483 # instance-level attributes:
1482 # instance-level attributes:
1484 #
1483 #
1485 # class A(object):
1484 # class A(object):
1486 # @property
1485 # @property
1487 # def foobar(self): return 123
1486 # def foobar(self): return 123
1488 # a = A()
1487 # a = A()
1489 # a.__dict__['foobar'] = 345
1488 # a.__dict__['foobar'] = 345
1490 # a.foobar # == 123
1489 # a.foobar # == 123
1491 #
1490 #
1492 # So, a property may be returned right away.
1491 # So, a property may be returned right away.
1493 if isinstance(attr, property):
1492 if isinstance(attr, property):
1494 return attr
1493 return attr
1495
1494
1496 # Nothing helped, fall back.
1495 # Nothing helped, fall back.
1497 return getattr(obj, attrname)
1496 return getattr(obj, attrname)
1498
1497
1499 def _object_find(self, oname, namespaces=None):
1498 def _object_find(self, oname, namespaces=None):
1500 """Find an object and return a struct with info about it."""
1499 """Find an object and return a struct with info about it."""
1501 return Struct(self._ofind(oname, namespaces))
1500 return Struct(self._ofind(oname, namespaces))
1502
1501
1503 def _inspect(self, meth, oname, namespaces=None, **kw):
1502 def _inspect(self, meth, oname, namespaces=None, **kw):
1504 """Generic interface to the inspector system.
1503 """Generic interface to the inspector system.
1505
1504
1506 This function is meant to be called by pdef, pdoc & friends.
1505 This function is meant to be called by pdef, pdoc & friends.
1507 """
1506 """
1508 info = self._object_find(oname, namespaces)
1507 info = self._object_find(oname, namespaces)
1509 docformat = sphinxify if self.sphinxify_docstring else None
1508 docformat = sphinxify if self.sphinxify_docstring else None
1510 if info.found:
1509 if info.found:
1511 pmethod = getattr(self.inspector, meth)
1510 pmethod = getattr(self.inspector, meth)
1512 # TODO: only apply format_screen to the plain/text repr of the mime
1511 # TODO: only apply format_screen to the plain/text repr of the mime
1513 # bundle.
1512 # bundle.
1514 formatter = format_screen if info.ismagic else docformat
1513 formatter = format_screen if info.ismagic else docformat
1515 if meth == 'pdoc':
1514 if meth == 'pdoc':
1516 pmethod(info.obj, oname, formatter)
1515 pmethod(info.obj, oname, formatter)
1517 elif meth == 'pinfo':
1516 elif meth == 'pinfo':
1518 pmethod(info.obj, oname, formatter, info,
1517 pmethod(info.obj, oname, formatter, info,
1519 enable_html_pager=self.enable_html_pager, **kw)
1518 enable_html_pager=self.enable_html_pager, **kw)
1520 else:
1519 else:
1521 pmethod(info.obj, oname)
1520 pmethod(info.obj, oname)
1522 else:
1521 else:
1523 print('Object `%s` not found.' % oname)
1522 print('Object `%s` not found.' % oname)
1524 return 'not found' # so callers can take other action
1523 return 'not found' # so callers can take other action
1525
1524
1526 def object_inspect(self, oname, detail_level=0):
1525 def object_inspect(self, oname, detail_level=0):
1527 """Get object info about oname"""
1526 """Get object info about oname"""
1528 with self.builtin_trap:
1527 with self.builtin_trap:
1529 info = self._object_find(oname)
1528 info = self._object_find(oname)
1530 if info.found:
1529 if info.found:
1531 return self.inspector.info(info.obj, oname, info=info,
1530 return self.inspector.info(info.obj, oname, info=info,
1532 detail_level=detail_level
1531 detail_level=detail_level
1533 )
1532 )
1534 else:
1533 else:
1535 return oinspect.object_info(name=oname, found=False)
1534 return oinspect.object_info(name=oname, found=False)
1536
1535
1537 def object_inspect_text(self, oname, detail_level=0):
1536 def object_inspect_text(self, oname, detail_level=0):
1538 """Get object info as formatted text"""
1537 """Get object info as formatted text"""
1539 return self.object_inspect_mime(oname, detail_level)['text/plain']
1538 return self.object_inspect_mime(oname, detail_level)['text/plain']
1540
1539
1541 def object_inspect_mime(self, oname, detail_level=0):
1540 def object_inspect_mime(self, oname, detail_level=0):
1542 """Get object info as a mimebundle of formatted representations.
1541 """Get object info as a mimebundle of formatted representations.
1543
1542
1544 A mimebundle is a dictionary, keyed by mime-type.
1543 A mimebundle is a dictionary, keyed by mime-type.
1545 It must always have the key `'text/plain'`.
1544 It must always have the key `'text/plain'`.
1546 """
1545 """
1547 with self.builtin_trap:
1546 with self.builtin_trap:
1548 info = self._object_find(oname)
1547 info = self._object_find(oname)
1549 if info.found:
1548 if info.found:
1550 return self.inspector._get_info(info.obj, oname, info=info,
1549 return self.inspector._get_info(info.obj, oname, info=info,
1551 detail_level=detail_level
1550 detail_level=detail_level
1552 )
1551 )
1553 else:
1552 else:
1554 raise KeyError(oname)
1553 raise KeyError(oname)
1555
1554
1556 #-------------------------------------------------------------------------
1555 #-------------------------------------------------------------------------
1557 # Things related to history management
1556 # Things related to history management
1558 #-------------------------------------------------------------------------
1557 #-------------------------------------------------------------------------
1559
1558
1560 def init_history(self):
1559 def init_history(self):
1561 """Sets up the command history, and starts regular autosaves."""
1560 """Sets up the command history, and starts regular autosaves."""
1562 self.history_manager = HistoryManager(shell=self, parent=self)
1561 self.history_manager = HistoryManager(shell=self, parent=self)
1563 self.configurables.append(self.history_manager)
1562 self.configurables.append(self.history_manager)
1564
1563
1565 #-------------------------------------------------------------------------
1564 #-------------------------------------------------------------------------
1566 # Things related to exception handling and tracebacks (not debugging)
1565 # Things related to exception handling and tracebacks (not debugging)
1567 #-------------------------------------------------------------------------
1566 #-------------------------------------------------------------------------
1568
1567
1569 debugger_cls = Pdb
1568 debugger_cls = Pdb
1570
1569
1571 def init_traceback_handlers(self, custom_exceptions):
1570 def init_traceback_handlers(self, custom_exceptions):
1572 # Syntax error handler.
1571 # Syntax error handler.
1573 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1572 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1574
1573
1575 # The interactive one is initialized with an offset, meaning we always
1574 # The interactive one is initialized with an offset, meaning we always
1576 # want to remove the topmost item in the traceback, which is our own
1575 # want to remove the topmost item in the traceback, which is our own
1577 # internal code. Valid modes: ['Plain','Context','Verbose']
1576 # internal code. Valid modes: ['Plain','Context','Verbose']
1578 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1577 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1579 color_scheme='NoColor',
1578 color_scheme='NoColor',
1580 tb_offset = 1,
1579 tb_offset = 1,
1581 check_cache=check_linecache_ipython,
1580 check_cache=check_linecache_ipython,
1582 debugger_cls=self.debugger_cls)
1581 debugger_cls=self.debugger_cls)
1583
1582
1584 # The instance will store a pointer to the system-wide exception hook,
1583 # The instance will store a pointer to the system-wide exception hook,
1585 # so that runtime code (such as magics) can access it. This is because
1584 # so that runtime code (such as magics) can access it. This is because
1586 # during the read-eval loop, it may get temporarily overwritten.
1585 # during the read-eval loop, it may get temporarily overwritten.
1587 self.sys_excepthook = sys.excepthook
1586 self.sys_excepthook = sys.excepthook
1588
1587
1589 # and add any custom exception handlers the user may have specified
1588 # and add any custom exception handlers the user may have specified
1590 self.set_custom_exc(*custom_exceptions)
1589 self.set_custom_exc(*custom_exceptions)
1591
1590
1592 # Set the exception mode
1591 # Set the exception mode
1593 self.InteractiveTB.set_mode(mode=self.xmode)
1592 self.InteractiveTB.set_mode(mode=self.xmode)
1594
1593
1595 def set_custom_exc(self, exc_tuple, handler):
1594 def set_custom_exc(self, exc_tuple, handler):
1596 """set_custom_exc(exc_tuple, handler)
1595 """set_custom_exc(exc_tuple, handler)
1597
1596
1598 Set a custom exception handler, which will be called if any of the
1597 Set a custom exception handler, which will be called if any of the
1599 exceptions in exc_tuple occur in the mainloop (specifically, in the
1598 exceptions in exc_tuple occur in the mainloop (specifically, in the
1600 run_code() method).
1599 run_code() method).
1601
1600
1602 Parameters
1601 Parameters
1603 ----------
1602 ----------
1604
1603
1605 exc_tuple : tuple of exception classes
1604 exc_tuple : tuple of exception classes
1606 A *tuple* of exception classes, for which to call the defined
1605 A *tuple* of exception classes, for which to call the defined
1607 handler. It is very important that you use a tuple, and NOT A
1606 handler. It is very important that you use a tuple, and NOT A
1608 LIST here, because of the way Python's except statement works. If
1607 LIST here, because of the way Python's except statement works. If
1609 you only want to trap a single exception, use a singleton tuple::
1608 you only want to trap a single exception, use a singleton tuple::
1610
1609
1611 exc_tuple == (MyCustomException,)
1610 exc_tuple == (MyCustomException,)
1612
1611
1613 handler : callable
1612 handler : callable
1614 handler must have the following signature::
1613 handler must have the following signature::
1615
1614
1616 def my_handler(self, etype, value, tb, tb_offset=None):
1615 def my_handler(self, etype, value, tb, tb_offset=None):
1617 ...
1616 ...
1618 return structured_traceback
1617 return structured_traceback
1619
1618
1620 Your handler must return a structured traceback (a list of strings),
1619 Your handler must return a structured traceback (a list of strings),
1621 or None.
1620 or None.
1622
1621
1623 This will be made into an instance method (via types.MethodType)
1622 This will be made into an instance method (via types.MethodType)
1624 of IPython itself, and it will be called if any of the exceptions
1623 of IPython itself, and it will be called if any of the exceptions
1625 listed in the exc_tuple are caught. If the handler is None, an
1624 listed in the exc_tuple are caught. If the handler is None, an
1626 internal basic one is used, which just prints basic info.
1625 internal basic one is used, which just prints basic info.
1627
1626
1628 To protect IPython from crashes, if your handler ever raises an
1627 To protect IPython from crashes, if your handler ever raises an
1629 exception or returns an invalid result, it will be immediately
1628 exception or returns an invalid result, it will be immediately
1630 disabled.
1629 disabled.
1631
1630
1632 WARNING: by putting in your own exception handler into IPython's main
1631 WARNING: by putting in your own exception handler into IPython's main
1633 execution loop, you run a very good chance of nasty crashes. This
1632 execution loop, you run a very good chance of nasty crashes. This
1634 facility should only be used if you really know what you are doing."""
1633 facility should only be used if you really know what you are doing."""
1635
1634
1636 assert type(exc_tuple)==type(()) , \
1635 assert type(exc_tuple)==type(()) , \
1637 "The custom exceptions must be given AS A TUPLE."
1636 "The custom exceptions must be given AS A TUPLE."
1638
1637
1639 def dummy_handler(self, etype, value, tb, tb_offset=None):
1638 def dummy_handler(self, etype, value, tb, tb_offset=None):
1640 print('*** Simple custom exception handler ***')
1639 print('*** Simple custom exception handler ***')
1641 print('Exception type :',etype)
1640 print('Exception type :',etype)
1642 print('Exception value:',value)
1641 print('Exception value:',value)
1643 print('Traceback :',tb)
1642 print('Traceback :',tb)
1644 #print 'Source code :','\n'.join(self.buffer)
1643 #print 'Source code :','\n'.join(self.buffer)
1645
1644
1646 def validate_stb(stb):
1645 def validate_stb(stb):
1647 """validate structured traceback return type
1646 """validate structured traceback return type
1648
1647
1649 return type of CustomTB *should* be a list of strings, but allow
1648 return type of CustomTB *should* be a list of strings, but allow
1650 single strings or None, which are harmless.
1649 single strings or None, which are harmless.
1651
1650
1652 This function will *always* return a list of strings,
1651 This function will *always* return a list of strings,
1653 and will raise a TypeError if stb is inappropriate.
1652 and will raise a TypeError if stb is inappropriate.
1654 """
1653 """
1655 msg = "CustomTB must return list of strings, not %r" % stb
1654 msg = "CustomTB must return list of strings, not %r" % stb
1656 if stb is None:
1655 if stb is None:
1657 return []
1656 return []
1658 elif isinstance(stb, string_types):
1657 elif isinstance(stb, string_types):
1659 return [stb]
1658 return [stb]
1660 elif not isinstance(stb, list):
1659 elif not isinstance(stb, list):
1661 raise TypeError(msg)
1660 raise TypeError(msg)
1662 # it's a list
1661 # it's a list
1663 for line in stb:
1662 for line in stb:
1664 # check every element
1663 # check every element
1665 if not isinstance(line, string_types):
1664 if not isinstance(line, string_types):
1666 raise TypeError(msg)
1665 raise TypeError(msg)
1667 return stb
1666 return stb
1668
1667
1669 if handler is None:
1668 if handler is None:
1670 wrapped = dummy_handler
1669 wrapped = dummy_handler
1671 else:
1670 else:
1672 def wrapped(self,etype,value,tb,tb_offset=None):
1671 def wrapped(self,etype,value,tb,tb_offset=None):
1673 """wrap CustomTB handler, to protect IPython from user code
1672 """wrap CustomTB handler, to protect IPython from user code
1674
1673
1675 This makes it harder (but not impossible) for custom exception
1674 This makes it harder (but not impossible) for custom exception
1676 handlers to crash IPython.
1675 handlers to crash IPython.
1677 """
1676 """
1678 try:
1677 try:
1679 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1678 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1680 return validate_stb(stb)
1679 return validate_stb(stb)
1681 except:
1680 except:
1682 # clear custom handler immediately
1681 # clear custom handler immediately
1683 self.set_custom_exc((), None)
1682 self.set_custom_exc((), None)
1684 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1683 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1685 # show the exception in handler first
1684 # show the exception in handler first
1686 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1685 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1687 print(self.InteractiveTB.stb2text(stb))
1686 print(self.InteractiveTB.stb2text(stb))
1688 print("The original exception:")
1687 print("The original exception:")
1689 stb = self.InteractiveTB.structured_traceback(
1688 stb = self.InteractiveTB.structured_traceback(
1690 (etype,value,tb), tb_offset=tb_offset
1689 (etype,value,tb), tb_offset=tb_offset
1691 )
1690 )
1692 return stb
1691 return stb
1693
1692
1694 self.CustomTB = types.MethodType(wrapped,self)
1693 self.CustomTB = types.MethodType(wrapped,self)
1695 self.custom_exceptions = exc_tuple
1694 self.custom_exceptions = exc_tuple
1696
1695
1697 def excepthook(self, etype, value, tb):
1696 def excepthook(self, etype, value, tb):
1698 """One more defense for GUI apps that call sys.excepthook.
1697 """One more defense for GUI apps that call sys.excepthook.
1699
1698
1700 GUI frameworks like wxPython trap exceptions and call
1699 GUI frameworks like wxPython trap exceptions and call
1701 sys.excepthook themselves. I guess this is a feature that
1700 sys.excepthook themselves. I guess this is a feature that
1702 enables them to keep running after exceptions that would
1701 enables them to keep running after exceptions that would
1703 otherwise kill their mainloop. This is a bother for IPython
1702 otherwise kill their mainloop. This is a bother for IPython
1704 which excepts to catch all of the program exceptions with a try:
1703 which excepts to catch all of the program exceptions with a try:
1705 except: statement.
1704 except: statement.
1706
1705
1707 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1706 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1708 any app directly invokes sys.excepthook, it will look to the user like
1707 any app directly invokes sys.excepthook, it will look to the user like
1709 IPython crashed. In order to work around this, we can disable the
1708 IPython crashed. In order to work around this, we can disable the
1710 CrashHandler and replace it with this excepthook instead, which prints a
1709 CrashHandler and replace it with this excepthook instead, which prints a
1711 regular traceback using our InteractiveTB. In this fashion, apps which
1710 regular traceback using our InteractiveTB. In this fashion, apps which
1712 call sys.excepthook will generate a regular-looking exception from
1711 call sys.excepthook will generate a regular-looking exception from
1713 IPython, and the CrashHandler will only be triggered by real IPython
1712 IPython, and the CrashHandler will only be triggered by real IPython
1714 crashes.
1713 crashes.
1715
1714
1716 This hook should be used sparingly, only in places which are not likely
1715 This hook should be used sparingly, only in places which are not likely
1717 to be true IPython errors.
1716 to be true IPython errors.
1718 """
1717 """
1719 self.showtraceback((etype, value, tb), tb_offset=0)
1718 self.showtraceback((etype, value, tb), tb_offset=0)
1720
1719
1721 def _get_exc_info(self, exc_tuple=None):
1720 def _get_exc_info(self, exc_tuple=None):
1722 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1721 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1723
1722
1724 Ensures sys.last_type,value,traceback hold the exc_info we found,
1723 Ensures sys.last_type,value,traceback hold the exc_info we found,
1725 from whichever source.
1724 from whichever source.
1726
1725
1727 raises ValueError if none of these contain any information
1726 raises ValueError if none of these contain any information
1728 """
1727 """
1729 if exc_tuple is None:
1728 if exc_tuple is None:
1730 etype, value, tb = sys.exc_info()
1729 etype, value, tb = sys.exc_info()
1731 else:
1730 else:
1732 etype, value, tb = exc_tuple
1731 etype, value, tb = exc_tuple
1733
1732
1734 if etype is None:
1733 if etype is None:
1735 if hasattr(sys, 'last_type'):
1734 if hasattr(sys, 'last_type'):
1736 etype, value, tb = sys.last_type, sys.last_value, \
1735 etype, value, tb = sys.last_type, sys.last_value, \
1737 sys.last_traceback
1736 sys.last_traceback
1738
1737
1739 if etype is None:
1738 if etype is None:
1740 raise ValueError("No exception to find")
1739 raise ValueError("No exception to find")
1741
1740
1742 # Now store the exception info in sys.last_type etc.
1741 # Now store the exception info in sys.last_type etc.
1743 # WARNING: these variables are somewhat deprecated and not
1742 # WARNING: these variables are somewhat deprecated and not
1744 # necessarily safe to use in a threaded environment, but tools
1743 # necessarily safe to use in a threaded environment, but tools
1745 # like pdb depend on their existence, so let's set them. If we
1744 # like pdb depend on their existence, so let's set them. If we
1746 # find problems in the field, we'll need to revisit their use.
1745 # find problems in the field, we'll need to revisit their use.
1747 sys.last_type = etype
1746 sys.last_type = etype
1748 sys.last_value = value
1747 sys.last_value = value
1749 sys.last_traceback = tb
1748 sys.last_traceback = tb
1750
1749
1751 return etype, value, tb
1750 return etype, value, tb
1752
1751
1753 def show_usage_error(self, exc):
1752 def show_usage_error(self, exc):
1754 """Show a short message for UsageErrors
1753 """Show a short message for UsageErrors
1755
1754
1756 These are special exceptions that shouldn't show a traceback.
1755 These are special exceptions that shouldn't show a traceback.
1757 """
1756 """
1758 print("UsageError: %s" % exc, file=sys.stderr)
1757 print("UsageError: %s" % exc, file=sys.stderr)
1759
1758
1760 def get_exception_only(self, exc_tuple=None):
1759 def get_exception_only(self, exc_tuple=None):
1761 """
1760 """
1762 Return as a string (ending with a newline) the exception that
1761 Return as a string (ending with a newline) the exception that
1763 just occurred, without any traceback.
1762 just occurred, without any traceback.
1764 """
1763 """
1765 etype, value, tb = self._get_exc_info(exc_tuple)
1764 etype, value, tb = self._get_exc_info(exc_tuple)
1766 msg = traceback.format_exception_only(etype, value)
1765 msg = traceback.format_exception_only(etype, value)
1767 return ''.join(msg)
1766 return ''.join(msg)
1768
1767
1769 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1768 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1770 exception_only=False):
1769 exception_only=False):
1771 """Display the exception that just occurred.
1770 """Display the exception that just occurred.
1772
1771
1773 If nothing is known about the exception, this is the method which
1772 If nothing is known about the exception, this is the method which
1774 should be used throughout the code for presenting user tracebacks,
1773 should be used throughout the code for presenting user tracebacks,
1775 rather than directly invoking the InteractiveTB object.
1774 rather than directly invoking the InteractiveTB object.
1776
1775
1777 A specific showsyntaxerror() also exists, but this method can take
1776 A specific showsyntaxerror() also exists, but this method can take
1778 care of calling it if needed, so unless you are explicitly catching a
1777 care of calling it if needed, so unless you are explicitly catching a
1779 SyntaxError exception, don't try to analyze the stack manually and
1778 SyntaxError exception, don't try to analyze the stack manually and
1780 simply call this method."""
1779 simply call this method."""
1781
1780
1782 try:
1781 try:
1783 try:
1782 try:
1784 etype, value, tb = self._get_exc_info(exc_tuple)
1783 etype, value, tb = self._get_exc_info(exc_tuple)
1785 except ValueError:
1784 except ValueError:
1786 print('No traceback available to show.', file=sys.stderr)
1785 print('No traceback available to show.', file=sys.stderr)
1787 return
1786 return
1788
1787
1789 if issubclass(etype, SyntaxError):
1788 if issubclass(etype, SyntaxError):
1790 # Though this won't be called by syntax errors in the input
1789 # Though this won't be called by syntax errors in the input
1791 # line, there may be SyntaxError cases with imported code.
1790 # line, there may be SyntaxError cases with imported code.
1792 self.showsyntaxerror(filename)
1791 self.showsyntaxerror(filename)
1793 elif etype is UsageError:
1792 elif etype is UsageError:
1794 self.show_usage_error(value)
1793 self.show_usage_error(value)
1795 else:
1794 else:
1796 if exception_only:
1795 if exception_only:
1797 stb = ['An exception has occurred, use %tb to see '
1796 stb = ['An exception has occurred, use %tb to see '
1798 'the full traceback.\n']
1797 'the full traceback.\n']
1799 stb.extend(self.InteractiveTB.get_exception_only(etype,
1798 stb.extend(self.InteractiveTB.get_exception_only(etype,
1800 value))
1799 value))
1801 else:
1800 else:
1802 try:
1801 try:
1803 # Exception classes can customise their traceback - we
1802 # Exception classes can customise their traceback - we
1804 # use this in IPython.parallel for exceptions occurring
1803 # use this in IPython.parallel for exceptions occurring
1805 # in the engines. This should return a list of strings.
1804 # in the engines. This should return a list of strings.
1806 stb = value._render_traceback_()
1805 stb = value._render_traceback_()
1807 except Exception:
1806 except Exception:
1808 stb = self.InteractiveTB.structured_traceback(etype,
1807 stb = self.InteractiveTB.structured_traceback(etype,
1809 value, tb, tb_offset=tb_offset)
1808 value, tb, tb_offset=tb_offset)
1810
1809
1811 self._showtraceback(etype, value, stb)
1810 self._showtraceback(etype, value, stb)
1812 if self.call_pdb:
1811 if self.call_pdb:
1813 # drop into debugger
1812 # drop into debugger
1814 self.debugger(force=True)
1813 self.debugger(force=True)
1815 return
1814 return
1816
1815
1817 # Actually show the traceback
1816 # Actually show the traceback
1818 self._showtraceback(etype, value, stb)
1817 self._showtraceback(etype, value, stb)
1819
1818
1820 except KeyboardInterrupt:
1819 except KeyboardInterrupt:
1821 print('\n' + self.get_exception_only(), file=sys.stderr)
1820 print('\n' + self.get_exception_only(), file=sys.stderr)
1822
1821
1823 def _showtraceback(self, etype, evalue, stb):
1822 def _showtraceback(self, etype, evalue, stb):
1824 """Actually show a traceback.
1823 """Actually show a traceback.
1825
1824
1826 Subclasses may override this method to put the traceback on a different
1825 Subclasses may override this method to put the traceback on a different
1827 place, like a side channel.
1826 place, like a side channel.
1828 """
1827 """
1829 print(self.InteractiveTB.stb2text(stb))
1828 print(self.InteractiveTB.stb2text(stb))
1830
1829
1831 def showsyntaxerror(self, filename=None):
1830 def showsyntaxerror(self, filename=None):
1832 """Display the syntax error that just occurred.
1831 """Display the syntax error that just occurred.
1833
1832
1834 This doesn't display a stack trace because there isn't one.
1833 This doesn't display a stack trace because there isn't one.
1835
1834
1836 If a filename is given, it is stuffed in the exception instead
1835 If a filename is given, it is stuffed in the exception instead
1837 of what was there before (because Python's parser always uses
1836 of what was there before (because Python's parser always uses
1838 "<string>" when reading from a string).
1837 "<string>" when reading from a string).
1839 """
1838 """
1840 etype, value, last_traceback = self._get_exc_info()
1839 etype, value, last_traceback = self._get_exc_info()
1841
1840
1842 if filename and issubclass(etype, SyntaxError):
1841 if filename and issubclass(etype, SyntaxError):
1843 try:
1842 try:
1844 value.filename = filename
1843 value.filename = filename
1845 except:
1844 except:
1846 # Not the format we expect; leave it alone
1845 # Not the format we expect; leave it alone
1847 pass
1846 pass
1848
1847
1849 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1848 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1850 self._showtraceback(etype, value, stb)
1849 self._showtraceback(etype, value, stb)
1851
1850
1852 # This is overridden in TerminalInteractiveShell to show a message about
1851 # This is overridden in TerminalInteractiveShell to show a message about
1853 # the %paste magic.
1852 # the %paste magic.
1854 def showindentationerror(self):
1853 def showindentationerror(self):
1855 """Called by run_cell when there's an IndentationError in code entered
1854 """Called by run_cell when there's an IndentationError in code entered
1856 at the prompt.
1855 at the prompt.
1857
1856
1858 This is overridden in TerminalInteractiveShell to show a message about
1857 This is overridden in TerminalInteractiveShell to show a message about
1859 the %paste magic."""
1858 the %paste magic."""
1860 self.showsyntaxerror()
1859 self.showsyntaxerror()
1861
1860
1862 #-------------------------------------------------------------------------
1861 #-------------------------------------------------------------------------
1863 # Things related to readline
1862 # Things related to readline
1864 #-------------------------------------------------------------------------
1863 #-------------------------------------------------------------------------
1865
1864
1866 def init_readline(self):
1865 def init_readline(self):
1867 """DEPRECATED
1866 """DEPRECATED
1868
1867
1869 Moved to terminal subclass, here only to simplify the init logic."""
1868 Moved to terminal subclass, here only to simplify the init logic."""
1870 # Set a number of methods that depend on readline to be no-op
1869 # Set a number of methods that depend on readline to be no-op
1871 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
1870 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
1872 DeprecationWarning, stacklevel=2)
1871 DeprecationWarning, stacklevel=2)
1873 self.set_custom_completer = no_op
1872 self.set_custom_completer = no_op
1874
1873
1875 @skip_doctest
1874 @skip_doctest
1876 def set_next_input(self, s, replace=False):
1875 def set_next_input(self, s, replace=False):
1877 """ Sets the 'default' input string for the next command line.
1876 """ Sets the 'default' input string for the next command line.
1878
1877
1879 Example::
1878 Example::
1880
1879
1881 In [1]: _ip.set_next_input("Hello Word")
1880 In [1]: _ip.set_next_input("Hello Word")
1882 In [2]: Hello Word_ # cursor is here
1881 In [2]: Hello Word_ # cursor is here
1883 """
1882 """
1884 self.rl_next_input = py3compat.cast_bytes_py2(s)
1883 self.rl_next_input = py3compat.cast_bytes_py2(s)
1885
1884
1886 def _indent_current_str(self):
1885 def _indent_current_str(self):
1887 """return the current level of indentation as a string"""
1886 """return the current level of indentation as a string"""
1888 return self.input_splitter.indent_spaces * ' '
1887 return self.input_splitter.indent_spaces * ' '
1889
1888
1890 #-------------------------------------------------------------------------
1889 #-------------------------------------------------------------------------
1891 # Things related to text completion
1890 # Things related to text completion
1892 #-------------------------------------------------------------------------
1891 #-------------------------------------------------------------------------
1893
1892
1894 def init_completer(self):
1893 def init_completer(self):
1895 """Initialize the completion machinery.
1894 """Initialize the completion machinery.
1896
1895
1897 This creates completion machinery that can be used by client code,
1896 This creates completion machinery that can be used by client code,
1898 either interactively in-process (typically triggered by the readline
1897 either interactively in-process (typically triggered by the readline
1899 library), programmatically (such as in test suites) or out-of-process
1898 library), programmatically (such as in test suites) or out-of-process
1900 (typically over the network by remote frontends).
1899 (typically over the network by remote frontends).
1901 """
1900 """
1902 from IPython.core.completer import IPCompleter
1901 from IPython.core.completer import IPCompleter
1903 from IPython.core.completerlib import (module_completer,
1902 from IPython.core.completerlib import (module_completer,
1904 magic_run_completer, cd_completer, reset_completer)
1903 magic_run_completer, cd_completer, reset_completer)
1905
1904
1906 self.Completer = IPCompleter(shell=self,
1905 self.Completer = IPCompleter(shell=self,
1907 namespace=self.user_ns,
1906 namespace=self.user_ns,
1908 global_namespace=self.user_global_ns,
1907 global_namespace=self.user_global_ns,
1909 use_readline=False,
1908 use_readline=False,
1910 parent=self,
1909 parent=self,
1911 )
1910 )
1912 self.configurables.append(self.Completer)
1911 self.configurables.append(self.Completer)
1913
1912
1914 # Add custom completers to the basic ones built into IPCompleter
1913 # Add custom completers to the basic ones built into IPCompleter
1915 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1914 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1916 self.strdispatchers['complete_command'] = sdisp
1915 self.strdispatchers['complete_command'] = sdisp
1917 self.Completer.custom_completers = sdisp
1916 self.Completer.custom_completers = sdisp
1918
1917
1919 self.set_hook('complete_command', module_completer, str_key = 'import')
1918 self.set_hook('complete_command', module_completer, str_key = 'import')
1920 self.set_hook('complete_command', module_completer, str_key = 'from')
1919 self.set_hook('complete_command', module_completer, str_key = 'from')
1921 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1920 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1922 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1921 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1923 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1922 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1924 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1923 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1925
1924
1926
1925
1927 @skip_doctest_py2
1926 @skip_doctest_py2
1928 def complete(self, text, line=None, cursor_pos=None):
1927 def complete(self, text, line=None, cursor_pos=None):
1929 """Return the completed text and a list of completions.
1928 """Return the completed text and a list of completions.
1930
1929
1931 Parameters
1930 Parameters
1932 ----------
1931 ----------
1933
1932
1934 text : string
1933 text : string
1935 A string of text to be completed on. It can be given as empty and
1934 A string of text to be completed on. It can be given as empty and
1936 instead a line/position pair are given. In this case, the
1935 instead a line/position pair are given. In this case, the
1937 completer itself will split the line like readline does.
1936 completer itself will split the line like readline does.
1938
1937
1939 line : string, optional
1938 line : string, optional
1940 The complete line that text is part of.
1939 The complete line that text is part of.
1941
1940
1942 cursor_pos : int, optional
1941 cursor_pos : int, optional
1943 The position of the cursor on the input line.
1942 The position of the cursor on the input line.
1944
1943
1945 Returns
1944 Returns
1946 -------
1945 -------
1947 text : string
1946 text : string
1948 The actual text that was completed.
1947 The actual text that was completed.
1949
1948
1950 matches : list
1949 matches : list
1951 A sorted list with all possible completions.
1950 A sorted list with all possible completions.
1952
1951
1953 The optional arguments allow the completion to take more context into
1952 The optional arguments allow the completion to take more context into
1954 account, and are part of the low-level completion API.
1953 account, and are part of the low-level completion API.
1955
1954
1956 This is a wrapper around the completion mechanism, similar to what
1955 This is a wrapper around the completion mechanism, similar to what
1957 readline does at the command line when the TAB key is hit. By
1956 readline does at the command line when the TAB key is hit. By
1958 exposing it as a method, it can be used by other non-readline
1957 exposing it as a method, it can be used by other non-readline
1959 environments (such as GUIs) for text completion.
1958 environments (such as GUIs) for text completion.
1960
1959
1961 Simple usage example:
1960 Simple usage example:
1962
1961
1963 In [1]: x = 'hello'
1962 In [1]: x = 'hello'
1964
1963
1965 In [2]: _ip.complete('x.l')
1964 In [2]: _ip.complete('x.l')
1966 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1965 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1967 """
1966 """
1968
1967
1969 # Inject names into __builtin__ so we can complete on the added names.
1968 # Inject names into __builtin__ so we can complete on the added names.
1970 with self.builtin_trap:
1969 with self.builtin_trap:
1971 return self.Completer.complete(text, line, cursor_pos)
1970 return self.Completer.complete(text, line, cursor_pos)
1972
1971
1973 def set_custom_completer(self, completer, pos=0):
1972 def set_custom_completer(self, completer, pos=0):
1974 """Adds a new custom completer function.
1973 """Adds a new custom completer function.
1975
1974
1976 The position argument (defaults to 0) is the index in the completers
1975 The position argument (defaults to 0) is the index in the completers
1977 list where you want the completer to be inserted."""
1976 list where you want the completer to be inserted."""
1978
1977
1979 newcomp = types.MethodType(completer,self.Completer)
1978 newcomp = types.MethodType(completer,self.Completer)
1980 self.Completer.matchers.insert(pos,newcomp)
1979 self.Completer.matchers.insert(pos,newcomp)
1981
1980
1982 def set_completer_frame(self, frame=None):
1981 def set_completer_frame(self, frame=None):
1983 """Set the frame of the completer."""
1982 """Set the frame of the completer."""
1984 if frame:
1983 if frame:
1985 self.Completer.namespace = frame.f_locals
1984 self.Completer.namespace = frame.f_locals
1986 self.Completer.global_namespace = frame.f_globals
1985 self.Completer.global_namespace = frame.f_globals
1987 else:
1986 else:
1988 self.Completer.namespace = self.user_ns
1987 self.Completer.namespace = self.user_ns
1989 self.Completer.global_namespace = self.user_global_ns
1988 self.Completer.global_namespace = self.user_global_ns
1990
1989
1991 #-------------------------------------------------------------------------
1990 #-------------------------------------------------------------------------
1992 # Things related to magics
1991 # Things related to magics
1993 #-------------------------------------------------------------------------
1992 #-------------------------------------------------------------------------
1994
1993
1995 def init_magics(self):
1994 def init_magics(self):
1996 from IPython.core import magics as m
1995 from IPython.core import magics as m
1997 self.magics_manager = magic.MagicsManager(shell=self,
1996 self.magics_manager = magic.MagicsManager(shell=self,
1998 parent=self,
1997 parent=self,
1999 user_magics=m.UserMagics(self))
1998 user_magics=m.UserMagics(self))
2000 self.configurables.append(self.magics_manager)
1999 self.configurables.append(self.magics_manager)
2001
2000
2002 # Expose as public API from the magics manager
2001 # Expose as public API from the magics manager
2003 self.register_magics = self.magics_manager.register
2002 self.register_magics = self.magics_manager.register
2004
2003
2005 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2004 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2006 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2005 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2007 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2006 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2008 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2007 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2009 )
2008 )
2010
2009
2011 # Register Magic Aliases
2010 # Register Magic Aliases
2012 mman = self.magics_manager
2011 mman = self.magics_manager
2013 # FIXME: magic aliases should be defined by the Magics classes
2012 # FIXME: magic aliases should be defined by the Magics classes
2014 # or in MagicsManager, not here
2013 # or in MagicsManager, not here
2015 mman.register_alias('ed', 'edit')
2014 mman.register_alias('ed', 'edit')
2016 mman.register_alias('hist', 'history')
2015 mman.register_alias('hist', 'history')
2017 mman.register_alias('rep', 'recall')
2016 mman.register_alias('rep', 'recall')
2018 mman.register_alias('SVG', 'svg', 'cell')
2017 mman.register_alias('SVG', 'svg', 'cell')
2019 mman.register_alias('HTML', 'html', 'cell')
2018 mman.register_alias('HTML', 'html', 'cell')
2020 mman.register_alias('file', 'writefile', 'cell')
2019 mman.register_alias('file', 'writefile', 'cell')
2021
2020
2022 # FIXME: Move the color initialization to the DisplayHook, which
2021 # FIXME: Move the color initialization to the DisplayHook, which
2023 # should be split into a prompt manager and displayhook. We probably
2022 # should be split into a prompt manager and displayhook. We probably
2024 # even need a centralize colors management object.
2023 # even need a centralize colors management object.
2025 self.magic('colors %s' % self.colors)
2024 self.magic('colors %s' % self.colors)
2026
2025
2027 # Defined here so that it's included in the documentation
2026 # Defined here so that it's included in the documentation
2028 @functools.wraps(magic.MagicsManager.register_function)
2027 @functools.wraps(magic.MagicsManager.register_function)
2029 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2028 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2030 self.magics_manager.register_function(func,
2029 self.magics_manager.register_function(func,
2031 magic_kind=magic_kind, magic_name=magic_name)
2030 magic_kind=magic_kind, magic_name=magic_name)
2032
2031
2033 def run_line_magic(self, magic_name, line):
2032 def run_line_magic(self, magic_name, line):
2034 """Execute the given line magic.
2033 """Execute the given line magic.
2035
2034
2036 Parameters
2035 Parameters
2037 ----------
2036 ----------
2038 magic_name : str
2037 magic_name : str
2039 Name of the desired magic function, without '%' prefix.
2038 Name of the desired magic function, without '%' prefix.
2040
2039
2041 line : str
2040 line : str
2042 The rest of the input line as a single string.
2041 The rest of the input line as a single string.
2043 """
2042 """
2044 fn = self.find_line_magic(magic_name)
2043 fn = self.find_line_magic(magic_name)
2045 if fn is None:
2044 if fn is None:
2046 cm = self.find_cell_magic(magic_name)
2045 cm = self.find_cell_magic(magic_name)
2047 etpl = "Line magic function `%%%s` not found%s."
2046 etpl = "Line magic function `%%%s` not found%s."
2048 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2047 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2049 'did you mean that instead?)' % magic_name )
2048 'did you mean that instead?)' % magic_name )
2050 error(etpl % (magic_name, extra))
2049 error(etpl % (magic_name, extra))
2051 else:
2050 else:
2052 # Note: this is the distance in the stack to the user's frame.
2051 # Note: this is the distance in the stack to the user's frame.
2053 # This will need to be updated if the internal calling logic gets
2052 # This will need to be updated if the internal calling logic gets
2054 # refactored, or else we'll be expanding the wrong variables.
2053 # refactored, or else we'll be expanding the wrong variables.
2055 stack_depth = 2
2054 stack_depth = 2
2056 magic_arg_s = self.var_expand(line, stack_depth)
2055 magic_arg_s = self.var_expand(line, stack_depth)
2057 # Put magic args in a list so we can call with f(*a) syntax
2056 # Put magic args in a list so we can call with f(*a) syntax
2058 args = [magic_arg_s]
2057 args = [magic_arg_s]
2059 kwargs = {}
2058 kwargs = {}
2060 # Grab local namespace if we need it:
2059 # Grab local namespace if we need it:
2061 if getattr(fn, "needs_local_scope", False):
2060 if getattr(fn, "needs_local_scope", False):
2062 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2061 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2063 with self.builtin_trap:
2062 with self.builtin_trap:
2064 result = fn(*args,**kwargs)
2063 result = fn(*args,**kwargs)
2065 return result
2064 return result
2066
2065
2067 def run_cell_magic(self, magic_name, line, cell):
2066 def run_cell_magic(self, magic_name, line, cell):
2068 """Execute the given cell magic.
2067 """Execute the given cell magic.
2069
2068
2070 Parameters
2069 Parameters
2071 ----------
2070 ----------
2072 magic_name : str
2071 magic_name : str
2073 Name of the desired magic function, without '%' prefix.
2072 Name of the desired magic function, without '%' prefix.
2074
2073
2075 line : str
2074 line : str
2076 The rest of the first input line as a single string.
2075 The rest of the first input line as a single string.
2077
2076
2078 cell : str
2077 cell : str
2079 The body of the cell as a (possibly multiline) string.
2078 The body of the cell as a (possibly multiline) string.
2080 """
2079 """
2081 fn = self.find_cell_magic(magic_name)
2080 fn = self.find_cell_magic(magic_name)
2082 if fn is None:
2081 if fn is None:
2083 lm = self.find_line_magic(magic_name)
2082 lm = self.find_line_magic(magic_name)
2084 etpl = "Cell magic `%%{0}` not found{1}."
2083 etpl = "Cell magic `%%{0}` not found{1}."
2085 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2084 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2086 'did you mean that instead?)'.format(magic_name))
2085 'did you mean that instead?)'.format(magic_name))
2087 error(etpl.format(magic_name, extra))
2086 error(etpl.format(magic_name, extra))
2088 elif cell == '':
2087 elif cell == '':
2089 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2088 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2090 if self.find_line_magic(magic_name) is not None:
2089 if self.find_line_magic(magic_name) is not None:
2091 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2090 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2092 raise UsageError(message)
2091 raise UsageError(message)
2093 else:
2092 else:
2094 # Note: this is the distance in the stack to the user's frame.
2093 # Note: this is the distance in the stack to the user's frame.
2095 # This will need to be updated if the internal calling logic gets
2094 # This will need to be updated if the internal calling logic gets
2096 # refactored, or else we'll be expanding the wrong variables.
2095 # refactored, or else we'll be expanding the wrong variables.
2097 stack_depth = 2
2096 stack_depth = 2
2098 magic_arg_s = self.var_expand(line, stack_depth)
2097 magic_arg_s = self.var_expand(line, stack_depth)
2099 with self.builtin_trap:
2098 with self.builtin_trap:
2100 result = fn(magic_arg_s, cell)
2099 result = fn(magic_arg_s, cell)
2101 return result
2100 return result
2102
2101
2103 def find_line_magic(self, magic_name):
2102 def find_line_magic(self, magic_name):
2104 """Find and return a line magic by name.
2103 """Find and return a line magic by name.
2105
2104
2106 Returns None if the magic isn't found."""
2105 Returns None if the magic isn't found."""
2107 return self.magics_manager.magics['line'].get(magic_name)
2106 return self.magics_manager.magics['line'].get(magic_name)
2108
2107
2109 def find_cell_magic(self, magic_name):
2108 def find_cell_magic(self, magic_name):
2110 """Find and return a cell magic by name.
2109 """Find and return a cell magic by name.
2111
2110
2112 Returns None if the magic isn't found."""
2111 Returns None if the magic isn't found."""
2113 return self.magics_manager.magics['cell'].get(magic_name)
2112 return self.magics_manager.magics['cell'].get(magic_name)
2114
2113
2115 def find_magic(self, magic_name, magic_kind='line'):
2114 def find_magic(self, magic_name, magic_kind='line'):
2116 """Find and return a magic of the given type by name.
2115 """Find and return a magic of the given type by name.
2117
2116
2118 Returns None if the magic isn't found."""
2117 Returns None if the magic isn't found."""
2119 return self.magics_manager.magics[magic_kind].get(magic_name)
2118 return self.magics_manager.magics[magic_kind].get(magic_name)
2120
2119
2121 def magic(self, arg_s):
2120 def magic(self, arg_s):
2122 """DEPRECATED. Use run_line_magic() instead.
2121 """DEPRECATED. Use run_line_magic() instead.
2123
2122
2124 Call a magic function by name.
2123 Call a magic function by name.
2125
2124
2126 Input: a string containing the name of the magic function to call and
2125 Input: a string containing the name of the magic function to call and
2127 any additional arguments to be passed to the magic.
2126 any additional arguments to be passed to the magic.
2128
2127
2129 magic('name -opt foo bar') is equivalent to typing at the ipython
2128 magic('name -opt foo bar') is equivalent to typing at the ipython
2130 prompt:
2129 prompt:
2131
2130
2132 In[1]: %name -opt foo bar
2131 In[1]: %name -opt foo bar
2133
2132
2134 To call a magic without arguments, simply use magic('name').
2133 To call a magic without arguments, simply use magic('name').
2135
2134
2136 This provides a proper Python function to call IPython's magics in any
2135 This provides a proper Python function to call IPython's magics in any
2137 valid Python code you can type at the interpreter, including loops and
2136 valid Python code you can type at the interpreter, including loops and
2138 compound statements.
2137 compound statements.
2139 """
2138 """
2140 # TODO: should we issue a loud deprecation warning here?
2139 # TODO: should we issue a loud deprecation warning here?
2141 magic_name, _, magic_arg_s = arg_s.partition(' ')
2140 magic_name, _, magic_arg_s = arg_s.partition(' ')
2142 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2141 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2143 return self.run_line_magic(magic_name, magic_arg_s)
2142 return self.run_line_magic(magic_name, magic_arg_s)
2144
2143
2145 #-------------------------------------------------------------------------
2144 #-------------------------------------------------------------------------
2146 # Things related to macros
2145 # Things related to macros
2147 #-------------------------------------------------------------------------
2146 #-------------------------------------------------------------------------
2148
2147
2149 def define_macro(self, name, themacro):
2148 def define_macro(self, name, themacro):
2150 """Define a new macro
2149 """Define a new macro
2151
2150
2152 Parameters
2151 Parameters
2153 ----------
2152 ----------
2154 name : str
2153 name : str
2155 The name of the macro.
2154 The name of the macro.
2156 themacro : str or Macro
2155 themacro : str or Macro
2157 The action to do upon invoking the macro. If a string, a new
2156 The action to do upon invoking the macro. If a string, a new
2158 Macro object is created by passing the string to it.
2157 Macro object is created by passing the string to it.
2159 """
2158 """
2160
2159
2161 from IPython.core import macro
2160 from IPython.core import macro
2162
2161
2163 if isinstance(themacro, string_types):
2162 if isinstance(themacro, string_types):
2164 themacro = macro.Macro(themacro)
2163 themacro = macro.Macro(themacro)
2165 if not isinstance(themacro, macro.Macro):
2164 if not isinstance(themacro, macro.Macro):
2166 raise ValueError('A macro must be a string or a Macro instance.')
2165 raise ValueError('A macro must be a string or a Macro instance.')
2167 self.user_ns[name] = themacro
2166 self.user_ns[name] = themacro
2168
2167
2169 #-------------------------------------------------------------------------
2168 #-------------------------------------------------------------------------
2170 # Things related to the running of system commands
2169 # Things related to the running of system commands
2171 #-------------------------------------------------------------------------
2170 #-------------------------------------------------------------------------
2172
2171
2173 def system_piped(self, cmd):
2172 def system_piped(self, cmd):
2174 """Call the given cmd in a subprocess, piping stdout/err
2173 """Call the given cmd in a subprocess, piping stdout/err
2175
2174
2176 Parameters
2175 Parameters
2177 ----------
2176 ----------
2178 cmd : str
2177 cmd : str
2179 Command to execute (can not end in '&', as background processes are
2178 Command to execute (can not end in '&', as background processes are
2180 not supported. Should not be a command that expects input
2179 not supported. Should not be a command that expects input
2181 other than simple text.
2180 other than simple text.
2182 """
2181 """
2183 if cmd.rstrip().endswith('&'):
2182 if cmd.rstrip().endswith('&'):
2184 # this is *far* from a rigorous test
2183 # this is *far* from a rigorous test
2185 # We do not support backgrounding processes because we either use
2184 # We do not support backgrounding processes because we either use
2186 # pexpect or pipes to read from. Users can always just call
2185 # pexpect or pipes to read from. Users can always just call
2187 # os.system() or use ip.system=ip.system_raw
2186 # os.system() or use ip.system=ip.system_raw
2188 # if they really want a background process.
2187 # if they really want a background process.
2189 raise OSError("Background processes not supported.")
2188 raise OSError("Background processes not supported.")
2190
2189
2191 # we explicitly do NOT return the subprocess status code, because
2190 # we explicitly do NOT return the subprocess status code, because
2192 # a non-None value would trigger :func:`sys.displayhook` calls.
2191 # a non-None value would trigger :func:`sys.displayhook` calls.
2193 # Instead, we store the exit_code in user_ns.
2192 # Instead, we store the exit_code in user_ns.
2194 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2193 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2195
2194
2196 def system_raw(self, cmd):
2195 def system_raw(self, cmd):
2197 """Call the given cmd in a subprocess using os.system on Windows or
2196 """Call the given cmd in a subprocess using os.system on Windows or
2198 subprocess.call using the system shell on other platforms.
2197 subprocess.call using the system shell on other platforms.
2199
2198
2200 Parameters
2199 Parameters
2201 ----------
2200 ----------
2202 cmd : str
2201 cmd : str
2203 Command to execute.
2202 Command to execute.
2204 """
2203 """
2205 cmd = self.var_expand(cmd, depth=1)
2204 cmd = self.var_expand(cmd, depth=1)
2206 # protect os.system from UNC paths on Windows, which it can't handle:
2205 # protect os.system from UNC paths on Windows, which it can't handle:
2207 if sys.platform == 'win32':
2206 if sys.platform == 'win32':
2208 from IPython.utils._process_win32 import AvoidUNCPath
2207 from IPython.utils._process_win32 import AvoidUNCPath
2209 with AvoidUNCPath() as path:
2208 with AvoidUNCPath() as path:
2210 if path is not None:
2209 if path is not None:
2211 cmd = '"pushd %s &&"%s' % (path, cmd)
2210 cmd = '"pushd %s &&"%s' % (path, cmd)
2212 cmd = py3compat.unicode_to_str(cmd)
2211 cmd = py3compat.unicode_to_str(cmd)
2213 try:
2212 try:
2214 ec = os.system(cmd)
2213 ec = os.system(cmd)
2215 except KeyboardInterrupt:
2214 except KeyboardInterrupt:
2216 print('\n' + self.get_exception_only(), file=sys.stderr)
2215 print('\n' + self.get_exception_only(), file=sys.stderr)
2217 ec = -2
2216 ec = -2
2218 else:
2217 else:
2219 cmd = py3compat.unicode_to_str(cmd)
2218 cmd = py3compat.unicode_to_str(cmd)
2220 # For posix the result of the subprocess.call() below is an exit
2219 # For posix the result of the subprocess.call() below is an exit
2221 # code, which by convention is zero for success, positive for
2220 # code, which by convention is zero for success, positive for
2222 # program failure. Exit codes above 128 are reserved for signals,
2221 # program failure. Exit codes above 128 are reserved for signals,
2223 # and the formula for converting a signal to an exit code is usually
2222 # and the formula for converting a signal to an exit code is usually
2224 # signal_number+128. To more easily differentiate between exit
2223 # signal_number+128. To more easily differentiate between exit
2225 # codes and signals, ipython uses negative numbers. For instance
2224 # codes and signals, ipython uses negative numbers. For instance
2226 # since control-c is signal 2 but exit code 130, ipython's
2225 # since control-c is signal 2 but exit code 130, ipython's
2227 # _exit_code variable will read -2. Note that some shells like
2226 # _exit_code variable will read -2. Note that some shells like
2228 # csh and fish don't follow sh/bash conventions for exit codes.
2227 # csh and fish don't follow sh/bash conventions for exit codes.
2229 executable = os.environ.get('SHELL', None)
2228 executable = os.environ.get('SHELL', None)
2230 try:
2229 try:
2231 # Use env shell instead of default /bin/sh
2230 # Use env shell instead of default /bin/sh
2232 ec = subprocess.call(cmd, shell=True, executable=executable)
2231 ec = subprocess.call(cmd, shell=True, executable=executable)
2233 except KeyboardInterrupt:
2232 except KeyboardInterrupt:
2234 # intercept control-C; a long traceback is not useful here
2233 # intercept control-C; a long traceback is not useful here
2235 print('\n' + self.get_exception_only(), file=sys.stderr)
2234 print('\n' + self.get_exception_only(), file=sys.stderr)
2236 ec = 130
2235 ec = 130
2237 if ec > 128:
2236 if ec > 128:
2238 ec = -(ec - 128)
2237 ec = -(ec - 128)
2239
2238
2240 # We explicitly do NOT return the subprocess status code, because
2239 # We explicitly do NOT return the subprocess status code, because
2241 # a non-None value would trigger :func:`sys.displayhook` calls.
2240 # a non-None value would trigger :func:`sys.displayhook` calls.
2242 # Instead, we store the exit_code in user_ns. Note the semantics
2241 # Instead, we store the exit_code in user_ns. Note the semantics
2243 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2242 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2244 # but raising SystemExit(_exit_code) will give status 254!
2243 # but raising SystemExit(_exit_code) will give status 254!
2245 self.user_ns['_exit_code'] = ec
2244 self.user_ns['_exit_code'] = ec
2246
2245
2247 # use piped system by default, because it is better behaved
2246 # use piped system by default, because it is better behaved
2248 system = system_piped
2247 system = system_piped
2249
2248
2250 def getoutput(self, cmd, split=True, depth=0):
2249 def getoutput(self, cmd, split=True, depth=0):
2251 """Get output (possibly including stderr) from a subprocess.
2250 """Get output (possibly including stderr) from a subprocess.
2252
2251
2253 Parameters
2252 Parameters
2254 ----------
2253 ----------
2255 cmd : str
2254 cmd : str
2256 Command to execute (can not end in '&', as background processes are
2255 Command to execute (can not end in '&', as background processes are
2257 not supported.
2256 not supported.
2258 split : bool, optional
2257 split : bool, optional
2259 If True, split the output into an IPython SList. Otherwise, an
2258 If True, split the output into an IPython SList. Otherwise, an
2260 IPython LSString is returned. These are objects similar to normal
2259 IPython LSString is returned. These are objects similar to normal
2261 lists and strings, with a few convenience attributes for easier
2260 lists and strings, with a few convenience attributes for easier
2262 manipulation of line-based output. You can use '?' on them for
2261 manipulation of line-based output. You can use '?' on them for
2263 details.
2262 details.
2264 depth : int, optional
2263 depth : int, optional
2265 How many frames above the caller are the local variables which should
2264 How many frames above the caller are the local variables which should
2266 be expanded in the command string? The default (0) assumes that the
2265 be expanded in the command string? The default (0) assumes that the
2267 expansion variables are in the stack frame calling this function.
2266 expansion variables are in the stack frame calling this function.
2268 """
2267 """
2269 if cmd.rstrip().endswith('&'):
2268 if cmd.rstrip().endswith('&'):
2270 # this is *far* from a rigorous test
2269 # this is *far* from a rigorous test
2271 raise OSError("Background processes not supported.")
2270 raise OSError("Background processes not supported.")
2272 out = getoutput(self.var_expand(cmd, depth=depth+1))
2271 out = getoutput(self.var_expand(cmd, depth=depth+1))
2273 if split:
2272 if split:
2274 out = SList(out.splitlines())
2273 out = SList(out.splitlines())
2275 else:
2274 else:
2276 out = LSString(out)
2275 out = LSString(out)
2277 return out
2276 return out
2278
2277
2279 #-------------------------------------------------------------------------
2278 #-------------------------------------------------------------------------
2280 # Things related to aliases
2279 # Things related to aliases
2281 #-------------------------------------------------------------------------
2280 #-------------------------------------------------------------------------
2282
2281
2283 def init_alias(self):
2282 def init_alias(self):
2284 self.alias_manager = AliasManager(shell=self, parent=self)
2283 self.alias_manager = AliasManager(shell=self, parent=self)
2285 self.configurables.append(self.alias_manager)
2284 self.configurables.append(self.alias_manager)
2286
2285
2287 #-------------------------------------------------------------------------
2286 #-------------------------------------------------------------------------
2288 # Things related to extensions
2287 # Things related to extensions
2289 #-------------------------------------------------------------------------
2288 #-------------------------------------------------------------------------
2290
2289
2291 def init_extension_manager(self):
2290 def init_extension_manager(self):
2292 self.extension_manager = ExtensionManager(shell=self, parent=self)
2291 self.extension_manager = ExtensionManager(shell=self, parent=self)
2293 self.configurables.append(self.extension_manager)
2292 self.configurables.append(self.extension_manager)
2294
2293
2295 #-------------------------------------------------------------------------
2294 #-------------------------------------------------------------------------
2296 # Things related to payloads
2295 # Things related to payloads
2297 #-------------------------------------------------------------------------
2296 #-------------------------------------------------------------------------
2298
2297
2299 def init_payload(self):
2298 def init_payload(self):
2300 self.payload_manager = PayloadManager(parent=self)
2299 self.payload_manager = PayloadManager(parent=self)
2301 self.configurables.append(self.payload_manager)
2300 self.configurables.append(self.payload_manager)
2302
2301
2303 #-------------------------------------------------------------------------
2302 #-------------------------------------------------------------------------
2304 # Things related to the prefilter
2303 # Things related to the prefilter
2305 #-------------------------------------------------------------------------
2304 #-------------------------------------------------------------------------
2306
2305
2307 def init_prefilter(self):
2306 def init_prefilter(self):
2308 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2307 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2309 self.configurables.append(self.prefilter_manager)
2308 self.configurables.append(self.prefilter_manager)
2310 # Ultimately this will be refactored in the new interpreter code, but
2309 # Ultimately this will be refactored in the new interpreter code, but
2311 # for now, we should expose the main prefilter method (there's legacy
2310 # for now, we should expose the main prefilter method (there's legacy
2312 # code out there that may rely on this).
2311 # code out there that may rely on this).
2313 self.prefilter = self.prefilter_manager.prefilter_lines
2312 self.prefilter = self.prefilter_manager.prefilter_lines
2314
2313
2315 def auto_rewrite_input(self, cmd):
2314 def auto_rewrite_input(self, cmd):
2316 """Print to the screen the rewritten form of the user's command.
2315 """Print to the screen the rewritten form of the user's command.
2317
2316
2318 This shows visual feedback by rewriting input lines that cause
2317 This shows visual feedback by rewriting input lines that cause
2319 automatic calling to kick in, like::
2318 automatic calling to kick in, like::
2320
2319
2321 /f x
2320 /f x
2322
2321
2323 into::
2322 into::
2324
2323
2325 ------> f(x)
2324 ------> f(x)
2326
2325
2327 after the user's input prompt. This helps the user understand that the
2326 after the user's input prompt. This helps the user understand that the
2328 input line was transformed automatically by IPython.
2327 input line was transformed automatically by IPython.
2329 """
2328 """
2330 if not self.show_rewritten_input:
2329 if not self.show_rewritten_input:
2331 return
2330 return
2332
2331
2333 # This is overridden in TerminalInteractiveShell to use fancy prompts
2332 # This is overridden in TerminalInteractiveShell to use fancy prompts
2334 print("------> " + cmd)
2333 print("------> " + cmd)
2335
2334
2336 #-------------------------------------------------------------------------
2335 #-------------------------------------------------------------------------
2337 # Things related to extracting values/expressions from kernel and user_ns
2336 # Things related to extracting values/expressions from kernel and user_ns
2338 #-------------------------------------------------------------------------
2337 #-------------------------------------------------------------------------
2339
2338
2340 def _user_obj_error(self):
2339 def _user_obj_error(self):
2341 """return simple exception dict
2340 """return simple exception dict
2342
2341
2343 for use in user_expressions
2342 for use in user_expressions
2344 """
2343 """
2345
2344
2346 etype, evalue, tb = self._get_exc_info()
2345 etype, evalue, tb = self._get_exc_info()
2347 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2346 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2348
2347
2349 exc_info = {
2348 exc_info = {
2350 u'status' : 'error',
2349 u'status' : 'error',
2351 u'traceback' : stb,
2350 u'traceback' : stb,
2352 u'ename' : unicode_type(etype.__name__),
2351 u'ename' : unicode_type(etype.__name__),
2353 u'evalue' : py3compat.safe_unicode(evalue),
2352 u'evalue' : py3compat.safe_unicode(evalue),
2354 }
2353 }
2355
2354
2356 return exc_info
2355 return exc_info
2357
2356
2358 def _format_user_obj(self, obj):
2357 def _format_user_obj(self, obj):
2359 """format a user object to display dict
2358 """format a user object to display dict
2360
2359
2361 for use in user_expressions
2360 for use in user_expressions
2362 """
2361 """
2363
2362
2364 data, md = self.display_formatter.format(obj)
2363 data, md = self.display_formatter.format(obj)
2365 value = {
2364 value = {
2366 'status' : 'ok',
2365 'status' : 'ok',
2367 'data' : data,
2366 'data' : data,
2368 'metadata' : md,
2367 'metadata' : md,
2369 }
2368 }
2370 return value
2369 return value
2371
2370
2372 def user_expressions(self, expressions):
2371 def user_expressions(self, expressions):
2373 """Evaluate a dict of expressions in the user's namespace.
2372 """Evaluate a dict of expressions in the user's namespace.
2374
2373
2375 Parameters
2374 Parameters
2376 ----------
2375 ----------
2377 expressions : dict
2376 expressions : dict
2378 A dict with string keys and string values. The expression values
2377 A dict with string keys and string values. The expression values
2379 should be valid Python expressions, each of which will be evaluated
2378 should be valid Python expressions, each of which will be evaluated
2380 in the user namespace.
2379 in the user namespace.
2381
2380
2382 Returns
2381 Returns
2383 -------
2382 -------
2384 A dict, keyed like the input expressions dict, with the rich mime-typed
2383 A dict, keyed like the input expressions dict, with the rich mime-typed
2385 display_data of each value.
2384 display_data of each value.
2386 """
2385 """
2387 out = {}
2386 out = {}
2388 user_ns = self.user_ns
2387 user_ns = self.user_ns
2389 global_ns = self.user_global_ns
2388 global_ns = self.user_global_ns
2390
2389
2391 for key, expr in iteritems(expressions):
2390 for key, expr in iteritems(expressions):
2392 try:
2391 try:
2393 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2392 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2394 except:
2393 except:
2395 value = self._user_obj_error()
2394 value = self._user_obj_error()
2396 out[key] = value
2395 out[key] = value
2397 return out
2396 return out
2398
2397
2399 #-------------------------------------------------------------------------
2398 #-------------------------------------------------------------------------
2400 # Things related to the running of code
2399 # Things related to the running of code
2401 #-------------------------------------------------------------------------
2400 #-------------------------------------------------------------------------
2402
2401
2403 def ex(self, cmd):
2402 def ex(self, cmd):
2404 """Execute a normal python statement in user namespace."""
2403 """Execute a normal python statement in user namespace."""
2405 with self.builtin_trap:
2404 with self.builtin_trap:
2406 exec(cmd, self.user_global_ns, self.user_ns)
2405 exec(cmd, self.user_global_ns, self.user_ns)
2407
2406
2408 def ev(self, expr):
2407 def ev(self, expr):
2409 """Evaluate python expression expr in user namespace.
2408 """Evaluate python expression expr in user namespace.
2410
2409
2411 Returns the result of evaluation
2410 Returns the result of evaluation
2412 """
2411 """
2413 with self.builtin_trap:
2412 with self.builtin_trap:
2414 return eval(expr, self.user_global_ns, self.user_ns)
2413 return eval(expr, self.user_global_ns, self.user_ns)
2415
2414
2416 def safe_execfile(self, fname, *where, **kw):
2415 def safe_execfile(self, fname, *where, **kw):
2417 """A safe version of the builtin execfile().
2416 """A safe version of the builtin execfile().
2418
2417
2419 This version will never throw an exception, but instead print
2418 This version will never throw an exception, but instead print
2420 helpful error messages to the screen. This only works on pure
2419 helpful error messages to the screen. This only works on pure
2421 Python files with the .py extension.
2420 Python files with the .py extension.
2422
2421
2423 Parameters
2422 Parameters
2424 ----------
2423 ----------
2425 fname : string
2424 fname : string
2426 The name of the file to be executed.
2425 The name of the file to be executed.
2427 where : tuple
2426 where : tuple
2428 One or two namespaces, passed to execfile() as (globals,locals).
2427 One or two namespaces, passed to execfile() as (globals,locals).
2429 If only one is given, it is passed as both.
2428 If only one is given, it is passed as both.
2430 exit_ignore : bool (False)
2429 exit_ignore : bool (False)
2431 If True, then silence SystemExit for non-zero status (it is always
2430 If True, then silence SystemExit for non-zero status (it is always
2432 silenced for zero status, as it is so common).
2431 silenced for zero status, as it is so common).
2433 raise_exceptions : bool (False)
2432 raise_exceptions : bool (False)
2434 If True raise exceptions everywhere. Meant for testing.
2433 If True raise exceptions everywhere. Meant for testing.
2435 shell_futures : bool (False)
2434 shell_futures : bool (False)
2436 If True, the code will share future statements with the interactive
2435 If True, the code will share future statements with the interactive
2437 shell. It will both be affected by previous __future__ imports, and
2436 shell. It will both be affected by previous __future__ imports, and
2438 any __future__ imports in the code will affect the shell. If False,
2437 any __future__ imports in the code will affect the shell. If False,
2439 __future__ imports are not shared in either direction.
2438 __future__ imports are not shared in either direction.
2440
2439
2441 """
2440 """
2442 kw.setdefault('exit_ignore', False)
2441 kw.setdefault('exit_ignore', False)
2443 kw.setdefault('raise_exceptions', False)
2442 kw.setdefault('raise_exceptions', False)
2444 kw.setdefault('shell_futures', False)
2443 kw.setdefault('shell_futures', False)
2445
2444
2446 fname = os.path.abspath(os.path.expanduser(fname))
2445 fname = os.path.abspath(os.path.expanduser(fname))
2447
2446
2448 # Make sure we can open the file
2447 # Make sure we can open the file
2449 try:
2448 try:
2450 with open(fname):
2449 with open(fname):
2451 pass
2450 pass
2452 except:
2451 except:
2453 warn('Could not open file <%s> for safe execution.' % fname)
2452 warn('Could not open file <%s> for safe execution.' % fname)
2454 return
2453 return
2455
2454
2456 # Find things also in current directory. This is needed to mimic the
2455 # Find things also in current directory. This is needed to mimic the
2457 # behavior of running a script from the system command line, where
2456 # behavior of running a script from the system command line, where
2458 # Python inserts the script's directory into sys.path
2457 # Python inserts the script's directory into sys.path
2459 dname = os.path.dirname(fname)
2458 dname = os.path.dirname(fname)
2460
2459
2461 with prepended_to_syspath(dname), self.builtin_trap:
2460 with prepended_to_syspath(dname), self.builtin_trap:
2462 try:
2461 try:
2463 glob, loc = (where + (None, ))[:2]
2462 glob, loc = (where + (None, ))[:2]
2464 py3compat.execfile(
2463 py3compat.execfile(
2465 fname, glob, loc,
2464 fname, glob, loc,
2466 self.compile if kw['shell_futures'] else None)
2465 self.compile if kw['shell_futures'] else None)
2467 except SystemExit as status:
2466 except SystemExit as status:
2468 # If the call was made with 0 or None exit status (sys.exit(0)
2467 # If the call was made with 0 or None exit status (sys.exit(0)
2469 # or sys.exit() ), don't bother showing a traceback, as both of
2468 # or sys.exit() ), don't bother showing a traceback, as both of
2470 # these are considered normal by the OS:
2469 # these are considered normal by the OS:
2471 # > python -c'import sys;sys.exit(0)'; echo $?
2470 # > python -c'import sys;sys.exit(0)'; echo $?
2472 # 0
2471 # 0
2473 # > python -c'import sys;sys.exit()'; echo $?
2472 # > python -c'import sys;sys.exit()'; echo $?
2474 # 0
2473 # 0
2475 # For other exit status, we show the exception unless
2474 # For other exit status, we show the exception unless
2476 # explicitly silenced, but only in short form.
2475 # explicitly silenced, but only in short form.
2477 if status.code:
2476 if status.code:
2478 if kw['raise_exceptions']:
2477 if kw['raise_exceptions']:
2479 raise
2478 raise
2480 if not kw['exit_ignore']:
2479 if not kw['exit_ignore']:
2481 self.showtraceback(exception_only=True)
2480 self.showtraceback(exception_only=True)
2482 except:
2481 except:
2483 if kw['raise_exceptions']:
2482 if kw['raise_exceptions']:
2484 raise
2483 raise
2485 # tb offset is 2 because we wrap execfile
2484 # tb offset is 2 because we wrap execfile
2486 self.showtraceback(tb_offset=2)
2485 self.showtraceback(tb_offset=2)
2487
2486
2488 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2487 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2489 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2488 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2490
2489
2491 Parameters
2490 Parameters
2492 ----------
2491 ----------
2493 fname : str
2492 fname : str
2494 The name of the file to execute. The filename must have a
2493 The name of the file to execute. The filename must have a
2495 .ipy or .ipynb extension.
2494 .ipy or .ipynb extension.
2496 shell_futures : bool (False)
2495 shell_futures : bool (False)
2497 If True, the code will share future statements with the interactive
2496 If True, the code will share future statements with the interactive
2498 shell. It will both be affected by previous __future__ imports, and
2497 shell. It will both be affected by previous __future__ imports, and
2499 any __future__ imports in the code will affect the shell. If False,
2498 any __future__ imports in the code will affect the shell. If False,
2500 __future__ imports are not shared in either direction.
2499 __future__ imports are not shared in either direction.
2501 raise_exceptions : bool (False)
2500 raise_exceptions : bool (False)
2502 If True raise exceptions everywhere. Meant for testing.
2501 If True raise exceptions everywhere. Meant for testing.
2503 """
2502 """
2504 fname = os.path.abspath(os.path.expanduser(fname))
2503 fname = os.path.abspath(os.path.expanduser(fname))
2505
2504
2506 # Make sure we can open the file
2505 # Make sure we can open the file
2507 try:
2506 try:
2508 with open(fname):
2507 with open(fname):
2509 pass
2508 pass
2510 except:
2509 except:
2511 warn('Could not open file <%s> for safe execution.' % fname)
2510 warn('Could not open file <%s> for safe execution.' % fname)
2512 return
2511 return
2513
2512
2514 # Find things also in current directory. This is needed to mimic the
2513 # Find things also in current directory. This is needed to mimic the
2515 # behavior of running a script from the system command line, where
2514 # behavior of running a script from the system command line, where
2516 # Python inserts the script's directory into sys.path
2515 # Python inserts the script's directory into sys.path
2517 dname = os.path.dirname(fname)
2516 dname = os.path.dirname(fname)
2518
2517
2519 def get_cells():
2518 def get_cells():
2520 """generator for sequence of code blocks to run"""
2519 """generator for sequence of code blocks to run"""
2521 if fname.endswith('.ipynb'):
2520 if fname.endswith('.ipynb'):
2522 from nbformat import read
2521 from nbformat import read
2523 with io_open(fname) as f:
2522 with io_open(fname) as f:
2524 nb = read(f, as_version=4)
2523 nb = read(f, as_version=4)
2525 if not nb.cells:
2524 if not nb.cells:
2526 return
2525 return
2527 for cell in nb.cells:
2526 for cell in nb.cells:
2528 if cell.cell_type == 'code':
2527 if cell.cell_type == 'code':
2529 yield cell.source
2528 yield cell.source
2530 else:
2529 else:
2531 with open(fname) as f:
2530 with open(fname) as f:
2532 yield f.read()
2531 yield f.read()
2533
2532
2534 with prepended_to_syspath(dname):
2533 with prepended_to_syspath(dname):
2535 try:
2534 try:
2536 for cell in get_cells():
2535 for cell in get_cells():
2537 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2536 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2538 if raise_exceptions:
2537 if raise_exceptions:
2539 result.raise_error()
2538 result.raise_error()
2540 elif not result.success:
2539 elif not result.success:
2541 break
2540 break
2542 except:
2541 except:
2543 if raise_exceptions:
2542 if raise_exceptions:
2544 raise
2543 raise
2545 self.showtraceback()
2544 self.showtraceback()
2546 warn('Unknown failure executing file: <%s>' % fname)
2545 warn('Unknown failure executing file: <%s>' % fname)
2547
2546
2548 def safe_run_module(self, mod_name, where):
2547 def safe_run_module(self, mod_name, where):
2549 """A safe version of runpy.run_module().
2548 """A safe version of runpy.run_module().
2550
2549
2551 This version will never throw an exception, but instead print
2550 This version will never throw an exception, but instead print
2552 helpful error messages to the screen.
2551 helpful error messages to the screen.
2553
2552
2554 `SystemExit` exceptions with status code 0 or None are ignored.
2553 `SystemExit` exceptions with status code 0 or None are ignored.
2555
2554
2556 Parameters
2555 Parameters
2557 ----------
2556 ----------
2558 mod_name : string
2557 mod_name : string
2559 The name of the module to be executed.
2558 The name of the module to be executed.
2560 where : dict
2559 where : dict
2561 The globals namespace.
2560 The globals namespace.
2562 """
2561 """
2563 try:
2562 try:
2564 try:
2563 try:
2565 where.update(
2564 where.update(
2566 runpy.run_module(str(mod_name), run_name="__main__",
2565 runpy.run_module(str(mod_name), run_name="__main__",
2567 alter_sys=True)
2566 alter_sys=True)
2568 )
2567 )
2569 except SystemExit as status:
2568 except SystemExit as status:
2570 if status.code:
2569 if status.code:
2571 raise
2570 raise
2572 except:
2571 except:
2573 self.showtraceback()
2572 self.showtraceback()
2574 warn('Unknown failure executing module: <%s>' % mod_name)
2573 warn('Unknown failure executing module: <%s>' % mod_name)
2575
2574
2576 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2575 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2577 """Run a complete IPython cell.
2576 """Run a complete IPython cell.
2578
2577
2579 Parameters
2578 Parameters
2580 ----------
2579 ----------
2581 raw_cell : str
2580 raw_cell : str
2582 The code (including IPython code such as %magic functions) to run.
2581 The code (including IPython code such as %magic functions) to run.
2583 store_history : bool
2582 store_history : bool
2584 If True, the raw and translated cell will be stored in IPython's
2583 If True, the raw and translated cell will be stored in IPython's
2585 history. For user code calling back into IPython's machinery, this
2584 history. For user code calling back into IPython's machinery, this
2586 should be set to False.
2585 should be set to False.
2587 silent : bool
2586 silent : bool
2588 If True, avoid side-effects, such as implicit displayhooks and
2587 If True, avoid side-effects, such as implicit displayhooks and
2589 and logging. silent=True forces store_history=False.
2588 and logging. silent=True forces store_history=False.
2590 shell_futures : bool
2589 shell_futures : bool
2591 If True, the code will share future statements with the interactive
2590 If True, the code will share future statements with the interactive
2592 shell. It will both be affected by previous __future__ imports, and
2591 shell. It will both be affected by previous __future__ imports, and
2593 any __future__ imports in the code will affect the shell. If False,
2592 any __future__ imports in the code will affect the shell. If False,
2594 __future__ imports are not shared in either direction.
2593 __future__ imports are not shared in either direction.
2595
2594
2596 Returns
2595 Returns
2597 -------
2596 -------
2598 result : :class:`ExecutionResult`
2597 result : :class:`ExecutionResult`
2599 """
2598 """
2600 result = ExecutionResult()
2599 result = ExecutionResult()
2601
2600
2602 if (not raw_cell) or raw_cell.isspace():
2601 if (not raw_cell) or raw_cell.isspace():
2603 self.last_execution_succeeded = True
2602 self.last_execution_succeeded = True
2604 return result
2603 return result
2605
2604
2606 if silent:
2605 if silent:
2607 store_history = False
2606 store_history = False
2608
2607
2609 if store_history:
2608 if store_history:
2610 result.execution_count = self.execution_count
2609 result.execution_count = self.execution_count
2611
2610
2612 def error_before_exec(value):
2611 def error_before_exec(value):
2613 result.error_before_exec = value
2612 result.error_before_exec = value
2614 self.last_execution_succeeded = False
2613 self.last_execution_succeeded = False
2615 return result
2614 return result
2616
2615
2617 self.events.trigger('pre_execute')
2616 self.events.trigger('pre_execute')
2618 if not silent:
2617 if not silent:
2619 self.events.trigger('pre_run_cell')
2618 self.events.trigger('pre_run_cell')
2620
2619
2621 # If any of our input transformation (input_transformer_manager or
2620 # If any of our input transformation (input_transformer_manager or
2622 # prefilter_manager) raises an exception, we store it in this variable
2621 # prefilter_manager) raises an exception, we store it in this variable
2623 # so that we can display the error after logging the input and storing
2622 # so that we can display the error after logging the input and storing
2624 # it in the history.
2623 # it in the history.
2625 preprocessing_exc_tuple = None
2624 preprocessing_exc_tuple = None
2626 try:
2625 try:
2627 # Static input transformations
2626 # Static input transformations
2628 cell = self.input_transformer_manager.transform_cell(raw_cell)
2627 cell = self.input_transformer_manager.transform_cell(raw_cell)
2629 except SyntaxError:
2628 except SyntaxError:
2630 preprocessing_exc_tuple = sys.exc_info()
2629 preprocessing_exc_tuple = sys.exc_info()
2631 cell = raw_cell # cell has to exist so it can be stored/logged
2630 cell = raw_cell # cell has to exist so it can be stored/logged
2632 else:
2631 else:
2633 if len(cell.splitlines()) == 1:
2632 if len(cell.splitlines()) == 1:
2634 # Dynamic transformations - only applied for single line commands
2633 # Dynamic transformations - only applied for single line commands
2635 with self.builtin_trap:
2634 with self.builtin_trap:
2636 try:
2635 try:
2637 # use prefilter_lines to handle trailing newlines
2636 # use prefilter_lines to handle trailing newlines
2638 # restore trailing newline for ast.parse
2637 # restore trailing newline for ast.parse
2639 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2638 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2640 except Exception:
2639 except Exception:
2641 # don't allow prefilter errors to crash IPython
2640 # don't allow prefilter errors to crash IPython
2642 preprocessing_exc_tuple = sys.exc_info()
2641 preprocessing_exc_tuple = sys.exc_info()
2643
2642
2644 # Store raw and processed history
2643 # Store raw and processed history
2645 if store_history:
2644 if store_history:
2646 self.history_manager.store_inputs(self.execution_count,
2645 self.history_manager.store_inputs(self.execution_count,
2647 cell, raw_cell)
2646 cell, raw_cell)
2648 if not silent:
2647 if not silent:
2649 self.logger.log(cell, raw_cell)
2648 self.logger.log(cell, raw_cell)
2650
2649
2651 # Display the exception if input processing failed.
2650 # Display the exception if input processing failed.
2652 if preprocessing_exc_tuple is not None:
2651 if preprocessing_exc_tuple is not None:
2653 self.showtraceback(preprocessing_exc_tuple)
2652 self.showtraceback(preprocessing_exc_tuple)
2654 if store_history:
2653 if store_history:
2655 self.execution_count += 1
2654 self.execution_count += 1
2656 return error_before_exec(preprocessing_exc_tuple[2])
2655 return error_before_exec(preprocessing_exc_tuple[2])
2657
2656
2658 # Our own compiler remembers the __future__ environment. If we want to
2657 # Our own compiler remembers the __future__ environment. If we want to
2659 # run code with a separate __future__ environment, use the default
2658 # run code with a separate __future__ environment, use the default
2660 # compiler
2659 # compiler
2661 compiler = self.compile if shell_futures else CachingCompiler()
2660 compiler = self.compile if shell_futures else CachingCompiler()
2662
2661
2663 with self.builtin_trap:
2662 with self.builtin_trap:
2664 cell_name = self.compile.cache(cell, self.execution_count)
2663 cell_name = self.compile.cache(cell, self.execution_count)
2665
2664
2666 with self.display_trap:
2665 with self.display_trap:
2667 # Compile to bytecode
2666 # Compile to bytecode
2668 try:
2667 try:
2669 code_ast = compiler.ast_parse(cell, filename=cell_name)
2668 code_ast = compiler.ast_parse(cell, filename=cell_name)
2670 except self.custom_exceptions as e:
2669 except self.custom_exceptions as e:
2671 etype, value, tb = sys.exc_info()
2670 etype, value, tb = sys.exc_info()
2672 self.CustomTB(etype, value, tb)
2671 self.CustomTB(etype, value, tb)
2673 return error_before_exec(e)
2672 return error_before_exec(e)
2674 except IndentationError as e:
2673 except IndentationError as e:
2675 self.showindentationerror()
2674 self.showindentationerror()
2676 if store_history:
2675 if store_history:
2677 self.execution_count += 1
2676 self.execution_count += 1
2678 return error_before_exec(e)
2677 return error_before_exec(e)
2679 except (OverflowError, SyntaxError, ValueError, TypeError,
2678 except (OverflowError, SyntaxError, ValueError, TypeError,
2680 MemoryError) as e:
2679 MemoryError) as e:
2681 self.showsyntaxerror()
2680 self.showsyntaxerror()
2682 if store_history:
2681 if store_history:
2683 self.execution_count += 1
2682 self.execution_count += 1
2684 return error_before_exec(e)
2683 return error_before_exec(e)
2685
2684
2686 # Apply AST transformations
2685 # Apply AST transformations
2687 try:
2686 try:
2688 code_ast = self.transform_ast(code_ast)
2687 code_ast = self.transform_ast(code_ast)
2689 except InputRejected as e:
2688 except InputRejected as e:
2690 self.showtraceback()
2689 self.showtraceback()
2691 if store_history:
2690 if store_history:
2692 self.execution_count += 1
2691 self.execution_count += 1
2693 return error_before_exec(e)
2692 return error_before_exec(e)
2694
2693
2695 # Give the displayhook a reference to our ExecutionResult so it
2694 # Give the displayhook a reference to our ExecutionResult so it
2696 # can fill in the output value.
2695 # can fill in the output value.
2697 self.displayhook.exec_result = result
2696 self.displayhook.exec_result = result
2698
2697
2699 # Execute the user code
2698 # Execute the user code
2700 interactivity = "none" if silent else self.ast_node_interactivity
2699 interactivity = "none" if silent else self.ast_node_interactivity
2701 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2700 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2702 interactivity=interactivity, compiler=compiler, result=result)
2701 interactivity=interactivity, compiler=compiler, result=result)
2703
2702
2704 self.last_execution_succeeded = not has_raised
2703 self.last_execution_succeeded = not has_raised
2705
2704
2706 # Reset this so later displayed values do not modify the
2705 # Reset this so later displayed values do not modify the
2707 # ExecutionResult
2706 # ExecutionResult
2708 self.displayhook.exec_result = None
2707 self.displayhook.exec_result = None
2709
2708
2710 self.events.trigger('post_execute')
2709 self.events.trigger('post_execute')
2711 if not silent:
2710 if not silent:
2712 self.events.trigger('post_run_cell')
2711 self.events.trigger('post_run_cell')
2713
2712
2714 if store_history:
2713 if store_history:
2715 # Write output to the database. Does nothing unless
2714 # Write output to the database. Does nothing unless
2716 # history output logging is enabled.
2715 # history output logging is enabled.
2717 self.history_manager.store_output(self.execution_count)
2716 self.history_manager.store_output(self.execution_count)
2718 # Each cell is a *single* input, regardless of how many lines it has
2717 # Each cell is a *single* input, regardless of how many lines it has
2719 self.execution_count += 1
2718 self.execution_count += 1
2720
2719
2721 return result
2720 return result
2722
2721
2723 def transform_ast(self, node):
2722 def transform_ast(self, node):
2724 """Apply the AST transformations from self.ast_transformers
2723 """Apply the AST transformations from self.ast_transformers
2725
2724
2726 Parameters
2725 Parameters
2727 ----------
2726 ----------
2728 node : ast.Node
2727 node : ast.Node
2729 The root node to be transformed. Typically called with the ast.Module
2728 The root node to be transformed. Typically called with the ast.Module
2730 produced by parsing user input.
2729 produced by parsing user input.
2731
2730
2732 Returns
2731 Returns
2733 -------
2732 -------
2734 An ast.Node corresponding to the node it was called with. Note that it
2733 An ast.Node corresponding to the node it was called with. Note that it
2735 may also modify the passed object, so don't rely on references to the
2734 may also modify the passed object, so don't rely on references to the
2736 original AST.
2735 original AST.
2737 """
2736 """
2738 for transformer in self.ast_transformers:
2737 for transformer in self.ast_transformers:
2739 try:
2738 try:
2740 node = transformer.visit(node)
2739 node = transformer.visit(node)
2741 except InputRejected:
2740 except InputRejected:
2742 # User-supplied AST transformers can reject an input by raising
2741 # User-supplied AST transformers can reject an input by raising
2743 # an InputRejected. Short-circuit in this case so that we
2742 # an InputRejected. Short-circuit in this case so that we
2744 # don't unregister the transform.
2743 # don't unregister the transform.
2745 raise
2744 raise
2746 except Exception:
2745 except Exception:
2747 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2746 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2748 self.ast_transformers.remove(transformer)
2747 self.ast_transformers.remove(transformer)
2749
2748
2750 if self.ast_transformers:
2749 if self.ast_transformers:
2751 ast.fix_missing_locations(node)
2750 ast.fix_missing_locations(node)
2752 return node
2751 return node
2753
2752
2754
2753
2755 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2754 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2756 compiler=compile, result=None):
2755 compiler=compile, result=None):
2757 """Run a sequence of AST nodes. The execution mode depends on the
2756 """Run a sequence of AST nodes. The execution mode depends on the
2758 interactivity parameter.
2757 interactivity parameter.
2759
2758
2760 Parameters
2759 Parameters
2761 ----------
2760 ----------
2762 nodelist : list
2761 nodelist : list
2763 A sequence of AST nodes to run.
2762 A sequence of AST nodes to run.
2764 cell_name : str
2763 cell_name : str
2765 Will be passed to the compiler as the filename of the cell. Typically
2764 Will be passed to the compiler as the filename of the cell. Typically
2766 the value returned by ip.compile.cache(cell).
2765 the value returned by ip.compile.cache(cell).
2767 interactivity : str
2766 interactivity : str
2768 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2767 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2769 run interactively (displaying output from expressions). 'last_expr'
2768 run interactively (displaying output from expressions). 'last_expr'
2770 will run the last node interactively only if it is an expression (i.e.
2769 will run the last node interactively only if it is an expression (i.e.
2771 expressions in loops or other blocks are not displayed. Other values
2770 expressions in loops or other blocks are not displayed. Other values
2772 for this parameter will raise a ValueError.
2771 for this parameter will raise a ValueError.
2773 compiler : callable
2772 compiler : callable
2774 A function with the same interface as the built-in compile(), to turn
2773 A function with the same interface as the built-in compile(), to turn
2775 the AST nodes into code objects. Default is the built-in compile().
2774 the AST nodes into code objects. Default is the built-in compile().
2776 result : ExecutionResult, optional
2775 result : ExecutionResult, optional
2777 An object to store exceptions that occur during execution.
2776 An object to store exceptions that occur during execution.
2778
2777
2779 Returns
2778 Returns
2780 -------
2779 -------
2781 True if an exception occurred while running code, False if it finished
2780 True if an exception occurred while running code, False if it finished
2782 running.
2781 running.
2783 """
2782 """
2784 if not nodelist:
2783 if not nodelist:
2785 return
2784 return
2786
2785
2787 if interactivity == 'last_expr':
2786 if interactivity == 'last_expr':
2788 if isinstance(nodelist[-1], ast.Expr):
2787 if isinstance(nodelist[-1], ast.Expr):
2789 interactivity = "last"
2788 interactivity = "last"
2790 else:
2789 else:
2791 interactivity = "none"
2790 interactivity = "none"
2792
2791
2793 if interactivity == 'none':
2792 if interactivity == 'none':
2794 to_run_exec, to_run_interactive = nodelist, []
2793 to_run_exec, to_run_interactive = nodelist, []
2795 elif interactivity == 'last':
2794 elif interactivity == 'last':
2796 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2795 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2797 elif interactivity == 'all':
2796 elif interactivity == 'all':
2798 to_run_exec, to_run_interactive = [], nodelist
2797 to_run_exec, to_run_interactive = [], nodelist
2799 else:
2798 else:
2800 raise ValueError("Interactivity was %r" % interactivity)
2799 raise ValueError("Interactivity was %r" % interactivity)
2801
2800
2802 try:
2801 try:
2803 for i, node in enumerate(to_run_exec):
2802 for i, node in enumerate(to_run_exec):
2804 mod = ast.Module([node])
2803 mod = ast.Module([node])
2805 code = compiler(mod, cell_name, "exec")
2804 code = compiler(mod, cell_name, "exec")
2806 if self.run_code(code, result):
2805 if self.run_code(code, result):
2807 return True
2806 return True
2808
2807
2809 for i, node in enumerate(to_run_interactive):
2808 for i, node in enumerate(to_run_interactive):
2810 mod = ast.Interactive([node])
2809 mod = ast.Interactive([node])
2811 code = compiler(mod, cell_name, "single")
2810 code = compiler(mod, cell_name, "single")
2812 if self.run_code(code, result):
2811 if self.run_code(code, result):
2813 return True
2812 return True
2814
2813
2815 # Flush softspace
2814 # Flush softspace
2816 if softspace(sys.stdout, 0):
2815 if softspace(sys.stdout, 0):
2817 print()
2816 print()
2818
2817
2819 except:
2818 except:
2820 # It's possible to have exceptions raised here, typically by
2819 # It's possible to have exceptions raised here, typically by
2821 # compilation of odd code (such as a naked 'return' outside a
2820 # compilation of odd code (such as a naked 'return' outside a
2822 # function) that did parse but isn't valid. Typically the exception
2821 # function) that did parse but isn't valid. Typically the exception
2823 # is a SyntaxError, but it's safest just to catch anything and show
2822 # is a SyntaxError, but it's safest just to catch anything and show
2824 # the user a traceback.
2823 # the user a traceback.
2825
2824
2826 # We do only one try/except outside the loop to minimize the impact
2825 # We do only one try/except outside the loop to minimize the impact
2827 # on runtime, and also because if any node in the node list is
2826 # on runtime, and also because if any node in the node list is
2828 # broken, we should stop execution completely.
2827 # broken, we should stop execution completely.
2829 if result:
2828 if result:
2830 result.error_before_exec = sys.exc_info()[1]
2829 result.error_before_exec = sys.exc_info()[1]
2831 self.showtraceback()
2830 self.showtraceback()
2832 return True
2831 return True
2833
2832
2834 return False
2833 return False
2835
2834
2836 def run_code(self, code_obj, result=None):
2835 def run_code(self, code_obj, result=None):
2837 """Execute a code object.
2836 """Execute a code object.
2838
2837
2839 When an exception occurs, self.showtraceback() is called to display a
2838 When an exception occurs, self.showtraceback() is called to display a
2840 traceback.
2839 traceback.
2841
2840
2842 Parameters
2841 Parameters
2843 ----------
2842 ----------
2844 code_obj : code object
2843 code_obj : code object
2845 A compiled code object, to be executed
2844 A compiled code object, to be executed
2846 result : ExecutionResult, optional
2845 result : ExecutionResult, optional
2847 An object to store exceptions that occur during execution.
2846 An object to store exceptions that occur during execution.
2848
2847
2849 Returns
2848 Returns
2850 -------
2849 -------
2851 False : successful execution.
2850 False : successful execution.
2852 True : an error occurred.
2851 True : an error occurred.
2853 """
2852 """
2854 # Set our own excepthook in case the user code tries to call it
2853 # Set our own excepthook in case the user code tries to call it
2855 # directly, so that the IPython crash handler doesn't get triggered
2854 # directly, so that the IPython crash handler doesn't get triggered
2856 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2855 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2857
2856
2858 # we save the original sys.excepthook in the instance, in case config
2857 # we save the original sys.excepthook in the instance, in case config
2859 # code (such as magics) needs access to it.
2858 # code (such as magics) needs access to it.
2860 self.sys_excepthook = old_excepthook
2859 self.sys_excepthook = old_excepthook
2861 outflag = 1 # happens in more places, so it's easier as default
2860 outflag = 1 # happens in more places, so it's easier as default
2862 try:
2861 try:
2863 try:
2862 try:
2864 self.hooks.pre_run_code_hook()
2863 self.hooks.pre_run_code_hook()
2865 #rprint('Running code', repr(code_obj)) # dbg
2864 #rprint('Running code', repr(code_obj)) # dbg
2866 exec(code_obj, self.user_global_ns, self.user_ns)
2865 exec(code_obj, self.user_global_ns, self.user_ns)
2867 finally:
2866 finally:
2868 # Reset our crash handler in place
2867 # Reset our crash handler in place
2869 sys.excepthook = old_excepthook
2868 sys.excepthook = old_excepthook
2870 except SystemExit as e:
2869 except SystemExit as e:
2871 if result is not None:
2870 if result is not None:
2872 result.error_in_exec = e
2871 result.error_in_exec = e
2873 self.showtraceback(exception_only=True)
2872 self.showtraceback(exception_only=True)
2874 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
2873 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
2875 except self.custom_exceptions:
2874 except self.custom_exceptions:
2876 etype, value, tb = sys.exc_info()
2875 etype, value, tb = sys.exc_info()
2877 if result is not None:
2876 if result is not None:
2878 result.error_in_exec = value
2877 result.error_in_exec = value
2879 self.CustomTB(etype, value, tb)
2878 self.CustomTB(etype, value, tb)
2880 except:
2879 except:
2881 if result is not None:
2880 if result is not None:
2882 result.error_in_exec = sys.exc_info()[1]
2881 result.error_in_exec = sys.exc_info()[1]
2883 self.showtraceback()
2882 self.showtraceback()
2884 else:
2883 else:
2885 outflag = 0
2884 outflag = 0
2886 return outflag
2885 return outflag
2887
2886
2888 # For backwards compatibility
2887 # For backwards compatibility
2889 runcode = run_code
2888 runcode = run_code
2890
2889
2891 #-------------------------------------------------------------------------
2890 #-------------------------------------------------------------------------
2892 # Things related to GUI support and pylab
2891 # Things related to GUI support and pylab
2893 #-------------------------------------------------------------------------
2892 #-------------------------------------------------------------------------
2894
2893
2895 def enable_gui(self, gui=None):
2894 def enable_gui(self, gui=None):
2896 raise NotImplementedError('Implement enable_gui in a subclass')
2895 raise NotImplementedError('Implement enable_gui in a subclass')
2897
2896
2898 def enable_matplotlib(self, gui=None):
2897 def enable_matplotlib(self, gui=None):
2899 """Enable interactive matplotlib and inline figure support.
2898 """Enable interactive matplotlib and inline figure support.
2900
2899
2901 This takes the following steps:
2900 This takes the following steps:
2902
2901
2903 1. select the appropriate eventloop and matplotlib backend
2902 1. select the appropriate eventloop and matplotlib backend
2904 2. set up matplotlib for interactive use with that backend
2903 2. set up matplotlib for interactive use with that backend
2905 3. configure formatters for inline figure display
2904 3. configure formatters for inline figure display
2906 4. enable the selected gui eventloop
2905 4. enable the selected gui eventloop
2907
2906
2908 Parameters
2907 Parameters
2909 ----------
2908 ----------
2910 gui : optional, string
2909 gui : optional, string
2911 If given, dictates the choice of matplotlib GUI backend to use
2910 If given, dictates the choice of matplotlib GUI backend to use
2912 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2911 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2913 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2912 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2914 matplotlib (as dictated by the matplotlib build-time options plus the
2913 matplotlib (as dictated by the matplotlib build-time options plus the
2915 user's matplotlibrc configuration file). Note that not all backends
2914 user's matplotlibrc configuration file). Note that not all backends
2916 make sense in all contexts, for example a terminal ipython can't
2915 make sense in all contexts, for example a terminal ipython can't
2917 display figures inline.
2916 display figures inline.
2918 """
2917 """
2919 from IPython.core import pylabtools as pt
2918 from IPython.core import pylabtools as pt
2920 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2919 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2921
2920
2922 if gui != 'inline':
2921 if gui != 'inline':
2923 # If we have our first gui selection, store it
2922 # If we have our first gui selection, store it
2924 if self.pylab_gui_select is None:
2923 if self.pylab_gui_select is None:
2925 self.pylab_gui_select = gui
2924 self.pylab_gui_select = gui
2926 # Otherwise if they are different
2925 # Otherwise if they are different
2927 elif gui != self.pylab_gui_select:
2926 elif gui != self.pylab_gui_select:
2928 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2927 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2929 ' Using %s instead.' % (gui, self.pylab_gui_select))
2928 ' Using %s instead.' % (gui, self.pylab_gui_select))
2930 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2929 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2931
2930
2932 pt.activate_matplotlib(backend)
2931 pt.activate_matplotlib(backend)
2933 pt.configure_inline_support(self, backend)
2932 pt.configure_inline_support(self, backend)
2934
2933
2935 # Now we must activate the gui pylab wants to use, and fix %run to take
2934 # Now we must activate the gui pylab wants to use, and fix %run to take
2936 # plot updates into account
2935 # plot updates into account
2937 self.enable_gui(gui)
2936 self.enable_gui(gui)
2938 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2937 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2939 pt.mpl_runner(self.safe_execfile)
2938 pt.mpl_runner(self.safe_execfile)
2940
2939
2941 return gui, backend
2940 return gui, backend
2942
2941
2943 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2942 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2944 """Activate pylab support at runtime.
2943 """Activate pylab support at runtime.
2945
2944
2946 This turns on support for matplotlib, preloads into the interactive
2945 This turns on support for matplotlib, preloads into the interactive
2947 namespace all of numpy and pylab, and configures IPython to correctly
2946 namespace all of numpy and pylab, and configures IPython to correctly
2948 interact with the GUI event loop. The GUI backend to be used can be
2947 interact with the GUI event loop. The GUI backend to be used can be
2949 optionally selected with the optional ``gui`` argument.
2948 optionally selected with the optional ``gui`` argument.
2950
2949
2951 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2950 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2952
2951
2953 Parameters
2952 Parameters
2954 ----------
2953 ----------
2955 gui : optional, string
2954 gui : optional, string
2956 If given, dictates the choice of matplotlib GUI backend to use
2955 If given, dictates the choice of matplotlib GUI backend to use
2957 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2956 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2958 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2957 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2959 matplotlib (as dictated by the matplotlib build-time options plus the
2958 matplotlib (as dictated by the matplotlib build-time options plus the
2960 user's matplotlibrc configuration file). Note that not all backends
2959 user's matplotlibrc configuration file). Note that not all backends
2961 make sense in all contexts, for example a terminal ipython can't
2960 make sense in all contexts, for example a terminal ipython can't
2962 display figures inline.
2961 display figures inline.
2963 import_all : optional, bool, default: True
2962 import_all : optional, bool, default: True
2964 Whether to do `from numpy import *` and `from pylab import *`
2963 Whether to do `from numpy import *` and `from pylab import *`
2965 in addition to module imports.
2964 in addition to module imports.
2966 welcome_message : deprecated
2965 welcome_message : deprecated
2967 This argument is ignored, no welcome message will be displayed.
2966 This argument is ignored, no welcome message will be displayed.
2968 """
2967 """
2969 from IPython.core.pylabtools import import_pylab
2968 from IPython.core.pylabtools import import_pylab
2970
2969
2971 gui, backend = self.enable_matplotlib(gui)
2970 gui, backend = self.enable_matplotlib(gui)
2972
2971
2973 # We want to prevent the loading of pylab to pollute the user's
2972 # We want to prevent the loading of pylab to pollute the user's
2974 # namespace as shown by the %who* magics, so we execute the activation
2973 # namespace as shown by the %who* magics, so we execute the activation
2975 # code in an empty namespace, and we update *both* user_ns and
2974 # code in an empty namespace, and we update *both* user_ns and
2976 # user_ns_hidden with this information.
2975 # user_ns_hidden with this information.
2977 ns = {}
2976 ns = {}
2978 import_pylab(ns, import_all)
2977 import_pylab(ns, import_all)
2979 # warn about clobbered names
2978 # warn about clobbered names
2980 ignored = {"__builtins__"}
2979 ignored = {"__builtins__"}
2981 both = set(ns).intersection(self.user_ns).difference(ignored)
2980 both = set(ns).intersection(self.user_ns).difference(ignored)
2982 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2981 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2983 self.user_ns.update(ns)
2982 self.user_ns.update(ns)
2984 self.user_ns_hidden.update(ns)
2983 self.user_ns_hidden.update(ns)
2985 return gui, backend, clobbered
2984 return gui, backend, clobbered
2986
2985
2987 #-------------------------------------------------------------------------
2986 #-------------------------------------------------------------------------
2988 # Utilities
2987 # Utilities
2989 #-------------------------------------------------------------------------
2988 #-------------------------------------------------------------------------
2990
2989
2991 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2990 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2992 """Expand python variables in a string.
2991 """Expand python variables in a string.
2993
2992
2994 The depth argument indicates how many frames above the caller should
2993 The depth argument indicates how many frames above the caller should
2995 be walked to look for the local namespace where to expand variables.
2994 be walked to look for the local namespace where to expand variables.
2996
2995
2997 The global namespace for expansion is always the user's interactive
2996 The global namespace for expansion is always the user's interactive
2998 namespace.
2997 namespace.
2999 """
2998 """
3000 ns = self.user_ns.copy()
2999 ns = self.user_ns.copy()
3001 try:
3000 try:
3002 frame = sys._getframe(depth+1)
3001 frame = sys._getframe(depth+1)
3003 except ValueError:
3002 except ValueError:
3004 # This is thrown if there aren't that many frames on the stack,
3003 # This is thrown if there aren't that many frames on the stack,
3005 # e.g. if a script called run_line_magic() directly.
3004 # e.g. if a script called run_line_magic() directly.
3006 pass
3005 pass
3007 else:
3006 else:
3008 ns.update(frame.f_locals)
3007 ns.update(frame.f_locals)
3009
3008
3010 try:
3009 try:
3011 # We have to use .vformat() here, because 'self' is a valid and common
3010 # We have to use .vformat() here, because 'self' is a valid and common
3012 # name, and expanding **ns for .format() would make it collide with
3011 # name, and expanding **ns for .format() would make it collide with
3013 # the 'self' argument of the method.
3012 # the 'self' argument of the method.
3014 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3013 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3015 except Exception:
3014 except Exception:
3016 # if formatter couldn't format, just let it go untransformed
3015 # if formatter couldn't format, just let it go untransformed
3017 pass
3016 pass
3018 return cmd
3017 return cmd
3019
3018
3020 def mktempfile(self, data=None, prefix='ipython_edit_'):
3019 def mktempfile(self, data=None, prefix='ipython_edit_'):
3021 """Make a new tempfile and return its filename.
3020 """Make a new tempfile and return its filename.
3022
3021
3023 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3022 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3024 but it registers the created filename internally so ipython cleans it up
3023 but it registers the created filename internally so ipython cleans it up
3025 at exit time.
3024 at exit time.
3026
3025
3027 Optional inputs:
3026 Optional inputs:
3028
3027
3029 - data(None): if data is given, it gets written out to the temp file
3028 - data(None): if data is given, it gets written out to the temp file
3030 immediately, and the file is closed again."""
3029 immediately, and the file is closed again."""
3031
3030
3032 dirname = tempfile.mkdtemp(prefix=prefix)
3031 dirname = tempfile.mkdtemp(prefix=prefix)
3033 self.tempdirs.append(dirname)
3032 self.tempdirs.append(dirname)
3034
3033
3035 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3034 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3036 os.close(handle) # On Windows, there can only be one open handle on a file
3035 os.close(handle) # On Windows, there can only be one open handle on a file
3037 self.tempfiles.append(filename)
3036 self.tempfiles.append(filename)
3038
3037
3039 if data:
3038 if data:
3040 tmp_file = open(filename,'w')
3039 tmp_file = open(filename,'w')
3041 tmp_file.write(data)
3040 tmp_file.write(data)
3042 tmp_file.close()
3041 tmp_file.close()
3043 return filename
3042 return filename
3044
3043
3045 @undoc
3044 @undoc
3046 def write(self,data):
3045 def write(self,data):
3047 """DEPRECATED: Write a string to the default output"""
3046 """DEPRECATED: Write a string to the default output"""
3048 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3047 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3049 DeprecationWarning, stacklevel=2)
3048 DeprecationWarning, stacklevel=2)
3050 sys.stdout.write(data)
3049 sys.stdout.write(data)
3051
3050
3052 @undoc
3051 @undoc
3053 def write_err(self,data):
3052 def write_err(self,data):
3054 """DEPRECATED: Write a string to the default error output"""
3053 """DEPRECATED: Write a string to the default error output"""
3055 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3054 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3056 DeprecationWarning, stacklevel=2)
3055 DeprecationWarning, stacklevel=2)
3057 sys.stderr.write(data)
3056 sys.stderr.write(data)
3058
3057
3059 def ask_yes_no(self, prompt, default=None, interrupt=None):
3058 def ask_yes_no(self, prompt, default=None, interrupt=None):
3060 if self.quiet:
3059 if self.quiet:
3061 return True
3060 return True
3062 return ask_yes_no(prompt,default,interrupt)
3061 return ask_yes_no(prompt,default,interrupt)
3063
3062
3064 def show_usage(self):
3063 def show_usage(self):
3065 """Show a usage message"""
3064 """Show a usage message"""
3066 page.page(IPython.core.usage.interactive_usage)
3065 page.page(IPython.core.usage.interactive_usage)
3067
3066
3068 def extract_input_lines(self, range_str, raw=False):
3067 def extract_input_lines(self, range_str, raw=False):
3069 """Return as a string a set of input history slices.
3068 """Return as a string a set of input history slices.
3070
3069
3071 Parameters
3070 Parameters
3072 ----------
3071 ----------
3073 range_str : string
3072 range_str : string
3074 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3073 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3075 since this function is for use by magic functions which get their
3074 since this function is for use by magic functions which get their
3076 arguments as strings. The number before the / is the session
3075 arguments as strings. The number before the / is the session
3077 number: ~n goes n back from the current session.
3076 number: ~n goes n back from the current session.
3078
3077
3079 raw : bool, optional
3078 raw : bool, optional
3080 By default, the processed input is used. If this is true, the raw
3079 By default, the processed input is used. If this is true, the raw
3081 input history is used instead.
3080 input history is used instead.
3082
3081
3083 Notes
3082 Notes
3084 -----
3083 -----
3085
3084
3086 Slices can be described with two notations:
3085 Slices can be described with two notations:
3087
3086
3088 * ``N:M`` -> standard python form, means including items N...(M-1).
3087 * ``N:M`` -> standard python form, means including items N...(M-1).
3089 * ``N-M`` -> include items N..M (closed endpoint).
3088 * ``N-M`` -> include items N..M (closed endpoint).
3090 """
3089 """
3091 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3090 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3092 return "\n".join(x for _, _, x in lines)
3091 return "\n".join(x for _, _, x in lines)
3093
3092
3094 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3093 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3095 """Get a code string from history, file, url, or a string or macro.
3094 """Get a code string from history, file, url, or a string or macro.
3096
3095
3097 This is mainly used by magic functions.
3096 This is mainly used by magic functions.
3098
3097
3099 Parameters
3098 Parameters
3100 ----------
3099 ----------
3101
3100
3102 target : str
3101 target : str
3103
3102
3104 A string specifying code to retrieve. This will be tried respectively
3103 A string specifying code to retrieve. This will be tried respectively
3105 as: ranges of input history (see %history for syntax), url,
3104 as: ranges of input history (see %history for syntax), url,
3106 corresponding .py file, filename, or an expression evaluating to a
3105 corresponding .py file, filename, or an expression evaluating to a
3107 string or Macro in the user namespace.
3106 string or Macro in the user namespace.
3108
3107
3109 raw : bool
3108 raw : bool
3110 If true (default), retrieve raw history. Has no effect on the other
3109 If true (default), retrieve raw history. Has no effect on the other
3111 retrieval mechanisms.
3110 retrieval mechanisms.
3112
3111
3113 py_only : bool (default False)
3112 py_only : bool (default False)
3114 Only try to fetch python code, do not try alternative methods to decode file
3113 Only try to fetch python code, do not try alternative methods to decode file
3115 if unicode fails.
3114 if unicode fails.
3116
3115
3117 Returns
3116 Returns
3118 -------
3117 -------
3119 A string of code.
3118 A string of code.
3120
3119
3121 ValueError is raised if nothing is found, and TypeError if it evaluates
3120 ValueError is raised if nothing is found, and TypeError if it evaluates
3122 to an object of another type. In each case, .args[0] is a printable
3121 to an object of another type. In each case, .args[0] is a printable
3123 message.
3122 message.
3124 """
3123 """
3125 code = self.extract_input_lines(target, raw=raw) # Grab history
3124 code = self.extract_input_lines(target, raw=raw) # Grab history
3126 if code:
3125 if code:
3127 return code
3126 return code
3128 try:
3127 try:
3129 if target.startswith(('http://', 'https://')):
3128 if target.startswith(('http://', 'https://')):
3130 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3129 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3131 except UnicodeDecodeError:
3130 except UnicodeDecodeError:
3132 if not py_only :
3131 if not py_only :
3133 # Deferred import
3132 # Deferred import
3134 try:
3133 try:
3135 from urllib.request import urlopen # Py3
3134 from urllib.request import urlopen # Py3
3136 except ImportError:
3135 except ImportError:
3137 from urllib import urlopen
3136 from urllib import urlopen
3138 response = urlopen(target)
3137 response = urlopen(target)
3139 return response.read().decode('latin1')
3138 return response.read().decode('latin1')
3140 raise ValueError(("'%s' seem to be unreadable.") % target)
3139 raise ValueError(("'%s' seem to be unreadable.") % target)
3141
3140
3142 potential_target = [target]
3141 potential_target = [target]
3143 try :
3142 try :
3144 potential_target.insert(0,get_py_filename(target))
3143 potential_target.insert(0,get_py_filename(target))
3145 except IOError:
3144 except IOError:
3146 pass
3145 pass
3147
3146
3148 for tgt in potential_target :
3147 for tgt in potential_target :
3149 if os.path.isfile(tgt): # Read file
3148 if os.path.isfile(tgt): # Read file
3150 try :
3149 try :
3151 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3150 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3152 except UnicodeDecodeError :
3151 except UnicodeDecodeError :
3153 if not py_only :
3152 if not py_only :
3154 with io_open(tgt,'r', encoding='latin1') as f :
3153 with io_open(tgt,'r', encoding='latin1') as f :
3155 return f.read()
3154 return f.read()
3156 raise ValueError(("'%s' seem to be unreadable.") % target)
3155 raise ValueError(("'%s' seem to be unreadable.") % target)
3157 elif os.path.isdir(os.path.expanduser(tgt)):
3156 elif os.path.isdir(os.path.expanduser(tgt)):
3158 raise ValueError("'%s' is a directory, not a regular file." % target)
3157 raise ValueError("'%s' is a directory, not a regular file." % target)
3159
3158
3160 if search_ns:
3159 if search_ns:
3161 # Inspect namespace to load object source
3160 # Inspect namespace to load object source
3162 object_info = self.object_inspect(target, detail_level=1)
3161 object_info = self.object_inspect(target, detail_level=1)
3163 if object_info['found'] and object_info['source']:
3162 if object_info['found'] and object_info['source']:
3164 return object_info['source']
3163 return object_info['source']
3165
3164
3166 try: # User namespace
3165 try: # User namespace
3167 codeobj = eval(target, self.user_ns)
3166 codeobj = eval(target, self.user_ns)
3168 except Exception:
3167 except Exception:
3169 raise ValueError(("'%s' was not found in history, as a file, url, "
3168 raise ValueError(("'%s' was not found in history, as a file, url, "
3170 "nor in the user namespace.") % target)
3169 "nor in the user namespace.") % target)
3171
3170
3172 if isinstance(codeobj, string_types):
3171 if isinstance(codeobj, string_types):
3173 return codeobj
3172 return codeobj
3174 elif isinstance(codeobj, Macro):
3173 elif isinstance(codeobj, Macro):
3175 return codeobj.value
3174 return codeobj.value
3176
3175
3177 raise TypeError("%s is neither a string nor a macro." % target,
3176 raise TypeError("%s is neither a string nor a macro." % target,
3178 codeobj)
3177 codeobj)
3179
3178
3180 #-------------------------------------------------------------------------
3179 #-------------------------------------------------------------------------
3181 # Things related to IPython exiting
3180 # Things related to IPython exiting
3182 #-------------------------------------------------------------------------
3181 #-------------------------------------------------------------------------
3183 def atexit_operations(self):
3182 def atexit_operations(self):
3184 """This will be executed at the time of exit.
3183 """This will be executed at the time of exit.
3185
3184
3186 Cleanup operations and saving of persistent data that is done
3185 Cleanup operations and saving of persistent data that is done
3187 unconditionally by IPython should be performed here.
3186 unconditionally by IPython should be performed here.
3188
3187
3189 For things that may depend on startup flags or platform specifics (such
3188 For things that may depend on startup flags or platform specifics (such
3190 as having readline or not), register a separate atexit function in the
3189 as having readline or not), register a separate atexit function in the
3191 code that has the appropriate information, rather than trying to
3190 code that has the appropriate information, rather than trying to
3192 clutter
3191 clutter
3193 """
3192 """
3194 # Close the history session (this stores the end time and line count)
3193 # Close the history session (this stores the end time and line count)
3195 # this must be *before* the tempfile cleanup, in case of temporary
3194 # this must be *before* the tempfile cleanup, in case of temporary
3196 # history db
3195 # history db
3197 self.history_manager.end_session()
3196 self.history_manager.end_session()
3198
3197
3199 # Cleanup all tempfiles and folders left around
3198 # Cleanup all tempfiles and folders left around
3200 for tfile in self.tempfiles:
3199 for tfile in self.tempfiles:
3201 try:
3200 try:
3202 os.unlink(tfile)
3201 os.unlink(tfile)
3203 except OSError:
3202 except OSError:
3204 pass
3203 pass
3205
3204
3206 for tdir in self.tempdirs:
3205 for tdir in self.tempdirs:
3207 try:
3206 try:
3208 os.rmdir(tdir)
3207 os.rmdir(tdir)
3209 except OSError:
3208 except OSError:
3210 pass
3209 pass
3211
3210
3212 # Clear all user namespaces to release all references cleanly.
3211 # Clear all user namespaces to release all references cleanly.
3213 self.reset(new_session=False)
3212 self.reset(new_session=False)
3214
3213
3215 # Run user hooks
3214 # Run user hooks
3216 self.hooks.shutdown_hook()
3215 self.hooks.shutdown_hook()
3217
3216
3218 def cleanup(self):
3217 def cleanup(self):
3219 self.restore_sys_module_state()
3218 self.restore_sys_module_state()
3220
3219
3221
3220
3222 # Overridden in terminal subclass to change prompts
3221 # Overridden in terminal subclass to change prompts
3223 def switch_doctest_mode(self, mode):
3222 def switch_doctest_mode(self, mode):
3224 pass
3223 pass
3225
3224
3226
3225
3227 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3226 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3228 """An abstract base class for InteractiveShell."""
3227 """An abstract base class for InteractiveShell."""
3229
3228
3230 InteractiveShellABC.register(InteractiveShell)
3229 InteractiveShellABC.register(InteractiveShell)
@@ -1,807 +1,806 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Tests for the IPython tab-completion machinery."""
2 """Tests for the IPython tab-completion machinery."""
3
3
4 # Copyright (c) IPython Development Team.
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
5 # Distributed under the terms of the Modified BSD License.
6
6
7 import os
7 import os
8 import sys
8 import sys
9 import unittest
9 import unittest
10
10
11 from contextlib import contextmanager
11 from contextlib import contextmanager
12
12
13 import nose.tools as nt
13 import nose.tools as nt
14
14
15 from traitlets.config.loader import Config
15 from traitlets.config.loader import Config
16 from IPython import get_ipython
16 from IPython import get_ipython
17 from IPython.core import completer
17 from IPython.core import completer
18 from IPython.external.decorators import knownfailureif
18 from IPython.external.decorators import knownfailureif
19 from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory
19 from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory
20 from IPython.utils.generics import complete_object
20 from IPython.utils.generics import complete_object
21 from IPython.utils.py3compat import string_types, unicode_type
21 from IPython.utils.py3compat import string_types, unicode_type
22 from IPython.testing import decorators as dec
22 from IPython.testing import decorators as dec
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Test functions
25 # Test functions
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 @contextmanager
28 @contextmanager
29 def greedy_completion():
29 def greedy_completion():
30 ip = get_ipython()
30 ip = get_ipython()
31 greedy_original = ip.Completer.greedy
31 greedy_original = ip.Completer.greedy
32 try:
32 try:
33 ip.Completer.greedy = True
33 ip.Completer.greedy = True
34 yield
34 yield
35 finally:
35 finally:
36 ip.Completer.greedy = greedy_original
36 ip.Completer.greedy = greedy_original
37
37
38 def test_protect_filename():
38 def test_protect_filename():
39 if sys.platform == 'win32':
39 if sys.platform == 'win32':
40 pairs = [('abc','abc'),
40 pairs = [('abc','abc'),
41 (' abc','" abc"'),
41 (' abc','" abc"'),
42 ('a bc','"a bc"'),
42 ('a bc','"a bc"'),
43 ('a bc','"a bc"'),
43 ('a bc','"a bc"'),
44 (' bc','" bc"'),
44 (' bc','" bc"'),
45 ]
45 ]
46 else:
46 else:
47 pairs = [('abc','abc'),
47 pairs = [('abc','abc'),
48 (' abc',r'\ abc'),
48 (' abc',r'\ abc'),
49 ('a bc',r'a\ bc'),
49 ('a bc',r'a\ bc'),
50 ('a bc',r'a\ \ bc'),
50 ('a bc',r'a\ \ bc'),
51 (' bc',r'\ \ bc'),
51 (' bc',r'\ \ bc'),
52 # On posix, we also protect parens and other special characters.
52 # On posix, we also protect parens and other special characters.
53 ('a(bc',r'a\(bc'),
53 ('a(bc',r'a\(bc'),
54 ('a)bc',r'a\)bc'),
54 ('a)bc',r'a\)bc'),
55 ('a( )bc',r'a\(\ \)bc'),
55 ('a( )bc',r'a\(\ \)bc'),
56 ('a[1]bc', r'a\[1\]bc'),
56 ('a[1]bc', r'a\[1\]bc'),
57 ('a{1}bc', r'a\{1\}bc'),
57 ('a{1}bc', r'a\{1\}bc'),
58 ('a#bc', r'a\#bc'),
58 ('a#bc', r'a\#bc'),
59 ('a?bc', r'a\?bc'),
59 ('a?bc', r'a\?bc'),
60 ('a=bc', r'a\=bc'),
60 ('a=bc', r'a\=bc'),
61 ('a\\bc', r'a\\bc'),
61 ('a\\bc', r'a\\bc'),
62 ('a|bc', r'a\|bc'),
62 ('a|bc', r'a\|bc'),
63 ('a;bc', r'a\;bc'),
63 ('a;bc', r'a\;bc'),
64 ('a:bc', r'a\:bc'),
64 ('a:bc', r'a\:bc'),
65 ("a'bc", r"a\'bc"),
65 ("a'bc", r"a\'bc"),
66 ('a*bc', r'a\*bc'),
66 ('a*bc', r'a\*bc'),
67 ('a"bc', r'a\"bc'),
67 ('a"bc', r'a\"bc'),
68 ('a^bc', r'a\^bc'),
68 ('a^bc', r'a\^bc'),
69 ('a&bc', r'a\&bc'),
69 ('a&bc', r'a\&bc'),
70 ]
70 ]
71 # run the actual tests
71 # run the actual tests
72 for s1, s2 in pairs:
72 for s1, s2 in pairs:
73 s1p = completer.protect_filename(s1)
73 s1p = completer.protect_filename(s1)
74 nt.assert_equal(s1p, s2)
74 nt.assert_equal(s1p, s2)
75
75
76
76
77 def check_line_split(splitter, test_specs):
77 def check_line_split(splitter, test_specs):
78 for part1, part2, split in test_specs:
78 for part1, part2, split in test_specs:
79 cursor_pos = len(part1)
79 cursor_pos = len(part1)
80 line = part1+part2
80 line = part1+part2
81 out = splitter.split_line(line, cursor_pos)
81 out = splitter.split_line(line, cursor_pos)
82 nt.assert_equal(out, split)
82 nt.assert_equal(out, split)
83
83
84
84
85 def test_line_split():
85 def test_line_split():
86 """Basic line splitter test with default specs."""
86 """Basic line splitter test with default specs."""
87 sp = completer.CompletionSplitter()
87 sp = completer.CompletionSplitter()
88 # The format of the test specs is: part1, part2, expected answer. Parts 1
88 # The format of the test specs is: part1, part2, expected answer. Parts 1
89 # and 2 are joined into the 'line' sent to the splitter, as if the cursor
89 # and 2 are joined into the 'line' sent to the splitter, as if the cursor
90 # was at the end of part1. So an empty part2 represents someone hitting
90 # was at the end of part1. So an empty part2 represents someone hitting
91 # tab at the end of the line, the most common case.
91 # tab at the end of the line, the most common case.
92 t = [('run some/scrip', '', 'some/scrip'),
92 t = [('run some/scrip', '', 'some/scrip'),
93 ('run scripts/er', 'ror.py foo', 'scripts/er'),
93 ('run scripts/er', 'ror.py foo', 'scripts/er'),
94 ('echo $HOM', '', 'HOM'),
94 ('echo $HOM', '', 'HOM'),
95 ('print sys.pa', '', 'sys.pa'),
95 ('print sys.pa', '', 'sys.pa'),
96 ('print(sys.pa', '', 'sys.pa'),
96 ('print(sys.pa', '', 'sys.pa'),
97 ("execfile('scripts/er", '', 'scripts/er'),
97 ("execfile('scripts/er", '', 'scripts/er'),
98 ('a[x.', '', 'x.'),
98 ('a[x.', '', 'x.'),
99 ('a[x.', 'y', 'x.'),
99 ('a[x.', 'y', 'x.'),
100 ('cd "some_file/', '', 'some_file/'),
100 ('cd "some_file/', '', 'some_file/'),
101 ]
101 ]
102 check_line_split(sp, t)
102 check_line_split(sp, t)
103 # Ensure splitting works OK with unicode by re-running the tests with
103 # Ensure splitting works OK with unicode by re-running the tests with
104 # all inputs turned into unicode
104 # all inputs turned into unicode
105 check_line_split(sp, [ map(unicode_type, p) for p in t] )
105 check_line_split(sp, [ map(unicode_type, p) for p in t] )
106
106
107
107
108 def test_custom_completion_error():
108 def test_custom_completion_error():
109 """Test that errors from custom attribute completers are silenced."""
109 """Test that errors from custom attribute completers are silenced."""
110 ip = get_ipython()
110 ip = get_ipython()
111 class A(object): pass
111 class A(object): pass
112 ip.user_ns['a'] = A()
112 ip.user_ns['a'] = A()
113
113
114 @complete_object.when_type(A)
114 @complete_object.when_type(A)
115 def complete_A(a, existing_completions):
115 def complete_A(a, existing_completions):
116 raise TypeError("this should be silenced")
116 raise TypeError("this should be silenced")
117
117
118 ip.complete("a.")
118 ip.complete("a.")
119
119
120
120
121 def test_unicode_completions():
121 def test_unicode_completions():
122 ip = get_ipython()
122 ip = get_ipython()
123 # Some strings that trigger different types of completion. Check them both
123 # Some strings that trigger different types of completion. Check them both
124 # in str and unicode forms
124 # in str and unicode forms
125 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
125 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
126 for t in s + list(map(unicode_type, s)):
126 for t in s + list(map(unicode_type, s)):
127 # We don't need to check exact completion values (they may change
127 # We don't need to check exact completion values (they may change
128 # depending on the state of the namespace, but at least no exceptions
128 # depending on the state of the namespace, but at least no exceptions
129 # should be thrown and the return value should be a pair of text, list
129 # should be thrown and the return value should be a pair of text, list
130 # values.
130 # values.
131 text, matches = ip.complete(t)
131 text, matches = ip.complete(t)
132 nt.assert_true(isinstance(text, string_types))
132 nt.assert_true(isinstance(text, string_types))
133 nt.assert_true(isinstance(matches, list))
133 nt.assert_true(isinstance(matches, list))
134
134
135 @dec.onlyif(sys.version_info[0] >= 3, 'This test only applies in Py>=3')
136 def test_latex_completions():
135 def test_latex_completions():
137 from IPython.core.latex_symbols import latex_symbols
136 from IPython.core.latex_symbols import latex_symbols
138 import random
137 import random
139 ip = get_ipython()
138 ip = get_ipython()
140 # Test some random unicode symbols
139 # Test some random unicode symbols
141 keys = random.sample(latex_symbols.keys(), 10)
140 keys = random.sample(latex_symbols.keys(), 10)
142 for k in keys:
141 for k in keys:
143 text, matches = ip.complete(k)
142 text, matches = ip.complete(k)
144 nt.assert_equal(len(matches),1)
143 nt.assert_equal(len(matches),1)
145 nt.assert_equal(text, k)
144 nt.assert_equal(text, k)
146 nt.assert_equal(matches[0], latex_symbols[k])
145 nt.assert_equal(matches[0], latex_symbols[k])
147 # Test a more complex line
146 # Test a more complex line
148 text, matches = ip.complete(u'print(\\alpha')
147 text, matches = ip.complete(u'print(\\alpha')
149 nt.assert_equals(text, u'\\alpha')
148 nt.assert_equals(text, u'\\alpha')
150 nt.assert_equals(matches[0], latex_symbols['\\alpha'])
149 nt.assert_equals(matches[0], latex_symbols['\\alpha'])
151 # Test multiple matching latex symbols
150 # Test multiple matching latex symbols
152 text, matches = ip.complete(u'\\al')
151 text, matches = ip.complete(u'\\al')
153 nt.assert_in('\\alpha', matches)
152 nt.assert_in('\\alpha', matches)
154 nt.assert_in('\\aleph', matches)
153 nt.assert_in('\\aleph', matches)
155
154
156
155
157
156
158
157
159 @dec.onlyif(sys.version_info[0] >= 3, 'This test only apply on python3')
158 @dec.onlyif(sys.version_info[0] >= 3, 'This test only apply on python3')
160 def test_back_latex_completion():
159 def test_back_latex_completion():
161 ip = get_ipython()
160 ip = get_ipython()
162
161
163 # do not return more than 1 matches fro \beta, only the latex one.
162 # do not return more than 1 matches fro \beta, only the latex one.
164 name, matches = ip.complete('\\Ξ²')
163 name, matches = ip.complete('\\Ξ²')
165 nt.assert_equal(len(matches), 1)
164 nt.assert_equal(len(matches), 1)
166 nt.assert_equal(matches[0], '\\beta')
165 nt.assert_equal(matches[0], '\\beta')
167
166
168 @dec.onlyif(sys.version_info[0] >= 3, 'This test only apply on python3')
167 @dec.onlyif(sys.version_info[0] >= 3, 'This test only apply on python3')
169 def test_back_unicode_completion():
168 def test_back_unicode_completion():
170 ip = get_ipython()
169 ip = get_ipython()
171
170
172 name, matches = ip.complete('\\β…€')
171 name, matches = ip.complete('\\β…€')
173 nt.assert_equal(len(matches), 1)
172 nt.assert_equal(len(matches), 1)
174 nt.assert_equal(matches[0], '\\ROMAN NUMERAL FIVE')
173 nt.assert_equal(matches[0], '\\ROMAN NUMERAL FIVE')
175
174
176
175
177 @dec.onlyif(sys.version_info[0] >= 3, 'This test only apply on python3')
176 @dec.onlyif(sys.version_info[0] >= 3, 'This test only apply on python3')
178 def test_forward_unicode_completion():
177 def test_forward_unicode_completion():
179 ip = get_ipython()
178 ip = get_ipython()
180
179
181 name, matches = ip.complete('\\ROMAN NUMERAL FIVE')
180 name, matches = ip.complete('\\ROMAN NUMERAL FIVE')
182 nt.assert_equal(len(matches), 1)
181 nt.assert_equal(len(matches), 1)
183 nt.assert_equal(matches[0], 'β…€')
182 nt.assert_equal(matches[0], 'β…€')
184
183
185 @dec.onlyif(sys.version_info[0] >= 3, 'This test only apply on python3')
184 @dec.onlyif(sys.version_info[0] >= 3, 'This test only apply on python3')
186 @dec.knownfailureif(sys.platform == 'win32', 'Fails if there is a C:\\j... path')
185 @dec.knownfailureif(sys.platform == 'win32', 'Fails if there is a C:\\j... path')
187 def test_no_ascii_back_completion():
186 def test_no_ascii_back_completion():
188 ip = get_ipython()
187 ip = get_ipython()
189 with TemporaryWorkingDirectory(): # Avoid any filename completions
188 with TemporaryWorkingDirectory(): # Avoid any filename completions
190 # single ascii letter that don't have yet completions
189 # single ascii letter that don't have yet completions
191 for letter in 'jJ' :
190 for letter in 'jJ' :
192 name, matches = ip.complete('\\'+letter)
191 name, matches = ip.complete('\\'+letter)
193 nt.assert_equal(matches, [])
192 nt.assert_equal(matches, [])
194
193
195
194
196
195
197
196
198 class CompletionSplitterTestCase(unittest.TestCase):
197 class CompletionSplitterTestCase(unittest.TestCase):
199 def setUp(self):
198 def setUp(self):
200 self.sp = completer.CompletionSplitter()
199 self.sp = completer.CompletionSplitter()
201
200
202 def test_delim_setting(self):
201 def test_delim_setting(self):
203 self.sp.delims = ' '
202 self.sp.delims = ' '
204 nt.assert_equal(self.sp.delims, ' ')
203 nt.assert_equal(self.sp.delims, ' ')
205 nt.assert_equal(self.sp._delim_expr, '[\ ]')
204 nt.assert_equal(self.sp._delim_expr, '[\ ]')
206
205
207 def test_spaces(self):
206 def test_spaces(self):
208 """Test with only spaces as split chars."""
207 """Test with only spaces as split chars."""
209 self.sp.delims = ' '
208 self.sp.delims = ' '
210 t = [('foo', '', 'foo'),
209 t = [('foo', '', 'foo'),
211 ('run foo', '', 'foo'),
210 ('run foo', '', 'foo'),
212 ('run foo', 'bar', 'foo'),
211 ('run foo', 'bar', 'foo'),
213 ]
212 ]
214 check_line_split(self.sp, t)
213 check_line_split(self.sp, t)
215
214
216
215
217 def test_has_open_quotes1():
216 def test_has_open_quotes1():
218 for s in ["'", "'''", "'hi' '"]:
217 for s in ["'", "'''", "'hi' '"]:
219 nt.assert_equal(completer.has_open_quotes(s), "'")
218 nt.assert_equal(completer.has_open_quotes(s), "'")
220
219
221
220
222 def test_has_open_quotes2():
221 def test_has_open_quotes2():
223 for s in ['"', '"""', '"hi" "']:
222 for s in ['"', '"""', '"hi" "']:
224 nt.assert_equal(completer.has_open_quotes(s), '"')
223 nt.assert_equal(completer.has_open_quotes(s), '"')
225
224
226
225
227 def test_has_open_quotes3():
226 def test_has_open_quotes3():
228 for s in ["''", "''' '''", "'hi' 'ipython'"]:
227 for s in ["''", "''' '''", "'hi' 'ipython'"]:
229 nt.assert_false(completer.has_open_quotes(s))
228 nt.assert_false(completer.has_open_quotes(s))
230
229
231
230
232 def test_has_open_quotes4():
231 def test_has_open_quotes4():
233 for s in ['""', '""" """', '"hi" "ipython"']:
232 for s in ['""', '""" """', '"hi" "ipython"']:
234 nt.assert_false(completer.has_open_quotes(s))
233 nt.assert_false(completer.has_open_quotes(s))
235
234
236
235
237 @knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows")
236 @knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows")
238 def test_abspath_file_completions():
237 def test_abspath_file_completions():
239 ip = get_ipython()
238 ip = get_ipython()
240 with TemporaryDirectory() as tmpdir:
239 with TemporaryDirectory() as tmpdir:
241 prefix = os.path.join(tmpdir, 'foo')
240 prefix = os.path.join(tmpdir, 'foo')
242 suffixes = ['1', '2']
241 suffixes = ['1', '2']
243 names = [prefix+s for s in suffixes]
242 names = [prefix+s for s in suffixes]
244 for n in names:
243 for n in names:
245 open(n, 'w').close()
244 open(n, 'w').close()
246
245
247 # Check simple completion
246 # Check simple completion
248 c = ip.complete(prefix)[1]
247 c = ip.complete(prefix)[1]
249 nt.assert_equal(c, names)
248 nt.assert_equal(c, names)
250
249
251 # Now check with a function call
250 # Now check with a function call
252 cmd = 'a = f("%s' % prefix
251 cmd = 'a = f("%s' % prefix
253 c = ip.complete(prefix, cmd)[1]
252 c = ip.complete(prefix, cmd)[1]
254 comp = [prefix+s for s in suffixes]
253 comp = [prefix+s for s in suffixes]
255 nt.assert_equal(c, comp)
254 nt.assert_equal(c, comp)
256
255
257
256
258 def test_local_file_completions():
257 def test_local_file_completions():
259 ip = get_ipython()
258 ip = get_ipython()
260 with TemporaryWorkingDirectory():
259 with TemporaryWorkingDirectory():
261 prefix = './foo'
260 prefix = './foo'
262 suffixes = ['1', '2']
261 suffixes = ['1', '2']
263 names = [prefix+s for s in suffixes]
262 names = [prefix+s for s in suffixes]
264 for n in names:
263 for n in names:
265 open(n, 'w').close()
264 open(n, 'w').close()
266
265
267 # Check simple completion
266 # Check simple completion
268 c = ip.complete(prefix)[1]
267 c = ip.complete(prefix)[1]
269 nt.assert_equal(c, names)
268 nt.assert_equal(c, names)
270
269
271 # Now check with a function call
270 # Now check with a function call
272 cmd = 'a = f("%s' % prefix
271 cmd = 'a = f("%s' % prefix
273 c = ip.complete(prefix, cmd)[1]
272 c = ip.complete(prefix, cmd)[1]
274 comp = set(prefix+s for s in suffixes)
273 comp = set(prefix+s for s in suffixes)
275 nt.assert_true(comp.issubset(set(c)))
274 nt.assert_true(comp.issubset(set(c)))
276
275
277
276
278 def test_greedy_completions():
277 def test_greedy_completions():
279 ip = get_ipython()
278 ip = get_ipython()
280 ip.ex('a=list(range(5))')
279 ip.ex('a=list(range(5))')
281 _,c = ip.complete('.',line='a[0].')
280 _,c = ip.complete('.',line='a[0].')
282 nt.assert_false('.real' in c,
281 nt.assert_false('.real' in c,
283 "Shouldn't have completed on a[0]: %s"%c)
282 "Shouldn't have completed on a[0]: %s"%c)
284 with greedy_completion():
283 with greedy_completion():
285 def _(line, cursor_pos, expect, message):
284 def _(line, cursor_pos, expect, message):
286 _,c = ip.complete('.', line=line, cursor_pos=cursor_pos)
285 _,c = ip.complete('.', line=line, cursor_pos=cursor_pos)
287 nt.assert_in(expect, c, message%c)
286 nt.assert_in(expect, c, message%c)
288
287
289 yield _, 'a[0].', 5, 'a[0].real', "Should have completed on a[0].: %s"
288 yield _, 'a[0].', 5, 'a[0].real', "Should have completed on a[0].: %s"
290 yield _, 'a[0].r', 6, 'a[0].real', "Should have completed on a[0].r: %s"
289 yield _, 'a[0].r', 6, 'a[0].real', "Should have completed on a[0].r: %s"
291
290
292 if sys.version_info > (3,4):
291 if sys.version_info > (3,4):
293 yield _, 'a[0].from_', 10, 'a[0].from_bytes', "Should have completed on a[0].from_: %s"
292 yield _, 'a[0].from_', 10, 'a[0].from_bytes', "Should have completed on a[0].from_: %s"
294
293
295
294
296
295
297 def test_omit__names():
296 def test_omit__names():
298 # also happens to test IPCompleter as a configurable
297 # also happens to test IPCompleter as a configurable
299 ip = get_ipython()
298 ip = get_ipython()
300 ip._hidden_attr = 1
299 ip._hidden_attr = 1
301 ip._x = {}
300 ip._x = {}
302 c = ip.Completer
301 c = ip.Completer
303 ip.ex('ip=get_ipython()')
302 ip.ex('ip=get_ipython()')
304 cfg = Config()
303 cfg = Config()
305 cfg.IPCompleter.omit__names = 0
304 cfg.IPCompleter.omit__names = 0
306 c.update_config(cfg)
305 c.update_config(cfg)
307 s,matches = c.complete('ip.')
306 s,matches = c.complete('ip.')
308 nt.assert_in('ip.__str__', matches)
307 nt.assert_in('ip.__str__', matches)
309 nt.assert_in('ip._hidden_attr', matches)
308 nt.assert_in('ip._hidden_attr', matches)
310 cfg = Config()
309 cfg = Config()
311 cfg.IPCompleter.omit__names = 1
310 cfg.IPCompleter.omit__names = 1
312 c.update_config(cfg)
311 c.update_config(cfg)
313 s,matches = c.complete('ip.')
312 s,matches = c.complete('ip.')
314 nt.assert_not_in('ip.__str__', matches)
313 nt.assert_not_in('ip.__str__', matches)
315 nt.assert_in('ip._hidden_attr', matches)
314 nt.assert_in('ip._hidden_attr', matches)
316 cfg = Config()
315 cfg = Config()
317 cfg.IPCompleter.omit__names = 2
316 cfg.IPCompleter.omit__names = 2
318 c.update_config(cfg)
317 c.update_config(cfg)
319 s,matches = c.complete('ip.')
318 s,matches = c.complete('ip.')
320 nt.assert_not_in('ip.__str__', matches)
319 nt.assert_not_in('ip.__str__', matches)
321 nt.assert_not_in('ip._hidden_attr', matches)
320 nt.assert_not_in('ip._hidden_attr', matches)
322 s,matches = c.complete('ip._x.')
321 s,matches = c.complete('ip._x.')
323 nt.assert_in('ip._x.keys', matches)
322 nt.assert_in('ip._x.keys', matches)
324 del ip._hidden_attr
323 del ip._hidden_attr
325
324
326
325
327 def test_limit_to__all__False_ok():
326 def test_limit_to__all__False_ok():
328 ip = get_ipython()
327 ip = get_ipython()
329 c = ip.Completer
328 c = ip.Completer
330 ip.ex('class D: x=24')
329 ip.ex('class D: x=24')
331 ip.ex('d=D()')
330 ip.ex('d=D()')
332 cfg = Config()
331 cfg = Config()
333 cfg.IPCompleter.limit_to__all__ = False
332 cfg.IPCompleter.limit_to__all__ = False
334 c.update_config(cfg)
333 c.update_config(cfg)
335 s, matches = c.complete('d.')
334 s, matches = c.complete('d.')
336 nt.assert_in('d.x', matches)
335 nt.assert_in('d.x', matches)
337
336
338
337
339 def test_get__all__entries_ok():
338 def test_get__all__entries_ok():
340 class A(object):
339 class A(object):
341 __all__ = ['x', 1]
340 __all__ = ['x', 1]
342 words = completer.get__all__entries(A())
341 words = completer.get__all__entries(A())
343 nt.assert_equal(words, ['x'])
342 nt.assert_equal(words, ['x'])
344
343
345
344
346 def test_get__all__entries_no__all__ok():
345 def test_get__all__entries_no__all__ok():
347 class A(object):
346 class A(object):
348 pass
347 pass
349 words = completer.get__all__entries(A())
348 words = completer.get__all__entries(A())
350 nt.assert_equal(words, [])
349 nt.assert_equal(words, [])
351
350
352
351
353 def test_func_kw_completions():
352 def test_func_kw_completions():
354 ip = get_ipython()
353 ip = get_ipython()
355 c = ip.Completer
354 c = ip.Completer
356 ip.ex('def myfunc(a=1,b=2): return a+b')
355 ip.ex('def myfunc(a=1,b=2): return a+b')
357 s, matches = c.complete(None, 'myfunc(1,b')
356 s, matches = c.complete(None, 'myfunc(1,b')
358 nt.assert_in('b=', matches)
357 nt.assert_in('b=', matches)
359 # Simulate completing with cursor right after b (pos==10):
358 # Simulate completing with cursor right after b (pos==10):
360 s, matches = c.complete(None, 'myfunc(1,b)', 10)
359 s, matches = c.complete(None, 'myfunc(1,b)', 10)
361 nt.assert_in('b=', matches)
360 nt.assert_in('b=', matches)
362 s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b')
361 s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b')
363 nt.assert_in('b=', matches)
362 nt.assert_in('b=', matches)
364 #builtin function
363 #builtin function
365 s, matches = c.complete(None, 'min(k, k')
364 s, matches = c.complete(None, 'min(k, k')
366 nt.assert_in('key=', matches)
365 nt.assert_in('key=', matches)
367
366
368
367
369 def test_default_arguments_from_docstring():
368 def test_default_arguments_from_docstring():
370 ip = get_ipython()
369 ip = get_ipython()
371 c = ip.Completer
370 c = ip.Completer
372 kwd = c._default_arguments_from_docstring(
371 kwd = c._default_arguments_from_docstring(
373 'min(iterable[, key=func]) -> value')
372 'min(iterable[, key=func]) -> value')
374 nt.assert_equal(kwd, ['key'])
373 nt.assert_equal(kwd, ['key'])
375 #with cython type etc
374 #with cython type etc
376 kwd = c._default_arguments_from_docstring(
375 kwd = c._default_arguments_from_docstring(
377 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
376 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
378 nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
377 nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
379 #white spaces
378 #white spaces
380 kwd = c._default_arguments_from_docstring(
379 kwd = c._default_arguments_from_docstring(
381 '\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
380 '\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
382 nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
381 nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
383
382
384 def test_line_magics():
383 def test_line_magics():
385 ip = get_ipython()
384 ip = get_ipython()
386 c = ip.Completer
385 c = ip.Completer
387 s, matches = c.complete(None, 'lsmag')
386 s, matches = c.complete(None, 'lsmag')
388 nt.assert_in('%lsmagic', matches)
387 nt.assert_in('%lsmagic', matches)
389 s, matches = c.complete(None, '%lsmag')
388 s, matches = c.complete(None, '%lsmag')
390 nt.assert_in('%lsmagic', matches)
389 nt.assert_in('%lsmagic', matches)
391
390
392
391
393 def test_cell_magics():
392 def test_cell_magics():
394 from IPython.core.magic import register_cell_magic
393 from IPython.core.magic import register_cell_magic
395
394
396 @register_cell_magic
395 @register_cell_magic
397 def _foo_cellm(line, cell):
396 def _foo_cellm(line, cell):
398 pass
397 pass
399
398
400 ip = get_ipython()
399 ip = get_ipython()
401 c = ip.Completer
400 c = ip.Completer
402
401
403 s, matches = c.complete(None, '_foo_ce')
402 s, matches = c.complete(None, '_foo_ce')
404 nt.assert_in('%%_foo_cellm', matches)
403 nt.assert_in('%%_foo_cellm', matches)
405 s, matches = c.complete(None, '%%_foo_ce')
404 s, matches = c.complete(None, '%%_foo_ce')
406 nt.assert_in('%%_foo_cellm', matches)
405 nt.assert_in('%%_foo_cellm', matches)
407
406
408
407
409 def test_line_cell_magics():
408 def test_line_cell_magics():
410 from IPython.core.magic import register_line_cell_magic
409 from IPython.core.magic import register_line_cell_magic
411
410
412 @register_line_cell_magic
411 @register_line_cell_magic
413 def _bar_cellm(line, cell):
412 def _bar_cellm(line, cell):
414 pass
413 pass
415
414
416 ip = get_ipython()
415 ip = get_ipython()
417 c = ip.Completer
416 c = ip.Completer
418
417
419 # The policy here is trickier, see comments in completion code. The
418 # The policy here is trickier, see comments in completion code. The
420 # returned values depend on whether the user passes %% or not explicitly,
419 # returned values depend on whether the user passes %% or not explicitly,
421 # and this will show a difference if the same name is both a line and cell
420 # and this will show a difference if the same name is both a line and cell
422 # magic.
421 # magic.
423 s, matches = c.complete(None, '_bar_ce')
422 s, matches = c.complete(None, '_bar_ce')
424 nt.assert_in('%_bar_cellm', matches)
423 nt.assert_in('%_bar_cellm', matches)
425 nt.assert_in('%%_bar_cellm', matches)
424 nt.assert_in('%%_bar_cellm', matches)
426 s, matches = c.complete(None, '%_bar_ce')
425 s, matches = c.complete(None, '%_bar_ce')
427 nt.assert_in('%_bar_cellm', matches)
426 nt.assert_in('%_bar_cellm', matches)
428 nt.assert_in('%%_bar_cellm', matches)
427 nt.assert_in('%%_bar_cellm', matches)
429 s, matches = c.complete(None, '%%_bar_ce')
428 s, matches = c.complete(None, '%%_bar_ce')
430 nt.assert_not_in('%_bar_cellm', matches)
429 nt.assert_not_in('%_bar_cellm', matches)
431 nt.assert_in('%%_bar_cellm', matches)
430 nt.assert_in('%%_bar_cellm', matches)
432
431
433
432
434 def test_magic_completion_order():
433 def test_magic_completion_order():
435
434
436 ip = get_ipython()
435 ip = get_ipython()
437 c = ip.Completer
436 c = ip.Completer
438
437
439 # Test ordering of magics and non-magics with the same name
438 # Test ordering of magics and non-magics with the same name
440 # We want the non-magic first
439 # We want the non-magic first
441
440
442 # Before importing matplotlib, there should only be one option:
441 # Before importing matplotlib, there should only be one option:
443
442
444 text, matches = c.complete('mat')
443 text, matches = c.complete('mat')
445 nt.assert_equal(matches, ["%matplotlib"])
444 nt.assert_equal(matches, ["%matplotlib"])
446
445
447
446
448 ip.run_cell("matplotlib = 1") # introduce name into namespace
447 ip.run_cell("matplotlib = 1") # introduce name into namespace
449
448
450 # After the import, there should be two options, ordered like this:
449 # After the import, there should be two options, ordered like this:
451 text, matches = c.complete('mat')
450 text, matches = c.complete('mat')
452 nt.assert_equal(matches, ["matplotlib", "%matplotlib"])
451 nt.assert_equal(matches, ["matplotlib", "%matplotlib"])
453
452
454
453
455 ip.run_cell("timeit = 1") # define a user variable called 'timeit'
454 ip.run_cell("timeit = 1") # define a user variable called 'timeit'
456
455
457 # Order of user variable and line and cell magics with same name:
456 # Order of user variable and line and cell magics with same name:
458 text, matches = c.complete('timeit')
457 text, matches = c.complete('timeit')
459 nt.assert_equal(matches, ["timeit", "%timeit","%%timeit"])
458 nt.assert_equal(matches, ["timeit", "%timeit","%%timeit"])
460
459
461
460
462 def test_dict_key_completion_string():
461 def test_dict_key_completion_string():
463 """Test dictionary key completion for string keys"""
462 """Test dictionary key completion for string keys"""
464 ip = get_ipython()
463 ip = get_ipython()
465 complete = ip.Completer.complete
464 complete = ip.Completer.complete
466
465
467 ip.user_ns['d'] = {'abc': None}
466 ip.user_ns['d'] = {'abc': None}
468
467
469 # check completion at different stages
468 # check completion at different stages
470 _, matches = complete(line_buffer="d[")
469 _, matches = complete(line_buffer="d[")
471 nt.assert_in("'abc'", matches)
470 nt.assert_in("'abc'", matches)
472 nt.assert_not_in("'abc']", matches)
471 nt.assert_not_in("'abc']", matches)
473
472
474 _, matches = complete(line_buffer="d['")
473 _, matches = complete(line_buffer="d['")
475 nt.assert_in("abc", matches)
474 nt.assert_in("abc", matches)
476 nt.assert_not_in("abc']", matches)
475 nt.assert_not_in("abc']", matches)
477
476
478 _, matches = complete(line_buffer="d['a")
477 _, matches = complete(line_buffer="d['a")
479 nt.assert_in("abc", matches)
478 nt.assert_in("abc", matches)
480 nt.assert_not_in("abc']", matches)
479 nt.assert_not_in("abc']", matches)
481
480
482 # check use of different quoting
481 # check use of different quoting
483 _, matches = complete(line_buffer="d[\"")
482 _, matches = complete(line_buffer="d[\"")
484 nt.assert_in("abc", matches)
483 nt.assert_in("abc", matches)
485 nt.assert_not_in('abc\"]', matches)
484 nt.assert_not_in('abc\"]', matches)
486
485
487 _, matches = complete(line_buffer="d[\"a")
486 _, matches = complete(line_buffer="d[\"a")
488 nt.assert_in("abc", matches)
487 nt.assert_in("abc", matches)
489 nt.assert_not_in('abc\"]', matches)
488 nt.assert_not_in('abc\"]', matches)
490
489
491 # check sensitivity to following context
490 # check sensitivity to following context
492 _, matches = complete(line_buffer="d[]", cursor_pos=2)
491 _, matches = complete(line_buffer="d[]", cursor_pos=2)
493 nt.assert_in("'abc'", matches)
492 nt.assert_in("'abc'", matches)
494
493
495 _, matches = complete(line_buffer="d['']", cursor_pos=3)
494 _, matches = complete(line_buffer="d['']", cursor_pos=3)
496 nt.assert_in("abc", matches)
495 nt.assert_in("abc", matches)
497 nt.assert_not_in("abc'", matches)
496 nt.assert_not_in("abc'", matches)
498 nt.assert_not_in("abc']", matches)
497 nt.assert_not_in("abc']", matches)
499
498
500 # check multiple solutions are correctly returned and that noise is not
499 # check multiple solutions are correctly returned and that noise is not
501 ip.user_ns['d'] = {'abc': None, 'abd': None, 'bad': None, object(): None,
500 ip.user_ns['d'] = {'abc': None, 'abd': None, 'bad': None, object(): None,
502 5: None}
501 5: None}
503
502
504 _, matches = complete(line_buffer="d['a")
503 _, matches = complete(line_buffer="d['a")
505 nt.assert_in("abc", matches)
504 nt.assert_in("abc", matches)
506 nt.assert_in("abd", matches)
505 nt.assert_in("abd", matches)
507 nt.assert_not_in("bad", matches)
506 nt.assert_not_in("bad", matches)
508 assert not any(m.endswith((']', '"', "'")) for m in matches), matches
507 assert not any(m.endswith((']', '"', "'")) for m in matches), matches
509
508
510 # check escaping and whitespace
509 # check escaping and whitespace
511 ip.user_ns['d'] = {'a\nb': None, 'a\'b': None, 'a"b': None, 'a word': None}
510 ip.user_ns['d'] = {'a\nb': None, 'a\'b': None, 'a"b': None, 'a word': None}
512 _, matches = complete(line_buffer="d['a")
511 _, matches = complete(line_buffer="d['a")
513 nt.assert_in("a\\nb", matches)
512 nt.assert_in("a\\nb", matches)
514 nt.assert_in("a\\'b", matches)
513 nt.assert_in("a\\'b", matches)
515 nt.assert_in("a\"b", matches)
514 nt.assert_in("a\"b", matches)
516 nt.assert_in("a word", matches)
515 nt.assert_in("a word", matches)
517 assert not any(m.endswith((']', '"', "'")) for m in matches), matches
516 assert not any(m.endswith((']', '"', "'")) for m in matches), matches
518
517
519 # - can complete on non-initial word of the string
518 # - can complete on non-initial word of the string
520 _, matches = complete(line_buffer="d['a w")
519 _, matches = complete(line_buffer="d['a w")
521 nt.assert_in("word", matches)
520 nt.assert_in("word", matches)
522
521
523 # - understands quote escaping
522 # - understands quote escaping
524 _, matches = complete(line_buffer="d['a\\'")
523 _, matches = complete(line_buffer="d['a\\'")
525 nt.assert_in("b", matches)
524 nt.assert_in("b", matches)
526
525
527 # - default quoting should work like repr
526 # - default quoting should work like repr
528 _, matches = complete(line_buffer="d[")
527 _, matches = complete(line_buffer="d[")
529 nt.assert_in("\"a'b\"", matches)
528 nt.assert_in("\"a'b\"", matches)
530
529
531 # - when opening quote with ", possible to match with unescaped apostrophe
530 # - when opening quote with ", possible to match with unescaped apostrophe
532 _, matches = complete(line_buffer="d[\"a'")
531 _, matches = complete(line_buffer="d[\"a'")
533 nt.assert_in("b", matches)
532 nt.assert_in("b", matches)
534
533
535 # need to not split at delims that readline won't split at
534 # need to not split at delims that readline won't split at
536 if '-' not in ip.Completer.splitter.delims:
535 if '-' not in ip.Completer.splitter.delims:
537 ip.user_ns['d'] = {'before-after': None}
536 ip.user_ns['d'] = {'before-after': None}
538 _, matches = complete(line_buffer="d['before-af")
537 _, matches = complete(line_buffer="d['before-af")
539 nt.assert_in('before-after', matches)
538 nt.assert_in('before-after', matches)
540
539
541 def test_dict_key_completion_contexts():
540 def test_dict_key_completion_contexts():
542 """Test expression contexts in which dict key completion occurs"""
541 """Test expression contexts in which dict key completion occurs"""
543 ip = get_ipython()
542 ip = get_ipython()
544 complete = ip.Completer.complete
543 complete = ip.Completer.complete
545 d = {'abc': None}
544 d = {'abc': None}
546 ip.user_ns['d'] = d
545 ip.user_ns['d'] = d
547
546
548 class C:
547 class C:
549 data = d
548 data = d
550 ip.user_ns['C'] = C
549 ip.user_ns['C'] = C
551 ip.user_ns['get'] = lambda: d
550 ip.user_ns['get'] = lambda: d
552
551
553 def assert_no_completion(**kwargs):
552 def assert_no_completion(**kwargs):
554 _, matches = complete(**kwargs)
553 _, matches = complete(**kwargs)
555 nt.assert_not_in('abc', matches)
554 nt.assert_not_in('abc', matches)
556 nt.assert_not_in('abc\'', matches)
555 nt.assert_not_in('abc\'', matches)
557 nt.assert_not_in('abc\']', matches)
556 nt.assert_not_in('abc\']', matches)
558 nt.assert_not_in('\'abc\'', matches)
557 nt.assert_not_in('\'abc\'', matches)
559 nt.assert_not_in('\'abc\']', matches)
558 nt.assert_not_in('\'abc\']', matches)
560
559
561 def assert_completion(**kwargs):
560 def assert_completion(**kwargs):
562 _, matches = complete(**kwargs)
561 _, matches = complete(**kwargs)
563 nt.assert_in("'abc'", matches)
562 nt.assert_in("'abc'", matches)
564 nt.assert_not_in("'abc']", matches)
563 nt.assert_not_in("'abc']", matches)
565
564
566 # no completion after string closed, even if reopened
565 # no completion after string closed, even if reopened
567 assert_no_completion(line_buffer="d['a'")
566 assert_no_completion(line_buffer="d['a'")
568 assert_no_completion(line_buffer="d[\"a\"")
567 assert_no_completion(line_buffer="d[\"a\"")
569 assert_no_completion(line_buffer="d['a' + ")
568 assert_no_completion(line_buffer="d['a' + ")
570 assert_no_completion(line_buffer="d['a' + '")
569 assert_no_completion(line_buffer="d['a' + '")
571
570
572 # completion in non-trivial expressions
571 # completion in non-trivial expressions
573 assert_completion(line_buffer="+ d[")
572 assert_completion(line_buffer="+ d[")
574 assert_completion(line_buffer="(d[")
573 assert_completion(line_buffer="(d[")
575 assert_completion(line_buffer="C.data[")
574 assert_completion(line_buffer="C.data[")
576
575
577 # greedy flag
576 # greedy flag
578 def assert_completion(**kwargs):
577 def assert_completion(**kwargs):
579 _, matches = complete(**kwargs)
578 _, matches = complete(**kwargs)
580 nt.assert_in("get()['abc']", matches)
579 nt.assert_in("get()['abc']", matches)
581
580
582 assert_no_completion(line_buffer="get()[")
581 assert_no_completion(line_buffer="get()[")
583 with greedy_completion():
582 with greedy_completion():
584 assert_completion(line_buffer="get()[")
583 assert_completion(line_buffer="get()[")
585 assert_completion(line_buffer="get()['")
584 assert_completion(line_buffer="get()['")
586 assert_completion(line_buffer="get()['a")
585 assert_completion(line_buffer="get()['a")
587 assert_completion(line_buffer="get()['ab")
586 assert_completion(line_buffer="get()['ab")
588 assert_completion(line_buffer="get()['abc")
587 assert_completion(line_buffer="get()['abc")
589
588
590
589
591
590
592 @dec.onlyif(sys.version_info[0] >= 3, 'This test only applies in Py>=3')
591 @dec.onlyif(sys.version_info[0] >= 3, 'This test only applies in Py>=3')
593 def test_dict_key_completion_bytes():
592 def test_dict_key_completion_bytes():
594 """Test handling of bytes in dict key completion"""
593 """Test handling of bytes in dict key completion"""
595 ip = get_ipython()
594 ip = get_ipython()
596 complete = ip.Completer.complete
595 complete = ip.Completer.complete
597
596
598 ip.user_ns['d'] = {'abc': None, b'abd': None}
597 ip.user_ns['d'] = {'abc': None, b'abd': None}
599
598
600 _, matches = complete(line_buffer="d[")
599 _, matches = complete(line_buffer="d[")
601 nt.assert_in("'abc'", matches)
600 nt.assert_in("'abc'", matches)
602 nt.assert_in("b'abd'", matches)
601 nt.assert_in("b'abd'", matches)
603
602
604 if False: # not currently implemented
603 if False: # not currently implemented
605 _, matches = complete(line_buffer="d[b")
604 _, matches = complete(line_buffer="d[b")
606 nt.assert_in("b'abd'", matches)
605 nt.assert_in("b'abd'", matches)
607 nt.assert_not_in("b'abc'", matches)
606 nt.assert_not_in("b'abc'", matches)
608
607
609 _, matches = complete(line_buffer="d[b'")
608 _, matches = complete(line_buffer="d[b'")
610 nt.assert_in("abd", matches)
609 nt.assert_in("abd", matches)
611 nt.assert_not_in("abc", matches)
610 nt.assert_not_in("abc", matches)
612
611
613 _, matches = complete(line_buffer="d[B'")
612 _, matches = complete(line_buffer="d[B'")
614 nt.assert_in("abd", matches)
613 nt.assert_in("abd", matches)
615 nt.assert_not_in("abc", matches)
614 nt.assert_not_in("abc", matches)
616
615
617 _, matches = complete(line_buffer="d['")
616 _, matches = complete(line_buffer="d['")
618 nt.assert_in("abc", matches)
617 nt.assert_in("abc", matches)
619 nt.assert_not_in("abd", matches)
618 nt.assert_not_in("abd", matches)
620
619
621
620
622 @dec.onlyif(sys.version_info[0] < 3, 'This test only applies in Py<3')
621 @dec.onlyif(sys.version_info[0] < 3, 'This test only applies in Py<3')
623 def test_dict_key_completion_unicode_py2():
622 def test_dict_key_completion_unicode_py2():
624 """Test handling of unicode in dict key completion"""
623 """Test handling of unicode in dict key completion"""
625 ip = get_ipython()
624 ip = get_ipython()
626 complete = ip.Completer.complete
625 complete = ip.Completer.complete
627
626
628 ip.user_ns['d'] = {u'abc': None,
627 ip.user_ns['d'] = {u'abc': None,
629 u'a\u05d0b': None}
628 u'a\u05d0b': None}
630
629
631 _, matches = complete(line_buffer="d[")
630 _, matches = complete(line_buffer="d[")
632 nt.assert_in("u'abc'", matches)
631 nt.assert_in("u'abc'", matches)
633 nt.assert_in("u'a\\u05d0b'", matches)
632 nt.assert_in("u'a\\u05d0b'", matches)
634
633
635 _, matches = complete(line_buffer="d['a")
634 _, matches = complete(line_buffer="d['a")
636 nt.assert_in("abc", matches)
635 nt.assert_in("abc", matches)
637 nt.assert_not_in("a\\u05d0b", matches)
636 nt.assert_not_in("a\\u05d0b", matches)
638
637
639 _, matches = complete(line_buffer="d[u'a")
638 _, matches = complete(line_buffer="d[u'a")
640 nt.assert_in("abc", matches)
639 nt.assert_in("abc", matches)
641 nt.assert_in("a\\u05d0b", matches)
640 nt.assert_in("a\\u05d0b", matches)
642
641
643 _, matches = complete(line_buffer="d[U'a")
642 _, matches = complete(line_buffer="d[U'a")
644 nt.assert_in("abc", matches)
643 nt.assert_in("abc", matches)
645 nt.assert_in("a\\u05d0b", matches)
644 nt.assert_in("a\\u05d0b", matches)
646
645
647 # query using escape
646 # query using escape
648 if sys.platform != 'win32':
647 if sys.platform != 'win32':
649 # Known failure on Windows
648 # Known failure on Windows
650 _, matches = complete(line_buffer=u"d[u'a\\u05d0")
649 _, matches = complete(line_buffer=u"d[u'a\\u05d0")
651 nt.assert_in("u05d0b", matches) # tokenized after \\
650 nt.assert_in("u05d0b", matches) # tokenized after \\
652
651
653 # query using character
652 # query using character
654 _, matches = complete(line_buffer=u"d[u'a\u05d0")
653 _, matches = complete(line_buffer=u"d[u'a\u05d0")
655 nt.assert_in(u"a\u05d0b", matches)
654 nt.assert_in(u"a\u05d0b", matches)
656
655
657 with greedy_completion():
656 with greedy_completion():
658 _, matches = complete(line_buffer="d[")
657 _, matches = complete(line_buffer="d[")
659 nt.assert_in("d[u'abc']", matches)
658 nt.assert_in("d[u'abc']", matches)
660 nt.assert_in("d[u'a\\u05d0b']", matches)
659 nt.assert_in("d[u'a\\u05d0b']", matches)
661
660
662 _, matches = complete(line_buffer="d['a")
661 _, matches = complete(line_buffer="d['a")
663 nt.assert_in("d['abc']", matches)
662 nt.assert_in("d['abc']", matches)
664 nt.assert_not_in("d[u'a\\u05d0b']", matches)
663 nt.assert_not_in("d[u'a\\u05d0b']", matches)
665
664
666 _, matches = complete(line_buffer="d[u'a")
665 _, matches = complete(line_buffer="d[u'a")
667 nt.assert_in("d[u'abc']", matches)
666 nt.assert_in("d[u'abc']", matches)
668 nt.assert_in("d[u'a\\u05d0b']", matches)
667 nt.assert_in("d[u'a\\u05d0b']", matches)
669
668
670 _, matches = complete(line_buffer="d[U'a")
669 _, matches = complete(line_buffer="d[U'a")
671 nt.assert_in("d[U'abc']", matches)
670 nt.assert_in("d[U'abc']", matches)
672 nt.assert_in("d[U'a\\u05d0b']", matches)
671 nt.assert_in("d[U'a\\u05d0b']", matches)
673
672
674 # query using escape
673 # query using escape
675 _, matches = complete(line_buffer=u"d[u'a\\u05d0")
674 _, matches = complete(line_buffer=u"d[u'a\\u05d0")
676 nt.assert_in("d[u'a\\u05d0b']", matches) # tokenized after \\
675 nt.assert_in("d[u'a\\u05d0b']", matches) # tokenized after \\
677
676
678 # query using character
677 # query using character
679 _, matches = complete(line_buffer=u"d[u'a\u05d0")
678 _, matches = complete(line_buffer=u"d[u'a\u05d0")
680 nt.assert_in(u"d[u'a\u05d0b']", matches)
679 nt.assert_in(u"d[u'a\u05d0b']", matches)
681
680
682
681
683 @dec.onlyif(sys.version_info[0] >= 3, 'This test only applies in Py>=3')
682 @dec.onlyif(sys.version_info[0] >= 3, 'This test only applies in Py>=3')
684 def test_dict_key_completion_unicode_py3():
683 def test_dict_key_completion_unicode_py3():
685 """Test handling of unicode in dict key completion"""
684 """Test handling of unicode in dict key completion"""
686 ip = get_ipython()
685 ip = get_ipython()
687 complete = ip.Completer.complete
686 complete = ip.Completer.complete
688
687
689 ip.user_ns['d'] = {u'a\u05d0': None}
688 ip.user_ns['d'] = {u'a\u05d0': None}
690
689
691 # query using escape
690 # query using escape
692 if sys.platform != 'win32':
691 if sys.platform != 'win32':
693 # Known failure on Windows
692 # Known failure on Windows
694 _, matches = complete(line_buffer="d['a\\u05d0")
693 _, matches = complete(line_buffer="d['a\\u05d0")
695 nt.assert_in("u05d0", matches) # tokenized after \\
694 nt.assert_in("u05d0", matches) # tokenized after \\
696
695
697 # query using character
696 # query using character
698 _, matches = complete(line_buffer="d['a\u05d0")
697 _, matches = complete(line_buffer="d['a\u05d0")
699 nt.assert_in(u"a\u05d0", matches)
698 nt.assert_in(u"a\u05d0", matches)
700
699
701 with greedy_completion():
700 with greedy_completion():
702 # query using escape
701 # query using escape
703 _, matches = complete(line_buffer="d['a\\u05d0")
702 _, matches = complete(line_buffer="d['a\\u05d0")
704 nt.assert_in("d['a\\u05d0']", matches) # tokenized after \\
703 nt.assert_in("d['a\\u05d0']", matches) # tokenized after \\
705
704
706 # query using character
705 # query using character
707 _, matches = complete(line_buffer="d['a\u05d0")
706 _, matches = complete(line_buffer="d['a\u05d0")
708 nt.assert_in(u"d['a\u05d0']", matches)
707 nt.assert_in(u"d['a\u05d0']", matches)
709
708
710
709
711
710
712 @dec.skip_without('numpy')
711 @dec.skip_without('numpy')
713 def test_struct_array_key_completion():
712 def test_struct_array_key_completion():
714 """Test dict key completion applies to numpy struct arrays"""
713 """Test dict key completion applies to numpy struct arrays"""
715 import numpy
714 import numpy
716 ip = get_ipython()
715 ip = get_ipython()
717 complete = ip.Completer.complete
716 complete = ip.Completer.complete
718 ip.user_ns['d'] = numpy.array([], dtype=[('hello', 'f'), ('world', 'f')])
717 ip.user_ns['d'] = numpy.array([], dtype=[('hello', 'f'), ('world', 'f')])
719 _, matches = complete(line_buffer="d['")
718 _, matches = complete(line_buffer="d['")
720 nt.assert_in("hello", matches)
719 nt.assert_in("hello", matches)
721 nt.assert_in("world", matches)
720 nt.assert_in("world", matches)
722 # complete on the numpy struct itself
721 # complete on the numpy struct itself
723 dt = numpy.dtype([('my_head', [('my_dt', '>u4'), ('my_df', '>u4')]),
722 dt = numpy.dtype([('my_head', [('my_dt', '>u4'), ('my_df', '>u4')]),
724 ('my_data', '>f4', 5)])
723 ('my_data', '>f4', 5)])
725 x = numpy.zeros(2, dtype=dt)
724 x = numpy.zeros(2, dtype=dt)
726 ip.user_ns['d'] = x[1]
725 ip.user_ns['d'] = x[1]
727 _, matches = complete(line_buffer="d['")
726 _, matches = complete(line_buffer="d['")
728 nt.assert_in("my_head", matches)
727 nt.assert_in("my_head", matches)
729 nt.assert_in("my_data", matches)
728 nt.assert_in("my_data", matches)
730 # complete on a nested level
729 # complete on a nested level
731 with greedy_completion():
730 with greedy_completion():
732 ip.user_ns['d'] = numpy.zeros(2, dtype=dt)
731 ip.user_ns['d'] = numpy.zeros(2, dtype=dt)
733 _, matches = complete(line_buffer="d[1]['my_head']['")
732 _, matches = complete(line_buffer="d[1]['my_head']['")
734 nt.assert_true(any(["my_dt" in m for m in matches]))
733 nt.assert_true(any(["my_dt" in m for m in matches]))
735 nt.assert_true(any(["my_df" in m for m in matches]))
734 nt.assert_true(any(["my_df" in m for m in matches]))
736
735
737
736
738 @dec.skip_without('pandas')
737 @dec.skip_without('pandas')
739 def test_dataframe_key_completion():
738 def test_dataframe_key_completion():
740 """Test dict key completion applies to pandas DataFrames"""
739 """Test dict key completion applies to pandas DataFrames"""
741 import pandas
740 import pandas
742 ip = get_ipython()
741 ip = get_ipython()
743 complete = ip.Completer.complete
742 complete = ip.Completer.complete
744 ip.user_ns['d'] = pandas.DataFrame({'hello': [1], 'world': [2]})
743 ip.user_ns['d'] = pandas.DataFrame({'hello': [1], 'world': [2]})
745 _, matches = complete(line_buffer="d['")
744 _, matches = complete(line_buffer="d['")
746 nt.assert_in("hello", matches)
745 nt.assert_in("hello", matches)
747 nt.assert_in("world", matches)
746 nt.assert_in("world", matches)
748
747
749
748
750 def test_dict_key_completion_invalids():
749 def test_dict_key_completion_invalids():
751 """Smoke test cases dict key completion can't handle"""
750 """Smoke test cases dict key completion can't handle"""
752 ip = get_ipython()
751 ip = get_ipython()
753 complete = ip.Completer.complete
752 complete = ip.Completer.complete
754
753
755 ip.user_ns['no_getitem'] = None
754 ip.user_ns['no_getitem'] = None
756 ip.user_ns['no_keys'] = []
755 ip.user_ns['no_keys'] = []
757 ip.user_ns['cant_call_keys'] = dict
756 ip.user_ns['cant_call_keys'] = dict
758 ip.user_ns['empty'] = {}
757 ip.user_ns['empty'] = {}
759 ip.user_ns['d'] = {'abc': 5}
758 ip.user_ns['d'] = {'abc': 5}
760
759
761 _, matches = complete(line_buffer="no_getitem['")
760 _, matches = complete(line_buffer="no_getitem['")
762 _, matches = complete(line_buffer="no_keys['")
761 _, matches = complete(line_buffer="no_keys['")
763 _, matches = complete(line_buffer="cant_call_keys['")
762 _, matches = complete(line_buffer="cant_call_keys['")
764 _, matches = complete(line_buffer="empty['")
763 _, matches = complete(line_buffer="empty['")
765 _, matches = complete(line_buffer="name_error['")
764 _, matches = complete(line_buffer="name_error['")
766 _, matches = complete(line_buffer="d['\\") # incomplete escape
765 _, matches = complete(line_buffer="d['\\") # incomplete escape
767
766
768 class KeyCompletable(object):
767 class KeyCompletable(object):
769 def __init__(self, things=()):
768 def __init__(self, things=()):
770 self.things = things
769 self.things = things
771
770
772 def _ipython_key_completions_(self):
771 def _ipython_key_completions_(self):
773 return list(self.things)
772 return list(self.things)
774
773
775 def test_object_key_completion():
774 def test_object_key_completion():
776 ip = get_ipython()
775 ip = get_ipython()
777 ip.user_ns['key_completable'] = KeyCompletable(['qwerty', 'qwick'])
776 ip.user_ns['key_completable'] = KeyCompletable(['qwerty', 'qwick'])
778
777
779 _, matches = ip.Completer.complete(line_buffer="key_completable['qw")
778 _, matches = ip.Completer.complete(line_buffer="key_completable['qw")
780 nt.assert_in('qwerty', matches)
779 nt.assert_in('qwerty', matches)
781 nt.assert_in('qwick', matches)
780 nt.assert_in('qwick', matches)
782
781
783
782
784 def test_aimport_module_completer():
783 def test_aimport_module_completer():
785 ip = get_ipython()
784 ip = get_ipython()
786 _, matches = ip.complete('i', '%aimport i')
785 _, matches = ip.complete('i', '%aimport i')
787 nt.assert_in('io', matches)
786 nt.assert_in('io', matches)
788 nt.assert_not_in('int', matches)
787 nt.assert_not_in('int', matches)
789
788
790 def test_nested_import_module_completer():
789 def test_nested_import_module_completer():
791 ip = get_ipython()
790 ip = get_ipython()
792 _, matches = ip.complete(None, 'import IPython.co', 17)
791 _, matches = ip.complete(None, 'import IPython.co', 17)
793 nt.assert_in('IPython.core', matches)
792 nt.assert_in('IPython.core', matches)
794 nt.assert_not_in('import IPython.core', matches)
793 nt.assert_not_in('import IPython.core', matches)
795 nt.assert_not_in('IPython.display', matches)
794 nt.assert_not_in('IPython.display', matches)
796
795
797 def test_import_module_completer():
796 def test_import_module_completer():
798 ip = get_ipython()
797 ip = get_ipython()
799 _, matches = ip.complete('i', 'import i')
798 _, matches = ip.complete('i', 'import i')
800 nt.assert_in('io', matches)
799 nt.assert_in('io', matches)
801 nt.assert_not_in('int', matches)
800 nt.assert_not_in('int', matches)
802
801
803 def test_from_module_completer():
802 def test_from_module_completer():
804 ip = get_ipython()
803 ip = get_ipython()
805 _, matches = ip.complete('B', 'from io import B', 16)
804 _, matches = ip.complete('B', 'from io import B', 16)
806 nt.assert_in('BytesIO', matches)
805 nt.assert_in('BytesIO', matches)
807 nt.assert_not_in('BaseException', matches)
806 nt.assert_not_in('BaseException', matches)
@@ -1,452 +1,456 b''
1 """Tests for the object inspection functionality.
1 """Tests for the object inspection functionality.
2 """
2 """
3
3
4 # Copyright (c) IPython Development Team.
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
5 # Distributed under the terms of the Modified BSD License.
6
6
7 from __future__ import print_function
7 from __future__ import print_function
8
8
9 import os
9 import os
10 import re
10 import re
11 import sys
11 import sys
12
12
13 import nose.tools as nt
13 import nose.tools as nt
14
14
15 from .. import oinspect
15 from .. import oinspect
16 from IPython.core.magic import (Magics, magics_class, line_magic,
16 from IPython.core.magic import (Magics, magics_class, line_magic,
17 cell_magic, line_cell_magic,
17 cell_magic, line_cell_magic,
18 register_line_magic, register_cell_magic,
18 register_line_magic, register_cell_magic,
19 register_line_cell_magic)
19 register_line_cell_magic)
20 from decorator import decorator
20 from decorator import decorator
21 from IPython.testing.decorators import skipif
21 from IPython.testing.decorators import skipif
22 from IPython.testing.tools import AssertPrints
22 from IPython.testing.tools import AssertPrints
23 from IPython.utils.path import compress_user
23 from IPython.utils.path import compress_user
24 from IPython.utils import py3compat
24 from IPython.utils import py3compat
25 from IPython.utils.signatures import Signature, Parameter
25 from IPython.utils.signatures import Signature, Parameter
26
26
27
27
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29 # Globals and constants
29 # Globals and constants
30 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
31
31
32 inspector = oinspect.Inspector()
32 inspector = oinspect.Inspector()
33 ip = get_ipython()
33 ip = get_ipython()
34
34
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
36 # Local utilities
36 # Local utilities
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38
38
39 # WARNING: since this test checks the line number where a function is
39 # WARNING: since this test checks the line number where a function is
40 # defined, if any code is inserted above, the following line will need to be
40 # defined, if any code is inserted above, the following line will need to be
41 # updated. Do NOT insert any whitespace between the next line and the function
41 # updated. Do NOT insert any whitespace between the next line and the function
42 # definition below.
42 # definition below.
43 THIS_LINE_NUMBER = 43 # Put here the actual number of this line
43 THIS_LINE_NUMBER = 43 # Put here the actual number of this line
44 def test_find_source_lines():
44
45 nt.assert_equal(oinspect.find_source_lines(test_find_source_lines),
45 from unittest import TestCase
46 THIS_LINE_NUMBER+1)
46
47 class Test(TestCase):
48
49 def test_find_source_lines(self):
50 self.assertEqual(oinspect.find_source_lines(Test.test_find_source_lines),
51 THIS_LINE_NUMBER+6)
47
52
48
53
49 # A couple of utilities to ensure these tests work the same from a source or a
54 # A couple of utilities to ensure these tests work the same from a source or a
50 # binary install
55 # binary install
51 def pyfile(fname):
56 def pyfile(fname):
52 return os.path.normcase(re.sub('.py[co]$', '.py', fname))
57 return os.path.normcase(re.sub('.py[co]$', '.py', fname))
53
58
54
59
55 def match_pyfiles(f1, f2):
60 def match_pyfiles(f1, f2):
56 nt.assert_equal(pyfile(f1), pyfile(f2))
61 nt.assert_equal(pyfile(f1), pyfile(f2))
57
62
58
63
59 def test_find_file():
64 def test_find_file():
60 match_pyfiles(oinspect.find_file(test_find_file), os.path.abspath(__file__))
65 match_pyfiles(oinspect.find_file(test_find_file), os.path.abspath(__file__))
61
66
62
67
63 def test_find_file_decorated1():
68 def test_find_file_decorated1():
64
69
65 @decorator
70 @decorator
66 def noop1(f):
71 def noop1(f):
67 def wrapper():
72 def wrapper():
68 return f(*a, **kw)
73 return f(*a, **kw)
69 return wrapper
74 return wrapper
70
75
71 @noop1
76 @noop1
72 def f(x):
77 def f(x):
73 "My docstring"
78 "My docstring"
74
79
75 match_pyfiles(oinspect.find_file(f), os.path.abspath(__file__))
80 match_pyfiles(oinspect.find_file(f), os.path.abspath(__file__))
76 nt.assert_equal(f.__doc__, "My docstring")
81 nt.assert_equal(f.__doc__, "My docstring")
77
82
78
83
79 def test_find_file_decorated2():
84 def test_find_file_decorated2():
80
85
81 @decorator
86 @decorator
82 def noop2(f, *a, **kw):
87 def noop2(f, *a, **kw):
83 return f(*a, **kw)
88 return f(*a, **kw)
84
89
85 @noop2
90 @noop2
86 @noop2
91 @noop2
87 @noop2
92 @noop2
88 def f(x):
93 def f(x):
89 "My docstring 2"
94 "My docstring 2"
90
95
91 match_pyfiles(oinspect.find_file(f), os.path.abspath(__file__))
96 match_pyfiles(oinspect.find_file(f), os.path.abspath(__file__))
92 nt.assert_equal(f.__doc__, "My docstring 2")
97 nt.assert_equal(f.__doc__, "My docstring 2")
93
98
94
99
95 def test_find_file_magic():
100 def test_find_file_magic():
96 run = ip.find_line_magic('run')
101 run = ip.find_line_magic('run')
97 nt.assert_not_equal(oinspect.find_file(run), None)
102 nt.assert_not_equal(oinspect.find_file(run), None)
98
103
99
104
100 # A few generic objects we can then inspect in the tests below
105 # A few generic objects we can then inspect in the tests below
101
106
102 class Call(object):
107 class Call(object):
103 """This is the class docstring."""
108 """This is the class docstring."""
104
109
105 def __init__(self, x, y=1):
110 def __init__(self, x, y=1):
106 """This is the constructor docstring."""
111 """This is the constructor docstring."""
107
112
108 def __call__(self, *a, **kw):
113 def __call__(self, *a, **kw):
109 """This is the call docstring."""
114 """This is the call docstring."""
110
115
111 def method(self, x, z=2):
116 def method(self, x, z=2):
112 """Some method's docstring"""
117 """Some method's docstring"""
113
118
114 class HasSignature(object):
119 class HasSignature(object):
115 """This is the class docstring."""
120 """This is the class docstring."""
116 __signature__ = Signature([Parameter('test', Parameter.POSITIONAL_OR_KEYWORD)])
121 __signature__ = Signature([Parameter('test', Parameter.POSITIONAL_OR_KEYWORD)])
117
122
118 def __init__(self, *args):
123 def __init__(self, *args):
119 """This is the init docstring"""
124 """This is the init docstring"""
120
125
121
126
122 class SimpleClass(object):
127 class SimpleClass(object):
123 def method(self, x, z=2):
128 def method(self, x, z=2):
124 """Some method's docstring"""
129 """Some method's docstring"""
125
130
126
131
127 class OldStyle:
132 class OldStyle:
128 """An old-style class for testing."""
133 """An old-style class for testing."""
129 pass
134 pass
130
135
131
136
132 def f(x, y=2, *a, **kw):
137 def f(x, y=2, *a, **kw):
133 """A simple function."""
138 """A simple function."""
134
139
135
140
136 def g(y, z=3, *a, **kw):
141 def g(y, z=3, *a, **kw):
137 pass # no docstring
142 pass # no docstring
138
143
139
144
140 @register_line_magic
145 @register_line_magic
141 def lmagic(line):
146 def lmagic(line):
142 "A line magic"
147 "A line magic"
143
148
144
149
145 @register_cell_magic
150 @register_cell_magic
146 def cmagic(line, cell):
151 def cmagic(line, cell):
147 "A cell magic"
152 "A cell magic"
148
153
149
154
150 @register_line_cell_magic
155 @register_line_cell_magic
151 def lcmagic(line, cell=None):
156 def lcmagic(line, cell=None):
152 "A line/cell magic"
157 "A line/cell magic"
153
158
154
159
155 @magics_class
160 @magics_class
156 class SimpleMagics(Magics):
161 class SimpleMagics(Magics):
157 @line_magic
162 @line_magic
158 def Clmagic(self, cline):
163 def Clmagic(self, cline):
159 "A class-based line magic"
164 "A class-based line magic"
160
165
161 @cell_magic
166 @cell_magic
162 def Ccmagic(self, cline, ccell):
167 def Ccmagic(self, cline, ccell):
163 "A class-based cell magic"
168 "A class-based cell magic"
164
169
165 @line_cell_magic
170 @line_cell_magic
166 def Clcmagic(self, cline, ccell=None):
171 def Clcmagic(self, cline, ccell=None):
167 "A class-based line/cell magic"
172 "A class-based line/cell magic"
168
173
169
174
170 class Awkward(object):
175 class Awkward(object):
171 def __getattr__(self, name):
176 def __getattr__(self, name):
172 raise Exception(name)
177 raise Exception(name)
173
178
174 class NoBoolCall:
179 class NoBoolCall:
175 """
180 """
176 callable with `__bool__` raising should still be inspect-able.
181 callable with `__bool__` raising should still be inspect-able.
177 """
182 """
178
183
179 def __call__(self):
184 def __call__(self):
180 """does nothing"""
185 """does nothing"""
181 pass
186 pass
182
187
183 def __bool__(self):
188 def __bool__(self):
184 """just raise NotImplemented"""
189 """just raise NotImplemented"""
185 raise NotImplementedError('Must be implemented')
190 raise NotImplementedError('Must be implemented')
186
191
187
192
188 class SerialLiar(object):
193 class SerialLiar(object):
189 """Attribute accesses always get another copy of the same class.
194 """Attribute accesses always get another copy of the same class.
190
195
191 unittest.mock.call does something similar, but it's not ideal for testing
196 unittest.mock.call does something similar, but it's not ideal for testing
192 as the failure mode is to eat all your RAM. This gives up after 10k levels.
197 as the failure mode is to eat all your RAM. This gives up after 10k levels.
193 """
198 """
194 def __init__(self, max_fibbing_twig, lies_told=0):
199 def __init__(self, max_fibbing_twig, lies_told=0):
195 if lies_told > 10000:
200 if lies_told > 10000:
196 raise RuntimeError('Nose too long, honesty is the best policy')
201 raise RuntimeError('Nose too long, honesty is the best policy')
197 self.max_fibbing_twig = max_fibbing_twig
202 self.max_fibbing_twig = max_fibbing_twig
198 self.lies_told = lies_told
203 self.lies_told = lies_told
199 max_fibbing_twig[0] = max(max_fibbing_twig[0], lies_told)
204 max_fibbing_twig[0] = max(max_fibbing_twig[0], lies_told)
200
205
201 def __getattr__(self, item):
206 def __getattr__(self, item):
202 return SerialLiar(self.max_fibbing_twig, self.lies_told + 1)
207 return SerialLiar(self.max_fibbing_twig, self.lies_told + 1)
203
208
204
209
205 def check_calltip(obj, name, call, docstring):
210 def check_calltip(obj, name, call, docstring):
206 """Generic check pattern all calltip tests will use"""
211 """Generic check pattern all calltip tests will use"""
207 info = inspector.info(obj, name)
212 info = inspector.info(obj, name)
208 call_line, ds = oinspect.call_tip(info)
213 call_line, ds = oinspect.call_tip(info)
209 nt.assert_equal(call_line, call)
214 nt.assert_equal(call_line, call)
210 nt.assert_equal(ds, docstring)
215 nt.assert_equal(ds, docstring)
211
216
212 #-----------------------------------------------------------------------------
217 #-----------------------------------------------------------------------------
213 # Tests
218 # Tests
214 #-----------------------------------------------------------------------------
219 #-----------------------------------------------------------------------------
215
220
216 def test_calltip_class():
221 def test_calltip_class():
217 check_calltip(Call, 'Call', 'Call(x, y=1)', Call.__init__.__doc__)
222 check_calltip(Call, 'Call', 'Call(x, y=1)', Call.__init__.__doc__)
218
223
219
224
220 def test_calltip_instance():
225 def test_calltip_instance():
221 c = Call(1)
226 c = Call(1)
222 check_calltip(c, 'c', 'c(*a, **kw)', c.__call__.__doc__)
227 check_calltip(c, 'c', 'c(*a, **kw)', c.__call__.__doc__)
223
228
224
229
225 def test_calltip_method():
230 def test_calltip_method():
226 c = Call(1)
231 c = Call(1)
227 check_calltip(c.method, 'c.method', 'c.method(x, z=2)', c.method.__doc__)
232 check_calltip(c.method, 'c.method', 'c.method(x, z=2)', c.method.__doc__)
228
233
229
234
230 def test_calltip_function():
235 def test_calltip_function():
231 check_calltip(f, 'f', 'f(x, y=2, *a, **kw)', f.__doc__)
236 check_calltip(f, 'f', 'f(x, y=2, *a, **kw)', f.__doc__)
232
237
233
238
234 def test_calltip_function2():
239 def test_calltip_function2():
235 check_calltip(g, 'g', 'g(y, z=3, *a, **kw)', '<no docstring>')
240 check_calltip(g, 'g', 'g(y, z=3, *a, **kw)', '<no docstring>')
236
241
237
242
238 @skipif(sys.version_info >= (3, 5))
243 @skipif(sys.version_info >= (3, 5))
239 def test_calltip_builtin():
244 def test_calltip_builtin():
240 check_calltip(sum, 'sum', None, sum.__doc__)
245 check_calltip(sum, 'sum', None, sum.__doc__)
241
246
242
247
243 def test_calltip_line_magic():
248 def test_calltip_line_magic():
244 check_calltip(lmagic, 'lmagic', 'lmagic(line)', "A line magic")
249 check_calltip(lmagic, 'lmagic', 'lmagic(line)', "A line magic")
245
250
246
251
247 def test_calltip_cell_magic():
252 def test_calltip_cell_magic():
248 check_calltip(cmagic, 'cmagic', 'cmagic(line, cell)', "A cell magic")
253 check_calltip(cmagic, 'cmagic', 'cmagic(line, cell)', "A cell magic")
249
254
250
255
251 def test_calltip_line_cell_magic():
256 def test_calltip_line_cell_magic():
252 check_calltip(lcmagic, 'lcmagic', 'lcmagic(line, cell=None)',
257 check_calltip(lcmagic, 'lcmagic', 'lcmagic(line, cell=None)',
253 "A line/cell magic")
258 "A line/cell magic")
254
259
255
260
256 def test_class_magics():
261 def test_class_magics():
257 cm = SimpleMagics(ip)
262 cm = SimpleMagics(ip)
258 ip.register_magics(cm)
263 ip.register_magics(cm)
259 check_calltip(cm.Clmagic, 'Clmagic', 'Clmagic(cline)',
264 check_calltip(cm.Clmagic, 'Clmagic', 'Clmagic(cline)',
260 "A class-based line magic")
265 "A class-based line magic")
261 check_calltip(cm.Ccmagic, 'Ccmagic', 'Ccmagic(cline, ccell)',
266 check_calltip(cm.Ccmagic, 'Ccmagic', 'Ccmagic(cline, ccell)',
262 "A class-based cell magic")
267 "A class-based cell magic")
263 check_calltip(cm.Clcmagic, 'Clcmagic', 'Clcmagic(cline, ccell=None)',
268 check_calltip(cm.Clcmagic, 'Clcmagic', 'Clcmagic(cline, ccell=None)',
264 "A class-based line/cell magic")
269 "A class-based line/cell magic")
265
270
266
271
267 def test_info():
272 def test_info():
268 "Check that Inspector.info fills out various fields as expected."
273 "Check that Inspector.info fills out various fields as expected."
269 i = inspector.info(Call, oname='Call')
274 i = inspector.info(Call, oname='Call')
270 nt.assert_equal(i['type_name'], 'type')
275 nt.assert_equal(i['type_name'], 'type')
271 expted_class = str(type(type)) # <class 'type'> (Python 3) or <type 'type'>
276 expted_class = str(type(type)) # <class 'type'> (Python 3) or <type 'type'>
272 nt.assert_equal(i['base_class'], expted_class)
277 nt.assert_equal(i['base_class'], expted_class)
273 if sys.version_info > (3,):
278 if sys.version_info > (3,):
274 nt.assert_regex(i['string_form'], "<class 'IPython.core.tests.test_oinspect.Call'( at 0x[0-9a-f]{1,9})?>")
279 nt.assert_regex(i['string_form'], "<class 'IPython.core.tests.test_oinspect.Call'( at 0x[0-9a-f]{1,9})?>")
275 fname = __file__
280 fname = __file__
276 if fname.endswith(".pyc"):
281 if fname.endswith(".pyc"):
277 fname = fname[:-1]
282 fname = fname[:-1]
278 # case-insensitive comparison needed on some filesystems
283 # case-insensitive comparison needed on some filesystems
279 # e.g. Windows:
284 # e.g. Windows:
280 nt.assert_equal(i['file'].lower(), compress_user(fname).lower())
285 nt.assert_equal(i['file'].lower(), compress_user(fname).lower())
281 nt.assert_equal(i['definition'], None)
286 nt.assert_equal(i['definition'], None)
282 nt.assert_equal(i['docstring'], Call.__doc__)
287 nt.assert_equal(i['docstring'], Call.__doc__)
283 nt.assert_equal(i['source'], None)
288 nt.assert_equal(i['source'], None)
284 nt.assert_true(i['isclass'])
289 nt.assert_true(i['isclass'])
285 _self_py2 = '' if py3compat.PY3 else 'self, '
290 _self_py2 = '' if py3compat.PY3 else 'self, '
286 nt.assert_equal(i['init_definition'], "Call(%sx, y=1)" % _self_py2)
291 nt.assert_equal(i['init_definition'], "Call(%sx, y=1)" % _self_py2)
287 nt.assert_equal(i['init_docstring'], Call.__init__.__doc__)
292 nt.assert_equal(i['init_docstring'], Call.__init__.__doc__)
288
293
289 i = inspector.info(Call, detail_level=1)
294 i = inspector.info(Call, detail_level=1)
290 nt.assert_not_equal(i['source'], None)
295 nt.assert_not_equal(i['source'], None)
291 nt.assert_equal(i['docstring'], None)
296 nt.assert_equal(i['docstring'], None)
292
297
293 c = Call(1)
298 c = Call(1)
294 c.__doc__ = "Modified instance docstring"
299 c.__doc__ = "Modified instance docstring"
295 i = inspector.info(c)
300 i = inspector.info(c)
296 nt.assert_equal(i['type_name'], 'Call')
301 nt.assert_equal(i['type_name'], 'Call')
297 nt.assert_equal(i['docstring'], "Modified instance docstring")
302 nt.assert_equal(i['docstring'], "Modified instance docstring")
298 nt.assert_equal(i['class_docstring'], Call.__doc__)
303 nt.assert_equal(i['class_docstring'], Call.__doc__)
299 nt.assert_equal(i['init_docstring'], Call.__init__.__doc__)
304 nt.assert_equal(i['init_docstring'], Call.__init__.__doc__)
300 nt.assert_equal(i['call_docstring'], Call.__call__.__doc__)
305 nt.assert_equal(i['call_docstring'], Call.__call__.__doc__)
301
306
302 # Test old-style classes, which for example may not have an __init__ method.
307 # Test old-style classes, which for example may not have an __init__ method.
303 if not py3compat.PY3:
308 if not py3compat.PY3:
304 i = inspector.info(OldStyle)
309 i = inspector.info(OldStyle)
305 nt.assert_equal(i['type_name'], 'classobj')
310 nt.assert_equal(i['type_name'], 'classobj')
306
311
307 i = inspector.info(OldStyle())
312 i = inspector.info(OldStyle())
308 nt.assert_equal(i['type_name'], 'instance')
313 nt.assert_equal(i['type_name'], 'instance')
309 nt.assert_equal(i['docstring'], OldStyle.__doc__)
314 nt.assert_equal(i['docstring'], OldStyle.__doc__)
310
315
311 def test_class_signature():
316 def test_class_signature():
312 info = inspector.info(HasSignature, 'HasSignature')
317 info = inspector.info(HasSignature, 'HasSignature')
313 nt.assert_equal(info['init_definition'], "HasSignature(test)")
318 nt.assert_equal(info['init_definition'], "HasSignature(test)")
314 nt.assert_equal(info['init_docstring'], HasSignature.__init__.__doc__)
319 nt.assert_equal(info['init_docstring'], HasSignature.__init__.__doc__)
315
320
316 def test_info_awkward():
321 def test_info_awkward():
317 # Just test that this doesn't throw an error.
322 # Just test that this doesn't throw an error.
318 inspector.info(Awkward())
323 inspector.info(Awkward())
319
324
320 def test_bool_raise():
325 def test_bool_raise():
321 inspector.info(NoBoolCall())
326 inspector.info(NoBoolCall())
322
327
323 def test_info_serialliar():
328 def test_info_serialliar():
324 fib_tracker = [0]
329 fib_tracker = [0]
325 i = inspector.info(SerialLiar(fib_tracker))
330 inspector.info(SerialLiar(fib_tracker))
326
331
327 # Nested attribute access should be cut off at 100 levels deep to avoid
332 # Nested attribute access should be cut off at 100 levels deep to avoid
328 # infinite loops: https://github.com/ipython/ipython/issues/9122
333 # infinite loops: https://github.com/ipython/ipython/issues/9122
329 nt.assert_less(fib_tracker[0], 9000)
334 nt.assert_less(fib_tracker[0], 9000)
330
335
331 def test_calldef_none():
336 def test_calldef_none():
332 # We should ignore __call__ for all of these.
337 # We should ignore __call__ for all of these.
333 for obj in [f, SimpleClass().method, any, str.upper]:
338 for obj in [f, SimpleClass().method, any, str.upper]:
334 print(obj)
339 print(obj)
335 i = inspector.info(obj)
340 i = inspector.info(obj)
336 nt.assert_is(i['call_def'], None)
341 nt.assert_is(i['call_def'], None)
337
342
338 if py3compat.PY3:
343 def f_kwarg(pos, *, kwonly):
339 exec("def f_kwarg(pos, *, kwonly): pass")
344 pass
340
345
341 @skipif(not py3compat.PY3)
342 def test_definition_kwonlyargs():
346 def test_definition_kwonlyargs():
343 i = inspector.info(f_kwarg, oname='f_kwarg') # analysis:ignore
347 i = inspector.info(f_kwarg, oname='f_kwarg') # analysis:ignore
344 nt.assert_equal(i['definition'], "f_kwarg(pos, *, kwonly)")
348 nt.assert_equal(i['definition'], "f_kwarg(pos, *, kwonly)")
345
349
346 def test_getdoc():
350 def test_getdoc():
347 class A(object):
351 class A(object):
348 """standard docstring"""
352 """standard docstring"""
349 pass
353 pass
350
354
351 class B(object):
355 class B(object):
352 """standard docstring"""
356 """standard docstring"""
353 def getdoc(self):
357 def getdoc(self):
354 return "custom docstring"
358 return "custom docstring"
355
359
356 class C(object):
360 class C(object):
357 """standard docstring"""
361 """standard docstring"""
358 def getdoc(self):
362 def getdoc(self):
359 return None
363 return None
360
364
361 a = A()
365 a = A()
362 b = B()
366 b = B()
363 c = C()
367 c = C()
364
368
365 nt.assert_equal(oinspect.getdoc(a), "standard docstring")
369 nt.assert_equal(oinspect.getdoc(a), "standard docstring")
366 nt.assert_equal(oinspect.getdoc(b), "custom docstring")
370 nt.assert_equal(oinspect.getdoc(b), "custom docstring")
367 nt.assert_equal(oinspect.getdoc(c), "standard docstring")
371 nt.assert_equal(oinspect.getdoc(c), "standard docstring")
368
372
369
373
370 def test_empty_property_has_no_source():
374 def test_empty_property_has_no_source():
371 i = inspector.info(property(), detail_level=1)
375 i = inspector.info(property(), detail_level=1)
372 nt.assert_is(i['source'], None)
376 nt.assert_is(i['source'], None)
373
377
374
378
375 def test_property_sources():
379 def test_property_sources():
376 import zlib
380 import zlib
377
381
378 class A(object):
382 class A(object):
379 @property
383 @property
380 def foo(self):
384 def foo(self):
381 return 'bar'
385 return 'bar'
382
386
383 foo = foo.setter(lambda self, v: setattr(self, 'bar', v))
387 foo = foo.setter(lambda self, v: setattr(self, 'bar', v))
384
388
385 id = property(id)
389 id = property(id)
386 compress = property(zlib.compress)
390 compress = property(zlib.compress)
387
391
388 i = inspector.info(A.foo, detail_level=1)
392 i = inspector.info(A.foo, detail_level=1)
389 nt.assert_in('def foo(self):', i['source'])
393 nt.assert_in('def foo(self):', i['source'])
390 nt.assert_in('lambda self, v:', i['source'])
394 nt.assert_in('lambda self, v:', i['source'])
391
395
392 i = inspector.info(A.id, detail_level=1)
396 i = inspector.info(A.id, detail_level=1)
393 nt.assert_in('fget = <function id>', i['source'])
397 nt.assert_in('fget = <function id>', i['source'])
394
398
395 i = inspector.info(A.compress, detail_level=1)
399 i = inspector.info(A.compress, detail_level=1)
396 nt.assert_in('fget = <function zlib.compress>', i['source'])
400 nt.assert_in('fget = <function zlib.compress>', i['source'])
397
401
398
402
399 def test_property_docstring_is_in_info_for_detail_level_0():
403 def test_property_docstring_is_in_info_for_detail_level_0():
400 class A(object):
404 class A(object):
401 @property
405 @property
402 def foobar(self):
406 def foobar(self):
403 """This is `foobar` property."""
407 """This is `foobar` property."""
404 pass
408 pass
405
409
406 ip.user_ns['a_obj'] = A()
410 ip.user_ns['a_obj'] = A()
407 nt.assert_equals(
411 nt.assert_equals(
408 'This is `foobar` property.',
412 'This is `foobar` property.',
409 ip.object_inspect('a_obj.foobar', detail_level=0)['docstring'])
413 ip.object_inspect('a_obj.foobar', detail_level=0)['docstring'])
410
414
411 ip.user_ns['a_cls'] = A
415 ip.user_ns['a_cls'] = A
412 nt.assert_equals(
416 nt.assert_equals(
413 'This is `foobar` property.',
417 'This is `foobar` property.',
414 ip.object_inspect('a_cls.foobar', detail_level=0)['docstring'])
418 ip.object_inspect('a_cls.foobar', detail_level=0)['docstring'])
415
419
416
420
417 def test_pdef():
421 def test_pdef():
418 # See gh-1914
422 # See gh-1914
419 def foo(): pass
423 def foo(): pass
420 inspector.pdef(foo, 'foo')
424 inspector.pdef(foo, 'foo')
421
425
422
426
423 def test_pinfo_nonascii():
427 def test_pinfo_nonascii():
424 # See gh-1177
428 # See gh-1177
425 from . import nonascii2
429 from . import nonascii2
426 ip.user_ns['nonascii2'] = nonascii2
430 ip.user_ns['nonascii2'] = nonascii2
427 ip._inspect('pinfo', 'nonascii2', detail_level=1)
431 ip._inspect('pinfo', 'nonascii2', detail_level=1)
428
432
429
433
430 def test_pinfo_magic():
434 def test_pinfo_magic():
431 with AssertPrints('Docstring:'):
435 with AssertPrints('Docstring:'):
432 ip._inspect('pinfo', 'lsmagic', detail_level=0)
436 ip._inspect('pinfo', 'lsmagic', detail_level=0)
433
437
434 with AssertPrints('Source:'):
438 with AssertPrints('Source:'):
435 ip._inspect('pinfo', 'lsmagic', detail_level=1)
439 ip._inspect('pinfo', 'lsmagic', detail_level=1)
436
440
437
441
438 def test_init_colors():
442 def test_init_colors():
439 # ensure colors are not present in signature info
443 # ensure colors are not present in signature info
440 info = inspector.info(HasSignature)
444 info = inspector.info(HasSignature)
441 init_def = info['init_definition']
445 init_def = info['init_definition']
442 nt.assert_not_in('[0m', init_def)
446 nt.assert_not_in('[0m', init_def)
443
447
444
448
445 def test_builtin_init():
449 def test_builtin_init():
446 info = inspector.info(list)
450 info = inspector.info(list)
447 init_def = info['init_definition']
451 init_def = info['init_definition']
448 # Python < 3.4 can't get init definition from builtins,
452 # Python < 3.4 can't get init definition from builtins,
449 # but still exercise the inspection in case of error-raising bugs.
453 # but still exercise the inspection in case of error-raising bugs.
450 if sys.version_info >= (3,4):
454 if sys.version_info >= (3,4):
451 nt.assert_is_not_none(init_def)
455 nt.assert_is_not_none(init_def)
452
456
@@ -1,1500 +1,1489 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Verbose and colourful traceback formatting.
3 Verbose and colourful traceback formatting.
4
4
5 **ColorTB**
5 **ColorTB**
6
6
7 I've always found it a bit hard to visually parse tracebacks in Python. The
7 I've always found it a bit hard to visually parse tracebacks in Python. The
8 ColorTB class is a solution to that problem. It colors the different parts of a
8 ColorTB class is a solution to that problem. It colors the different parts of a
9 traceback in a manner similar to what you would expect from a syntax-highlighting
9 traceback in a manner similar to what you would expect from a syntax-highlighting
10 text editor.
10 text editor.
11
11
12 Installation instructions for ColorTB::
12 Installation instructions for ColorTB::
13
13
14 import sys,ultratb
14 import sys,ultratb
15 sys.excepthook = ultratb.ColorTB()
15 sys.excepthook = ultratb.ColorTB()
16
16
17 **VerboseTB**
17 **VerboseTB**
18
18
19 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
19 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
20 of useful info when a traceback occurs. Ping originally had it spit out HTML
20 of useful info when a traceback occurs. Ping originally had it spit out HTML
21 and intended it for CGI programmers, but why should they have all the fun? I
21 and intended it for CGI programmers, but why should they have all the fun? I
22 altered it to spit out colored text to the terminal. It's a bit overwhelming,
22 altered it to spit out colored text to the terminal. It's a bit overwhelming,
23 but kind of neat, and maybe useful for long-running programs that you believe
23 but kind of neat, and maybe useful for long-running programs that you believe
24 are bug-free. If a crash *does* occur in that type of program you want details.
24 are bug-free. If a crash *does* occur in that type of program you want details.
25 Give it a shot--you'll love it or you'll hate it.
25 Give it a shot--you'll love it or you'll hate it.
26
26
27 .. note::
27 .. note::
28
28
29 The Verbose mode prints the variables currently visible where the exception
29 The Verbose mode prints the variables currently visible where the exception
30 happened (shortening their strings if too long). This can potentially be
30 happened (shortening their strings if too long). This can potentially be
31 very slow, if you happen to have a huge data structure whose string
31 very slow, if you happen to have a huge data structure whose string
32 representation is complex to compute. Your computer may appear to freeze for
32 representation is complex to compute. Your computer may appear to freeze for
33 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
33 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
34 with Ctrl-C (maybe hitting it more than once).
34 with Ctrl-C (maybe hitting it more than once).
35
35
36 If you encounter this kind of situation often, you may want to use the
36 If you encounter this kind of situation often, you may want to use the
37 Verbose_novars mode instead of the regular Verbose, which avoids formatting
37 Verbose_novars mode instead of the regular Verbose, which avoids formatting
38 variables (but otherwise includes the information and context given by
38 variables (but otherwise includes the information and context given by
39 Verbose).
39 Verbose).
40
40
41 .. note::
41 .. note::
42
42
43 The verbose mode print all variables in the stack, which means it can
43 The verbose mode print all variables in the stack, which means it can
44 potentially leak sensitive information like access keys, or unencryted
44 potentially leak sensitive information like access keys, or unencryted
45 password.
45 password.
46
46
47 Installation instructions for VerboseTB::
47 Installation instructions for VerboseTB::
48
48
49 import sys,ultratb
49 import sys,ultratb
50 sys.excepthook = ultratb.VerboseTB()
50 sys.excepthook = ultratb.VerboseTB()
51
51
52 Note: Much of the code in this module was lifted verbatim from the standard
52 Note: Much of the code in this module was lifted verbatim from the standard
53 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
53 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
54
54
55 Color schemes
55 Color schemes
56 -------------
56 -------------
57
57
58 The colors are defined in the class TBTools through the use of the
58 The colors are defined in the class TBTools through the use of the
59 ColorSchemeTable class. Currently the following exist:
59 ColorSchemeTable class. Currently the following exist:
60
60
61 - NoColor: allows all of this module to be used in any terminal (the color
61 - NoColor: allows all of this module to be used in any terminal (the color
62 escapes are just dummy blank strings).
62 escapes are just dummy blank strings).
63
63
64 - Linux: is meant to look good in a terminal like the Linux console (black
64 - Linux: is meant to look good in a terminal like the Linux console (black
65 or very dark background).
65 or very dark background).
66
66
67 - LightBG: similar to Linux but swaps dark/light colors to be more readable
67 - LightBG: similar to Linux but swaps dark/light colors to be more readable
68 in light background terminals.
68 in light background terminals.
69
69
70 - Neutral: a neutral color scheme that should be readable on both light and
70 - Neutral: a neutral color scheme that should be readable on both light and
71 dark background
71 dark background
72
72
73 You can implement other color schemes easily, the syntax is fairly
73 You can implement other color schemes easily, the syntax is fairly
74 self-explanatory. Please send back new schemes you develop to the author for
74 self-explanatory. Please send back new schemes you develop to the author for
75 possible inclusion in future releases.
75 possible inclusion in future releases.
76
76
77 Inheritance diagram:
77 Inheritance diagram:
78
78
79 .. inheritance-diagram:: IPython.core.ultratb
79 .. inheritance-diagram:: IPython.core.ultratb
80 :parts: 3
80 :parts: 3
81 """
81 """
82
82
83 #*****************************************************************************
83 #*****************************************************************************
84 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
84 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
85 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
85 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
86 #
86 #
87 # Distributed under the terms of the BSD License. The full license is in
87 # Distributed under the terms of the BSD License. The full license is in
88 # the file COPYING, distributed as part of this software.
88 # the file COPYING, distributed as part of this software.
89 #*****************************************************************************
89 #*****************************************************************************
90
90
91 from __future__ import absolute_import
91 from __future__ import absolute_import
92 from __future__ import unicode_literals
92 from __future__ import unicode_literals
93 from __future__ import print_function
93 from __future__ import print_function
94
94
95 import dis
95 import dis
96 import inspect
96 import inspect
97 import keyword
97 import keyword
98 import linecache
98 import linecache
99 import os
99 import os
100 import pydoc
100 import pydoc
101 import re
101 import re
102 import sys
102 import sys
103 import time
103 import time
104 import tokenize
104 import tokenize
105 import traceback
105 import traceback
106 import types
106 import types
107
107
108 try: # Python 2
108 try: # Python 2
109 generate_tokens = tokenize.generate_tokens
109 generate_tokens = tokenize.generate_tokens
110 except AttributeError: # Python 3
110 except AttributeError: # Python 3
111 generate_tokens = tokenize.tokenize
111 generate_tokens = tokenize.tokenize
112
112
113 # For purposes of monkeypatching inspect to fix a bug in it.
113 # For purposes of monkeypatching inspect to fix a bug in it.
114 from inspect import getsourcefile, getfile, getmodule, \
114 from inspect import getsourcefile, getfile, getmodule, \
115 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
115 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
116
116
117 # IPython's own modules
117 # IPython's own modules
118 from IPython import get_ipython
118 from IPython import get_ipython
119 from IPython.core import debugger
119 from IPython.core import debugger
120 from IPython.core.display_trap import DisplayTrap
120 from IPython.core.display_trap import DisplayTrap
121 from IPython.core.excolors import exception_colors
121 from IPython.core.excolors import exception_colors
122 from IPython.utils import PyColorize
122 from IPython.utils import PyColorize
123 from IPython.utils import openpy
123 from IPython.utils import openpy
124 from IPython.utils import path as util_path
124 from IPython.utils import path as util_path
125 from IPython.utils import py3compat
125 from IPython.utils import py3compat
126 from IPython.utils import ulinecache
126 from IPython.utils import ulinecache
127 from IPython.utils.data import uniq_stable
127 from IPython.utils.data import uniq_stable
128 from IPython.utils.terminal import get_terminal_size
128 from IPython.utils.terminal import get_terminal_size
129 from logging import info, error
129 from logging import info, error
130
130
131 import IPython.utils.colorable as colorable
131 import IPython.utils.colorable as colorable
132
132
133 # Globals
133 # Globals
134 # amount of space to put line numbers before verbose tracebacks
134 # amount of space to put line numbers before verbose tracebacks
135 INDENT_SIZE = 8
135 INDENT_SIZE = 8
136
136
137 # Default color scheme. This is used, for example, by the traceback
137 # Default color scheme. This is used, for example, by the traceback
138 # formatter. When running in an actual IPython instance, the user's rc.colors
138 # formatter. When running in an actual IPython instance, the user's rc.colors
139 # value is used, but having a module global makes this functionality available
139 # value is used, but having a module global makes this functionality available
140 # to users of ultratb who are NOT running inside ipython.
140 # to users of ultratb who are NOT running inside ipython.
141 DEFAULT_SCHEME = 'NoColor'
141 DEFAULT_SCHEME = 'NoColor'
142
142
143 # ---------------------------------------------------------------------------
143 # ---------------------------------------------------------------------------
144 # Code begins
144 # Code begins
145
145
146 # Utility functions
146 # Utility functions
147 def inspect_error():
147 def inspect_error():
148 """Print a message about internal inspect errors.
148 """Print a message about internal inspect errors.
149
149
150 These are unfortunately quite common."""
150 These are unfortunately quite common."""
151
151
152 error('Internal Python error in the inspect module.\n'
152 error('Internal Python error in the inspect module.\n'
153 'Below is the traceback from this internal error.\n')
153 'Below is the traceback from this internal error.\n')
154
154
155
155
156 # This function is a monkeypatch we apply to the Python inspect module. We have
156 # This function is a monkeypatch we apply to the Python inspect module. We have
157 # now found when it's needed (see discussion on issue gh-1456), and we have a
157 # now found when it's needed (see discussion on issue gh-1456), and we have a
158 # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
158 # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
159 # the monkeypatch is not applied. TK, Aug 2012.
159 # the monkeypatch is not applied. TK, Aug 2012.
160 def findsource(object):
160 def findsource(object):
161 """Return the entire source file and starting line number for an object.
161 """Return the entire source file and starting line number for an object.
162
162
163 The argument may be a module, class, method, function, traceback, frame,
163 The argument may be a module, class, method, function, traceback, frame,
164 or code object. The source code is returned as a list of all the lines
164 or code object. The source code is returned as a list of all the lines
165 in the file and the line number indexes a line in that list. An IOError
165 in the file and the line number indexes a line in that list. An IOError
166 is raised if the source code cannot be retrieved.
166 is raised if the source code cannot be retrieved.
167
167
168 FIXED version with which we monkeypatch the stdlib to work around a bug."""
168 FIXED version with which we monkeypatch the stdlib to work around a bug."""
169
169
170 file = getsourcefile(object) or getfile(object)
170 file = getsourcefile(object) or getfile(object)
171 # If the object is a frame, then trying to get the globals dict from its
171 # If the object is a frame, then trying to get the globals dict from its
172 # module won't work. Instead, the frame object itself has the globals
172 # module won't work. Instead, the frame object itself has the globals
173 # dictionary.
173 # dictionary.
174 globals_dict = None
174 globals_dict = None
175 if inspect.isframe(object):
175 if inspect.isframe(object):
176 # XXX: can this ever be false?
176 # XXX: can this ever be false?
177 globals_dict = object.f_globals
177 globals_dict = object.f_globals
178 else:
178 else:
179 module = getmodule(object, file)
179 module = getmodule(object, file)
180 if module:
180 if module:
181 globals_dict = module.__dict__
181 globals_dict = module.__dict__
182 lines = linecache.getlines(file, globals_dict)
182 lines = linecache.getlines(file, globals_dict)
183 if not lines:
183 if not lines:
184 raise IOError('could not get source code')
184 raise IOError('could not get source code')
185
185
186 if ismodule(object):
186 if ismodule(object):
187 return lines, 0
187 return lines, 0
188
188
189 if isclass(object):
189 if isclass(object):
190 name = object.__name__
190 name = object.__name__
191 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
191 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
192 # make some effort to find the best matching class definition:
192 # make some effort to find the best matching class definition:
193 # use the one with the least indentation, which is the one
193 # use the one with the least indentation, which is the one
194 # that's most probably not inside a function definition.
194 # that's most probably not inside a function definition.
195 candidates = []
195 candidates = []
196 for i in range(len(lines)):
196 for i in range(len(lines)):
197 match = pat.match(lines[i])
197 match = pat.match(lines[i])
198 if match:
198 if match:
199 # if it's at toplevel, it's already the best one
199 # if it's at toplevel, it's already the best one
200 if lines[i][0] == 'c':
200 if lines[i][0] == 'c':
201 return lines, i
201 return lines, i
202 # else add whitespace to candidate list
202 # else add whitespace to candidate list
203 candidates.append((match.group(1), i))
203 candidates.append((match.group(1), i))
204 if candidates:
204 if candidates:
205 # this will sort by whitespace, and by line number,
205 # this will sort by whitespace, and by line number,
206 # less whitespace first
206 # less whitespace first
207 candidates.sort()
207 candidates.sort()
208 return lines, candidates[0][1]
208 return lines, candidates[0][1]
209 else:
209 else:
210 raise IOError('could not find class definition')
210 raise IOError('could not find class definition')
211
211
212 if ismethod(object):
212 if ismethod(object):
213 object = object.__func__
213 object = object.__func__
214 if isfunction(object):
214 if isfunction(object):
215 object = object.__code__
215 object = object.__code__
216 if istraceback(object):
216 if istraceback(object):
217 object = object.tb_frame
217 object = object.tb_frame
218 if isframe(object):
218 if isframe(object):
219 object = object.f_code
219 object = object.f_code
220 if iscode(object):
220 if iscode(object):
221 if not hasattr(object, 'co_firstlineno'):
221 if not hasattr(object, 'co_firstlineno'):
222 raise IOError('could not find function definition')
222 raise IOError('could not find function definition')
223 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
223 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
224 pmatch = pat.match
224 pmatch = pat.match
225 # fperez - fix: sometimes, co_firstlineno can give a number larger than
225 # fperez - fix: sometimes, co_firstlineno can give a number larger than
226 # the length of lines, which causes an error. Safeguard against that.
226 # the length of lines, which causes an error. Safeguard against that.
227 lnum = min(object.co_firstlineno, len(lines)) - 1
227 lnum = min(object.co_firstlineno, len(lines)) - 1
228 while lnum > 0:
228 while lnum > 0:
229 if pmatch(lines[lnum]):
229 if pmatch(lines[lnum]):
230 break
230 break
231 lnum -= 1
231 lnum -= 1
232
232
233 return lines, lnum
233 return lines, lnum
234 raise IOError('could not find code object')
234 raise IOError('could not find code object')
235
235
236
236
237 # This is a patched version of inspect.getargs that applies the (unmerged)
237 # This is a patched version of inspect.getargs that applies the (unmerged)
238 # patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes
238 # patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes
239 # https://github.com/ipython/ipython/issues/8205 and
239 # https://github.com/ipython/ipython/issues/8205 and
240 # https://github.com/ipython/ipython/issues/8293
240 # https://github.com/ipython/ipython/issues/8293
241 def getargs(co):
241 def getargs(co):
242 """Get information about the arguments accepted by a code object.
242 """Get information about the arguments accepted by a code object.
243
243
244 Three things are returned: (args, varargs, varkw), where 'args' is
244 Three things are returned: (args, varargs, varkw), where 'args' is
245 a list of argument names (possibly containing nested lists), and
245 a list of argument names (possibly containing nested lists), and
246 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
246 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
247 if not iscode(co):
247 if not iscode(co):
248 raise TypeError('{!r} is not a code object'.format(co))
248 raise TypeError('{!r} is not a code object'.format(co))
249
249
250 nargs = co.co_argcount
250 nargs = co.co_argcount
251 names = co.co_varnames
251 names = co.co_varnames
252 args = list(names[:nargs])
252 args = list(names[:nargs])
253 step = 0
253 step = 0
254
254
255 # The following acrobatics are for anonymous (tuple) arguments.
255 # The following acrobatics are for anonymous (tuple) arguments.
256 for i in range(nargs):
256 for i in range(nargs):
257 if args[i][:1] in ('', '.'):
257 if args[i][:1] in ('', '.'):
258 stack, remain, count = [], [], []
258 stack, remain, count = [], [], []
259 while step < len(co.co_code):
259 while step < len(co.co_code):
260 op = ord(co.co_code[step])
260 op = ord(co.co_code[step])
261 step = step + 1
261 step = step + 1
262 if op >= dis.HAVE_ARGUMENT:
262 if op >= dis.HAVE_ARGUMENT:
263 opname = dis.opname[op]
263 opname = dis.opname[op]
264 value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256
264 value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256
265 step = step + 2
265 step = step + 2
266 if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
266 if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
267 remain.append(value)
267 remain.append(value)
268 count.append(value)
268 count.append(value)
269 elif opname in ('STORE_FAST', 'STORE_DEREF'):
269 elif opname in ('STORE_FAST', 'STORE_DEREF'):
270 if op in dis.haslocal:
270 if op in dis.haslocal:
271 stack.append(co.co_varnames[value])
271 stack.append(co.co_varnames[value])
272 elif op in dis.hasfree:
272 elif op in dis.hasfree:
273 stack.append((co.co_cellvars + co.co_freevars)[value])
273 stack.append((co.co_cellvars + co.co_freevars)[value])
274 # Special case for sublists of length 1: def foo((bar))
274 # Special case for sublists of length 1: def foo((bar))
275 # doesn't generate the UNPACK_TUPLE bytecode, so if
275 # doesn't generate the UNPACK_TUPLE bytecode, so if
276 # `remain` is empty here, we have such a sublist.
276 # `remain` is empty here, we have such a sublist.
277 if not remain:
277 if not remain:
278 stack[0] = [stack[0]]
278 stack[0] = [stack[0]]
279 break
279 break
280 else:
280 else:
281 remain[-1] = remain[-1] - 1
281 remain[-1] = remain[-1] - 1
282 while remain[-1] == 0:
282 while remain[-1] == 0:
283 remain.pop()
283 remain.pop()
284 size = count.pop()
284 size = count.pop()
285 stack[-size:] = [stack[-size:]]
285 stack[-size:] = [stack[-size:]]
286 if not remain:
286 if not remain:
287 break
287 break
288 remain[-1] = remain[-1] - 1
288 remain[-1] = remain[-1] - 1
289 if not remain:
289 if not remain:
290 break
290 break
291 args[i] = stack[0]
291 args[i] = stack[0]
292
292
293 varargs = None
293 varargs = None
294 if co.co_flags & inspect.CO_VARARGS:
294 if co.co_flags & inspect.CO_VARARGS:
295 varargs = co.co_varnames[nargs]
295 varargs = co.co_varnames[nargs]
296 nargs = nargs + 1
296 nargs = nargs + 1
297 varkw = None
297 varkw = None
298 if co.co_flags & inspect.CO_VARKEYWORDS:
298 if co.co_flags & inspect.CO_VARKEYWORDS:
299 varkw = co.co_varnames[nargs]
299 varkw = co.co_varnames[nargs]
300 return inspect.Arguments(args, varargs, varkw)
300 return inspect.Arguments(args, varargs, varkw)
301
301
302
302
303 # Monkeypatch inspect to apply our bugfix.
303 # Monkeypatch inspect to apply our bugfix.
304 def with_patch_inspect(f):
304 def with_patch_inspect(f):
305 """decorator for monkeypatching inspect.findsource"""
305 """decorator for monkeypatching inspect.findsource"""
306
306
307 def wrapped(*args, **kwargs):
307 def wrapped(*args, **kwargs):
308 save_findsource = inspect.findsource
308 save_findsource = inspect.findsource
309 save_getargs = inspect.getargs
309 save_getargs = inspect.getargs
310 inspect.findsource = findsource
310 inspect.findsource = findsource
311 inspect.getargs = getargs
311 inspect.getargs = getargs
312 try:
312 try:
313 return f(*args, **kwargs)
313 return f(*args, **kwargs)
314 finally:
314 finally:
315 inspect.findsource = save_findsource
315 inspect.findsource = save_findsource
316 inspect.getargs = save_getargs
316 inspect.getargs = save_getargs
317
317
318 return wrapped
318 return wrapped
319
319
320
320
321 if py3compat.PY3:
321 if py3compat.PY3:
322 fixed_getargvalues = inspect.getargvalues
322 fixed_getargvalues = inspect.getargvalues
323 else:
323 else:
324 # Fixes for https://github.com/ipython/ipython/issues/8293
324 # Fixes for https://github.com/ipython/ipython/issues/8293
325 # and https://github.com/ipython/ipython/issues/8205.
325 # and https://github.com/ipython/ipython/issues/8205.
326 # The relevant bug is caused by failure to correctly handle anonymous tuple
326 # The relevant bug is caused by failure to correctly handle anonymous tuple
327 # unpacking, which only exists in Python 2.
327 # unpacking, which only exists in Python 2.
328 fixed_getargvalues = with_patch_inspect(inspect.getargvalues)
328 fixed_getargvalues = with_patch_inspect(inspect.getargvalues)
329
329
330
330
331 def fix_frame_records_filenames(records):
331 def fix_frame_records_filenames(records):
332 """Try to fix the filenames in each record from inspect.getinnerframes().
332 """Try to fix the filenames in each record from inspect.getinnerframes().
333
333
334 Particularly, modules loaded from within zip files have useless filenames
334 Particularly, modules loaded from within zip files have useless filenames
335 attached to their code object, and inspect.getinnerframes() just uses it.
335 attached to their code object, and inspect.getinnerframes() just uses it.
336 """
336 """
337 fixed_records = []
337 fixed_records = []
338 for frame, filename, line_no, func_name, lines, index in records:
338 for frame, filename, line_no, func_name, lines, index in records:
339 # Look inside the frame's globals dictionary for __file__,
339 # Look inside the frame's globals dictionary for __file__,
340 # which should be better. However, keep Cython filenames since
340 # which should be better. However, keep Cython filenames since
341 # we prefer the source filenames over the compiled .so file.
341 # we prefer the source filenames over the compiled .so file.
342 filename = py3compat.cast_unicode_py2(filename, "utf-8")
342 filename = py3compat.cast_unicode_py2(filename, "utf-8")
343 if not filename.endswith(('.pyx', '.pxd', '.pxi')):
343 if not filename.endswith(('.pyx', '.pxd', '.pxi')):
344 better_fn = frame.f_globals.get('__file__', None)
344 better_fn = frame.f_globals.get('__file__', None)
345 if isinstance(better_fn, str):
345 if isinstance(better_fn, str):
346 # Check the type just in case someone did something weird with
346 # Check the type just in case someone did something weird with
347 # __file__. It might also be None if the error occurred during
347 # __file__. It might also be None if the error occurred during
348 # import.
348 # import.
349 filename = better_fn
349 filename = better_fn
350 fixed_records.append((frame, filename, line_no, func_name, lines, index))
350 fixed_records.append((frame, filename, line_no, func_name, lines, index))
351 return fixed_records
351 return fixed_records
352
352
353
353
354 @with_patch_inspect
354 @with_patch_inspect
355 def _fixed_getinnerframes(etb, context=1, tb_offset=0):
355 def _fixed_getinnerframes(etb, context=1, tb_offset=0):
356 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
356 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
357
357
358 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
358 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
359 # If the error is at the console, don't build any context, since it would
359 # If the error is at the console, don't build any context, since it would
360 # otherwise produce 5 blank lines printed out (there is no file at the
360 # otherwise produce 5 blank lines printed out (there is no file at the
361 # console)
361 # console)
362 rec_check = records[tb_offset:]
362 rec_check = records[tb_offset:]
363 try:
363 try:
364 rname = rec_check[0][1]
364 rname = rec_check[0][1]
365 if rname == '<ipython console>' or rname.endswith('<string>'):
365 if rname == '<ipython console>' or rname.endswith('<string>'):
366 return rec_check
366 return rec_check
367 except IndexError:
367 except IndexError:
368 pass
368 pass
369
369
370 aux = traceback.extract_tb(etb)
370 aux = traceback.extract_tb(etb)
371 assert len(records) == len(aux)
371 assert len(records) == len(aux)
372 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
372 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
373 maybeStart = lnum - 1 - context // 2
373 maybeStart = lnum - 1 - context // 2
374 start = max(maybeStart, 0)
374 start = max(maybeStart, 0)
375 end = start + context
375 end = start + context
376 lines = ulinecache.getlines(file)[start:end]
376 lines = ulinecache.getlines(file)[start:end]
377 buf = list(records[i])
377 buf = list(records[i])
378 buf[LNUM_POS] = lnum
378 buf[LNUM_POS] = lnum
379 buf[INDEX_POS] = lnum - 1 - start
379 buf[INDEX_POS] = lnum - 1 - start
380 buf[LINES_POS] = lines
380 buf[LINES_POS] = lines
381 records[i] = tuple(buf)
381 records[i] = tuple(buf)
382 return records[tb_offset:]
382 return records[tb_offset:]
383
383
384 # Helper function -- largely belongs to VerboseTB, but we need the same
384 # Helper function -- largely belongs to VerboseTB, but we need the same
385 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
385 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
386 # can be recognized properly by ipython.el's py-traceback-line-re
386 # can be recognized properly by ipython.el's py-traceback-line-re
387 # (SyntaxErrors have to be treated specially because they have no traceback)
387 # (SyntaxErrors have to be treated specially because they have no traceback)
388
388
389 _parser = PyColorize.Parser()
390
391
389
392 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None, scheme=None):
390 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None, scheme=None):
393 numbers_width = INDENT_SIZE - 1
391 numbers_width = INDENT_SIZE - 1
394 res = []
392 res = []
395 i = lnum - index
393 i = lnum - index
396
394
397 # This lets us get fully syntax-highlighted tracebacks.
395 _line_format = PyColorize.Parser(style=scheme).format2
398 if scheme is None:
399 ipinst = get_ipython()
400 if ipinst is not None:
401 scheme = ipinst.colors
402 else:
403 scheme = DEFAULT_SCHEME
404
405 _line_format = _parser.format2
406
396
407 for line in lines:
397 for line in lines:
408 line = py3compat.cast_unicode(line)
398 line = py3compat.cast_unicode(line)
409
399
410 new_line, err = _line_format(line, 'str', scheme)
400 new_line, err = _line_format(line, 'str')
411 if not err: line = new_line
401 if not err: line = new_line
412
402
413 if i == lnum:
403 if i == lnum:
414 # This is the line with the error
404 # This is the line with the error
415 pad = numbers_width - len(str(i))
405 pad = numbers_width - len(str(i))
416 num = '%s%s' % (debugger.make_arrow(pad), str(lnum))
406 num = '%s%s' % (debugger.make_arrow(pad), str(lnum))
417 line = '%s%s%s %s%s' % (Colors.linenoEm, num,
407 line = '%s%s%s %s%s' % (Colors.linenoEm, num,
418 Colors.line, line, Colors.Normal)
408 Colors.line, line, Colors.Normal)
419 else:
409 else:
420 num = '%*s' % (numbers_width, i)
410 num = '%*s' % (numbers_width, i)
421 line = '%s%s%s %s' % (Colors.lineno, num,
411 line = '%s%s%s %s' % (Colors.lineno, num,
422 Colors.Normal, line)
412 Colors.Normal, line)
423
413
424 res.append(line)
414 res.append(line)
425 if lvals and i == lnum:
415 if lvals and i == lnum:
426 res.append(lvals + '\n')
416 res.append(lvals + '\n')
427 i = i + 1
417 i = i + 1
428 return res
418 return res
429
419
430 def is_recursion_error(etype, value, records):
420 def is_recursion_error(etype, value, records):
431 try:
421 try:
432 # RecursionError is new in Python 3.5
422 # RecursionError is new in Python 3.5
433 recursion_error_type = RecursionError
423 recursion_error_type = RecursionError
434 except NameError:
424 except NameError:
435 recursion_error_type = RuntimeError
425 recursion_error_type = RuntimeError
436
426
437 # The default recursion limit is 1000, but some of that will be taken up
427 # The default recursion limit is 1000, but some of that will be taken up
438 # by stack frames in IPython itself. >500 frames probably indicates
428 # by stack frames in IPython itself. >500 frames probably indicates
439 # a recursion error.
429 # a recursion error.
440 return (etype is recursion_error_type) \
430 return (etype is recursion_error_type) \
441 and "recursion" in str(value).lower() \
431 and "recursion" in str(value).lower() \
442 and len(records) > 500
432 and len(records) > 500
443
433
444 def find_recursion(etype, value, records):
434 def find_recursion(etype, value, records):
445 """Identify the repeating stack frames from a RecursionError traceback
435 """Identify the repeating stack frames from a RecursionError traceback
446
436
447 'records' is a list as returned by VerboseTB.get_records()
437 'records' is a list as returned by VerboseTB.get_records()
448
438
449 Returns (last_unique, repeat_length)
439 Returns (last_unique, repeat_length)
450 """
440 """
451 # This involves a bit of guesswork - we want to show enough of the traceback
441 # This involves a bit of guesswork - we want to show enough of the traceback
452 # to indicate where the recursion is occurring. We guess that the innermost
442 # to indicate where the recursion is occurring. We guess that the innermost
453 # quarter of the traceback (250 frames by default) is repeats, and find the
443 # quarter of the traceback (250 frames by default) is repeats, and find the
454 # first frame (from in to out) that looks different.
444 # first frame (from in to out) that looks different.
455 if not is_recursion_error(etype, value, records):
445 if not is_recursion_error(etype, value, records):
456 return len(records), 0
446 return len(records), 0
457
447
458 # Select filename, lineno, func_name to track frames with
448 # Select filename, lineno, func_name to track frames with
459 records = [r[1:4] for r in records]
449 records = [r[1:4] for r in records]
460 inner_frames = records[-(len(records)//4):]
450 inner_frames = records[-(len(records)//4):]
461 frames_repeated = set(inner_frames)
451 frames_repeated = set(inner_frames)
462
452
463 last_seen_at = {}
453 last_seen_at = {}
464 longest_repeat = 0
454 longest_repeat = 0
465 i = len(records)
455 i = len(records)
466 for frame in reversed(records):
456 for frame in reversed(records):
467 i -= 1
457 i -= 1
468 if frame not in frames_repeated:
458 if frame not in frames_repeated:
469 last_unique = i
459 last_unique = i
470 break
460 break
471
461
472 if frame in last_seen_at:
462 if frame in last_seen_at:
473 distance = last_seen_at[frame] - i
463 distance = last_seen_at[frame] - i
474 longest_repeat = max(longest_repeat, distance)
464 longest_repeat = max(longest_repeat, distance)
475
465
476 last_seen_at[frame] = i
466 last_seen_at[frame] = i
477 else:
467 else:
478 last_unique = 0 # The whole traceback was recursion
468 last_unique = 0 # The whole traceback was recursion
479
469
480 return last_unique, longest_repeat
470 return last_unique, longest_repeat
481
471
482 #---------------------------------------------------------------------------
472 #---------------------------------------------------------------------------
483 # Module classes
473 # Module classes
484 class TBTools(colorable.Colorable):
474 class TBTools(colorable.Colorable):
485 """Basic tools used by all traceback printer classes."""
475 """Basic tools used by all traceback printer classes."""
486
476
487 # Number of frames to skip when reporting tracebacks
477 # Number of frames to skip when reporting tracebacks
488 tb_offset = 0
478 tb_offset = 0
489
479
490 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
480 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
491 # Whether to call the interactive pdb debugger after printing
481 # Whether to call the interactive pdb debugger after printing
492 # tracebacks or not
482 # tracebacks or not
493 super(TBTools, self).__init__(parent=parent, config=config)
483 super(TBTools, self).__init__(parent=parent, config=config)
494 self.call_pdb = call_pdb
484 self.call_pdb = call_pdb
495
485
496 # Output stream to write to. Note that we store the original value in
486 # Output stream to write to. Note that we store the original value in
497 # a private attribute and then make the public ostream a property, so
487 # a private attribute and then make the public ostream a property, so
498 # that we can delay accessing sys.stdout until runtime. The way
488 # that we can delay accessing sys.stdout until runtime. The way
499 # things are written now, the sys.stdout object is dynamically managed
489 # things are written now, the sys.stdout object is dynamically managed
500 # so a reference to it should NEVER be stored statically. This
490 # so a reference to it should NEVER be stored statically. This
501 # property approach confines this detail to a single location, and all
491 # property approach confines this detail to a single location, and all
502 # subclasses can simply access self.ostream for writing.
492 # subclasses can simply access self.ostream for writing.
503 self._ostream = ostream
493 self._ostream = ostream
504
494
505 # Create color table
495 # Create color table
506 self.color_scheme_table = exception_colors()
496 self.color_scheme_table = exception_colors()
507
497
508 self.set_colors(color_scheme)
498 self.set_colors(color_scheme)
509 self.old_scheme = color_scheme # save initial value for toggles
499 self.old_scheme = color_scheme # save initial value for toggles
510
500
511 if call_pdb:
501 if call_pdb:
512 self.pdb = debugger.Pdb()
502 self.pdb = debugger.Pdb()
513 else:
503 else:
514 self.pdb = None
504 self.pdb = None
515
505
516 def _get_ostream(self):
506 def _get_ostream(self):
517 """Output stream that exceptions are written to.
507 """Output stream that exceptions are written to.
518
508
519 Valid values are:
509 Valid values are:
520
510
521 - None: the default, which means that IPython will dynamically resolve
511 - None: the default, which means that IPython will dynamically resolve
522 to sys.stdout. This ensures compatibility with most tools, including
512 to sys.stdout. This ensures compatibility with most tools, including
523 Windows (where plain stdout doesn't recognize ANSI escapes).
513 Windows (where plain stdout doesn't recognize ANSI escapes).
524
514
525 - Any object with 'write' and 'flush' attributes.
515 - Any object with 'write' and 'flush' attributes.
526 """
516 """
527 return sys.stdout if self._ostream is None else self._ostream
517 return sys.stdout if self._ostream is None else self._ostream
528
518
529 def _set_ostream(self, val):
519 def _set_ostream(self, val):
530 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
520 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
531 self._ostream = val
521 self._ostream = val
532
522
533 ostream = property(_get_ostream, _set_ostream)
523 ostream = property(_get_ostream, _set_ostream)
534
524
535 def set_colors(self, *args, **kw):
525 def set_colors(self, *args, **kw):
536 """Shorthand access to the color table scheme selector method."""
526 """Shorthand access to the color table scheme selector method."""
537
527
538 # Set own color table
528 # Set own color table
539 self.color_scheme_table.set_active_scheme(*args, **kw)
529 self.color_scheme_table.set_active_scheme(*args, **kw)
540 # for convenience, set Colors to the active scheme
530 # for convenience, set Colors to the active scheme
541 self.Colors = self.color_scheme_table.active_colors
531 self.Colors = self.color_scheme_table.active_colors
542 # Also set colors of debugger
532 # Also set colors of debugger
543 if hasattr(self, 'pdb') and self.pdb is not None:
533 if hasattr(self, 'pdb') and self.pdb is not None:
544 self.pdb.set_colors(*args, **kw)
534 self.pdb.set_colors(*args, **kw)
545
535
546 def color_toggle(self):
536 def color_toggle(self):
547 """Toggle between the currently active color scheme and NoColor."""
537 """Toggle between the currently active color scheme and NoColor."""
548
538
549 if self.color_scheme_table.active_scheme_name == 'NoColor':
539 if self.color_scheme_table.active_scheme_name == 'NoColor':
550 self.color_scheme_table.set_active_scheme(self.old_scheme)
540 self.color_scheme_table.set_active_scheme(self.old_scheme)
551 self.Colors = self.color_scheme_table.active_colors
541 self.Colors = self.color_scheme_table.active_colors
552 else:
542 else:
553 self.old_scheme = self.color_scheme_table.active_scheme_name
543 self.old_scheme = self.color_scheme_table.active_scheme_name
554 self.color_scheme_table.set_active_scheme('NoColor')
544 self.color_scheme_table.set_active_scheme('NoColor')
555 self.Colors = self.color_scheme_table.active_colors
545 self.Colors = self.color_scheme_table.active_colors
556
546
557 def stb2text(self, stb):
547 def stb2text(self, stb):
558 """Convert a structured traceback (a list) to a string."""
548 """Convert a structured traceback (a list) to a string."""
559 return '\n'.join(stb)
549 return '\n'.join(stb)
560
550
561 def text(self, etype, value, tb, tb_offset=None, context=5):
551 def text(self, etype, value, tb, tb_offset=None, context=5):
562 """Return formatted traceback.
552 """Return formatted traceback.
563
553
564 Subclasses may override this if they add extra arguments.
554 Subclasses may override this if they add extra arguments.
565 """
555 """
566 tb_list = self.structured_traceback(etype, value, tb,
556 tb_list = self.structured_traceback(etype, value, tb,
567 tb_offset, context)
557 tb_offset, context)
568 return self.stb2text(tb_list)
558 return self.stb2text(tb_list)
569
559
570 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
560 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
571 context=5, mode=None):
561 context=5, mode=None):
572 """Return a list of traceback frames.
562 """Return a list of traceback frames.
573
563
574 Must be implemented by each class.
564 Must be implemented by each class.
575 """
565 """
576 raise NotImplementedError()
566 raise NotImplementedError()
577
567
578
568
579 #---------------------------------------------------------------------------
569 #---------------------------------------------------------------------------
580 class ListTB(TBTools):
570 class ListTB(TBTools):
581 """Print traceback information from a traceback list, with optional color.
571 """Print traceback information from a traceback list, with optional color.
582
572
583 Calling requires 3 arguments: (etype, evalue, elist)
573 Calling requires 3 arguments: (etype, evalue, elist)
584 as would be obtained by::
574 as would be obtained by::
585
575
586 etype, evalue, tb = sys.exc_info()
576 etype, evalue, tb = sys.exc_info()
587 if tb:
577 if tb:
588 elist = traceback.extract_tb(tb)
578 elist = traceback.extract_tb(tb)
589 else:
579 else:
590 elist = None
580 elist = None
591
581
592 It can thus be used by programs which need to process the traceback before
582 It can thus be used by programs which need to process the traceback before
593 printing (such as console replacements based on the code module from the
583 printing (such as console replacements based on the code module from the
594 standard library).
584 standard library).
595
585
596 Because they are meant to be called without a full traceback (only a
586 Because they are meant to be called without a full traceback (only a
597 list), instances of this class can't call the interactive pdb debugger."""
587 list), instances of this class can't call the interactive pdb debugger."""
598
588
599 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None):
589 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None):
600 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
590 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
601 ostream=ostream, parent=parent)
591 ostream=ostream, parent=parent)
602
592
603 def __call__(self, etype, value, elist):
593 def __call__(self, etype, value, elist):
604 self.ostream.flush()
594 self.ostream.flush()
605 self.ostream.write(self.text(etype, value, elist))
595 self.ostream.write(self.text(etype, value, elist))
606 self.ostream.write('\n')
596 self.ostream.write('\n')
607
597
608 def structured_traceback(self, etype, value, elist, tb_offset=None,
598 def structured_traceback(self, etype, value, elist, tb_offset=None,
609 context=5):
599 context=5):
610 """Return a color formatted string with the traceback info.
600 """Return a color formatted string with the traceback info.
611
601
612 Parameters
602 Parameters
613 ----------
603 ----------
614 etype : exception type
604 etype : exception type
615 Type of the exception raised.
605 Type of the exception raised.
616
606
617 value : object
607 value : object
618 Data stored in the exception
608 Data stored in the exception
619
609
620 elist : list
610 elist : list
621 List of frames, see class docstring for details.
611 List of frames, see class docstring for details.
622
612
623 tb_offset : int, optional
613 tb_offset : int, optional
624 Number of frames in the traceback to skip. If not given, the
614 Number of frames in the traceback to skip. If not given, the
625 instance value is used (set in constructor).
615 instance value is used (set in constructor).
626
616
627 context : int, optional
617 context : int, optional
628 Number of lines of context information to print.
618 Number of lines of context information to print.
629
619
630 Returns
620 Returns
631 -------
621 -------
632 String with formatted exception.
622 String with formatted exception.
633 """
623 """
634 tb_offset = self.tb_offset if tb_offset is None else tb_offset
624 tb_offset = self.tb_offset if tb_offset is None else tb_offset
635 Colors = self.Colors
625 Colors = self.Colors
636 out_list = []
626 out_list = []
637 if elist:
627 if elist:
638
628
639 if tb_offset and len(elist) > tb_offset:
629 if tb_offset and len(elist) > tb_offset:
640 elist = elist[tb_offset:]
630 elist = elist[tb_offset:]
641
631
642 out_list.append('Traceback %s(most recent call last)%s:' %
632 out_list.append('Traceback %s(most recent call last)%s:' %
643 (Colors.normalEm, Colors.Normal) + '\n')
633 (Colors.normalEm, Colors.Normal) + '\n')
644 out_list.extend(self._format_list(elist))
634 out_list.extend(self._format_list(elist))
645 # The exception info should be a single entry in the list.
635 # The exception info should be a single entry in the list.
646 lines = ''.join(self._format_exception_only(etype, value))
636 lines = ''.join(self._format_exception_only(etype, value))
647 out_list.append(lines)
637 out_list.append(lines)
648
638
649 # Note: this code originally read:
639 # Note: this code originally read:
650
640
651 ## for line in lines[:-1]:
641 ## for line in lines[:-1]:
652 ## out_list.append(" "+line)
642 ## out_list.append(" "+line)
653 ## out_list.append(lines[-1])
643 ## out_list.append(lines[-1])
654
644
655 # This means it was indenting everything but the last line by a little
645 # This means it was indenting everything but the last line by a little
656 # bit. I've disabled this for now, but if we see ugliness somewhere we
646 # bit. I've disabled this for now, but if we see ugliness somewhere we
657 # can restore it.
647 # can restore it.
658
648
659 return out_list
649 return out_list
660
650
661 def _format_list(self, extracted_list):
651 def _format_list(self, extracted_list):
662 """Format a list of traceback entry tuples for printing.
652 """Format a list of traceback entry tuples for printing.
663
653
664 Given a list of tuples as returned by extract_tb() or
654 Given a list of tuples as returned by extract_tb() or
665 extract_stack(), return a list of strings ready for printing.
655 extract_stack(), return a list of strings ready for printing.
666 Each string in the resulting list corresponds to the item with the
656 Each string in the resulting list corresponds to the item with the
667 same index in the argument list. Each string ends in a newline;
657 same index in the argument list. Each string ends in a newline;
668 the strings may contain internal newlines as well, for those items
658 the strings may contain internal newlines as well, for those items
669 whose source text line is not None.
659 whose source text line is not None.
670
660
671 Lifted almost verbatim from traceback.py
661 Lifted almost verbatim from traceback.py
672 """
662 """
673
663
674 Colors = self.Colors
664 Colors = self.Colors
675 list = []
665 list = []
676 for filename, lineno, name, line in extracted_list[:-1]:
666 for filename, lineno, name, line in extracted_list[:-1]:
677 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
667 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
678 (Colors.filename, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.Normal,
668 (Colors.filename, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.Normal,
679 Colors.lineno, lineno, Colors.Normal,
669 Colors.lineno, lineno, Colors.Normal,
680 Colors.name, py3compat.cast_unicode_py2(name, "utf-8"), Colors.Normal)
670 Colors.name, py3compat.cast_unicode_py2(name, "utf-8"), Colors.Normal)
681 if line:
671 if line:
682 item += ' %s\n' % line.strip()
672 item += ' %s\n' % line.strip()
683 list.append(item)
673 list.append(item)
684 # Emphasize the last entry
674 # Emphasize the last entry
685 filename, lineno, name, line = extracted_list[-1]
675 filename, lineno, name, line = extracted_list[-1]
686 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
676 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
687 (Colors.normalEm,
677 (Colors.normalEm,
688 Colors.filenameEm, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.normalEm,
678 Colors.filenameEm, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.normalEm,
689 Colors.linenoEm, lineno, Colors.normalEm,
679 Colors.linenoEm, lineno, Colors.normalEm,
690 Colors.nameEm, py3compat.cast_unicode_py2(name, "utf-8"), Colors.normalEm,
680 Colors.nameEm, py3compat.cast_unicode_py2(name, "utf-8"), Colors.normalEm,
691 Colors.Normal)
681 Colors.Normal)
692 if line:
682 if line:
693 item += '%s %s%s\n' % (Colors.line, line.strip(),
683 item += '%s %s%s\n' % (Colors.line, line.strip(),
694 Colors.Normal)
684 Colors.Normal)
695 list.append(item)
685 list.append(item)
696 return list
686 return list
697
687
698 def _format_exception_only(self, etype, value):
688 def _format_exception_only(self, etype, value):
699 """Format the exception part of a traceback.
689 """Format the exception part of a traceback.
700
690
701 The arguments are the exception type and value such as given by
691 The arguments are the exception type and value such as given by
702 sys.exc_info()[:2]. The return value is a list of strings, each ending
692 sys.exc_info()[:2]. The return value is a list of strings, each ending
703 in a newline. Normally, the list contains a single string; however,
693 in a newline. Normally, the list contains a single string; however,
704 for SyntaxError exceptions, it contains several lines that (when
694 for SyntaxError exceptions, it contains several lines that (when
705 printed) display detailed information about where the syntax error
695 printed) display detailed information about where the syntax error
706 occurred. The message indicating which exception occurred is the
696 occurred. The message indicating which exception occurred is the
707 always last string in the list.
697 always last string in the list.
708
698
709 Also lifted nearly verbatim from traceback.py
699 Also lifted nearly verbatim from traceback.py
710 """
700 """
711 have_filedata = False
701 have_filedata = False
712 Colors = self.Colors
702 Colors = self.Colors
713 list = []
703 list = []
714 stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
704 stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
715 if value is None:
705 if value is None:
716 # Not sure if this can still happen in Python 2.6 and above
706 # Not sure if this can still happen in Python 2.6 and above
717 list.append(stype + '\n')
707 list.append(stype + '\n')
718 else:
708 else:
719 if issubclass(etype, SyntaxError):
709 if issubclass(etype, SyntaxError):
720 have_filedata = True
710 have_filedata = True
721 if not value.filename: value.filename = "<string>"
711 if not value.filename: value.filename = "<string>"
722 if value.lineno:
712 if value.lineno:
723 lineno = value.lineno
713 lineno = value.lineno
724 textline = ulinecache.getline(value.filename, value.lineno)
714 textline = ulinecache.getline(value.filename, value.lineno)
725 else:
715 else:
726 lineno = 'unknown'
716 lineno = 'unknown'
727 textline = ''
717 textline = ''
728 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
718 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
729 (Colors.normalEm,
719 (Colors.normalEm,
730 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
720 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
731 Colors.linenoEm, lineno, Colors.Normal ))
721 Colors.linenoEm, lineno, Colors.Normal ))
732 if textline == '':
722 if textline == '':
733 textline = py3compat.cast_unicode(value.text, "utf-8")
723 textline = py3compat.cast_unicode(value.text, "utf-8")
734
724
735 if textline is not None:
725 if textline is not None:
736 i = 0
726 i = 0
737 while i < len(textline) and textline[i].isspace():
727 while i < len(textline) and textline[i].isspace():
738 i += 1
728 i += 1
739 list.append('%s %s%s\n' % (Colors.line,
729 list.append('%s %s%s\n' % (Colors.line,
740 textline.strip(),
730 textline.strip(),
741 Colors.Normal))
731 Colors.Normal))
742 if value.offset is not None:
732 if value.offset is not None:
743 s = ' '
733 s = ' '
744 for c in textline[i:value.offset - 1]:
734 for c in textline[i:value.offset - 1]:
745 if c.isspace():
735 if c.isspace():
746 s += c
736 s += c
747 else:
737 else:
748 s += ' '
738 s += ' '
749 list.append('%s%s^%s\n' % (Colors.caret, s,
739 list.append('%s%s^%s\n' % (Colors.caret, s,
750 Colors.Normal))
740 Colors.Normal))
751
741
752 try:
742 try:
753 s = value.msg
743 s = value.msg
754 except Exception:
744 except Exception:
755 s = self._some_str(value)
745 s = self._some_str(value)
756 if s:
746 if s:
757 list.append('%s%s:%s %s\n' % (stype, Colors.excName,
747 list.append('%s%s:%s %s\n' % (stype, Colors.excName,
758 Colors.Normal, s))
748 Colors.Normal, s))
759 else:
749 else:
760 list.append('%s\n' % stype)
750 list.append('%s\n' % stype)
761
751
762 # sync with user hooks
752 # sync with user hooks
763 if have_filedata:
753 if have_filedata:
764 ipinst = get_ipython()
754 ipinst = get_ipython()
765 if ipinst is not None:
755 if ipinst is not None:
766 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
756 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
767
757
768 return list
758 return list
769
759
770 def get_exception_only(self, etype, value):
760 def get_exception_only(self, etype, value):
771 """Only print the exception type and message, without a traceback.
761 """Only print the exception type and message, without a traceback.
772
762
773 Parameters
763 Parameters
774 ----------
764 ----------
775 etype : exception type
765 etype : exception type
776 value : exception value
766 value : exception value
777 """
767 """
778 return ListTB.structured_traceback(self, etype, value, [])
768 return ListTB.structured_traceback(self, etype, value, [])
779
769
780 def show_exception_only(self, etype, evalue):
770 def show_exception_only(self, etype, evalue):
781 """Only print the exception type and message, without a traceback.
771 """Only print the exception type and message, without a traceback.
782
772
783 Parameters
773 Parameters
784 ----------
774 ----------
785 etype : exception type
775 etype : exception type
786 value : exception value
776 value : exception value
787 """
777 """
788 # This method needs to use __call__ from *this* class, not the one from
778 # This method needs to use __call__ from *this* class, not the one from
789 # a subclass whose signature or behavior may be different
779 # a subclass whose signature or behavior may be different
790 ostream = self.ostream
780 ostream = self.ostream
791 ostream.flush()
781 ostream.flush()
792 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
782 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
793 ostream.flush()
783 ostream.flush()
794
784
795 def _some_str(self, value):
785 def _some_str(self, value):
796 # Lifted from traceback.py
786 # Lifted from traceback.py
797 try:
787 try:
798 return py3compat.cast_unicode(str(value))
788 return py3compat.cast_unicode(str(value))
799 except:
789 except:
800 return u'<unprintable %s object>' % type(value).__name__
790 return u'<unprintable %s object>' % type(value).__name__
801
791
802
792
803 #----------------------------------------------------------------------------
793 #----------------------------------------------------------------------------
804 class VerboseTB(TBTools):
794 class VerboseTB(TBTools):
805 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
795 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
806 of HTML. Requires inspect and pydoc. Crazy, man.
796 of HTML. Requires inspect and pydoc. Crazy, man.
807
797
808 Modified version which optionally strips the topmost entries from the
798 Modified version which optionally strips the topmost entries from the
809 traceback, to be used with alternate interpreters (because their own code
799 traceback, to be used with alternate interpreters (because their own code
810 would appear in the traceback)."""
800 would appear in the traceback)."""
811
801
812 def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
802 def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
813 tb_offset=0, long_header=False, include_vars=True,
803 tb_offset=0, long_header=False, include_vars=True,
814 check_cache=None, debugger_cls = None):
804 check_cache=None, debugger_cls = None):
815 """Specify traceback offset, headers and color scheme.
805 """Specify traceback offset, headers and color scheme.
816
806
817 Define how many frames to drop from the tracebacks. Calling it with
807 Define how many frames to drop from the tracebacks. Calling it with
818 tb_offset=1 allows use of this handler in interpreters which will have
808 tb_offset=1 allows use of this handler in interpreters which will have
819 their own code at the top of the traceback (VerboseTB will first
809 their own code at the top of the traceback (VerboseTB will first
820 remove that frame before printing the traceback info)."""
810 remove that frame before printing the traceback info)."""
821 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
811 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
822 ostream=ostream)
812 ostream=ostream)
823 self.tb_offset = tb_offset
813 self.tb_offset = tb_offset
824 self.long_header = long_header
814 self.long_header = long_header
825 self.include_vars = include_vars
815 self.include_vars = include_vars
826 # By default we use linecache.checkcache, but the user can provide a
816 # By default we use linecache.checkcache, but the user can provide a
827 # different check_cache implementation. This is used by the IPython
817 # different check_cache implementation. This is used by the IPython
828 # kernel to provide tracebacks for interactive code that is cached,
818 # kernel to provide tracebacks for interactive code that is cached,
829 # by a compiler instance that flushes the linecache but preserves its
819 # by a compiler instance that flushes the linecache but preserves its
830 # own code cache.
820 # own code cache.
831 if check_cache is None:
821 if check_cache is None:
832 check_cache = linecache.checkcache
822 check_cache = linecache.checkcache
833 self.check_cache = check_cache
823 self.check_cache = check_cache
834
824
835 self.debugger_cls = debugger_cls or debugger.Pdb
825 self.debugger_cls = debugger_cls or debugger.Pdb
836
826
837 def format_records(self, records, last_unique, recursion_repeat):
827 def format_records(self, records, last_unique, recursion_repeat):
838 """Format the stack frames of the traceback"""
828 """Format the stack frames of the traceback"""
839 frames = []
829 frames = []
840 for r in records[:last_unique+recursion_repeat+1]:
830 for r in records[:last_unique+recursion_repeat+1]:
841 #print '*** record:',file,lnum,func,lines,index # dbg
831 #print '*** record:',file,lnum,func,lines,index # dbg
842 frames.append(self.format_record(*r))
832 frames.append(self.format_record(*r))
843
833
844 if recursion_repeat:
834 if recursion_repeat:
845 frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat)
835 frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat)
846 frames.append(self.format_record(*records[last_unique+recursion_repeat+1]))
836 frames.append(self.format_record(*records[last_unique+recursion_repeat+1]))
847
837
848 return frames
838 return frames
849
839
850 def format_record(self, frame, file, lnum, func, lines, index):
840 def format_record(self, frame, file, lnum, func, lines, index):
851 """Format a single stack frame"""
841 """Format a single stack frame"""
852 Colors = self.Colors # just a shorthand + quicker name lookup
842 Colors = self.Colors # just a shorthand + quicker name lookup
853 ColorsNormal = Colors.Normal # used a lot
843 ColorsNormal = Colors.Normal # used a lot
854 col_scheme = self.color_scheme_table.active_scheme_name
844 col_scheme = self.color_scheme_table.active_scheme_name
855 indent = ' ' * INDENT_SIZE
845 indent = ' ' * INDENT_SIZE
856 em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
846 em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
857 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
847 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
858 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
848 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
859 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
849 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
860 ColorsNormal)
850 ColorsNormal)
861 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
851 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
862 (Colors.vName, Colors.valEm, ColorsNormal)
852 (Colors.vName, Colors.valEm, ColorsNormal)
863 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
853 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
864 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
854 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
865 Colors.vName, ColorsNormal)
855 Colors.vName, ColorsNormal)
866 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
856 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
867
857
868 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
858 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
869 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm, Colors.line,
859 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm, Colors.line,
870 ColorsNormal)
860 ColorsNormal)
871
861
872 abspath = os.path.abspath
862 abspath = os.path.abspath
873
863
874
864
875 if not file:
865 if not file:
876 file = '?'
866 file = '?'
877 elif file.startswith(str("<")) and file.endswith(str(">")):
867 elif file.startswith(str("<")) and file.endswith(str(">")):
878 # Not a real filename, no problem...
868 # Not a real filename, no problem...
879 pass
869 pass
880 elif not os.path.isabs(file):
870 elif not os.path.isabs(file):
881 # Try to make the filename absolute by trying all
871 # Try to make the filename absolute by trying all
882 # sys.path entries (which is also what linecache does)
872 # sys.path entries (which is also what linecache does)
883 for dirname in sys.path:
873 for dirname in sys.path:
884 try:
874 try:
885 fullname = os.path.join(dirname, file)
875 fullname = os.path.join(dirname, file)
886 if os.path.isfile(fullname):
876 if os.path.isfile(fullname):
887 file = os.path.abspath(fullname)
877 file = os.path.abspath(fullname)
888 break
878 break
889 except Exception:
879 except Exception:
890 # Just in case that sys.path contains very
880 # Just in case that sys.path contains very
891 # strange entries...
881 # strange entries...
892 pass
882 pass
893
883
894 file = py3compat.cast_unicode(file, util_path.fs_encoding)
884 file = py3compat.cast_unicode(file, util_path.fs_encoding)
895 link = tpl_link % file
885 link = tpl_link % file
896 args, varargs, varkw, locals = fixed_getargvalues(frame)
886 args, varargs, varkw, locals = fixed_getargvalues(frame)
897
887
898 if func == '?':
888 if func == '?':
899 call = ''
889 call = ''
900 else:
890 else:
901 # Decide whether to include variable details or not
891 # Decide whether to include variable details or not
902 var_repr = self.include_vars and eqrepr or nullrepr
892 var_repr = self.include_vars and eqrepr or nullrepr
903 try:
893 try:
904 call = tpl_call % (func, inspect.formatargvalues(args,
894 call = tpl_call % (func, inspect.formatargvalues(args,
905 varargs, varkw,
895 varargs, varkw,
906 locals, formatvalue=var_repr))
896 locals, formatvalue=var_repr))
907 except KeyError:
897 except KeyError:
908 # This happens in situations like errors inside generator
898 # This happens in situations like errors inside generator
909 # expressions, where local variables are listed in the
899 # expressions, where local variables are listed in the
910 # line, but can't be extracted from the frame. I'm not
900 # line, but can't be extracted from the frame. I'm not
911 # 100% sure this isn't actually a bug in inspect itself,
901 # 100% sure this isn't actually a bug in inspect itself,
912 # but since there's no info for us to compute with, the
902 # but since there's no info for us to compute with, the
913 # best we can do is report the failure and move on. Here
903 # best we can do is report the failure and move on. Here
914 # we must *not* call any traceback construction again,
904 # we must *not* call any traceback construction again,
915 # because that would mess up use of %debug later on. So we
905 # because that would mess up use of %debug later on. So we
916 # simply report the failure and move on. The only
906 # simply report the failure and move on. The only
917 # limitation will be that this frame won't have locals
907 # limitation will be that this frame won't have locals
918 # listed in the call signature. Quite subtle problem...
908 # listed in the call signature. Quite subtle problem...
919 # I can't think of a good way to validate this in a unit
909 # I can't think of a good way to validate this in a unit
920 # test, but running a script consisting of:
910 # test, but running a script consisting of:
921 # dict( (k,v.strip()) for (k,v) in range(10) )
911 # dict( (k,v.strip()) for (k,v) in range(10) )
922 # will illustrate the error, if this exception catch is
912 # will illustrate the error, if this exception catch is
923 # disabled.
913 # disabled.
924 call = tpl_call_fail % func
914 call = tpl_call_fail % func
925
915
926 # Don't attempt to tokenize binary files.
916 # Don't attempt to tokenize binary files.
927 if file.endswith(('.so', '.pyd', '.dll')):
917 if file.endswith(('.so', '.pyd', '.dll')):
928 return '%s %s\n' % (link, call)
918 return '%s %s\n' % (link, call)
929
919
930 elif file.endswith(('.pyc', '.pyo')):
920 elif file.endswith(('.pyc', '.pyo')):
931 # Look up the corresponding source file.
921 # Look up the corresponding source file.
932 try:
922 try:
933 file = openpy.source_from_cache(file)
923 file = openpy.source_from_cache(file)
934 except ValueError:
924 except ValueError:
935 # Failed to get the source file for some reason
925 # Failed to get the source file for some reason
936 # E.g. https://github.com/ipython/ipython/issues/9486
926 # E.g. https://github.com/ipython/ipython/issues/9486
937 return '%s %s\n' % (link, call)
927 return '%s %s\n' % (link, call)
938
928
939 def linereader(file=file, lnum=[lnum], getline=ulinecache.getline):
929 def linereader(file=file, lnum=[lnum], getline=ulinecache.getline):
940 line = getline(file, lnum[0])
930 line = getline(file, lnum[0])
941 lnum[0] += 1
931 lnum[0] += 1
942 return line
932 return line
943
933
944 # Build the list of names on this line of code where the exception
934 # Build the list of names on this line of code where the exception
945 # occurred.
935 # occurred.
946 try:
936 try:
947 names = []
937 names = []
948 name_cont = False
938 name_cont = False
949
939
950 for token_type, token, start, end, line in generate_tokens(linereader):
940 for token_type, token, start, end, line in generate_tokens(linereader):
951 # build composite names
941 # build composite names
952 if token_type == tokenize.NAME and token not in keyword.kwlist:
942 if token_type == tokenize.NAME and token not in keyword.kwlist:
953 if name_cont:
943 if name_cont:
954 # Continuation of a dotted name
944 # Continuation of a dotted name
955 try:
945 try:
956 names[-1].append(token)
946 names[-1].append(token)
957 except IndexError:
947 except IndexError:
958 names.append([token])
948 names.append([token])
959 name_cont = False
949 name_cont = False
960 else:
950 else:
961 # Regular new names. We append everything, the caller
951 # Regular new names. We append everything, the caller
962 # will be responsible for pruning the list later. It's
952 # will be responsible for pruning the list later. It's
963 # very tricky to try to prune as we go, b/c composite
953 # very tricky to try to prune as we go, b/c composite
964 # names can fool us. The pruning at the end is easy
954 # names can fool us. The pruning at the end is easy
965 # to do (or the caller can print a list with repeated
955 # to do (or the caller can print a list with repeated
966 # names if so desired.
956 # names if so desired.
967 names.append([token])
957 names.append([token])
968 elif token == '.':
958 elif token == '.':
969 name_cont = True
959 name_cont = True
970 elif token_type == tokenize.NEWLINE:
960 elif token_type == tokenize.NEWLINE:
971 break
961 break
972
962
973 except (IndexError, UnicodeDecodeError, SyntaxError):
963 except (IndexError, UnicodeDecodeError, SyntaxError):
974 # signals exit of tokenizer
964 # signals exit of tokenizer
975 # SyntaxError can occur if the file is not actually Python
965 # SyntaxError can occur if the file is not actually Python
976 # - see gh-6300
966 # - see gh-6300
977 pass
967 pass
978 except tokenize.TokenError as msg:
968 except tokenize.TokenError as msg:
979 _m = ("An unexpected error occurred while tokenizing input\n"
969 _m = ("An unexpected error occurred while tokenizing input\n"
980 "The following traceback may be corrupted or invalid\n"
970 "The following traceback may be corrupted or invalid\n"
981 "The error message is: %s\n" % msg)
971 "The error message is: %s\n" % msg)
982 error(_m)
972 error(_m)
983
973
984 # Join composite names (e.g. "dict.fromkeys")
974 # Join composite names (e.g. "dict.fromkeys")
985 names = ['.'.join(n) for n in names]
975 names = ['.'.join(n) for n in names]
986 # prune names list of duplicates, but keep the right order
976 # prune names list of duplicates, but keep the right order
987 unique_names = uniq_stable(names)
977 unique_names = uniq_stable(names)
988
978
989 # Start loop over vars
979 # Start loop over vars
990 lvals = []
980 lvals = []
991 if self.include_vars:
981 if self.include_vars:
992 for name_full in unique_names:
982 for name_full in unique_names:
993 name_base = name_full.split('.', 1)[0]
983 name_base = name_full.split('.', 1)[0]
994 if name_base in frame.f_code.co_varnames:
984 if name_base in frame.f_code.co_varnames:
995 if name_base in locals:
985 if name_base in locals:
996 try:
986 try:
997 value = repr(eval(name_full, locals))
987 value = repr(eval(name_full, locals))
998 except:
988 except:
999 value = undefined
989 value = undefined
1000 else:
990 else:
1001 value = undefined
991 value = undefined
1002 name = tpl_local_var % name_full
992 name = tpl_local_var % name_full
1003 else:
993 else:
1004 if name_base in frame.f_globals:
994 if name_base in frame.f_globals:
1005 try:
995 try:
1006 value = repr(eval(name_full, frame.f_globals))
996 value = repr(eval(name_full, frame.f_globals))
1007 except:
997 except:
1008 value = undefined
998 value = undefined
1009 else:
999 else:
1010 value = undefined
1000 value = undefined
1011 name = tpl_global_var % name_full
1001 name = tpl_global_var % name_full
1012 lvals.append(tpl_name_val % (name, value))
1002 lvals.append(tpl_name_val % (name, value))
1013 if lvals:
1003 if lvals:
1014 lvals = '%s%s' % (indent, em_normal.join(lvals))
1004 lvals = '%s%s' % (indent, em_normal.join(lvals))
1015 else:
1005 else:
1016 lvals = ''
1006 lvals = ''
1017
1007
1018 level = '%s %s\n' % (link, call)
1008 level = '%s %s\n' % (link, call)
1019
1009
1020 if index is None:
1010 if index is None:
1021 return level
1011 return level
1022 else:
1012 else:
1023 return '%s%s' % (level, ''.join(
1013 return '%s%s' % (level, ''.join(
1024 _format_traceback_lines(lnum, index, lines, Colors, lvals,
1014 _format_traceback_lines(lnum, index, lines, Colors, lvals,
1025 col_scheme)))
1015 col_scheme)))
1026
1016
1027 def prepare_chained_exception_message(self, cause):
1017 def prepare_chained_exception_message(self, cause):
1028 direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
1018 direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
1029 exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
1019 exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
1030
1020
1031 if cause:
1021 if cause:
1032 message = [[direct_cause]]
1022 message = [[direct_cause]]
1033 else:
1023 else:
1034 message = [[exception_during_handling]]
1024 message = [[exception_during_handling]]
1035 return message
1025 return message
1036
1026
1037 def prepare_header(self, etype, long_version=False):
1027 def prepare_header(self, etype, long_version=False):
1038 colors = self.Colors # just a shorthand + quicker name lookup
1028 colors = self.Colors # just a shorthand + quicker name lookup
1039 colorsnormal = colors.Normal # used a lot
1029 colorsnormal = colors.Normal # used a lot
1040 exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
1030 exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
1041 width = min(75, get_terminal_size()[0])
1031 width = min(75, get_terminal_size()[0])
1042 if long_version:
1032 if long_version:
1043 # Header with the exception type, python version, and date
1033 # Header with the exception type, python version, and date
1044 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
1034 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
1045 date = time.ctime(time.time())
1035 date = time.ctime(time.time())
1046
1036
1047 head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
1037 head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
1048 exc, ' ' * (width - len(str(etype)) - len(pyver)),
1038 exc, ' ' * (width - len(str(etype)) - len(pyver)),
1049 pyver, date.rjust(width) )
1039 pyver, date.rjust(width) )
1050 head += "\nA problem occurred executing Python code. Here is the sequence of function" \
1040 head += "\nA problem occurred executing Python code. Here is the sequence of function" \
1051 "\ncalls leading up to the error, with the most recent (innermost) call last."
1041 "\ncalls leading up to the error, with the most recent (innermost) call last."
1052 else:
1042 else:
1053 # Simplified header
1043 # Simplified header
1054 head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
1044 head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
1055 rjust(width - len(str(etype))) )
1045 rjust(width - len(str(etype))) )
1056
1046
1057 return head
1047 return head
1058
1048
1059 def format_exception(self, etype, evalue):
1049 def format_exception(self, etype, evalue):
1060 colors = self.Colors # just a shorthand + quicker name lookup
1050 colors = self.Colors # just a shorthand + quicker name lookup
1061 colorsnormal = colors.Normal # used a lot
1051 colorsnormal = colors.Normal # used a lot
1062 indent = ' ' * INDENT_SIZE
1052 indent = ' ' * INDENT_SIZE
1063 # Get (safely) a string form of the exception info
1053 # Get (safely) a string form of the exception info
1064 try:
1054 try:
1065 etype_str, evalue_str = map(str, (etype, evalue))
1055 etype_str, evalue_str = map(str, (etype, evalue))
1066 except:
1056 except:
1067 # User exception is improperly defined.
1057 # User exception is improperly defined.
1068 etype, evalue = str, sys.exc_info()[:2]
1058 etype, evalue = str, sys.exc_info()[:2]
1069 etype_str, evalue_str = map(str, (etype, evalue))
1059 etype_str, evalue_str = map(str, (etype, evalue))
1070 # ... and format it
1060 # ... and format it
1071 exception = ['%s%s%s: %s' % (colors.excName, etype_str,
1061 exception = ['%s%s%s: %s' % (colors.excName, etype_str,
1072 colorsnormal, py3compat.cast_unicode(evalue_str))]
1062 colorsnormal, py3compat.cast_unicode(evalue_str))]
1073
1063
1074 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
1064 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
1075 try:
1065 try:
1076 names = [w for w in dir(evalue) if isinstance(w, py3compat.string_types)]
1066 names = [w for w in dir(evalue) if isinstance(w, py3compat.string_types)]
1077 except:
1067 except:
1078 # Every now and then, an object with funny internals blows up
1068 # Every now and then, an object with funny internals blows up
1079 # when dir() is called on it. We do the best we can to report
1069 # when dir() is called on it. We do the best we can to report
1080 # the problem and continue
1070 # the problem and continue
1081 _m = '%sException reporting error (object with broken dir())%s:'
1071 _m = '%sException reporting error (object with broken dir())%s:'
1082 exception.append(_m % (colors.excName, colorsnormal))
1072 exception.append(_m % (colors.excName, colorsnormal))
1083 etype_str, evalue_str = map(str, sys.exc_info()[:2])
1073 etype_str, evalue_str = map(str, sys.exc_info()[:2])
1084 exception.append('%s%s%s: %s' % (colors.excName, etype_str,
1074 exception.append('%s%s%s: %s' % (colors.excName, etype_str,
1085 colorsnormal, py3compat.cast_unicode(evalue_str)))
1075 colorsnormal, py3compat.cast_unicode(evalue_str)))
1086 names = []
1076 names = []
1087 for name in names:
1077 for name in names:
1088 value = text_repr(getattr(evalue, name))
1078 value = text_repr(getattr(evalue, name))
1089 exception.append('\n%s%s = %s' % (indent, name, value))
1079 exception.append('\n%s%s = %s' % (indent, name, value))
1090
1080
1091 return exception
1081 return exception
1092
1082
1093 def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
1083 def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
1094 """Formats the header, traceback and exception message for a single exception.
1084 """Formats the header, traceback and exception message for a single exception.
1095
1085
1096 This may be called multiple times by Python 3 exception chaining
1086 This may be called multiple times by Python 3 exception chaining
1097 (PEP 3134).
1087 (PEP 3134).
1098 """
1088 """
1099 # some locals
1089 # some locals
1100 orig_etype = etype
1090 orig_etype = etype
1101 try:
1091 try:
1102 etype = etype.__name__
1092 etype = etype.__name__
1103 except AttributeError:
1093 except AttributeError:
1104 pass
1094 pass
1105
1095
1106 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1096 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1107 head = self.prepare_header(etype, self.long_header)
1097 head = self.prepare_header(etype, self.long_header)
1108 records = self.get_records(etb, number_of_lines_of_context, tb_offset)
1098 records = self.get_records(etb, number_of_lines_of_context, tb_offset)
1109
1099
1110 if records is None:
1100 if records is None:
1111 return ""
1101 return ""
1112
1102
1113 last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
1103 last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
1114
1104
1115 frames = self.format_records(records, last_unique, recursion_repeat)
1105 frames = self.format_records(records, last_unique, recursion_repeat)
1116
1106
1117 formatted_exception = self.format_exception(etype, evalue)
1107 formatted_exception = self.format_exception(etype, evalue)
1118 if records:
1108 if records:
1119 filepath, lnum = records[-1][1:3]
1109 filepath, lnum = records[-1][1:3]
1120 filepath = os.path.abspath(filepath)
1110 filepath = os.path.abspath(filepath)
1121 ipinst = get_ipython()
1111 ipinst = get_ipython()
1122 if ipinst is not None:
1112 if ipinst is not None:
1123 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
1113 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
1124
1114
1125 return [[head] + frames + [''.join(formatted_exception[0])]]
1115 return [[head] + frames + [''.join(formatted_exception[0])]]
1126
1116
1127 def get_records(self, etb, number_of_lines_of_context, tb_offset):
1117 def get_records(self, etb, number_of_lines_of_context, tb_offset):
1128 try:
1118 try:
1129 # Try the default getinnerframes and Alex's: Alex's fixes some
1119 # Try the default getinnerframes and Alex's: Alex's fixes some
1130 # problems, but it generates empty tracebacks for console errors
1120 # problems, but it generates empty tracebacks for console errors
1131 # (5 blanks lines) where none should be returned.
1121 # (5 blanks lines) where none should be returned.
1132 return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
1122 return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
1133 except UnicodeDecodeError:
1123 except UnicodeDecodeError:
1134 # This can occur if a file's encoding magic comment is wrong.
1124 # This can occur if a file's encoding magic comment is wrong.
1135 # I can't see a way to recover without duplicating a bunch of code
1125 # I can't see a way to recover without duplicating a bunch of code
1136 # from the stdlib traceback module. --TK
1126 # from the stdlib traceback module. --TK
1137 error('\nUnicodeDecodeError while processing traceback.\n')
1127 error('\nUnicodeDecodeError while processing traceback.\n')
1138 return None
1128 return None
1139 except:
1129 except:
1140 # FIXME: I've been getting many crash reports from python 2.3
1130 # FIXME: I've been getting many crash reports from python 2.3
1141 # users, traceable to inspect.py. If I can find a small test-case
1131 # users, traceable to inspect.py. If I can find a small test-case
1142 # to reproduce this, I should either write a better workaround or
1132 # to reproduce this, I should either write a better workaround or
1143 # file a bug report against inspect (if that's the real problem).
1133 # file a bug report against inspect (if that's the real problem).
1144 # So far, I haven't been able to find an isolated example to
1134 # So far, I haven't been able to find an isolated example to
1145 # reproduce the problem.
1135 # reproduce the problem.
1146 inspect_error()
1136 inspect_error()
1147 traceback.print_exc(file=self.ostream)
1137 traceback.print_exc(file=self.ostream)
1148 info('\nUnfortunately, your original traceback can not be constructed.\n')
1138 info('\nUnfortunately, your original traceback can not be constructed.\n')
1149 return None
1139 return None
1150
1140
1151 def get_parts_of_chained_exception(self, evalue):
1141 def get_parts_of_chained_exception(self, evalue):
1152 def get_chained_exception(exception_value):
1142 def get_chained_exception(exception_value):
1153 cause = getattr(exception_value, '__cause__', None)
1143 cause = getattr(exception_value, '__cause__', None)
1154 if cause:
1144 if cause:
1155 return cause
1145 return cause
1156 if getattr(exception_value, '__suppress_context__', False):
1146 if getattr(exception_value, '__suppress_context__', False):
1157 return None
1147 return None
1158 return getattr(exception_value, '__context__', None)
1148 return getattr(exception_value, '__context__', None)
1159
1149
1160 chained_evalue = get_chained_exception(evalue)
1150 chained_evalue = get_chained_exception(evalue)
1161
1151
1162 if chained_evalue:
1152 if chained_evalue:
1163 return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
1153 return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
1164
1154
1165 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
1155 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
1166 number_of_lines_of_context=5):
1156 number_of_lines_of_context=5):
1167 """Return a nice text document describing the traceback."""
1157 """Return a nice text document describing the traceback."""
1168
1158
1169 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
1159 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
1170 tb_offset)
1160 tb_offset)
1171
1161
1172 colors = self.Colors # just a shorthand + quicker name lookup
1162 colors = self.Colors # just a shorthand + quicker name lookup
1173 colorsnormal = colors.Normal # used a lot
1163 colorsnormal = colors.Normal # used a lot
1174 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
1164 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
1175 structured_traceback_parts = [head]
1165 structured_traceback_parts = [head]
1176 if py3compat.PY3:
1166 if py3compat.PY3:
1177 chained_exceptions_tb_offset = 0
1167 chained_exceptions_tb_offset = 0
1178 lines_of_context = 3
1168 lines_of_context = 3
1179 formatted_exceptions = formatted_exception
1169 formatted_exceptions = formatted_exception
1180 exception = self.get_parts_of_chained_exception(evalue)
1170 exception = self.get_parts_of_chained_exception(evalue)
1181 if exception:
1171 if exception:
1182 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1172 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1183 etype, evalue, etb = exception
1173 etype, evalue, etb = exception
1184 else:
1174 else:
1185 evalue = None
1175 evalue = None
1186 chained_exc_ids = set()
1176 chained_exc_ids = set()
1187 while evalue:
1177 while evalue:
1188 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
1178 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
1189 chained_exceptions_tb_offset)
1179 chained_exceptions_tb_offset)
1190 exception = self.get_parts_of_chained_exception(evalue)
1180 exception = self.get_parts_of_chained_exception(evalue)
1191
1181
1192 if exception and not id(exception[1]) in chained_exc_ids:
1182 if exception and not id(exception[1]) in chained_exc_ids:
1193 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
1183 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
1194 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1184 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1195 etype, evalue, etb = exception
1185 etype, evalue, etb = exception
1196 else:
1186 else:
1197 evalue = None
1187 evalue = None
1198
1188
1199 # we want to see exceptions in a reversed order:
1189 # we want to see exceptions in a reversed order:
1200 # the first exception should be on top
1190 # the first exception should be on top
1201 for formatted_exception in reversed(formatted_exceptions):
1191 for formatted_exception in reversed(formatted_exceptions):
1202 structured_traceback_parts += formatted_exception
1192 structured_traceback_parts += formatted_exception
1203 else:
1193 else:
1204 structured_traceback_parts += formatted_exception[0]
1194 structured_traceback_parts += formatted_exception[0]
1205
1195
1206 return structured_traceback_parts
1196 return structured_traceback_parts
1207
1197
1208 def debugger(self, force=False):
1198 def debugger(self, force=False):
1209 """Call up the pdb debugger if desired, always clean up the tb
1199 """Call up the pdb debugger if desired, always clean up the tb
1210 reference.
1200 reference.
1211
1201
1212 Keywords:
1202 Keywords:
1213
1203
1214 - force(False): by default, this routine checks the instance call_pdb
1204 - force(False): by default, this routine checks the instance call_pdb
1215 flag and does not actually invoke the debugger if the flag is false.
1205 flag and does not actually invoke the debugger if the flag is false.
1216 The 'force' option forces the debugger to activate even if the flag
1206 The 'force' option forces the debugger to activate even if the flag
1217 is false.
1207 is false.
1218
1208
1219 If the call_pdb flag is set, the pdb interactive debugger is
1209 If the call_pdb flag is set, the pdb interactive debugger is
1220 invoked. In all cases, the self.tb reference to the current traceback
1210 invoked. In all cases, the self.tb reference to the current traceback
1221 is deleted to prevent lingering references which hamper memory
1211 is deleted to prevent lingering references which hamper memory
1222 management.
1212 management.
1223
1213
1224 Note that each call to pdb() does an 'import readline', so if your app
1214 Note that each call to pdb() does an 'import readline', so if your app
1225 requires a special setup for the readline completers, you'll have to
1215 requires a special setup for the readline completers, you'll have to
1226 fix that by hand after invoking the exception handler."""
1216 fix that by hand after invoking the exception handler."""
1227
1217
1228 if force or self.call_pdb:
1218 if force or self.call_pdb:
1229 if self.pdb is None:
1219 if self.pdb is None:
1230 self.pdb = self.debugger_cls(
1220 self.pdb = self.debugger_cls()
1231 self.color_scheme_table.active_scheme_name)
1232 # the system displayhook may have changed, restore the original
1221 # the system displayhook may have changed, restore the original
1233 # for pdb
1222 # for pdb
1234 display_trap = DisplayTrap(hook=sys.__displayhook__)
1223 display_trap = DisplayTrap(hook=sys.__displayhook__)
1235 with display_trap:
1224 with display_trap:
1236 self.pdb.reset()
1225 self.pdb.reset()
1237 # Find the right frame so we don't pop up inside ipython itself
1226 # Find the right frame so we don't pop up inside ipython itself
1238 if hasattr(self, 'tb') and self.tb is not None:
1227 if hasattr(self, 'tb') and self.tb is not None:
1239 etb = self.tb
1228 etb = self.tb
1240 else:
1229 else:
1241 etb = self.tb = sys.last_traceback
1230 etb = self.tb = sys.last_traceback
1242 while self.tb is not None and self.tb.tb_next is not None:
1231 while self.tb is not None and self.tb.tb_next is not None:
1243 self.tb = self.tb.tb_next
1232 self.tb = self.tb.tb_next
1244 if etb and etb.tb_next:
1233 if etb and etb.tb_next:
1245 etb = etb.tb_next
1234 etb = etb.tb_next
1246 self.pdb.botframe = etb.tb_frame
1235 self.pdb.botframe = etb.tb_frame
1247 self.pdb.interaction(self.tb.tb_frame, self.tb)
1236 self.pdb.interaction(self.tb.tb_frame, self.tb)
1248
1237
1249 if hasattr(self, 'tb'):
1238 if hasattr(self, 'tb'):
1250 del self.tb
1239 del self.tb
1251
1240
1252 def handler(self, info=None):
1241 def handler(self, info=None):
1253 (etype, evalue, etb) = info or sys.exc_info()
1242 (etype, evalue, etb) = info or sys.exc_info()
1254 self.tb = etb
1243 self.tb = etb
1255 ostream = self.ostream
1244 ostream = self.ostream
1256 ostream.flush()
1245 ostream.flush()
1257 ostream.write(self.text(etype, evalue, etb))
1246 ostream.write(self.text(etype, evalue, etb))
1258 ostream.write('\n')
1247 ostream.write('\n')
1259 ostream.flush()
1248 ostream.flush()
1260
1249
1261 # Changed so an instance can just be called as VerboseTB_inst() and print
1250 # Changed so an instance can just be called as VerboseTB_inst() and print
1262 # out the right info on its own.
1251 # out the right info on its own.
1263 def __call__(self, etype=None, evalue=None, etb=None):
1252 def __call__(self, etype=None, evalue=None, etb=None):
1264 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1253 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1265 if etb is None:
1254 if etb is None:
1266 self.handler()
1255 self.handler()
1267 else:
1256 else:
1268 self.handler((etype, evalue, etb))
1257 self.handler((etype, evalue, etb))
1269 try:
1258 try:
1270 self.debugger()
1259 self.debugger()
1271 except KeyboardInterrupt:
1260 except KeyboardInterrupt:
1272 print("\nKeyboardInterrupt")
1261 print("\nKeyboardInterrupt")
1273
1262
1274
1263
1275 #----------------------------------------------------------------------------
1264 #----------------------------------------------------------------------------
1276 class FormattedTB(VerboseTB, ListTB):
1265 class FormattedTB(VerboseTB, ListTB):
1277 """Subclass ListTB but allow calling with a traceback.
1266 """Subclass ListTB but allow calling with a traceback.
1278
1267
1279 It can thus be used as a sys.excepthook for Python > 2.1.
1268 It can thus be used as a sys.excepthook for Python > 2.1.
1280
1269
1281 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1270 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1282
1271
1283 Allows a tb_offset to be specified. This is useful for situations where
1272 Allows a tb_offset to be specified. This is useful for situations where
1284 one needs to remove a number of topmost frames from the traceback (such as
1273 one needs to remove a number of topmost frames from the traceback (such as
1285 occurs with python programs that themselves execute other python code,
1274 occurs with python programs that themselves execute other python code,
1286 like Python shells). """
1275 like Python shells). """
1287
1276
1288 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1277 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1289 ostream=None,
1278 ostream=None,
1290 tb_offset=0, long_header=False, include_vars=False,
1279 tb_offset=0, long_header=False, include_vars=False,
1291 check_cache=None, debugger_cls=None):
1280 check_cache=None, debugger_cls=None):
1292
1281
1293 # NEVER change the order of this list. Put new modes at the end:
1282 # NEVER change the order of this list. Put new modes at the end:
1294 self.valid_modes = ['Plain', 'Context', 'Verbose']
1283 self.valid_modes = ['Plain', 'Context', 'Verbose']
1295 self.verbose_modes = self.valid_modes[1:3]
1284 self.verbose_modes = self.valid_modes[1:3]
1296
1285
1297 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1286 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1298 ostream=ostream, tb_offset=tb_offset,
1287 ostream=ostream, tb_offset=tb_offset,
1299 long_header=long_header, include_vars=include_vars,
1288 long_header=long_header, include_vars=include_vars,
1300 check_cache=check_cache, debugger_cls=debugger_cls)
1289 check_cache=check_cache, debugger_cls=debugger_cls)
1301
1290
1302 # Different types of tracebacks are joined with different separators to
1291 # Different types of tracebacks are joined with different separators to
1303 # form a single string. They are taken from this dict
1292 # form a single string. They are taken from this dict
1304 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1293 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1305 # set_mode also sets the tb_join_char attribute
1294 # set_mode also sets the tb_join_char attribute
1306 self.set_mode(mode)
1295 self.set_mode(mode)
1307
1296
1308 def _extract_tb(self, tb):
1297 def _extract_tb(self, tb):
1309 if tb:
1298 if tb:
1310 return traceback.extract_tb(tb)
1299 return traceback.extract_tb(tb)
1311 else:
1300 else:
1312 return None
1301 return None
1313
1302
1314 def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
1303 def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
1315 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1304 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1316 mode = self.mode
1305 mode = self.mode
1317 if mode in self.verbose_modes:
1306 if mode in self.verbose_modes:
1318 # Verbose modes need a full traceback
1307 # Verbose modes need a full traceback
1319 return VerboseTB.structured_traceback(
1308 return VerboseTB.structured_traceback(
1320 self, etype, value, tb, tb_offset, number_of_lines_of_context
1309 self, etype, value, tb, tb_offset, number_of_lines_of_context
1321 )
1310 )
1322 else:
1311 else:
1323 # We must check the source cache because otherwise we can print
1312 # We must check the source cache because otherwise we can print
1324 # out-of-date source code.
1313 # out-of-date source code.
1325 self.check_cache()
1314 self.check_cache()
1326 # Now we can extract and format the exception
1315 # Now we can extract and format the exception
1327 elist = self._extract_tb(tb)
1316 elist = self._extract_tb(tb)
1328 return ListTB.structured_traceback(
1317 return ListTB.structured_traceback(
1329 self, etype, value, elist, tb_offset, number_of_lines_of_context
1318 self, etype, value, elist, tb_offset, number_of_lines_of_context
1330 )
1319 )
1331
1320
1332 def stb2text(self, stb):
1321 def stb2text(self, stb):
1333 """Convert a structured traceback (a list) to a string."""
1322 """Convert a structured traceback (a list) to a string."""
1334 return self.tb_join_char.join(stb)
1323 return self.tb_join_char.join(stb)
1335
1324
1336
1325
1337 def set_mode(self, mode=None):
1326 def set_mode(self, mode=None):
1338 """Switch to the desired mode.
1327 """Switch to the desired mode.
1339
1328
1340 If mode is not specified, cycles through the available modes."""
1329 If mode is not specified, cycles through the available modes."""
1341
1330
1342 if not mode:
1331 if not mode:
1343 new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
1332 new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
1344 len(self.valid_modes)
1333 len(self.valid_modes)
1345 self.mode = self.valid_modes[new_idx]
1334 self.mode = self.valid_modes[new_idx]
1346 elif mode not in self.valid_modes:
1335 elif mode not in self.valid_modes:
1347 raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
1336 raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
1348 'Valid modes: ' + str(self.valid_modes))
1337 'Valid modes: ' + str(self.valid_modes))
1349 else:
1338 else:
1350 self.mode = mode
1339 self.mode = mode
1351 # include variable details only in 'Verbose' mode
1340 # include variable details only in 'Verbose' mode
1352 self.include_vars = (self.mode == self.valid_modes[2])
1341 self.include_vars = (self.mode == self.valid_modes[2])
1353 # Set the join character for generating text tracebacks
1342 # Set the join character for generating text tracebacks
1354 self.tb_join_char = self._join_chars[self.mode]
1343 self.tb_join_char = self._join_chars[self.mode]
1355
1344
1356 # some convenient shortcuts
1345 # some convenient shortcuts
1357 def plain(self):
1346 def plain(self):
1358 self.set_mode(self.valid_modes[0])
1347 self.set_mode(self.valid_modes[0])
1359
1348
1360 def context(self):
1349 def context(self):
1361 self.set_mode(self.valid_modes[1])
1350 self.set_mode(self.valid_modes[1])
1362
1351
1363 def verbose(self):
1352 def verbose(self):
1364 self.set_mode(self.valid_modes[2])
1353 self.set_mode(self.valid_modes[2])
1365
1354
1366
1355
1367 #----------------------------------------------------------------------------
1356 #----------------------------------------------------------------------------
1368 class AutoFormattedTB(FormattedTB):
1357 class AutoFormattedTB(FormattedTB):
1369 """A traceback printer which can be called on the fly.
1358 """A traceback printer which can be called on the fly.
1370
1359
1371 It will find out about exceptions by itself.
1360 It will find out about exceptions by itself.
1372
1361
1373 A brief example::
1362 A brief example::
1374
1363
1375 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1364 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1376 try:
1365 try:
1377 ...
1366 ...
1378 except:
1367 except:
1379 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1368 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1380 """
1369 """
1381
1370
1382 def __call__(self, etype=None, evalue=None, etb=None,
1371 def __call__(self, etype=None, evalue=None, etb=None,
1383 out=None, tb_offset=None):
1372 out=None, tb_offset=None):
1384 """Print out a formatted exception traceback.
1373 """Print out a formatted exception traceback.
1385
1374
1386 Optional arguments:
1375 Optional arguments:
1387 - out: an open file-like object to direct output to.
1376 - out: an open file-like object to direct output to.
1388
1377
1389 - tb_offset: the number of frames to skip over in the stack, on a
1378 - tb_offset: the number of frames to skip over in the stack, on a
1390 per-call basis (this overrides temporarily the instance's tb_offset
1379 per-call basis (this overrides temporarily the instance's tb_offset
1391 given at initialization time. """
1380 given at initialization time. """
1392
1381
1393 if out is None:
1382 if out is None:
1394 out = self.ostream
1383 out = self.ostream
1395 out.flush()
1384 out.flush()
1396 out.write(self.text(etype, evalue, etb, tb_offset))
1385 out.write(self.text(etype, evalue, etb, tb_offset))
1397 out.write('\n')
1386 out.write('\n')
1398 out.flush()
1387 out.flush()
1399 # FIXME: we should remove the auto pdb behavior from here and leave
1388 # FIXME: we should remove the auto pdb behavior from here and leave
1400 # that to the clients.
1389 # that to the clients.
1401 try:
1390 try:
1402 self.debugger()
1391 self.debugger()
1403 except KeyboardInterrupt:
1392 except KeyboardInterrupt:
1404 print("\nKeyboardInterrupt")
1393 print("\nKeyboardInterrupt")
1405
1394
1406 def structured_traceback(self, etype=None, value=None, tb=None,
1395 def structured_traceback(self, etype=None, value=None, tb=None,
1407 tb_offset=None, number_of_lines_of_context=5):
1396 tb_offset=None, number_of_lines_of_context=5):
1408 if etype is None:
1397 if etype is None:
1409 etype, value, tb = sys.exc_info()
1398 etype, value, tb = sys.exc_info()
1410 self.tb = tb
1399 self.tb = tb
1411 return FormattedTB.structured_traceback(
1400 return FormattedTB.structured_traceback(
1412 self, etype, value, tb, tb_offset, number_of_lines_of_context)
1401 self, etype, value, tb, tb_offset, number_of_lines_of_context)
1413
1402
1414
1403
1415 #---------------------------------------------------------------------------
1404 #---------------------------------------------------------------------------
1416
1405
1417 # A simple class to preserve Nathan's original functionality.
1406 # A simple class to preserve Nathan's original functionality.
1418 class ColorTB(FormattedTB):
1407 class ColorTB(FormattedTB):
1419 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1408 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1420
1409
1421 def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
1410 def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
1422 FormattedTB.__init__(self, color_scheme=color_scheme,
1411 FormattedTB.__init__(self, color_scheme=color_scheme,
1423 call_pdb=call_pdb, **kwargs)
1412 call_pdb=call_pdb, **kwargs)
1424
1413
1425
1414
1426 class SyntaxTB(ListTB):
1415 class SyntaxTB(ListTB):
1427 """Extension which holds some state: the last exception value"""
1416 """Extension which holds some state: the last exception value"""
1428
1417
1429 def __init__(self, color_scheme='NoColor'):
1418 def __init__(self, color_scheme='NoColor'):
1430 ListTB.__init__(self, color_scheme)
1419 ListTB.__init__(self, color_scheme)
1431 self.last_syntax_error = None
1420 self.last_syntax_error = None
1432
1421
1433 def __call__(self, etype, value, elist):
1422 def __call__(self, etype, value, elist):
1434 self.last_syntax_error = value
1423 self.last_syntax_error = value
1435
1424
1436 ListTB.__call__(self, etype, value, elist)
1425 ListTB.__call__(self, etype, value, elist)
1437
1426
1438 def structured_traceback(self, etype, value, elist, tb_offset=None,
1427 def structured_traceback(self, etype, value, elist, tb_offset=None,
1439 context=5):
1428 context=5):
1440 # If the source file has been edited, the line in the syntax error can
1429 # If the source file has been edited, the line in the syntax error can
1441 # be wrong (retrieved from an outdated cache). This replaces it with
1430 # be wrong (retrieved from an outdated cache). This replaces it with
1442 # the current value.
1431 # the current value.
1443 if isinstance(value, SyntaxError) \
1432 if isinstance(value, SyntaxError) \
1444 and isinstance(value.filename, py3compat.string_types) \
1433 and isinstance(value.filename, py3compat.string_types) \
1445 and isinstance(value.lineno, int):
1434 and isinstance(value.lineno, int):
1446 linecache.checkcache(value.filename)
1435 linecache.checkcache(value.filename)
1447 newtext = ulinecache.getline(value.filename, value.lineno)
1436 newtext = ulinecache.getline(value.filename, value.lineno)
1448 if newtext:
1437 if newtext:
1449 value.text = newtext
1438 value.text = newtext
1450 self.last_syntax_error = value
1439 self.last_syntax_error = value
1451 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1440 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1452 tb_offset=tb_offset, context=context)
1441 tb_offset=tb_offset, context=context)
1453
1442
1454 def clear_err_state(self):
1443 def clear_err_state(self):
1455 """Return the current error state and clear it"""
1444 """Return the current error state and clear it"""
1456 e = self.last_syntax_error
1445 e = self.last_syntax_error
1457 self.last_syntax_error = None
1446 self.last_syntax_error = None
1458 return e
1447 return e
1459
1448
1460 def stb2text(self, stb):
1449 def stb2text(self, stb):
1461 """Convert a structured traceback (a list) to a string."""
1450 """Convert a structured traceback (a list) to a string."""
1462 return ''.join(stb)
1451 return ''.join(stb)
1463
1452
1464
1453
1465 # some internal-use functions
1454 # some internal-use functions
1466 def text_repr(value):
1455 def text_repr(value):
1467 """Hopefully pretty robust repr equivalent."""
1456 """Hopefully pretty robust repr equivalent."""
1468 # this is pretty horrible but should always return *something*
1457 # this is pretty horrible but should always return *something*
1469 try:
1458 try:
1470 return pydoc.text.repr(value)
1459 return pydoc.text.repr(value)
1471 except KeyboardInterrupt:
1460 except KeyboardInterrupt:
1472 raise
1461 raise
1473 except:
1462 except:
1474 try:
1463 try:
1475 return repr(value)
1464 return repr(value)
1476 except KeyboardInterrupt:
1465 except KeyboardInterrupt:
1477 raise
1466 raise
1478 except:
1467 except:
1479 try:
1468 try:
1480 # all still in an except block so we catch
1469 # all still in an except block so we catch
1481 # getattr raising
1470 # getattr raising
1482 name = getattr(value, '__name__', None)
1471 name = getattr(value, '__name__', None)
1483 if name:
1472 if name:
1484 # ick, recursion
1473 # ick, recursion
1485 return text_repr(name)
1474 return text_repr(name)
1486 klass = getattr(value, '__class__', None)
1475 klass = getattr(value, '__class__', None)
1487 if klass:
1476 if klass:
1488 return '%s instance' % text_repr(klass)
1477 return '%s instance' % text_repr(klass)
1489 except KeyboardInterrupt:
1478 except KeyboardInterrupt:
1490 raise
1479 raise
1491 except:
1480 except:
1492 return 'UNRECOVERABLE REPR FAILURE'
1481 return 'UNRECOVERABLE REPR FAILURE'
1493
1482
1494
1483
1495 def eqrepr(value, repr=text_repr):
1484 def eqrepr(value, repr=text_repr):
1496 return '=%s' % repr(value)
1485 return '=%s' % repr(value)
1497
1486
1498
1487
1499 def nullrepr(value, repr=text_repr):
1488 def nullrepr(value, repr=text_repr):
1500 return ''
1489 return ''
@@ -1,382 +1,332 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Class and program to colorize python source code for ANSI terminals.
3 Class and program to colorize python source code for ANSI terminals.
4
4
5 Based on an HTML code highlighter by Jurgen Hermann found at:
5 Based on an HTML code highlighter by Jurgen Hermann found at:
6 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52298
6 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52298
7
7
8 Modifications by Fernando Perez (fperez@colorado.edu).
8 Modifications by Fernando Perez (fperez@colorado.edu).
9
9
10 Information on the original HTML highlighter follows:
10 Information on the original HTML highlighter follows:
11
11
12 MoinMoin - Python Source Parser
12 MoinMoin - Python Source Parser
13
13
14 Title: Colorize Python source using the built-in tokenizer
14 Title: Colorize Python source using the built-in tokenizer
15
15
16 Submitter: Jurgen Hermann
16 Submitter: Jurgen Hermann
17 Last Updated:2001/04/06
17 Last Updated:2001/04/06
18
18
19 Version no:1.2
19 Version no:1.2
20
20
21 Description:
21 Description:
22
22
23 This code is part of MoinMoin (http://moin.sourceforge.net/) and converts
23 This code is part of MoinMoin (http://moin.sourceforge.net/) and converts
24 Python source code to HTML markup, rendering comments, keywords,
24 Python source code to HTML markup, rendering comments, keywords,
25 operators, numeric and string literals in different colors.
25 operators, numeric and string literals in different colors.
26
26
27 It shows how to use the built-in keyword, token and tokenize modules to
27 It shows how to use the built-in keyword, token and tokenize modules to
28 scan Python source code and re-emit it with no changes to its original
28 scan Python source code and re-emit it with no changes to its original
29 formatting (which is the hard part).
29 formatting (which is the hard part).
30 """
30 """
31 from __future__ import print_function
31 from __future__ import print_function
32 from __future__ import absolute_import
32 from __future__ import absolute_import
33 from __future__ import unicode_literals
33 from __future__ import unicode_literals
34
34
35 __all__ = ['ANSICodeColors','Parser']
35 __all__ = ['ANSICodeColors','Parser']
36
36
37 _scheme_default = 'Linux'
37 _scheme_default = 'Linux'
38
38
39
39
40 # Imports
40 # Imports
41 import keyword
41 import keyword
42 import os
42 import os
43 import sys
43 import sys
44 import token
44 import token
45 import tokenize
45 import tokenize
46
46
47 try:
47 try:
48 generate_tokens = tokenize.generate_tokens
48 generate_tokens = tokenize.generate_tokens
49 except AttributeError:
49 except AttributeError:
50 # Python 3. Note that we use the undocumented _tokenize because it expects
50 # Python 3. Note that we use the undocumented _tokenize because it expects
51 # strings, not bytes. See also Python issue #9969.
51 # strings, not bytes. See also Python issue #9969.
52 generate_tokens = tokenize._tokenize
52 generate_tokens = tokenize._tokenize
53
53
54 from IPython.utils.coloransi import TermColors, InputTermColors ,ColorScheme, ColorSchemeTable
54 from IPython.utils.coloransi import TermColors, InputTermColors ,ColorScheme, ColorSchemeTable
55 from IPython.utils.py3compat import PY3
55 from IPython.utils.py3compat import PY3
56
56
57 from .colorable import Colorable
57 from .colorable import Colorable
58
58
59 if PY3:
59 if PY3:
60 from io import StringIO
60 from io import StringIO
61 else:
61 else:
62 from StringIO import StringIO
62 from StringIO import StringIO
63
63
64 #############################################################################
64 #############################################################################
65 ### Python Source Parser (does Hilighting)
65 ### Python Source Parser (does Hilighting)
66 #############################################################################
66 #############################################################################
67
67
68 _KEYWORD = token.NT_OFFSET + 1
68 _KEYWORD = token.NT_OFFSET + 1
69 _TEXT = token.NT_OFFSET + 2
69 _TEXT = token.NT_OFFSET + 2
70
70
71 #****************************************************************************
71 #****************************************************************************
72 # Builtin color schemes
72 # Builtin color schemes
73
73
74 Colors = TermColors # just a shorthand
74 Colors = TermColors # just a shorthand
75
75
76 # Build a few color schemes
76 # Build a few color schemes
77 NoColor = ColorScheme(
77 NoColor = ColorScheme(
78 'NoColor',{
78 'NoColor',{
79 'header' : Colors.NoColor,
79 'header' : Colors.NoColor,
80 token.NUMBER : Colors.NoColor,
80 token.NUMBER : Colors.NoColor,
81 token.OP : Colors.NoColor,
81 token.OP : Colors.NoColor,
82 token.STRING : Colors.NoColor,
82 token.STRING : Colors.NoColor,
83 tokenize.COMMENT : Colors.NoColor,
83 tokenize.COMMENT : Colors.NoColor,
84 token.NAME : Colors.NoColor,
84 token.NAME : Colors.NoColor,
85 token.ERRORTOKEN : Colors.NoColor,
85 token.ERRORTOKEN : Colors.NoColor,
86
86
87 _KEYWORD : Colors.NoColor,
87 _KEYWORD : Colors.NoColor,
88 _TEXT : Colors.NoColor,
88 _TEXT : Colors.NoColor,
89
89
90 'in_prompt' : InputTermColors.NoColor, # Input prompt
90 'in_prompt' : InputTermColors.NoColor, # Input prompt
91 'in_number' : InputTermColors.NoColor, # Input prompt number
91 'in_number' : InputTermColors.NoColor, # Input prompt number
92 'in_prompt2' : InputTermColors.NoColor, # Continuation prompt
92 'in_prompt2' : InputTermColors.NoColor, # Continuation prompt
93 'in_normal' : InputTermColors.NoColor, # color off (usu. Colors.Normal)
93 'in_normal' : InputTermColors.NoColor, # color off (usu. Colors.Normal)
94
94
95 'out_prompt' : Colors.NoColor, # Output prompt
95 'out_prompt' : Colors.NoColor, # Output prompt
96 'out_number' : Colors.NoColor, # Output prompt number
96 'out_number' : Colors.NoColor, # Output prompt number
97
97
98 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
98 'normal' : Colors.NoColor # color off (usu. Colors.Normal)
99 } )
99 } )
100
100
101 LinuxColors = ColorScheme(
101 LinuxColors = ColorScheme(
102 'Linux',{
102 'Linux',{
103 'header' : Colors.LightRed,
103 'header' : Colors.LightRed,
104 token.NUMBER : Colors.LightCyan,
104 token.NUMBER : Colors.LightCyan,
105 token.OP : Colors.Yellow,
105 token.OP : Colors.Yellow,
106 token.STRING : Colors.LightBlue,
106 token.STRING : Colors.LightBlue,
107 tokenize.COMMENT : Colors.LightRed,
107 tokenize.COMMENT : Colors.LightRed,
108 token.NAME : Colors.Normal,
108 token.NAME : Colors.Normal,
109 token.ERRORTOKEN : Colors.Red,
109 token.ERRORTOKEN : Colors.Red,
110
110
111 _KEYWORD : Colors.LightGreen,
111 _KEYWORD : Colors.LightGreen,
112 _TEXT : Colors.Yellow,
112 _TEXT : Colors.Yellow,
113
113
114 'in_prompt' : InputTermColors.Green,
114 'in_prompt' : InputTermColors.Green,
115 'in_number' : InputTermColors.LightGreen,
115 'in_number' : InputTermColors.LightGreen,
116 'in_prompt2' : InputTermColors.Green,
116 'in_prompt2' : InputTermColors.Green,
117 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
117 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
118
118
119 'out_prompt' : Colors.Red,
119 'out_prompt' : Colors.Red,
120 'out_number' : Colors.LightRed,
120 'out_number' : Colors.LightRed,
121
121
122 'normal' : Colors.Normal # color off (usu. Colors.Normal)
122 'normal' : Colors.Normal # color off (usu. Colors.Normal)
123 } )
123 } )
124
124
125 NeutralColors = ColorScheme(
125 NeutralColors = ColorScheme(
126 'Neutral',{
126 'Neutral',{
127 'header' : Colors.Red,
127 'header' : Colors.Red,
128 token.NUMBER : Colors.Cyan,
128 token.NUMBER : Colors.Cyan,
129 token.OP : Colors.Blue,
129 token.OP : Colors.Blue,
130 token.STRING : Colors.Blue,
130 token.STRING : Colors.Blue,
131 tokenize.COMMENT : Colors.Red,
131 tokenize.COMMENT : Colors.Red,
132 token.NAME : Colors.Normal,
132 token.NAME : Colors.Normal,
133 token.ERRORTOKEN : Colors.Red,
133 token.ERRORTOKEN : Colors.Red,
134
134
135 _KEYWORD : Colors.Green,
135 _KEYWORD : Colors.Green,
136 _TEXT : Colors.Blue,
136 _TEXT : Colors.Blue,
137
137
138 'in_prompt' : InputTermColors.Blue,
138 'in_prompt' : InputTermColors.Blue,
139 'in_number' : InputTermColors.LightBlue,
139 'in_number' : InputTermColors.LightBlue,
140 'in_prompt2' : InputTermColors.Blue,
140 'in_prompt2' : InputTermColors.Blue,
141 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
141 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
142
142
143 'out_prompt' : Colors.Red,
143 'out_prompt' : Colors.Red,
144 'out_number' : Colors.LightRed,
144 'out_number' : Colors.LightRed,
145
145
146 'normal' : Colors.Normal # color off (usu. Colors.Normal)
146 'normal' : Colors.Normal # color off (usu. Colors.Normal)
147 } )
147 } )
148
148
149 # Hack: the 'neutral' colours are not very visible on a dark background on
149 # Hack: the 'neutral' colours are not very visible on a dark background on
150 # Windows. Since Windows command prompts have a dark background by default, and
150 # Windows. Since Windows command prompts have a dark background by default, and
151 # relatively few users are likely to alter that, we will use the 'Linux' colours,
151 # relatively few users are likely to alter that, we will use the 'Linux' colours,
152 # designed for a dark background, as the default on Windows. Changing it here
152 # designed for a dark background, as the default on Windows. Changing it here
153 # avoids affecting the prompt colours rendered by prompt_toolkit, where the
153 # avoids affecting the prompt colours rendered by prompt_toolkit, where the
154 # neutral defaults do work OK.
154 # neutral defaults do work OK.
155
155
156 if os.name == 'nt':
156 if os.name == 'nt':
157 NeutralColors = LinuxColors.copy(name='Neutral')
157 NeutralColors = LinuxColors.copy(name='Neutral')
158
158
159 LightBGColors = ColorScheme(
159 LightBGColors = ColorScheme(
160 'LightBG',{
160 'LightBG',{
161 'header' : Colors.Red,
161 'header' : Colors.Red,
162 token.NUMBER : Colors.Cyan,
162 token.NUMBER : Colors.Cyan,
163 token.OP : Colors.Blue,
163 token.OP : Colors.Blue,
164 token.STRING : Colors.Blue,
164 token.STRING : Colors.Blue,
165 tokenize.COMMENT : Colors.Red,
165 tokenize.COMMENT : Colors.Red,
166 token.NAME : Colors.Normal,
166 token.NAME : Colors.Normal,
167 token.ERRORTOKEN : Colors.Red,
167 token.ERRORTOKEN : Colors.Red,
168
168
169
169
170 _KEYWORD : Colors.Green,
170 _KEYWORD : Colors.Green,
171 _TEXT : Colors.Blue,
171 _TEXT : Colors.Blue,
172
172
173 'in_prompt' : InputTermColors.Blue,
173 'in_prompt' : InputTermColors.Blue,
174 'in_number' : InputTermColors.LightBlue,
174 'in_number' : InputTermColors.LightBlue,
175 'in_prompt2' : InputTermColors.Blue,
175 'in_prompt2' : InputTermColors.Blue,
176 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
176 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
177
177
178 'out_prompt' : Colors.Red,
178 'out_prompt' : Colors.Red,
179 'out_number' : Colors.LightRed,
179 'out_number' : Colors.LightRed,
180
180
181 'normal' : Colors.Normal # color off (usu. Colors.Normal)
181 'normal' : Colors.Normal # color off (usu. Colors.Normal)
182 } )
182 } )
183
183
184 # Build table of color schemes (needed by the parser)
184 # Build table of color schemes (needed by the parser)
185 ANSICodeColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors, NeutralColors],
185 ANSICodeColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors, NeutralColors],
186 _scheme_default)
186 _scheme_default)
187
187
188 Undefined = object()
189
188 class Parser(Colorable):
190 class Parser(Colorable):
189 """ Format colored Python source.
191 """ Format colored Python source.
190 """
192 """
191
193
192 def __init__(self, color_table=None, out = sys.stdout, parent=None, style=None):
194 def __init__(self, color_table=None, out = sys.stdout, parent=None, style=None):
193 """ Create a parser with a specified color table and output channel.
195 """ Create a parser with a specified color table and output channel.
194
196
195 Call format() to process code.
197 Call format() to process code.
196 """
198 """
197
199
198 super(Parser, self).__init__(parent=parent)
200 super(Parser, self).__init__(parent=parent)
199
201
200 self.color_table = color_table and color_table or ANSICodeColors
202 self.color_table = color_table and color_table or ANSICodeColors
201 self.out = out
203 self.out = out
204 if not style:
205 self.style = self.default_style
206 else:
207 self.style = style
208
202
209
203 def format(self, raw, out = None, scheme = ''):
210 def format(self, raw, out=None, scheme=Undefined):
204 return self.format2(raw, out, scheme)[0]
211 import warnings
212 if scheme is not Undefined:
213 warnings.warn('The `scheme` argument of IPython.utils.PyColorize:Parser.format is deprecated since IPython 6.0.'
214 'It will have no effect. Set the parser `style` directly.',
215 stacklevel=2)
216 return self.format2(raw, out)[0]
205
217
206 def format2(self, raw, out = None, scheme = ''):
218 def format2(self, raw, out = None):
207 """ Parse and send the colored source.
219 """ Parse and send the colored source.
208
220
209 If out and scheme are not specified, the defaults (given to
221 If out and scheme are not specified, the defaults (given to
210 constructor) are used.
222 constructor) are used.
211
223
212 out should be a file-type object. Optionally, out can be given as the
224 out should be a file-type object. Optionally, out can be given as the
213 string 'str' and the parser will automatically return the output in a
225 string 'str' and the parser will automatically return the output in a
214 string."""
226 string."""
215
227
216 string_output = 0
228 string_output = 0
217 if out == 'str' or self.out == 'str' or \
229 if out == 'str' or self.out == 'str' or \
218 isinstance(self.out,StringIO):
230 isinstance(self.out,StringIO):
219 # XXX - I don't really like this state handling logic, but at this
231 # XXX - I don't really like this state handling logic, but at this
220 # point I don't want to make major changes, so adding the
232 # point I don't want to make major changes, so adding the
221 # isinstance() check is the simplest I can do to ensure correct
233 # isinstance() check is the simplest I can do to ensure correct
222 # behavior.
234 # behavior.
223 out_old = self.out
235 out_old = self.out
224 self.out = StringIO()
236 self.out = StringIO()
225 string_output = 1
237 string_output = 1
226 elif out is not None:
238 elif out is not None:
227 self.out = out
239 self.out = out
228
240
229 # Fast return of the unmodified input for NoColor scheme
241 # Fast return of the unmodified input for NoColor scheme
230 if scheme == 'NoColor':
242 if self.style == 'NoColor':
231 error = False
243 error = False
232 self.out.write(raw)
244 self.out.write(raw)
233 if string_output:
245 if string_output:
234 return raw,error
246 return raw,error
235 else:
247 else:
236 return None,error
248 return None,error
237
249
238 # local shorthands
250 # local shorthands
239 colors = self.color_table[scheme].colors
251 colors = self.color_table[self.style].colors
240 self.colors = colors # put in object so __call__ sees it
252 self.colors = colors # put in object so __call__ sees it
241
253
242 # Remove trailing whitespace and normalize tabs
254 # Remove trailing whitespace and normalize tabs
243 self.raw = raw.expandtabs().rstrip()
255 self.raw = raw.expandtabs().rstrip()
244
256
245 # store line offsets in self.lines
257 # store line offsets in self.lines
246 self.lines = [0, 0]
258 self.lines = [0, 0]
247 pos = 0
259 pos = 0
248 raw_find = self.raw.find
260 raw_find = self.raw.find
249 lines_append = self.lines.append
261 lines_append = self.lines.append
250 while 1:
262 while 1:
251 pos = raw_find('\n', pos) + 1
263 pos = raw_find('\n', pos) + 1
252 if not pos: break
264 if not pos: break
253 lines_append(pos)
265 lines_append(pos)
254 lines_append(len(self.raw))
266 lines_append(len(self.raw))
255
267
256 # parse the source and write it
268 # parse the source and write it
257 self.pos = 0
269 self.pos = 0
258 text = StringIO(self.raw)
270 text = StringIO(self.raw)
259
271
260 error = False
272 error = False
261 try:
273 try:
262 for atoken in generate_tokens(text.readline):
274 for atoken in generate_tokens(text.readline):
263 self(*atoken)
275 self(*atoken)
264 except tokenize.TokenError as ex:
276 except tokenize.TokenError as ex:
265 msg = ex.args[0]
277 msg = ex.args[0]
266 line = ex.args[1][0]
278 line = ex.args[1][0]
267 self.out.write("%s\n\n*** ERROR: %s%s%s\n" %
279 self.out.write("%s\n\n*** ERROR: %s%s%s\n" %
268 (colors[token.ERRORTOKEN],
280 (colors[token.ERRORTOKEN],
269 msg, self.raw[self.lines[line]:],
281 msg, self.raw[self.lines[line]:],
270 colors.normal)
282 colors.normal)
271 )
283 )
272 error = True
284 error = True
273 self.out.write(colors.normal+'\n')
285 self.out.write(colors.normal+'\n')
274 if string_output:
286 if string_output:
275 output = self.out.getvalue()
287 output = self.out.getvalue()
276 self.out = out_old
288 self.out = out_old
277 return (output, error)
289 return (output, error)
278 return (None, error)
290 return (None, error)
279
291
280 def __call__(self, toktype, toktext, start_pos, end_pos, line):
292 def __call__(self, toktype, toktext, start_pos, end_pos, line):
281 """ Token handler, with syntax highlighting."""
293 """ Token handler, with syntax highlighting."""
282 (srow,scol) = start_pos
294 (srow,scol) = start_pos
283 (erow,ecol) = end_pos
295 (erow,ecol) = end_pos
284 colors = self.colors
296 colors = self.colors
285 owrite = self.out.write
297 owrite = self.out.write
286
298
287 # line separator, so this works across platforms
299 # line separator, so this works across platforms
288 linesep = os.linesep
300 linesep = os.linesep
289
301
290 # calculate new positions
302 # calculate new positions
291 oldpos = self.pos
303 oldpos = self.pos
292 newpos = self.lines[srow] + scol
304 newpos = self.lines[srow] + scol
293 self.pos = newpos + len(toktext)
305 self.pos = newpos + len(toktext)
294
306
295 # send the original whitespace, if needed
307 # send the original whitespace, if needed
296 if newpos > oldpos:
308 if newpos > oldpos:
297 owrite(self.raw[oldpos:newpos])
309 owrite(self.raw[oldpos:newpos])
298
310
299 # skip indenting tokens
311 # skip indenting tokens
300 if toktype in [token.INDENT, token.DEDENT]:
312 if toktype in [token.INDENT, token.DEDENT]:
301 self.pos = newpos
313 self.pos = newpos
302 return
314 return
303
315
304 # map token type to a color group
316 # map token type to a color group
305 if token.LPAR <= toktype <= token.OP:
317 if token.LPAR <= toktype <= token.OP:
306 toktype = token.OP
318 toktype = token.OP
307 elif toktype == token.NAME and keyword.iskeyword(toktext):
319 elif toktype == token.NAME and keyword.iskeyword(toktext):
308 toktype = _KEYWORD
320 toktype = _KEYWORD
309 color = colors.get(toktype, colors[_TEXT])
321 color = colors.get(toktype, colors[_TEXT])
310
322
311 #print '<%s>' % toktext, # dbg
323 #print '<%s>' % toktext, # dbg
312
324
313 # Triple quoted strings must be handled carefully so that backtracking
325 # Triple quoted strings must be handled carefully so that backtracking
314 # in pagers works correctly. We need color terminators on _each_ line.
326 # in pagers works correctly. We need color terminators on _each_ line.
315 if linesep in toktext:
327 if linesep in toktext:
316 toktext = toktext.replace(linesep, '%s%s%s' %
328 toktext = toktext.replace(linesep, '%s%s%s' %
317 (colors.normal,linesep,color))
329 (colors.normal,linesep,color))
318
330
319 # send text
331 # send text
320 owrite('%s%s%s' % (color,toktext,colors.normal))
332 owrite('%s%s%s' % (color,toktext,colors.normal))
321
322 def main(argv=None):
323 """Run as a command-line script: colorize a python file or stdin using ANSI
324 color escapes and print to stdout.
325
326 Inputs:
327
328 - argv(None): a list of strings like sys.argv[1:] giving the command-line
329 arguments. If None, use sys.argv[1:].
330 """
331
332 usage_msg = """%prog [options] [filename]
333
334 Colorize a python file or stdin using ANSI color escapes and print to stdout.
335 If no filename is given, or if filename is -, read standard input."""
336
337 import optparse
338 parser = optparse.OptionParser(usage=usage_msg)
339 newopt = parser.add_option
340 newopt('-s','--scheme',metavar='NAME',dest='scheme_name',action='store',
341 choices=['Linux','LightBG','NoColor'],default=_scheme_default,
342 help="give the color scheme to use. Currently only 'Linux'\
343 (default) and 'LightBG' and 'NoColor' are implemented (give without\
344 quotes)")
345
346 opts,args = parser.parse_args(argv)
347
348 if len(args) > 1:
349 parser.error("you must give at most one filename.")
350
351 if len(args) == 0:
352 fname = '-' # no filename given; setup to read from stdin
353 else:
354 fname = args[0]
355
356 if fname == '-':
357 stream = sys.stdin
358 else:
359 try:
360 stream = open(fname)
361 except IOError as msg:
362 print(msg, file=sys.stderr)
363 sys.exit(1)
364
365 parser = Parser()
366
367 # we need nested try blocks because pre-2.5 python doesn't support unified
368 # try-except-finally
369 try:
370 try:
371 # write colorized version to stdout
372 parser.format(stream.read(),scheme=opts.scheme_name)
373 except IOError as msg:
374 # if user reads through a pager and quits, don't print traceback
375 if msg.args != (32,'Broken pipe'):
376 raise
377 finally:
378 if stream is not sys.stdin:
379 stream.close() # in case a non-handled exception happened above
380
381 if __name__ == "__main__":
382 main()
@@ -1,26 +1,26 b''
1 #*****************************************************************************
1 #*****************************************************************************
2 # Copyright (C) 2016 The IPython Team <ipython-dev@scipy.org>
2 # Copyright (C) 2016 The IPython Team <ipython-dev@scipy.org>
3 #
3 #
4 # Distributed under the terms of the BSD License. The full license is in
4 # Distributed under the terms of the BSD License. The full license is in
5 # the file COPYING, distributed as part of this software.
5 # the file COPYING, distributed as part of this software.
6 #*****************************************************************************
6 #*****************************************************************************
7 from __future__ import absolute_import
7 from __future__ import absolute_import
8
8
9 """
9 """
10 Color managing related utilities
10 Color managing related utilities
11 """
11 """
12
12
13 import pygments
13 import pygments
14
14
15 from traitlets.config import Configurable
15 from traitlets.config import Configurable
16 from traitlets import Unicode
16 from traitlets import Unicode
17
17
18
18
19 available_themes = lambda : [s for s in pygments.styles.get_all_styles()]+['NoColor','LightBG','Linux', 'Neutral']
19 available_themes = lambda : [s for s in pygments.styles.get_all_styles()]+['NoColor','LightBG','Linux', 'Neutral']
20
20
21 class Colorable(Configurable):
21 class Colorable(Configurable):
22 """
22 """
23 A subclass of configurable for all the classes that have a `default_scheme`
23 A subclass of configurable for all the classes that have a `default_scheme`
24 """
24 """
25 default_style=Unicode('lightbg').tag(config=True)
25 default_style=Unicode('LightBG').tag(config=True)
26
26
@@ -1,78 +1,78 b''
1 # coding: utf-8
1 # coding: utf-8
2 """Test suite for our color utilities.
2 """Test suite for our color utilities.
3
3
4 Authors
4 Authors
5 -------
5 -------
6
6
7 * Min RK
7 * Min RK
8 """
8 """
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10 # Copyright (C) 2011 The IPython Development Team
10 # Copyright (C) 2011 The IPython Development Team
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING.txt, distributed as part of this software.
13 # the file COPYING.txt, distributed as part of this software.
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Imports
17 # Imports
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 # third party
20 # third party
21 import nose.tools as nt
21 import nose.tools as nt
22
22
23 # our own
23 # our own
24 from IPython.utils.PyColorize import Parser
24 from IPython.utils.PyColorize import Parser
25 import io
25 import io
26
26
27 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
28 # Test functions
28 # Test functions
29 #-----------------------------------------------------------------------------
29 #-----------------------------------------------------------------------------
30
30
31 sample = u"""
31 sample = u"""
32 def function(arg, *args, kwarg=True, **kwargs):
32 def function(arg, *args, kwarg=True, **kwargs):
33 '''
33 '''
34 this is docs
34 this is docs
35 '''
35 '''
36 pass is True
36 pass is True
37 False == None
37 False == None
38
38
39 with io.open(ru'unicode'):
39 with io.open(ru'unicode'):
40 raise ValueError("\n escape \r sequence")
40 raise ValueError("\n escape \r sequence")
41
41
42 print("wΔ›ird ΓΌnicoΓ°e")
42 print("wΔ›ird ΓΌnicoΓ°e")
43
43
44 class Bar(Super):
44 class Bar(Super):
45
45
46 def __init__(self):
46 def __init__(self):
47 super(Bar, self).__init__(1**2, 3^4, 5 or 6)
47 super(Bar, self).__init__(1**2, 3^4, 5 or 6)
48 """
48 """
49
49
50 def test_loop_colors():
50 def test_loop_colors():
51
51
52 for scheme in ('Linux', 'NoColor','LightBG', 'Neutral'):
52 for style in ('Linux', 'NoColor','LightBG', 'Neutral'):
53
53
54 def test_unicode_colorize():
54 def test_unicode_colorize():
55 p = Parser()
55 p = Parser(style=style)
56 f1 = p.format('1/0', 'str', scheme=scheme)
56 f1 = p.format('1/0', 'str')
57 f2 = p.format(u'1/0', 'str', scheme=scheme)
57 f2 = p.format(u'1/0', 'str')
58 nt.assert_equal(f1, f2)
58 nt.assert_equal(f1, f2)
59
59
60 def test_parse_sample():
60 def test_parse_sample():
61 """and test writing to a buffer"""
61 """and test writing to a buffer"""
62 buf = io.StringIO()
62 buf = io.StringIO()
63 p = Parser()
63 p = Parser(style=style)
64 p.format(sample, buf, scheme=scheme)
64 p.format(sample, buf)
65 buf.seek(0)
65 buf.seek(0)
66 f1 = buf.read()
66 f1 = buf.read()
67
67
68 nt.assert_not_in('ERROR', f1)
68 nt.assert_not_in('ERROR', f1)
69
69
70 def test_parse_error():
70 def test_parse_error():
71 p = Parser()
71 p = Parser(style=style)
72 f1 = p.format(')', 'str', scheme=scheme)
72 f1 = p.format(')', 'str')
73 if scheme != 'NoColor':
73 if style != 'NoColor':
74 nt.assert_in('ERROR', f1)
74 nt.assert_in('ERROR', f1)
75
75
76 yield test_unicode_colorize
76 yield test_unicode_colorize
77 yield test_parse_sample
77 yield test_parse_sample
78 yield test_parse_error
78 yield test_parse_error
General Comments 0
You need to be logged in to leave comments. Login now