##// END OF EJS Templates
Make everyone happy with a neutral colortheme by default.
Matthias Bussonnier -
Show More
@@ -1,585 +1,589 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
33
34 from IPython import get_ipython
34 from IPython import get_ipython
35 from IPython.utils import PyColorize, ulinecache
35 from IPython.utils import PyColorize, ulinecache
36 from IPython.utils import coloransi, py3compat
36 from IPython.utils import coloransi, py3compat
37 from IPython.core.excolors import exception_colors
37 from IPython.core.excolors import exception_colors
38 from IPython.testing.skipdoctest import skip_doctest
38 from IPython.testing.skipdoctest import skip_doctest
39
39
40
40
41 prompt = 'ipdb> '
41 prompt = 'ipdb> '
42
42
43 #We have to check this directly from sys.argv, config struct not yet available
43 #We have to check this directly from sys.argv, config struct not yet available
44 from pdb import Pdb as OldPdb
44 from pdb import Pdb as OldPdb
45
45
46 # Allow the set_trace code to operate outside of an ipython instance, even if
46 # Allow the set_trace code to operate outside of an ipython instance, even if
47 # it does so with some limitations. The rest of this support is implemented in
47 # it does so with some limitations. The rest of this support is implemented in
48 # the Tracer constructor.
48 # the Tracer constructor.
49
49
50 def make_arrow(pad):
50 def make_arrow(pad):
51 """generate the leading arrow in front of traceback or debugger"""
51 """generate the leading arrow in front of traceback or debugger"""
52 if pad >= 2:
52 if pad >= 2:
53 return '-'*(pad-2) + '> '
53 return '-'*(pad-2) + '> '
54 elif pad == 1:
54 elif pad == 1:
55 return '>'
55 return '>'
56 return ''
56 return ''
57
57
58
58
59 def BdbQuit_excepthook(et, ev, tb, excepthook=None):
59 def BdbQuit_excepthook(et, ev, tb, excepthook=None):
60 """Exception hook which handles `BdbQuit` exceptions.
60 """Exception hook which handles `BdbQuit` exceptions.
61
61
62 All other exceptions are processed using the `excepthook`
62 All other exceptions are processed using the `excepthook`
63 parameter.
63 parameter.
64 """
64 """
65 if et==bdb.BdbQuit:
65 if et==bdb.BdbQuit:
66 print('Exiting Debugger.')
66 print('Exiting Debugger.')
67 elif excepthook is not None:
67 elif excepthook is not None:
68 excepthook(et, ev, tb)
68 excepthook(et, ev, tb)
69 else:
69 else:
70 # Backwards compatibility. Raise deprecation warning?
70 # Backwards compatibility. Raise deprecation warning?
71 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
71 BdbQuit_excepthook.excepthook_ori(et,ev,tb)
72
72
73 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
73 def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
74 print('Exiting Debugger.')
74 print('Exiting Debugger.')
75
75
76
76
77 class Tracer(object):
77 class Tracer(object):
78 """Class for local debugging, similar to pdb.set_trace.
78 """Class for local debugging, similar to pdb.set_trace.
79
79
80 Instances of this class, when called, behave like pdb.set_trace, but
80 Instances of this class, when called, behave like pdb.set_trace, but
81 providing IPython's enhanced capabilities.
81 providing IPython's enhanced capabilities.
82
82
83 This is implemented as a class which must be initialized in your own code
83 This is implemented as a class which must be initialized in your own code
84 and not as a standalone function because we need to detect at runtime
84 and not as a standalone function because we need to detect at runtime
85 whether IPython is already active or not. That detection is done in the
85 whether IPython is already active or not. That detection is done in the
86 constructor, ensuring that this code plays nicely with a running IPython,
86 constructor, ensuring that this code plays nicely with a running IPython,
87 while functioning acceptably (though with limitations) if outside of it.
87 while functioning acceptably (though with limitations) if outside of it.
88 """
88 """
89
89
90 @skip_doctest
90 @skip_doctest
91 def __init__(self, colors=None):
91 def __init__(self, colors=None):
92 """Create a local debugger instance.
92 """Create a local debugger instance.
93
93
94 Parameters
94 Parameters
95 ----------
95 ----------
96
96
97 colors : str, optional
97 colors : str, optional
98 The name of the color scheme to use, it must be one of IPython's
98 The name of the color scheme to use, it must be one of IPython's
99 valid color schemes. If not given, the function will default to
99 valid color schemes. If not given, the function will default to
100 the current IPython scheme when running inside IPython, and to
100 the current IPython scheme when running inside IPython, and to
101 'NoColor' otherwise.
101 'NoColor' otherwise.
102
102
103 Examples
103 Examples
104 --------
104 --------
105 ::
105 ::
106
106
107 from IPython.core.debugger import Tracer; debug_here = Tracer()
107 from IPython.core.debugger import Tracer; debug_here = Tracer()
108
108
109 Later in your code::
109 Later in your code::
110
110
111 debug_here() # -> will open up the debugger at that point.
111 debug_here() # -> will open up the debugger at that point.
112
112
113 Once the debugger activates, you can use all of its regular commands to
113 Once the debugger activates, you can use all of its regular commands to
114 step through code, set breakpoints, etc. See the pdb documentation
114 step through code, set breakpoints, etc. See the pdb documentation
115 from the Python standard library for usage details.
115 from the Python standard library for usage details.
116 """
116 """
117
117
118 ip = get_ipython()
118 ip = get_ipython()
119 if ip is None:
119 if ip is None:
120 # Outside of ipython, we set our own exception hook manually
120 # Outside of ipython, we set our own exception hook manually
121 sys.excepthook = functools.partial(BdbQuit_excepthook,
121 sys.excepthook = functools.partial(BdbQuit_excepthook,
122 excepthook=sys.excepthook)
122 excepthook=sys.excepthook)
123 def_colors = 'NoColor'
123 def_colors = 'NoColor'
124 else:
124 else:
125 # In ipython, we use its custom exception handler mechanism
125 # In ipython, we use its custom exception handler mechanism
126 def_colors = ip.colors
126 def_colors = ip.colors
127 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
127 ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook)
128
128
129 if colors is None:
129 if colors is None:
130 colors = def_colors
130 colors = def_colors
131
131
132 # The stdlib debugger internally uses a modified repr from the `repr`
132 # The stdlib debugger internally uses a modified repr from the `repr`
133 # module, that limits the length of printed strings to a hardcoded
133 # module, that limits the length of printed strings to a hardcoded
134 # limit of 30 characters. That much trimming is too aggressive, let's
134 # limit of 30 characters. That much trimming is too aggressive, let's
135 # at least raise that limit to 80 chars, which should be enough for
135 # at least raise that limit to 80 chars, which should be enough for
136 # most interactive uses.
136 # most interactive uses.
137 try:
137 try:
138 try:
138 try:
139 from reprlib import aRepr # Py 3
139 from reprlib import aRepr # Py 3
140 except ImportError:
140 except ImportError:
141 from repr import aRepr # Py 2
141 from repr import aRepr # Py 2
142 aRepr.maxstring = 80
142 aRepr.maxstring = 80
143 except:
143 except:
144 # This is only a user-facing convenience, so any error we encounter
144 # This is only a user-facing convenience, so any error we encounter
145 # here can be warned about but can be otherwise ignored. These
145 # here can be warned about but can be otherwise ignored. These
146 # printouts will tell us about problems if this API changes
146 # printouts will tell us about problems if this API changes
147 import traceback
147 import traceback
148 traceback.print_exc()
148 traceback.print_exc()
149
149
150 self.debugger = Pdb(colors)
150 self.debugger = Pdb(colors)
151
151
152 def __call__(self):
152 def __call__(self):
153 """Starts an interactive debugger at the point where called.
153 """Starts an interactive debugger at the point where called.
154
154
155 This is similar to the pdb.set_trace() function from the std lib, but
155 This is similar to the pdb.set_trace() function from the std lib, but
156 using IPython's enhanced debugger."""
156 using IPython's enhanced debugger."""
157
157
158 self.debugger.set_trace(sys._getframe().f_back)
158 self.debugger.set_trace(sys._getframe().f_back)
159
159
160
160
161 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
161 def decorate_fn_with_doc(new_fn, old_fn, additional_text=""):
162 """Make new_fn have old_fn's doc string. This is particularly useful
162 """Make new_fn have old_fn's doc string. This is particularly useful
163 for the ``do_...`` commands that hook into the help system.
163 for the ``do_...`` commands that hook into the help system.
164 Adapted from from a comp.lang.python posting
164 Adapted from from a comp.lang.python posting
165 by Duncan Booth."""
165 by Duncan Booth."""
166 def wrapper(*args, **kw):
166 def wrapper(*args, **kw):
167 return new_fn(*args, **kw)
167 return new_fn(*args, **kw)
168 if old_fn.__doc__:
168 if old_fn.__doc__:
169 wrapper.__doc__ = old_fn.__doc__ + additional_text
169 wrapper.__doc__ = old_fn.__doc__ + additional_text
170 return wrapper
170 return wrapper
171
171
172
172
173 def _file_lines(fname):
173 def _file_lines(fname):
174 """Return the contents of a named file as a list of lines.
174 """Return the contents of a named file as a list of lines.
175
175
176 This function never raises an IOError exception: if the file can't be
176 This function never raises an IOError exception: if the file can't be
177 read, it simply returns an empty list."""
177 read, it simply returns an empty list."""
178
178
179 try:
179 try:
180 outfile = open(fname)
180 outfile = open(fname)
181 except IOError:
181 except IOError:
182 return []
182 return []
183 else:
183 else:
184 out = outfile.readlines()
184 out = outfile.readlines()
185 outfile.close()
185 outfile.close()
186 return out
186 return out
187
187
188
188
189 class Pdb(OldPdb, object):
189 class Pdb(OldPdb, object):
190 """Modified Pdb class, does not load readline."""
190 """Modified Pdb class, does not load readline."""
191
191
192 def __init__(self,color_scheme='NoColor',completekey=None,
192 def __init__(self,color_scheme='NoColor',completekey=None,
193 stdin=None, stdout=None, context=5):
193 stdin=None, stdout=None, context=5):
194
194
195 # Parent constructor:
195 # Parent constructor:
196 try:
196 try:
197 self.context=int(context)
197 self.context=int(context)
198 if self.context <= 0:
198 if self.context <= 0:
199 raise ValueError("Context must be a positive integer")
199 raise ValueError("Context must be a positive integer")
200 except (TypeError, ValueError):
200 except (TypeError, ValueError):
201 raise ValueError("Context must be a positive integer")
201 raise ValueError("Context must be a positive integer")
202
202
203 OldPdb.__init__(self, completekey, stdin, stdout)
203 OldPdb.__init__(self, completekey, stdin, stdout)
204
204
205 # IPython changes...
205 # IPython changes...
206 self.shell = get_ipython()
206 self.shell = get_ipython()
207
207
208 if self.shell is None:
208 if self.shell is None:
209 # No IPython instance running, we must create one
209 # No IPython instance running, we must create one
210 from IPython.terminal.interactiveshell import \
210 from IPython.terminal.interactiveshell import \
211 TerminalInteractiveShell
211 TerminalInteractiveShell
212 self.shell = TerminalInteractiveShell.instance()
212 self.shell = TerminalInteractiveShell.instance()
213
213
214 self.aliases = {}
214 self.aliases = {}
215
215
216 # Create color table: we copy the default one from the traceback
216 # Create color table: we copy the default one from the traceback
217 # module and add a few attributes needed for debugging
217 # module and add a few attributes needed for debugging
218 self.color_scheme_table = exception_colors()
218 self.color_scheme_table = exception_colors()
219
219
220 # shorthands
220 # shorthands
221 C = coloransi.TermColors
221 C = coloransi.TermColors
222 cst = self.color_scheme_table
222 cst = self.color_scheme_table
223
223
224 cst['NoColor'].colors.prompt = C.NoColor
224 cst['NoColor'].colors.prompt = C.NoColor
225 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
225 cst['NoColor'].colors.breakpoint_enabled = C.NoColor
226 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
226 cst['NoColor'].colors.breakpoint_disabled = C.NoColor
227
227
228 cst['Linux'].colors.prompt = C.Green
228 cst['Linux'].colors.prompt = C.Green
229 cst['Linux'].colors.breakpoint_enabled = C.LightRed
229 cst['Linux'].colors.breakpoint_enabled = C.LightRed
230 cst['Linux'].colors.breakpoint_disabled = C.Red
230 cst['Linux'].colors.breakpoint_disabled = C.Red
231
231
232 cst['LightBG'].colors.prompt = C.Blue
232 cst['LightBG'].colors.prompt = C.Blue
233 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
233 cst['LightBG'].colors.breakpoint_enabled = C.LightRed
234 cst['LightBG'].colors.breakpoint_disabled = C.Red
234 cst['LightBG'].colors.breakpoint_disabled = C.Red
235
235
236 cst['Neutral'].colors.prompt = C.Blue
237 cst['Neutral'].colors.breakpoint_enabled = C.LightRed
238 cst['Neutral'].colors.breakpoint_disabled = C.Red
239
236 self.set_colors(color_scheme)
240 self.set_colors(color_scheme)
237
241
238 # Add a python parser so we can syntax highlight source while
242 # Add a python parser so we can syntax highlight source while
239 # debugging.
243 # debugging.
240 self.parser = PyColorize.Parser()
244 self.parser = PyColorize.Parser()
241
245
242 # Set the prompt - the default prompt is '(Pdb)'
246 # Set the prompt - the default prompt is '(Pdb)'
243 self.prompt = prompt
247 self.prompt = prompt
244
248
245 def set_colors(self, scheme):
249 def set_colors(self, scheme):
246 """Shorthand access to the color table scheme selector method."""
250 """Shorthand access to the color table scheme selector method."""
247 self.color_scheme_table.set_active_scheme(scheme)
251 self.color_scheme_table.set_active_scheme(scheme)
248
252
249 def interaction(self, frame, traceback):
253 def interaction(self, frame, traceback):
250 try:
254 try:
251 OldPdb.interaction(self, frame, traceback)
255 OldPdb.interaction(self, frame, traceback)
252 except KeyboardInterrupt:
256 except KeyboardInterrupt:
253 sys.stdout.write('\n' + self.shell.get_exception_only())
257 sys.stdout.write('\n' + self.shell.get_exception_only())
254
258
255 def parseline(self, line):
259 def parseline(self, line):
256 if line.startswith("!!"):
260 if line.startswith("!!"):
257 # Force standard behavior.
261 # Force standard behavior.
258 return super(Pdb, self).parseline(line[2:])
262 return super(Pdb, self).parseline(line[2:])
259 # "Smart command mode" from pdb++: don't execute commands if a variable
263 # "Smart command mode" from pdb++: don't execute commands if a variable
260 # with the same name exists.
264 # with the same name exists.
261 cmd, arg, newline = super(Pdb, self).parseline(line)
265 cmd, arg, newline = super(Pdb, self).parseline(line)
262 # Fix for #9611: Do not trigger smart command if the command is `exit`
266 # Fix for #9611: Do not trigger smart command if the command is `exit`
263 # or `quit` and it would resolve to their *global* value (the
267 # or `quit` and it would resolve to their *global* value (the
264 # `ExitAutocall` object). Just checking that it is not present in the
268 # `ExitAutocall` object). Just checking that it is not present in the
265 # locals dict is not enough as locals and globals match at the
269 # locals dict is not enough as locals and globals match at the
266 # toplevel.
270 # toplevel.
267 if ((cmd in self.curframe.f_locals or cmd in self.curframe.f_globals)
271 if ((cmd in self.curframe.f_locals or cmd in self.curframe.f_globals)
268 and not (cmd in ["exit", "quit"]
272 and not (cmd in ["exit", "quit"]
269 and (self.curframe.f_locals is self.curframe.f_globals
273 and (self.curframe.f_locals is self.curframe.f_globals
270 or cmd not in self.curframe.f_locals))):
274 or cmd not in self.curframe.f_locals))):
271 return super(Pdb, self).parseline("!" + line)
275 return super(Pdb, self).parseline("!" + line)
272 return super(Pdb, self).parseline(line)
276 return super(Pdb, self).parseline(line)
273
277
274 def new_do_up(self, arg):
278 def new_do_up(self, arg):
275 OldPdb.do_up(self, arg)
279 OldPdb.do_up(self, arg)
276 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
280 do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up)
277
281
278 def new_do_down(self, arg):
282 def new_do_down(self, arg):
279 OldPdb.do_down(self, arg)
283 OldPdb.do_down(self, arg)
280
284
281 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
285 do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down)
282
286
283 def new_do_frame(self, arg):
287 def new_do_frame(self, arg):
284 OldPdb.do_frame(self, arg)
288 OldPdb.do_frame(self, arg)
285
289
286 def new_do_quit(self, arg):
290 def new_do_quit(self, arg):
287
291
288 if hasattr(self, 'old_all_completions'):
292 if hasattr(self, 'old_all_completions'):
289 self.shell.Completer.all_completions=self.old_all_completions
293 self.shell.Completer.all_completions=self.old_all_completions
290
294
291 return OldPdb.do_quit(self, arg)
295 return OldPdb.do_quit(self, arg)
292
296
293 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
297 do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit)
294
298
295 def new_do_restart(self, arg):
299 def new_do_restart(self, arg):
296 """Restart command. In the context of ipython this is exactly the same
300 """Restart command. In the context of ipython this is exactly the same
297 thing as 'quit'."""
301 thing as 'quit'."""
298 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
302 self.msg("Restart doesn't make sense here. Using 'quit' instead.")
299 return self.do_quit(arg)
303 return self.do_quit(arg)
300
304
301 def print_stack_trace(self, context=None):
305 def print_stack_trace(self, context=None):
302 if context is None:
306 if context is None:
303 context = self.context
307 context = self.context
304 try:
308 try:
305 context=int(context)
309 context=int(context)
306 if context <= 0:
310 if context <= 0:
307 raise ValueError("Context must be a positive integer")
311 raise ValueError("Context must be a positive integer")
308 except (TypeError, ValueError):
312 except (TypeError, ValueError):
309 raise ValueError("Context must be a positive integer")
313 raise ValueError("Context must be a positive integer")
310 try:
314 try:
311 for frame_lineno in self.stack:
315 for frame_lineno in self.stack:
312 self.print_stack_entry(frame_lineno, context=context)
316 self.print_stack_entry(frame_lineno, context=context)
313 except KeyboardInterrupt:
317 except KeyboardInterrupt:
314 pass
318 pass
315
319
316 def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ',
320 def print_stack_entry(self,frame_lineno, prompt_prefix='\n-> ',
317 context=None):
321 context=None):
318 if context is None:
322 if context is None:
319 context = self.context
323 context = self.context
320 try:
324 try:
321 context=int(context)
325 context=int(context)
322 if context <= 0:
326 if context <= 0:
323 raise ValueError("Context must be a positive integer")
327 raise ValueError("Context must be a positive integer")
324 except (TypeError, ValueError):
328 except (TypeError, ValueError):
325 raise ValueError("Context must be a positive integer")
329 raise ValueError("Context must be a positive integer")
326 print(self.format_stack_entry(frame_lineno, '', context))
330 print(self.format_stack_entry(frame_lineno, '', context))
327
331
328 # vds: >>
332 # vds: >>
329 frame, lineno = frame_lineno
333 frame, lineno = frame_lineno
330 filename = frame.f_code.co_filename
334 filename = frame.f_code.co_filename
331 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
335 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
332 # vds: <<
336 # vds: <<
333
337
334 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
338 def format_stack_entry(self, frame_lineno, lprefix=': ', context=None):
335 if context is None:
339 if context is None:
336 context = self.context
340 context = self.context
337 try:
341 try:
338 context=int(context)
342 context=int(context)
339 if context <= 0:
343 if context <= 0:
340 print("Context must be a positive integer")
344 print("Context must be a positive integer")
341 except (TypeError, ValueError):
345 except (TypeError, ValueError):
342 print("Context must be a positive integer")
346 print("Context must be a positive integer")
343 try:
347 try:
344 import reprlib # Py 3
348 import reprlib # Py 3
345 except ImportError:
349 except ImportError:
346 import repr as reprlib # Py 2
350 import repr as reprlib # Py 2
347
351
348 ret = []
352 ret = []
349
353
350 Colors = self.color_scheme_table.active_colors
354 Colors = self.color_scheme_table.active_colors
351 ColorsNormal = Colors.Normal
355 ColorsNormal = Colors.Normal
352 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
356 tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal)
353 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
357 tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal)
354 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
358 tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
355 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
359 tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line,
356 ColorsNormal)
360 ColorsNormal)
357
361
358 frame, lineno = frame_lineno
362 frame, lineno = frame_lineno
359
363
360 return_value = ''
364 return_value = ''
361 if '__return__' in frame.f_locals:
365 if '__return__' in frame.f_locals:
362 rv = frame.f_locals['__return__']
366 rv = frame.f_locals['__return__']
363 #return_value += '->'
367 #return_value += '->'
364 return_value += reprlib.repr(rv) + '\n'
368 return_value += reprlib.repr(rv) + '\n'
365 ret.append(return_value)
369 ret.append(return_value)
366
370
367 #s = filename + '(' + `lineno` + ')'
371 #s = filename + '(' + `lineno` + ')'
368 filename = self.canonic(frame.f_code.co_filename)
372 filename = self.canonic(frame.f_code.co_filename)
369 link = tpl_link % py3compat.cast_unicode(filename)
373 link = tpl_link % py3compat.cast_unicode(filename)
370
374
371 if frame.f_code.co_name:
375 if frame.f_code.co_name:
372 func = frame.f_code.co_name
376 func = frame.f_code.co_name
373 else:
377 else:
374 func = "<lambda>"
378 func = "<lambda>"
375
379
376 call = ''
380 call = ''
377 if func != '?':
381 if func != '?':
378 if '__args__' in frame.f_locals:
382 if '__args__' in frame.f_locals:
379 args = reprlib.repr(frame.f_locals['__args__'])
383 args = reprlib.repr(frame.f_locals['__args__'])
380 else:
384 else:
381 args = '()'
385 args = '()'
382 call = tpl_call % (func, args)
386 call = tpl_call % (func, args)
383
387
384 # The level info should be generated in the same format pdb uses, to
388 # The level info should be generated in the same format pdb uses, to
385 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
389 # avoid breaking the pdbtrack functionality of python-mode in *emacs.
386 if frame is self.curframe:
390 if frame is self.curframe:
387 ret.append('> ')
391 ret.append('> ')
388 else:
392 else:
389 ret.append(' ')
393 ret.append(' ')
390 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
394 ret.append(u'%s(%s)%s\n' % (link,lineno,call))
391
395
392 start = lineno - 1 - context//2
396 start = lineno - 1 - context//2
393 lines = ulinecache.getlines(filename)
397 lines = ulinecache.getlines(filename)
394 start = min(start, len(lines) - context)
398 start = min(start, len(lines) - context)
395 start = max(start, 0)
399 start = max(start, 0)
396 lines = lines[start : start + context]
400 lines = lines[start : start + context]
397
401
398 for i,line in enumerate(lines):
402 for i,line in enumerate(lines):
399 show_arrow = (start + 1 + i == lineno)
403 show_arrow = (start + 1 + i == lineno)
400 linetpl = (frame is self.curframe or show_arrow) \
404 linetpl = (frame is self.curframe or show_arrow) \
401 and tpl_line_em \
405 and tpl_line_em \
402 or tpl_line
406 or tpl_line
403 ret.append(self.__format_line(linetpl, filename,
407 ret.append(self.__format_line(linetpl, filename,
404 start + 1 + i, line,
408 start + 1 + i, line,
405 arrow = show_arrow) )
409 arrow = show_arrow) )
406 return ''.join(ret)
410 return ''.join(ret)
407
411
408 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
412 def __format_line(self, tpl_line, filename, lineno, line, arrow = False):
409 bp_mark = ""
413 bp_mark = ""
410 bp_mark_color = ""
414 bp_mark_color = ""
411
415
412 scheme = self.color_scheme_table.active_scheme_name
416 scheme = self.color_scheme_table.active_scheme_name
413 new_line, err = self.parser.format2(line, 'str', scheme)
417 new_line, err = self.parser.format2(line, 'str', scheme)
414 if not err: line = new_line
418 if not err: line = new_line
415
419
416 bp = None
420 bp = None
417 if lineno in self.get_file_breaks(filename):
421 if lineno in self.get_file_breaks(filename):
418 bps = self.get_breaks(filename, lineno)
422 bps = self.get_breaks(filename, lineno)
419 bp = bps[-1]
423 bp = bps[-1]
420
424
421 if bp:
425 if bp:
422 Colors = self.color_scheme_table.active_colors
426 Colors = self.color_scheme_table.active_colors
423 bp_mark = str(bp.number)
427 bp_mark = str(bp.number)
424 bp_mark_color = Colors.breakpoint_enabled
428 bp_mark_color = Colors.breakpoint_enabled
425 if not bp.enabled:
429 if not bp.enabled:
426 bp_mark_color = Colors.breakpoint_disabled
430 bp_mark_color = Colors.breakpoint_disabled
427
431
428 numbers_width = 7
432 numbers_width = 7
429 if arrow:
433 if arrow:
430 # This is the line with the error
434 # This is the line with the error
431 pad = numbers_width - len(str(lineno)) - len(bp_mark)
435 pad = numbers_width - len(str(lineno)) - len(bp_mark)
432 num = '%s%s' % (make_arrow(pad), str(lineno))
436 num = '%s%s' % (make_arrow(pad), str(lineno))
433 else:
437 else:
434 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
438 num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
435
439
436 return tpl_line % (bp_mark_color + bp_mark, num, line)
440 return tpl_line % (bp_mark_color + bp_mark, num, line)
437
441
438
442
439 def print_list_lines(self, filename, first, last):
443 def print_list_lines(self, filename, first, last):
440 """The printing (as opposed to the parsing part of a 'list'
444 """The printing (as opposed to the parsing part of a 'list'
441 command."""
445 command."""
442 try:
446 try:
443 Colors = self.color_scheme_table.active_colors
447 Colors = self.color_scheme_table.active_colors
444 ColorsNormal = Colors.Normal
448 ColorsNormal = Colors.Normal
445 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
449 tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal)
446 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
450 tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal)
447 src = []
451 src = []
448 if filename == "<string>" and hasattr(self, "_exec_filename"):
452 if filename == "<string>" and hasattr(self, "_exec_filename"):
449 filename = self._exec_filename
453 filename = self._exec_filename
450
454
451 for lineno in range(first, last+1):
455 for lineno in range(first, last+1):
452 line = ulinecache.getline(filename, lineno)
456 line = ulinecache.getline(filename, lineno)
453 if not line:
457 if not line:
454 break
458 break
455
459
456 if lineno == self.curframe.f_lineno:
460 if lineno == self.curframe.f_lineno:
457 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
461 line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True)
458 else:
462 else:
459 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
463 line = self.__format_line(tpl_line, filename, lineno, line, arrow = False)
460
464
461 src.append(line)
465 src.append(line)
462 self.lineno = lineno
466 self.lineno = lineno
463
467
464 print(''.join(src))
468 print(''.join(src))
465
469
466 except KeyboardInterrupt:
470 except KeyboardInterrupt:
467 pass
471 pass
468
472
469 def do_list(self, arg):
473 def do_list(self, arg):
470 self.lastcmd = 'list'
474 self.lastcmd = 'list'
471 last = None
475 last = None
472 if arg:
476 if arg:
473 try:
477 try:
474 x = eval(arg, {}, {})
478 x = eval(arg, {}, {})
475 if type(x) == type(()):
479 if type(x) == type(()):
476 first, last = x
480 first, last = x
477 first = int(first)
481 first = int(first)
478 last = int(last)
482 last = int(last)
479 if last < first:
483 if last < first:
480 # Assume it's a count
484 # Assume it's a count
481 last = first + last
485 last = first + last
482 else:
486 else:
483 first = max(1, int(x) - 5)
487 first = max(1, int(x) - 5)
484 except:
488 except:
485 print('*** Error in argument:', repr(arg))
489 print('*** Error in argument:', repr(arg))
486 return
490 return
487 elif self.lineno is None:
491 elif self.lineno is None:
488 first = max(1, self.curframe.f_lineno - 5)
492 first = max(1, self.curframe.f_lineno - 5)
489 else:
493 else:
490 first = self.lineno + 1
494 first = self.lineno + 1
491 if last is None:
495 if last is None:
492 last = first + 10
496 last = first + 10
493 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
497 self.print_list_lines(self.curframe.f_code.co_filename, first, last)
494
498
495 # vds: >>
499 # vds: >>
496 lineno = first
500 lineno = first
497 filename = self.curframe.f_code.co_filename
501 filename = self.curframe.f_code.co_filename
498 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
502 self.shell.hooks.synchronize_with_editor(filename, lineno, 0)
499 # vds: <<
503 # vds: <<
500
504
501 do_l = do_list
505 do_l = do_list
502
506
503 def getsourcelines(self, obj):
507 def getsourcelines(self, obj):
504 lines, lineno = inspect.findsource(obj)
508 lines, lineno = inspect.findsource(obj)
505 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
509 if inspect.isframe(obj) and obj.f_globals is obj.f_locals:
506 # must be a module frame: do not try to cut a block out of it
510 # must be a module frame: do not try to cut a block out of it
507 return lines, 1
511 return lines, 1
508 elif inspect.ismodule(obj):
512 elif inspect.ismodule(obj):
509 return lines, 1
513 return lines, 1
510 return inspect.getblock(lines[lineno:]), lineno+1
514 return inspect.getblock(lines[lineno:]), lineno+1
511
515
512 def do_longlist(self, arg):
516 def do_longlist(self, arg):
513 self.lastcmd = 'longlist'
517 self.lastcmd = 'longlist'
514 try:
518 try:
515 lines, lineno = self.getsourcelines(self.curframe)
519 lines, lineno = self.getsourcelines(self.curframe)
516 except OSError as err:
520 except OSError as err:
517 self.error(err)
521 self.error(err)
518 return
522 return
519 last = lineno + len(lines)
523 last = lineno + len(lines)
520 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
524 self.print_list_lines(self.curframe.f_code.co_filename, lineno, last)
521 do_ll = do_longlist
525 do_ll = do_longlist
522
526
523 def do_pdef(self, arg):
527 def do_pdef(self, arg):
524 """Print the call signature for any callable object.
528 """Print the call signature for any callable object.
525
529
526 The debugger interface to %pdef"""
530 The debugger interface to %pdef"""
527 namespaces = [('Locals', self.curframe.f_locals),
531 namespaces = [('Locals', self.curframe.f_locals),
528 ('Globals', self.curframe.f_globals)]
532 ('Globals', self.curframe.f_globals)]
529 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
533 self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
530
534
531 def do_pdoc(self, arg):
535 def do_pdoc(self, arg):
532 """Print the docstring for an object.
536 """Print the docstring for an object.
533
537
534 The debugger interface to %pdoc."""
538 The debugger interface to %pdoc."""
535 namespaces = [('Locals', self.curframe.f_locals),
539 namespaces = [('Locals', self.curframe.f_locals),
536 ('Globals', self.curframe.f_globals)]
540 ('Globals', self.curframe.f_globals)]
537 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
541 self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces)
538
542
539 def do_pfile(self, arg):
543 def do_pfile(self, arg):
540 """Print (or run through pager) the file where an object is defined.
544 """Print (or run through pager) the file where an object is defined.
541
545
542 The debugger interface to %pfile.
546 The debugger interface to %pfile.
543 """
547 """
544 namespaces = [('Locals', self.curframe.f_locals),
548 namespaces = [('Locals', self.curframe.f_locals),
545 ('Globals', self.curframe.f_globals)]
549 ('Globals', self.curframe.f_globals)]
546 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
550 self.shell.find_line_magic('pfile')(arg, namespaces=namespaces)
547
551
548 def do_pinfo(self, arg):
552 def do_pinfo(self, arg):
549 """Provide detailed information about an object.
553 """Provide detailed information about an object.
550
554
551 The debugger interface to %pinfo, i.e., obj?."""
555 The debugger interface to %pinfo, i.e., obj?."""
552 namespaces = [('Locals', self.curframe.f_locals),
556 namespaces = [('Locals', self.curframe.f_locals),
553 ('Globals', self.curframe.f_globals)]
557 ('Globals', self.curframe.f_globals)]
554 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
558 self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces)
555
559
556 def do_pinfo2(self, arg):
560 def do_pinfo2(self, arg):
557 """Provide extra detailed information about an object.
561 """Provide extra detailed information about an object.
558
562
559 The debugger interface to %pinfo2, i.e., obj??."""
563 The debugger interface to %pinfo2, i.e., obj??."""
560 namespaces = [('Locals', self.curframe.f_locals),
564 namespaces = [('Locals', self.curframe.f_locals),
561 ('Globals', self.curframe.f_globals)]
565 ('Globals', self.curframe.f_globals)]
562 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
566 self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces)
563
567
564 def do_psource(self, arg):
568 def do_psource(self, arg):
565 """Print (or run through pager) the source code for an object."""
569 """Print (or run through pager) the source code for an object."""
566 namespaces = [('Locals', self.curframe.f_locals),
570 namespaces = [('Locals', self.curframe.f_locals),
567 ('Globals', self.curframe.f_globals)]
571 ('Globals', self.curframe.f_globals)]
568 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
572 self.shell.find_line_magic('psource')(arg, namespaces=namespaces)
569
573
570 if sys.version_info > (3, ):
574 if sys.version_info > (3, ):
571 def do_where(self, arg):
575 def do_where(self, arg):
572 """w(here)
576 """w(here)
573 Print a stack trace, with the most recent frame at the bottom.
577 Print a stack trace, with the most recent frame at the bottom.
574 An arrow indicates the "current frame", which determines the
578 An arrow indicates the "current frame", which determines the
575 context of most commands. 'bt' is an alias for this command.
579 context of most commands. 'bt' is an alias for this command.
576
580
577 Take a number as argument as an (optional) number of context line to
581 Take a number as argument as an (optional) number of context line to
578 print"""
582 print"""
579 if arg:
583 if arg:
580 context = int(arg)
584 context = int(arg)
581 self.print_stack_trace(context)
585 self.print_stack_trace(context)
582 else:
586 else:
583 self.print_stack_trace()
587 self.print_stack_trace()
584
588
585 do_w = do_where
589 do_w = do_where
@@ -1,147 +1,176 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Color schemes for exception handling code in IPython.
3 Color schemes for exception handling code in IPython.
4 """
4 """
5
5
6 import warnings
6 import warnings
7
7
8 #*****************************************************************************
8 #*****************************************************************************
9 # Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>
9 # Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>
10 #
10 #
11 # Distributed under the terms of the BSD License. The full license is in
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
12 # the file COPYING, distributed as part of this software.
13 #*****************************************************************************
13 #*****************************************************************************
14
14
15 from IPython.utils.coloransi import ColorSchemeTable, TermColors, ColorScheme
15 from IPython.utils.coloransi import ColorSchemeTable, TermColors, ColorScheme
16
16
17 def exception_colors():
17 def exception_colors():
18 """Return a color table with fields for exception reporting.
18 """Return a color table with fields for exception reporting.
19
19
20 The table is an instance of ColorSchemeTable with schemes added for
20 The table is an instance of ColorSchemeTable with schemes added for
21 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled
21 'Neutral', 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled
22 in.
22 in.
23
23
24 Examples:
24 Examples:
25
25
26 >>> ec = exception_colors()
26 >>> ec = exception_colors()
27 >>> ec.active_scheme_name
27 >>> ec.active_scheme_name
28 ''
28 ''
29 >>> print(ec.active_colors)
29 >>> print(ec.active_colors)
30 None
30 None
31
31
32 Now we activate a color scheme:
32 Now we activate a color scheme:
33 >>> ec.set_active_scheme('NoColor')
33 >>> ec.set_active_scheme('NoColor')
34 >>> ec.active_scheme_name
34 >>> ec.active_scheme_name
35 'NoColor'
35 'NoColor'
36 >>> sorted(ec.active_colors.keys())
36 >>> sorted(ec.active_colors.keys())
37 ['Normal', 'caret', 'em', 'excName', 'filename', 'filenameEm', 'line',
37 ['Normal', 'caret', 'em', 'excName', 'filename', 'filenameEm', 'line',
38 'lineno', 'linenoEm', 'name', 'nameEm', 'normalEm', 'topline', 'vName',
38 'lineno', 'linenoEm', 'name', 'nameEm', 'normalEm', 'topline', 'vName',
39 'val', 'valEm']
39 'val', 'valEm']
40 """
40 """
41
41
42 ex_colors = ColorSchemeTable()
42 ex_colors = ColorSchemeTable()
43
43
44 # Populate it with color schemes
44 # Populate it with color schemes
45 C = TermColors # shorthand and local lookup
45 C = TermColors # shorthand and local lookup
46 ex_colors.add_scheme(ColorScheme(
46 ex_colors.add_scheme(ColorScheme(
47 'NoColor',
47 'NoColor',
48 # The color to be used for the top line
48 # The color to be used for the top line
49 topline = C.NoColor,
49 topline = C.NoColor,
50
50
51 # The colors to be used in the traceback
51 # The colors to be used in the traceback
52 filename = C.NoColor,
52 filename = C.NoColor,
53 lineno = C.NoColor,
53 lineno = C.NoColor,
54 name = C.NoColor,
54 name = C.NoColor,
55 vName = C.NoColor,
55 vName = C.NoColor,
56 val = C.NoColor,
56 val = C.NoColor,
57 em = C.NoColor,
57 em = C.NoColor,
58
58
59 # Emphasized colors for the last frame of the traceback
59 # Emphasized colors for the last frame of the traceback
60 normalEm = C.NoColor,
60 normalEm = C.NoColor,
61 filenameEm = C.NoColor,
61 filenameEm = C.NoColor,
62 linenoEm = C.NoColor,
62 linenoEm = C.NoColor,
63 nameEm = C.NoColor,
63 nameEm = C.NoColor,
64 valEm = C.NoColor,
64 valEm = C.NoColor,
65
65
66 # Colors for printing the exception
66 # Colors for printing the exception
67 excName = C.NoColor,
67 excName = C.NoColor,
68 line = C.NoColor,
68 line = C.NoColor,
69 caret = C.NoColor,
69 caret = C.NoColor,
70 Normal = C.NoColor
70 Normal = C.NoColor
71 ))
71 ))
72
72
73 # make some schemes as instances so we can copy them for modification easily
73 # make some schemes as instances so we can copy them for modification easily
74 ex_colors.add_scheme(ColorScheme(
74 ex_colors.add_scheme(ColorScheme(
75 'Linux',
75 'Linux',
76 # The color to be used for the top line
76 # The color to be used for the top line
77 topline = C.LightRed,
77 topline = C.LightRed,
78
78
79 # The colors to be used in the traceback
79 # The colors to be used in the traceback
80 filename = C.Green,
80 filename = C.Green,
81 lineno = C.Green,
81 lineno = C.Green,
82 name = C.Purple,
82 name = C.Purple,
83 vName = C.Cyan,
83 vName = C.Cyan,
84 val = C.Green,
84 val = C.Green,
85 em = C.LightCyan,
85 em = C.LightCyan,
86
86
87 # Emphasized colors for the last frame of the traceback
87 # Emphasized colors for the last frame of the traceback
88 normalEm = C.LightCyan,
88 normalEm = C.LightCyan,
89 filenameEm = C.LightGreen,
89 filenameEm = C.LightGreen,
90 linenoEm = C.LightGreen,
90 linenoEm = C.LightGreen,
91 nameEm = C.LightPurple,
91 nameEm = C.LightPurple,
92 valEm = C.LightBlue,
92 valEm = C.LightBlue,
93
93
94 # Colors for printing the exception
94 # Colors for printing the exception
95 excName = C.LightRed,
95 excName = C.LightRed,
96 line = C.Yellow,
96 line = C.Yellow,
97 caret = C.White,
97 caret = C.White,
98 Normal = C.Normal
98 Normal = C.Normal
99 ))
99 ))
100
100
101 # For light backgrounds, swap dark/light colors
101 # For light backgrounds, swap dark/light colors
102 ex_colors.add_scheme(ColorScheme(
102 ex_colors.add_scheme(ColorScheme(
103 'LightBG',
103 'LightBG',
104 # The color to be used for the top line
104 # The color to be used for the top line
105 topline = C.Red,
105 topline = C.Red,
106
106
107 # The colors to be used in the traceback
107 # The colors to be used in the traceback
108 filename = C.LightGreen,
108 filename = C.LightGreen,
109 lineno = C.LightGreen,
109 lineno = C.LightGreen,
110 name = C.LightPurple,
110 name = C.LightPurple,
111 vName = C.Cyan,
111 vName = C.Cyan,
112 val = C.LightGreen,
112 val = C.LightGreen,
113 em = C.Cyan,
113 em = C.Cyan,
114
114
115 # Emphasized colors for the last frame of the traceback
115 # Emphasized colors for the last frame of the traceback
116 normalEm = C.Cyan,
116 normalEm = C.Cyan,
117 filenameEm = C.Green,
117 filenameEm = C.Green,
118 linenoEm = C.Green,
118 linenoEm = C.Green,
119 nameEm = C.Purple,
119 nameEm = C.Purple,
120 valEm = C.Blue,
120 valEm = C.Blue,
121
121
122 # Colors for printing the exception
122 # Colors for printing the exception
123 excName = C.Red,
123 excName = C.Red,
124 #line = C.Brown, # brown often is displayed as yellow
124 #line = C.Brown, # brown often is displayed as yellow
125 line = C.Red,
125 line = C.Red,
126 caret = C.Normal,
126 caret = C.Normal,
127 Normal = C.Normal,
127 Normal = C.Normal,
128 ))
128 ))
129
129
130 ex_colors.add_scheme(ColorScheme(
131 'Neutral',
132 # The color to be used for the top line
133 topline = C.Red,
134
135 # The colors to be used in the traceback
136 filename = C.LightGreen,
137 lineno = C.LightGreen,
138 name = C.LightPurple,
139 vName = C.Cyan,
140 val = C.LightGreen,
141 em = C.Cyan,
142
143 # Emphasized colors for the last frame of the traceback
144 normalEm = C.Cyan,
145 filenameEm = C.Green,
146 linenoEm = C.Green,
147 nameEm = C.Purple,
148 valEm = C.Blue,
149
150 # Colors for printing the exception
151 excName = C.Red,
152 #line = C.Brown, # brown often is displayed as yellow
153 line = C.Red,
154 caret = C.Normal,
155 Normal = C.Normal,
156 ))
157
158
130 return ex_colors
159 return ex_colors
131
160
132 class Deprec(object):
161 class Deprec(object):
133
162
134 def __init__(self, wrapped_obj):
163 def __init__(self, wrapped_obj):
135 self.wrapped=wrapped_obj
164 self.wrapped=wrapped_obj
136
165
137 def __getattr__(self, name):
166 def __getattr__(self, name):
138 val = getattr(self.wrapped, name)
167 val = getattr(self.wrapped, name)
139 warnings.warn("Using ExceptionColors global is deprecated and will be removed in IPython 6.0", DeprecationWarning)
168 warnings.warn("Using ExceptionColors global is deprecated and will be removed in IPython 6.0", DeprecationWarning)
140 # using getattr after warnings break ipydoctest in weird way for 3.5
169 # using getattr after warnings break ipydoctest in weird way for 3.5
141 return val
170 return val
142
171
143 # For backwards compatibility, keep around a single global object. Note that
172 # For backwards compatibility, keep around a single global object. Note that
144 # this should NOT be used, the factory function should be used instead, since
173 # this should NOT be used, the factory function should be used instead, since
145 # these objects are stateful and it's very easy to get strange bugs if any code
174 # these objects are stateful and it's very easy to get strange bugs if any code
146 # modifies the module-level object's state.
175 # modifies the module-level object's state.
147 ExceptionColors = Deprec(exception_colors())
176 ExceptionColors = Deprec(exception_colors())
@@ -1,3293 +1,3291 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.contexts import NoOpContext
65 from IPython.utils.contexts import NoOpContext
66 from IPython.utils.decorators import undoc
66 from IPython.utils.decorators import undoc
67 from IPython.utils.io import ask_yes_no
67 from IPython.utils.io import ask_yes_no
68 from IPython.utils.ipstruct import Struct
68 from IPython.utils.ipstruct import Struct
69 from IPython.paths import get_ipython_dir
69 from IPython.paths import get_ipython_dir
70 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
70 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
71 from IPython.utils.process import system, getoutput
71 from IPython.utils.process import system, getoutput
72 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
72 from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
73 with_metaclass, iteritems)
73 with_metaclass, iteritems)
74 from IPython.utils.strdispatch import StrDispatch
74 from IPython.utils.strdispatch import StrDispatch
75 from IPython.utils.syspathcontext import prepended_to_syspath
75 from IPython.utils.syspathcontext import prepended_to_syspath
76 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
76 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
77 from IPython.utils.tempdir import TemporaryDirectory
77 from IPython.utils.tempdir import TemporaryDirectory
78 from traitlets import (
78 from traitlets import (
79 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
79 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
80 observe, default,
80 observe, default,
81 )
81 )
82 from warnings import warn
82 from warnings import warn
83 from logging import error
83 from logging import error
84 import IPython.core.hooks
84 import IPython.core.hooks
85
85
86 try:
86 try:
87 import docrepr.sphinxify as sphx
87 import docrepr.sphinxify as sphx
88
88
89 def sphinxify(doc):
89 def sphinxify(doc):
90 with TemporaryDirectory() as dirname:
90 with TemporaryDirectory() as dirname:
91 return {
91 return {
92 'text/html': sphx.sphinxify(doc, dirname),
92 'text/html': sphx.sphinxify(doc, dirname),
93 'text/plain': doc
93 'text/plain': doc
94 }
94 }
95 except ImportError:
95 except ImportError:
96 sphinxify = None
96 sphinxify = None
97
97
98
98
99 class ProvisionalWarning(DeprecationWarning):
99 class ProvisionalWarning(DeprecationWarning):
100 """
100 """
101 Warning class for unstable features
101 Warning class for unstable features
102 """
102 """
103 pass
103 pass
104
104
105 #-----------------------------------------------------------------------------
105 #-----------------------------------------------------------------------------
106 # Globals
106 # Globals
107 #-----------------------------------------------------------------------------
107 #-----------------------------------------------------------------------------
108
108
109 # compiled regexps for autoindent management
109 # compiled regexps for autoindent management
110 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
110 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
111
111
112 #-----------------------------------------------------------------------------
112 #-----------------------------------------------------------------------------
113 # Utilities
113 # Utilities
114 #-----------------------------------------------------------------------------
114 #-----------------------------------------------------------------------------
115
115
116 @undoc
116 @undoc
117 def softspace(file, newvalue):
117 def softspace(file, newvalue):
118 """Copied from code.py, to remove the dependency"""
118 """Copied from code.py, to remove the dependency"""
119
119
120 oldvalue = 0
120 oldvalue = 0
121 try:
121 try:
122 oldvalue = file.softspace
122 oldvalue = file.softspace
123 except AttributeError:
123 except AttributeError:
124 pass
124 pass
125 try:
125 try:
126 file.softspace = newvalue
126 file.softspace = newvalue
127 except (AttributeError, TypeError):
127 except (AttributeError, TypeError):
128 # "attribute-less object" or "read-only attributes"
128 # "attribute-less object" or "read-only attributes"
129 pass
129 pass
130 return oldvalue
130 return oldvalue
131
131
132 @undoc
132 @undoc
133 def no_op(*a, **kw): pass
133 def no_op(*a, **kw): pass
134
134
135
135
136 class SpaceInInput(Exception): pass
136 class SpaceInInput(Exception): pass
137
137
138
138
139 def get_default_colors():
139 def get_default_colors():
140 if sys.platform=='darwin':
140 "DEPRECATED"
141 return "LightBG"
141 warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
142 elif os.name=='nt':
142 DeprecationWarning, stacklevel=2)
143 return 'Linux'
143 return 'Neutral'
144 else:
145 return 'Linux'
146
144
147
145
148 class SeparateUnicode(Unicode):
146 class SeparateUnicode(Unicode):
149 r"""A Unicode subclass to validate separate_in, separate_out, etc.
147 r"""A Unicode subclass to validate separate_in, separate_out, etc.
150
148
151 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
149 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
152 """
150 """
153
151
154 def validate(self, obj, value):
152 def validate(self, obj, value):
155 if value == '0': value = ''
153 if value == '0': value = ''
156 value = value.replace('\\n','\n')
154 value = value.replace('\\n','\n')
157 return super(SeparateUnicode, self).validate(obj, value)
155 return super(SeparateUnicode, self).validate(obj, value)
158
156
159
157
160 @undoc
158 @undoc
161 class DummyMod(object):
159 class DummyMod(object):
162 """A dummy module used for IPython's interactive module when
160 """A dummy module used for IPython's interactive module when
163 a namespace must be assigned to the module's __dict__."""
161 a namespace must be assigned to the module's __dict__."""
164 pass
162 pass
165
163
166
164
167 class ExecutionResult(object):
165 class ExecutionResult(object):
168 """The result of a call to :meth:`InteractiveShell.run_cell`
166 """The result of a call to :meth:`InteractiveShell.run_cell`
169
167
170 Stores information about what took place.
168 Stores information about what took place.
171 """
169 """
172 execution_count = None
170 execution_count = None
173 error_before_exec = None
171 error_before_exec = None
174 error_in_exec = None
172 error_in_exec = None
175 result = None
173 result = None
176
174
177 @property
175 @property
178 def success(self):
176 def success(self):
179 return (self.error_before_exec is None) and (self.error_in_exec is None)
177 return (self.error_before_exec is None) and (self.error_in_exec is None)
180
178
181 def raise_error(self):
179 def raise_error(self):
182 """Reraises error if `success` is `False`, otherwise does nothing"""
180 """Reraises error if `success` is `False`, otherwise does nothing"""
183 if self.error_before_exec is not None:
181 if self.error_before_exec is not None:
184 raise self.error_before_exec
182 raise self.error_before_exec
185 if self.error_in_exec is not None:
183 if self.error_in_exec is not None:
186 raise self.error_in_exec
184 raise self.error_in_exec
187
185
188 def __repr__(self):
186 def __repr__(self):
189 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
187 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
190 (self.__class__.__qualname__, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
188 (self.__class__.__qualname__, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
191
189
192
190
193 class InteractiveShell(SingletonConfigurable):
191 class InteractiveShell(SingletonConfigurable):
194 """An enhanced, interactive shell for Python."""
192 """An enhanced, interactive shell for Python."""
195
193
196 _instance = None
194 _instance = None
197
195
198 ast_transformers = List([], help=
196 ast_transformers = List([], help=
199 """
197 """
200 A list of ast.NodeTransformer subclass instances, which will be applied
198 A list of ast.NodeTransformer subclass instances, which will be applied
201 to user input before code is run.
199 to user input before code is run.
202 """
200 """
203 ).tag(config=True)
201 ).tag(config=True)
204
202
205 autocall = Enum((0,1,2), default_value=0, help=
203 autocall = Enum((0,1,2), default_value=0, help=
206 """
204 """
207 Make IPython automatically call any callable object even if you didn't
205 Make IPython automatically call any callable object even if you didn't
208 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
206 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
209 automatically. The value can be '0' to disable the feature, '1' for
207 automatically. The value can be '0' to disable the feature, '1' for
210 'smart' autocall, where it is not applied if there are no more
208 'smart' autocall, where it is not applied if there are no more
211 arguments on the line, and '2' for 'full' autocall, where all callable
209 arguments on the line, and '2' for 'full' autocall, where all callable
212 objects are automatically called (even if no arguments are present).
210 objects are automatically called (even if no arguments are present).
213 """
211 """
214 ).tag(config=True)
212 ).tag(config=True)
215 # TODO: remove all autoindent logic and put into frontends.
213 # TODO: remove all autoindent logic and put into frontends.
216 # We can't do this yet because even runlines uses the autoindent.
214 # We can't do this yet because even runlines uses the autoindent.
217 autoindent = Bool(True, help=
215 autoindent = Bool(True, help=
218 """
216 """
219 Autoindent IPython code entered interactively.
217 Autoindent IPython code entered interactively.
220 """
218 """
221 ).tag(config=True)
219 ).tag(config=True)
222
220
223 automagic = Bool(True, help=
221 automagic = Bool(True, help=
224 """
222 """
225 Enable magic commands to be called without the leading %.
223 Enable magic commands to be called without the leading %.
226 """
224 """
227 ).tag(config=True)
225 ).tag(config=True)
228
226
229 banner1 = Unicode(default_banner,
227 banner1 = Unicode(default_banner,
230 help="""The part of the banner to be printed before the profile"""
228 help="""The part of the banner to be printed before the profile"""
231 ).tag(config=True)
229 ).tag(config=True)
232 banner2 = Unicode('',
230 banner2 = Unicode('',
233 help="""The part of the banner to be printed after the profile"""
231 help="""The part of the banner to be printed after the profile"""
234 ).tag(config=True)
232 ).tag(config=True)
235
233
236 cache_size = Integer(1000, help=
234 cache_size = Integer(1000, help=
237 """
235 """
238 Set the size of the output cache. The default is 1000, you can
236 Set the size of the output cache. The default is 1000, you can
239 change it permanently in your config file. Setting it to 0 completely
237 change it permanently in your config file. Setting it to 0 completely
240 disables the caching system, and the minimum value accepted is 20 (if
238 disables the caching system, and the minimum value accepted is 20 (if
241 you provide a value less than 20, it is reset to 0 and a warning is
239 you provide a value less than 20, it is reset to 0 and a warning is
242 issued). This limit is defined because otherwise you'll spend more
240 issued). This limit is defined because otherwise you'll spend more
243 time re-flushing a too small cache than working
241 time re-flushing a too small cache than working
244 """
242 """
245 ).tag(config=True)
243 ).tag(config=True)
246 color_info = Bool(True, help=
244 color_info = Bool(True, help=
247 """
245 """
248 Use colors for displaying information about objects. Because this
246 Use colors for displaying information about objects. Because this
249 information is passed through a pager (like 'less'), and some pagers
247 information is passed through a pager (like 'less'), and some pagers
250 get confused with color codes, this capability can be turned off.
248 get confused with color codes, this capability can be turned off.
251 """
249 """
252 ).tag(config=True)
250 ).tag(config=True)
253 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
251 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
254 default_value=get_default_colors(),
252 default_value='Neutral',
255 help="Set the color scheme (NoColor, Linux, or LightBG)."
253 help="Set the color scheme (NoColor, Linux, or LightBG)."
256 ).tag(config=True)
254 ).tag(config=True)
257 colors_force = Bool(False, help=
255 colors_force = Bool(False, help=
258 """
256 """
259 Force use of ANSI color codes, regardless of OS and readline
257 Force use of ANSI color codes, regardless of OS and readline
260 availability.
258 availability.
261 """
259 """
262 # FIXME: This is essentially a hack to allow ZMQShell to show colors
260 # FIXME: This is essentially a hack to allow ZMQShell to show colors
263 # without readline on Win32. When the ZMQ formatting system is
261 # without readline on Win32. When the ZMQ formatting system is
264 # refactored, this should be removed.
262 # refactored, this should be removed.
265 )
263 )
266 debug = Bool(False).tag(config=True)
264 debug = Bool(False).tag(config=True)
267 deep_reload = Bool(False, help=
265 deep_reload = Bool(False, help=
268 """
266 """
269 **Deprecated**
267 **Deprecated**
270
268
271 Will be removed in IPython 6.0
269 Will be removed in IPython 6.0
272
270
273 Enable deep (recursive) reloading by default. IPython can use the
271 Enable deep (recursive) reloading by default. IPython can use the
274 deep_reload module which reloads changes in modules recursively (it
272 deep_reload module which reloads changes in modules recursively (it
275 replaces the reload() function, so you don't need to change anything to
273 replaces the reload() function, so you don't need to change anything to
276 use it). `deep_reload` forces a full reload of modules whose code may
274 use it). `deep_reload` forces a full reload of modules whose code may
277 have changed, which the default reload() function does not. When
275 have changed, which the default reload() function does not. When
278 deep_reload is off, IPython will use the normal reload(), but
276 deep_reload is off, IPython will use the normal reload(), but
279 deep_reload will still be available as dreload().
277 deep_reload will still be available as dreload().
280 """
278 """
281 ).tag(config=True)
279 ).tag(config=True)
282 disable_failing_post_execute = Bool(False,
280 disable_failing_post_execute = Bool(False,
283 help="Don't call post-execute functions that have failed in the past."
281 help="Don't call post-execute functions that have failed in the past."
284 ).tag(config=True)
282 ).tag(config=True)
285 display_formatter = Instance(DisplayFormatter, allow_none=True)
283 display_formatter = Instance(DisplayFormatter, allow_none=True)
286 displayhook_class = Type(DisplayHook)
284 displayhook_class = Type(DisplayHook)
287 display_pub_class = Type(DisplayPublisher)
285 display_pub_class = Type(DisplayPublisher)
288
286
289 sphinxify_docstring = Bool(False, help=
287 sphinxify_docstring = Bool(False, help=
290 """
288 """
291 Enables rich html representation of docstrings. (This requires the
289 Enables rich html representation of docstrings. (This requires the
292 docrepr module).
290 docrepr module).
293 """).tag(config=True)
291 """).tag(config=True)
294
292
295 @observe("sphinxify_docstring")
293 @observe("sphinxify_docstring")
296 def _sphinxify_docstring_changed(self, change):
294 def _sphinxify_docstring_changed(self, change):
297 if change['new']:
295 if change['new']:
298 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
296 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
299
297
300 enable_html_pager = Bool(False, help=
298 enable_html_pager = Bool(False, help=
301 """
299 """
302 (Provisional API) enables html representation in mime bundles sent
300 (Provisional API) enables html representation in mime bundles sent
303 to pagers.
301 to pagers.
304 """).tag(config=True)
302 """).tag(config=True)
305
303
306 @observe("enable_html_pager")
304 @observe("enable_html_pager")
307 def _enable_html_pager_changed(self, change):
305 def _enable_html_pager_changed(self, change):
308 if change['new']:
306 if change['new']:
309 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
307 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
310
308
311 data_pub_class = None
309 data_pub_class = None
312
310
313 exit_now = Bool(False)
311 exit_now = Bool(False)
314 exiter = Instance(ExitAutocall)
312 exiter = Instance(ExitAutocall)
315 @default('exiter')
313 @default('exiter')
316 def _exiter_default(self):
314 def _exiter_default(self):
317 return ExitAutocall(self)
315 return ExitAutocall(self)
318 # Monotonically increasing execution counter
316 # Monotonically increasing execution counter
319 execution_count = Integer(1)
317 execution_count = Integer(1)
320 filename = Unicode("<ipython console>")
318 filename = Unicode("<ipython console>")
321 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
319 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
322
320
323 # Input splitter, to transform input line by line and detect when a block
321 # Input splitter, to transform input line by line and detect when a block
324 # is ready to be executed.
322 # is ready to be executed.
325 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
323 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
326 (), {'line_input_checker': True})
324 (), {'line_input_checker': True})
327
325
328 # This InputSplitter instance is used to transform completed cells before
326 # This InputSplitter instance is used to transform completed cells before
329 # running them. It allows cell magics to contain blank lines.
327 # running them. It allows cell magics to contain blank lines.
330 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
328 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
331 (), {'line_input_checker': False})
329 (), {'line_input_checker': False})
332
330
333 logstart = Bool(False, help=
331 logstart = Bool(False, help=
334 """
332 """
335 Start logging to the default log file in overwrite mode.
333 Start logging to the default log file in overwrite mode.
336 Use `logappend` to specify a log file to **append** logs to.
334 Use `logappend` to specify a log file to **append** logs to.
337 """
335 """
338 ).tag(config=True)
336 ).tag(config=True)
339 logfile = Unicode('', help=
337 logfile = Unicode('', help=
340 """
338 """
341 The name of the logfile to use.
339 The name of the logfile to use.
342 """
340 """
343 ).tag(config=True)
341 ).tag(config=True)
344 logappend = Unicode('', help=
342 logappend = Unicode('', help=
345 """
343 """
346 Start logging to the given file in append mode.
344 Start logging to the given file in append mode.
347 Use `logfile` to specify a log file to **overwrite** logs to.
345 Use `logfile` to specify a log file to **overwrite** logs to.
348 """
346 """
349 ).tag(config=True)
347 ).tag(config=True)
350 object_info_string_level = Enum((0,1,2), default_value=0,
348 object_info_string_level = Enum((0,1,2), default_value=0,
351 ).tag(config=True)
349 ).tag(config=True)
352 pdb = Bool(False, help=
350 pdb = Bool(False, help=
353 """
351 """
354 Automatically call the pdb debugger after every exception.
352 Automatically call the pdb debugger after every exception.
355 """
353 """
356 ).tag(config=True)
354 ).tag(config=True)
357 multiline_history = Bool(sys.platform != 'win32',
355 multiline_history = Bool(sys.platform != 'win32',
358 help="Save multi-line entries as one entry in readline history"
356 help="Save multi-line entries as one entry in readline history"
359 ).tag(config=True)
357 ).tag(config=True)
360 display_page = Bool(False,
358 display_page = Bool(False,
361 help="""If True, anything that would be passed to the pager
359 help="""If True, anything that would be passed to the pager
362 will be displayed as regular output instead."""
360 will be displayed as regular output instead."""
363 ).tag(config=True)
361 ).tag(config=True)
364
362
365 # deprecated prompt traits:
363 # deprecated prompt traits:
366
364
367 prompt_in1 = Unicode('In [\\#]: ',
365 prompt_in1 = Unicode('In [\\#]: ',
368 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
366 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
369 ).tag(config=True)
367 ).tag(config=True)
370 prompt_in2 = Unicode(' .\\D.: ',
368 prompt_in2 = Unicode(' .\\D.: ',
371 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
369 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
372 ).tag(config=True)
370 ).tag(config=True)
373 prompt_out = Unicode('Out[\\#]: ',
371 prompt_out = Unicode('Out[\\#]: ',
374 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
372 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
375 ).tag(config=True)
373 ).tag(config=True)
376 prompts_pad_left = Bool(True,
374 prompts_pad_left = Bool(True,
377 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
375 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
378 ).tag(config=True)
376 ).tag(config=True)
379
377
380 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
378 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
381 def _prompt_trait_changed(self, change):
379 def _prompt_trait_changed(self, change):
382 name = change['name']
380 name = change['name']
383 warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format(
381 warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format(
384 name=name)
382 name=name)
385 )
383 )
386 # protect against weird cases where self.config may not exist:
384 # protect against weird cases where self.config may not exist:
387
385
388 show_rewritten_input = Bool(True,
386 show_rewritten_input = Bool(True,
389 help="Show rewritten input, e.g. for autocall."
387 help="Show rewritten input, e.g. for autocall."
390 ).tag(config=True)
388 ).tag(config=True)
391
389
392 quiet = Bool(False).tag(config=True)
390 quiet = Bool(False).tag(config=True)
393
391
394 history_length = Integer(10000,
392 history_length = Integer(10000,
395 help='Total length of command history'
393 help='Total length of command history'
396 ).tag(config=True)
394 ).tag(config=True)
397
395
398 history_load_length = Integer(1000, help=
396 history_load_length = Integer(1000, help=
399 """
397 """
400 The number of saved history entries to be loaded
398 The number of saved history entries to be loaded
401 into the readline buffer at startup.
399 into the readline buffer at startup.
402 """
400 """
403 ).tag(config=True)
401 ).tag(config=True)
404
402
405 # The readline stuff will eventually be moved to the terminal subclass
403 # The readline stuff will eventually be moved to the terminal subclass
406 # but for now, we can't do that as readline is welded in everywhere.
404 # but for now, we can't do that as readline is welded in everywhere.
407 readline_use = Bool(True).tag(config=True)
405 readline_use = Bool(True).tag(config=True)
408 readline_remove_delims = Unicode('-/~').tag(config=True)
406 readline_remove_delims = Unicode('-/~').tag(config=True)
409 readline_delims = Unicode() # set by init_readline()
407 readline_delims = Unicode() # set by init_readline()
410 # don't use \M- bindings by default, because they
408 # don't use \M- bindings by default, because they
411 # conflict with 8-bit encodings. See gh-58,gh-88
409 # conflict with 8-bit encodings. See gh-58,gh-88
412 readline_parse_and_bind = List([
410 readline_parse_and_bind = List([
413 'tab: complete',
411 'tab: complete',
414 '"\C-l": clear-screen',
412 '"\C-l": clear-screen',
415 'set show-all-if-ambiguous on',
413 'set show-all-if-ambiguous on',
416 '"\C-o": tab-insert',
414 '"\C-o": tab-insert',
417 '"\C-r": reverse-search-history',
415 '"\C-r": reverse-search-history',
418 '"\C-s": forward-search-history',
416 '"\C-s": forward-search-history',
419 '"\C-p": history-search-backward',
417 '"\C-p": history-search-backward',
420 '"\C-n": history-search-forward',
418 '"\C-n": history-search-forward',
421 '"\e[A": history-search-backward',
419 '"\e[A": history-search-backward',
422 '"\e[B": history-search-forward',
420 '"\e[B": history-search-forward',
423 '"\C-k": kill-line',
421 '"\C-k": kill-line',
424 '"\C-u": unix-line-discard',
422 '"\C-u": unix-line-discard',
425 ]).tag(config=True)
423 ]).tag(config=True)
426
424
427 _custom_readline_config = False
425 _custom_readline_config = False
428
426
429 @observe('readline_parse_and_bind')
427 @observe('readline_parse_and_bind')
430 def _readline_parse_and_bind_changed(self, change):
428 def _readline_parse_and_bind_changed(self, change):
431 # notice that readline config is customized
429 # notice that readline config is customized
432 # indicates that it should have higher priority than inputrc
430 # indicates that it should have higher priority than inputrc
433 self._custom_readline_config = True
431 self._custom_readline_config = True
434
432
435 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
433 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
436 default_value='last_expr',
434 default_value='last_expr',
437 help="""
435 help="""
438 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
436 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
439 run interactively (displaying output from expressions)."""
437 run interactively (displaying output from expressions)."""
440 ).tag(config=True)
438 ).tag(config=True)
441
439
442 # TODO: this part of prompt management should be moved to the frontends.
440 # TODO: this part of prompt management should be moved to the frontends.
443 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
441 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
444 separate_in = SeparateUnicode('\n').tag(config=True)
442 separate_in = SeparateUnicode('\n').tag(config=True)
445 separate_out = SeparateUnicode('').tag(config=True)
443 separate_out = SeparateUnicode('').tag(config=True)
446 separate_out2 = SeparateUnicode('').tag(config=True)
444 separate_out2 = SeparateUnicode('').tag(config=True)
447 wildcards_case_sensitive = Bool(True).tag(config=True)
445 wildcards_case_sensitive = Bool(True).tag(config=True)
448 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
446 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
449 default_value='Context').tag(config=True)
447 default_value='Context').tag(config=True)
450
448
451 # Subcomponents of InteractiveShell
449 # Subcomponents of InteractiveShell
452 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
450 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
453 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
451 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
454 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
452 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
455 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
453 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
456 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
454 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
457 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
455 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
458 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
456 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
459 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
457 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
460
458
461 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
459 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
462 @property
460 @property
463 def profile(self):
461 def profile(self):
464 if self.profile_dir is not None:
462 if self.profile_dir is not None:
465 name = os.path.basename(self.profile_dir.location)
463 name = os.path.basename(self.profile_dir.location)
466 return name.replace('profile_','')
464 return name.replace('profile_','')
467
465
468
466
469 # Private interface
467 # Private interface
470 _post_execute = Dict()
468 _post_execute = Dict()
471
469
472 # Tracks any GUI loop loaded for pylab
470 # Tracks any GUI loop loaded for pylab
473 pylab_gui_select = None
471 pylab_gui_select = None
474
472
475 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
473 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
476
474
477 def __init__(self, ipython_dir=None, profile_dir=None,
475 def __init__(self, ipython_dir=None, profile_dir=None,
478 user_module=None, user_ns=None,
476 user_module=None, user_ns=None,
479 custom_exceptions=((), None), **kwargs):
477 custom_exceptions=((), None), **kwargs):
480
478
481 # This is where traits with a config_key argument are updated
479 # This is where traits with a config_key argument are updated
482 # from the values on config.
480 # from the values on config.
483 super(InteractiveShell, self).__init__(**kwargs)
481 super(InteractiveShell, self).__init__(**kwargs)
484 if 'PromptManager' in self.config:
482 if 'PromptManager' in self.config:
485 warn('As of IPython 5.0 `PromptManager` config will have no effect'
483 warn('As of IPython 5.0 `PromptManager` config will have no effect'
486 ' and has been replaced by TerminalInteractiveShell.prompts_class')
484 ' and has been replaced by TerminalInteractiveShell.prompts_class')
487 self.configurables = [self]
485 self.configurables = [self]
488
486
489 # These are relatively independent and stateless
487 # These are relatively independent and stateless
490 self.init_ipython_dir(ipython_dir)
488 self.init_ipython_dir(ipython_dir)
491 self.init_profile_dir(profile_dir)
489 self.init_profile_dir(profile_dir)
492 self.init_instance_attrs()
490 self.init_instance_attrs()
493 self.init_environment()
491 self.init_environment()
494
492
495 # Check if we're in a virtualenv, and set up sys.path.
493 # Check if we're in a virtualenv, and set up sys.path.
496 self.init_virtualenv()
494 self.init_virtualenv()
497
495
498 # Create namespaces (user_ns, user_global_ns, etc.)
496 # Create namespaces (user_ns, user_global_ns, etc.)
499 self.init_create_namespaces(user_module, user_ns)
497 self.init_create_namespaces(user_module, user_ns)
500 # This has to be done after init_create_namespaces because it uses
498 # This has to be done after init_create_namespaces because it uses
501 # something in self.user_ns, but before init_sys_modules, which
499 # something in self.user_ns, but before init_sys_modules, which
502 # is the first thing to modify sys.
500 # is the first thing to modify sys.
503 # TODO: When we override sys.stdout and sys.stderr before this class
501 # TODO: When we override sys.stdout and sys.stderr before this class
504 # is created, we are saving the overridden ones here. Not sure if this
502 # is created, we are saving the overridden ones here. Not sure if this
505 # is what we want to do.
503 # is what we want to do.
506 self.save_sys_module_state()
504 self.save_sys_module_state()
507 self.init_sys_modules()
505 self.init_sys_modules()
508
506
509 # While we're trying to have each part of the code directly access what
507 # While we're trying to have each part of the code directly access what
510 # it needs without keeping redundant references to objects, we have too
508 # it needs without keeping redundant references to objects, we have too
511 # much legacy code that expects ip.db to exist.
509 # much legacy code that expects ip.db to exist.
512 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
510 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
513
511
514 self.init_history()
512 self.init_history()
515 self.init_encoding()
513 self.init_encoding()
516 self.init_prefilter()
514 self.init_prefilter()
517
515
518 self.init_syntax_highlighting()
516 self.init_syntax_highlighting()
519 self.init_hooks()
517 self.init_hooks()
520 self.init_events()
518 self.init_events()
521 self.init_pushd_popd_magic()
519 self.init_pushd_popd_magic()
522 # self.init_traceback_handlers use to be here, but we moved it below
520 # self.init_traceback_handlers use to be here, but we moved it below
523 # because it and init_io have to come after init_readline.
521 # because it and init_io have to come after init_readline.
524 self.init_user_ns()
522 self.init_user_ns()
525 self.init_logger()
523 self.init_logger()
526 self.init_builtins()
524 self.init_builtins()
527
525
528 # The following was in post_config_initialization
526 # The following was in post_config_initialization
529 self.init_inspector()
527 self.init_inspector()
530 # init_readline() must come before init_io(), because init_io uses
528 # init_readline() must come before init_io(), because init_io uses
531 # readline related things.
529 # readline related things.
532 self.init_readline()
530 self.init_readline()
533 # We save this here in case user code replaces raw_input, but it needs
531 # We save this here in case user code replaces raw_input, but it needs
534 # to be after init_readline(), because PyPy's readline works by replacing
532 # to be after init_readline(), because PyPy's readline works by replacing
535 # raw_input.
533 # raw_input.
536 if py3compat.PY3:
534 if py3compat.PY3:
537 self.raw_input_original = input
535 self.raw_input_original = input
538 else:
536 else:
539 self.raw_input_original = raw_input
537 self.raw_input_original = raw_input
540 # init_completer must come after init_readline, because it needs to
538 # init_completer must come after init_readline, because it needs to
541 # know whether readline is present or not system-wide to configure the
539 # know whether readline is present or not system-wide to configure the
542 # completers, since the completion machinery can now operate
540 # completers, since the completion machinery can now operate
543 # independently of readline (e.g. over the network)
541 # independently of readline (e.g. over the network)
544 self.init_completer()
542 self.init_completer()
545 # TODO: init_io() needs to happen before init_traceback handlers
543 # TODO: init_io() needs to happen before init_traceback handlers
546 # because the traceback handlers hardcode the stdout/stderr streams.
544 # because the traceback handlers hardcode the stdout/stderr streams.
547 # This logic in in debugger.Pdb and should eventually be changed.
545 # This logic in in debugger.Pdb and should eventually be changed.
548 self.init_io()
546 self.init_io()
549 self.init_traceback_handlers(custom_exceptions)
547 self.init_traceback_handlers(custom_exceptions)
550 self.init_prompts()
548 self.init_prompts()
551 self.init_display_formatter()
549 self.init_display_formatter()
552 self.init_display_pub()
550 self.init_display_pub()
553 self.init_data_pub()
551 self.init_data_pub()
554 self.init_displayhook()
552 self.init_displayhook()
555 self.init_magics()
553 self.init_magics()
556 self.init_alias()
554 self.init_alias()
557 self.init_logstart()
555 self.init_logstart()
558 self.init_pdb()
556 self.init_pdb()
559 self.init_extension_manager()
557 self.init_extension_manager()
560 self.init_payload()
558 self.init_payload()
561 self.init_deprecation_warnings()
559 self.init_deprecation_warnings()
562 self.hooks.late_startup_hook()
560 self.hooks.late_startup_hook()
563 self.events.trigger('shell_initialized', self)
561 self.events.trigger('shell_initialized', self)
564 atexit.register(self.atexit_operations)
562 atexit.register(self.atexit_operations)
565
563
566 def get_ipython(self):
564 def get_ipython(self):
567 """Return the currently running IPython instance."""
565 """Return the currently running IPython instance."""
568 return self
566 return self
569
567
570 #-------------------------------------------------------------------------
568 #-------------------------------------------------------------------------
571 # Trait changed handlers
569 # Trait changed handlers
572 #-------------------------------------------------------------------------
570 #-------------------------------------------------------------------------
573 @observe('ipython_dir')
571 @observe('ipython_dir')
574 def _ipython_dir_changed(self, change):
572 def _ipython_dir_changed(self, change):
575 ensure_dir_exists(change['new'])
573 ensure_dir_exists(change['new'])
576
574
577 def set_autoindent(self,value=None):
575 def set_autoindent(self,value=None):
578 """Set the autoindent flag.
576 """Set the autoindent flag.
579
577
580 If called with no arguments, it acts as a toggle."""
578 If called with no arguments, it acts as a toggle."""
581 if value is None:
579 if value is None:
582 self.autoindent = not self.autoindent
580 self.autoindent = not self.autoindent
583 else:
581 else:
584 self.autoindent = value
582 self.autoindent = value
585
583
586 #-------------------------------------------------------------------------
584 #-------------------------------------------------------------------------
587 # init_* methods called by __init__
585 # init_* methods called by __init__
588 #-------------------------------------------------------------------------
586 #-------------------------------------------------------------------------
589
587
590 def init_ipython_dir(self, ipython_dir):
588 def init_ipython_dir(self, ipython_dir):
591 if ipython_dir is not None:
589 if ipython_dir is not None:
592 self.ipython_dir = ipython_dir
590 self.ipython_dir = ipython_dir
593 return
591 return
594
592
595 self.ipython_dir = get_ipython_dir()
593 self.ipython_dir = get_ipython_dir()
596
594
597 def init_profile_dir(self, profile_dir):
595 def init_profile_dir(self, profile_dir):
598 if profile_dir is not None:
596 if profile_dir is not None:
599 self.profile_dir = profile_dir
597 self.profile_dir = profile_dir
600 return
598 return
601 self.profile_dir =\
599 self.profile_dir =\
602 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
600 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
603
601
604 def init_instance_attrs(self):
602 def init_instance_attrs(self):
605 self.more = False
603 self.more = False
606
604
607 # command compiler
605 # command compiler
608 self.compile = CachingCompiler()
606 self.compile = CachingCompiler()
609
607
610 # Make an empty namespace, which extension writers can rely on both
608 # Make an empty namespace, which extension writers can rely on both
611 # existing and NEVER being used by ipython itself. This gives them a
609 # existing and NEVER being used by ipython itself. This gives them a
612 # convenient location for storing additional information and state
610 # convenient location for storing additional information and state
613 # their extensions may require, without fear of collisions with other
611 # their extensions may require, without fear of collisions with other
614 # ipython names that may develop later.
612 # ipython names that may develop later.
615 self.meta = Struct()
613 self.meta = Struct()
616
614
617 # Temporary files used for various purposes. Deleted at exit.
615 # Temporary files used for various purposes. Deleted at exit.
618 self.tempfiles = []
616 self.tempfiles = []
619 self.tempdirs = []
617 self.tempdirs = []
620
618
621 # Keep track of readline usage (later set by init_readline)
619 # Keep track of readline usage (later set by init_readline)
622 self.has_readline = False
620 self.has_readline = False
623
621
624 # keep track of where we started running (mainly for crash post-mortem)
622 # keep track of where we started running (mainly for crash post-mortem)
625 # This is not being used anywhere currently.
623 # This is not being used anywhere currently.
626 self.starting_dir = py3compat.getcwd()
624 self.starting_dir = py3compat.getcwd()
627
625
628 # Indentation management
626 # Indentation management
629 self.indent_current_nsp = 0
627 self.indent_current_nsp = 0
630
628
631 # Dict to track post-execution functions that have been registered
629 # Dict to track post-execution functions that have been registered
632 self._post_execute = {}
630 self._post_execute = {}
633
631
634 def init_environment(self):
632 def init_environment(self):
635 """Any changes we need to make to the user's environment."""
633 """Any changes we need to make to the user's environment."""
636 pass
634 pass
637
635
638 def init_encoding(self):
636 def init_encoding(self):
639 # Get system encoding at startup time. Certain terminals (like Emacs
637 # Get system encoding at startup time. Certain terminals (like Emacs
640 # under Win32 have it set to None, and we need to have a known valid
638 # under Win32 have it set to None, and we need to have a known valid
641 # encoding to use in the raw_input() method
639 # encoding to use in the raw_input() method
642 try:
640 try:
643 self.stdin_encoding = sys.stdin.encoding or 'ascii'
641 self.stdin_encoding = sys.stdin.encoding or 'ascii'
644 except AttributeError:
642 except AttributeError:
645 self.stdin_encoding = 'ascii'
643 self.stdin_encoding = 'ascii'
646
644
647 def init_syntax_highlighting(self):
645 def init_syntax_highlighting(self):
648 # Python source parser/formatter for syntax highlighting
646 # Python source parser/formatter for syntax highlighting
649 pyformat = PyColorize.Parser().format
647 pyformat = PyColorize.Parser().format
650 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
648 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
651
649
652 def init_pushd_popd_magic(self):
650 def init_pushd_popd_magic(self):
653 # for pushd/popd management
651 # for pushd/popd management
654 self.home_dir = get_home_dir()
652 self.home_dir = get_home_dir()
655
653
656 self.dir_stack = []
654 self.dir_stack = []
657
655
658 def init_logger(self):
656 def init_logger(self):
659 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
657 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
660 logmode='rotate')
658 logmode='rotate')
661
659
662 def init_logstart(self):
660 def init_logstart(self):
663 """Initialize logging in case it was requested at the command line.
661 """Initialize logging in case it was requested at the command line.
664 """
662 """
665 if self.logappend:
663 if self.logappend:
666 self.magic('logstart %s append' % self.logappend)
664 self.magic('logstart %s append' % self.logappend)
667 elif self.logfile:
665 elif self.logfile:
668 self.magic('logstart %s' % self.logfile)
666 self.magic('logstart %s' % self.logfile)
669 elif self.logstart:
667 elif self.logstart:
670 self.magic('logstart')
668 self.magic('logstart')
671
669
672 def init_deprecation_warnings(self):
670 def init_deprecation_warnings(self):
673 """
671 """
674 register default filter for deprecation warning.
672 register default filter for deprecation warning.
675
673
676 This will allow deprecation warning of function used interactively to show
674 This will allow deprecation warning of function used interactively to show
677 warning to users, and still hide deprecation warning from libraries import.
675 warning to users, and still hide deprecation warning from libraries import.
678 """
676 """
679 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
677 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
680
678
681 def init_builtins(self):
679 def init_builtins(self):
682 # A single, static flag that we set to True. Its presence indicates
680 # A single, static flag that we set to True. Its presence indicates
683 # that an IPython shell has been created, and we make no attempts at
681 # that an IPython shell has been created, and we make no attempts at
684 # removing on exit or representing the existence of more than one
682 # removing on exit or representing the existence of more than one
685 # IPython at a time.
683 # IPython at a time.
686 builtin_mod.__dict__['__IPYTHON__'] = True
684 builtin_mod.__dict__['__IPYTHON__'] = True
687
685
688 self.builtin_trap = BuiltinTrap(shell=self)
686 self.builtin_trap = BuiltinTrap(shell=self)
689
687
690 def init_inspector(self):
688 def init_inspector(self):
691 # Object inspector
689 # Object inspector
692 self.inspector = oinspect.Inspector(oinspect.InspectColors,
690 self.inspector = oinspect.Inspector(oinspect.InspectColors,
693 PyColorize.ANSICodeColors,
691 PyColorize.ANSICodeColors,
694 'NoColor',
692 'NoColor',
695 self.object_info_string_level)
693 self.object_info_string_level)
696
694
697 def init_io(self):
695 def init_io(self):
698 # This will just use sys.stdout and sys.stderr. If you want to
696 # This will just use sys.stdout and sys.stderr. If you want to
699 # override sys.stdout and sys.stderr themselves, you need to do that
697 # override sys.stdout and sys.stderr themselves, you need to do that
700 # *before* instantiating this class, because io holds onto
698 # *before* instantiating this class, because io holds onto
701 # references to the underlying streams.
699 # references to the underlying streams.
702 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
700 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
703 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
701 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
704 else:
702 else:
705 io.stdout = io.IOStream(sys.stdout)
703 io.stdout = io.IOStream(sys.stdout)
706 io.stderr = io.IOStream(sys.stderr)
704 io.stderr = io.IOStream(sys.stderr)
707
705
708 def init_prompts(self):
706 def init_prompts(self):
709 # Set system prompts, so that scripts can decide if they are running
707 # Set system prompts, so that scripts can decide if they are running
710 # interactively.
708 # interactively.
711 sys.ps1 = 'In : '
709 sys.ps1 = 'In : '
712 sys.ps2 = '...: '
710 sys.ps2 = '...: '
713 sys.ps3 = 'Out: '
711 sys.ps3 = 'Out: '
714
712
715 def init_display_formatter(self):
713 def init_display_formatter(self):
716 self.display_formatter = DisplayFormatter(parent=self)
714 self.display_formatter = DisplayFormatter(parent=self)
717 self.configurables.append(self.display_formatter)
715 self.configurables.append(self.display_formatter)
718
716
719 def init_display_pub(self):
717 def init_display_pub(self):
720 self.display_pub = self.display_pub_class(parent=self)
718 self.display_pub = self.display_pub_class(parent=self)
721 self.configurables.append(self.display_pub)
719 self.configurables.append(self.display_pub)
722
720
723 def init_data_pub(self):
721 def init_data_pub(self):
724 if not self.data_pub_class:
722 if not self.data_pub_class:
725 self.data_pub = None
723 self.data_pub = None
726 return
724 return
727 self.data_pub = self.data_pub_class(parent=self)
725 self.data_pub = self.data_pub_class(parent=self)
728 self.configurables.append(self.data_pub)
726 self.configurables.append(self.data_pub)
729
727
730 def init_displayhook(self):
728 def init_displayhook(self):
731 # Initialize displayhook, set in/out prompts and printing system
729 # Initialize displayhook, set in/out prompts and printing system
732 self.displayhook = self.displayhook_class(
730 self.displayhook = self.displayhook_class(
733 parent=self,
731 parent=self,
734 shell=self,
732 shell=self,
735 cache_size=self.cache_size,
733 cache_size=self.cache_size,
736 )
734 )
737 self.configurables.append(self.displayhook)
735 self.configurables.append(self.displayhook)
738 # This is a context manager that installs/revmoes the displayhook at
736 # This is a context manager that installs/revmoes the displayhook at
739 # the appropriate time.
737 # the appropriate time.
740 self.display_trap = DisplayTrap(hook=self.displayhook)
738 self.display_trap = DisplayTrap(hook=self.displayhook)
741
739
742 def init_virtualenv(self):
740 def init_virtualenv(self):
743 """Add a virtualenv to sys.path so the user can import modules from it.
741 """Add a virtualenv to sys.path so the user can import modules from it.
744 This isn't perfect: it doesn't use the Python interpreter with which the
742 This isn't perfect: it doesn't use the Python interpreter with which the
745 virtualenv was built, and it ignores the --no-site-packages option. A
743 virtualenv was built, and it ignores the --no-site-packages option. A
746 warning will appear suggesting the user installs IPython in the
744 warning will appear suggesting the user installs IPython in the
747 virtualenv, but for many cases, it probably works well enough.
745 virtualenv, but for many cases, it probably works well enough.
748
746
749 Adapted from code snippets online.
747 Adapted from code snippets online.
750
748
751 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
749 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
752 """
750 """
753 if 'VIRTUAL_ENV' not in os.environ:
751 if 'VIRTUAL_ENV' not in os.environ:
754 # Not in a virtualenv
752 # Not in a virtualenv
755 return
753 return
756
754
757 # venv detection:
755 # venv detection:
758 # stdlib venv may symlink sys.executable, so we can't use realpath.
756 # stdlib venv may symlink sys.executable, so we can't use realpath.
759 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
757 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
760 # So we just check every item in the symlink tree (generally <= 3)
758 # So we just check every item in the symlink tree (generally <= 3)
761 p = os.path.normcase(sys.executable)
759 p = os.path.normcase(sys.executable)
762 paths = [p]
760 paths = [p]
763 while os.path.islink(p):
761 while os.path.islink(p):
764 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
762 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
765 paths.append(p)
763 paths.append(p)
766 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
764 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
767 if any(p.startswith(p_venv) for p in paths):
765 if any(p.startswith(p_venv) for p in paths):
768 # Running properly in the virtualenv, don't need to do anything
766 # Running properly in the virtualenv, don't need to do anything
769 return
767 return
770
768
771 warn("Attempting to work in a virtualenv. If you encounter problems, please "
769 warn("Attempting to work in a virtualenv. If you encounter problems, please "
772 "install IPython inside the virtualenv.")
770 "install IPython inside the virtualenv.")
773 if sys.platform == "win32":
771 if sys.platform == "win32":
774 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
772 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
775 else:
773 else:
776 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
774 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
777 'python%d.%d' % sys.version_info[:2], 'site-packages')
775 'python%d.%d' % sys.version_info[:2], 'site-packages')
778
776
779 import site
777 import site
780 sys.path.insert(0, virtual_env)
778 sys.path.insert(0, virtual_env)
781 site.addsitedir(virtual_env)
779 site.addsitedir(virtual_env)
782
780
783 #-------------------------------------------------------------------------
781 #-------------------------------------------------------------------------
784 # Things related to injections into the sys module
782 # Things related to injections into the sys module
785 #-------------------------------------------------------------------------
783 #-------------------------------------------------------------------------
786
784
787 def save_sys_module_state(self):
785 def save_sys_module_state(self):
788 """Save the state of hooks in the sys module.
786 """Save the state of hooks in the sys module.
789
787
790 This has to be called after self.user_module is created.
788 This has to be called after self.user_module is created.
791 """
789 """
792 self._orig_sys_module_state = {'stdin': sys.stdin,
790 self._orig_sys_module_state = {'stdin': sys.stdin,
793 'stdout': sys.stdout,
791 'stdout': sys.stdout,
794 'stderr': sys.stderr,
792 'stderr': sys.stderr,
795 'excepthook': sys.excepthook}
793 'excepthook': sys.excepthook}
796 self._orig_sys_modules_main_name = self.user_module.__name__
794 self._orig_sys_modules_main_name = self.user_module.__name__
797 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
795 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
798
796
799 def restore_sys_module_state(self):
797 def restore_sys_module_state(self):
800 """Restore the state of the sys module."""
798 """Restore the state of the sys module."""
801 try:
799 try:
802 for k, v in iteritems(self._orig_sys_module_state):
800 for k, v in iteritems(self._orig_sys_module_state):
803 setattr(sys, k, v)
801 setattr(sys, k, v)
804 except AttributeError:
802 except AttributeError:
805 pass
803 pass
806 # Reset what what done in self.init_sys_modules
804 # Reset what what done in self.init_sys_modules
807 if self._orig_sys_modules_main_mod is not None:
805 if self._orig_sys_modules_main_mod is not None:
808 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
806 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
809
807
810 #-------------------------------------------------------------------------
808 #-------------------------------------------------------------------------
811 # Things related to the banner
809 # Things related to the banner
812 #-------------------------------------------------------------------------
810 #-------------------------------------------------------------------------
813
811
814 @property
812 @property
815 def banner(self):
813 def banner(self):
816 banner = self.banner1
814 banner = self.banner1
817 if self.profile and self.profile != 'default':
815 if self.profile and self.profile != 'default':
818 banner += '\nIPython profile: %s\n' % self.profile
816 banner += '\nIPython profile: %s\n' % self.profile
819 if self.banner2:
817 if self.banner2:
820 banner += '\n' + self.banner2
818 banner += '\n' + self.banner2
821 return banner
819 return banner
822
820
823 def show_banner(self, banner=None):
821 def show_banner(self, banner=None):
824 if banner is None:
822 if banner is None:
825 banner = self.banner
823 banner = self.banner
826 sys.stdout.write(banner)
824 sys.stdout.write(banner)
827
825
828 #-------------------------------------------------------------------------
826 #-------------------------------------------------------------------------
829 # Things related to hooks
827 # Things related to hooks
830 #-------------------------------------------------------------------------
828 #-------------------------------------------------------------------------
831
829
832 def init_hooks(self):
830 def init_hooks(self):
833 # hooks holds pointers used for user-side customizations
831 # hooks holds pointers used for user-side customizations
834 self.hooks = Struct()
832 self.hooks = Struct()
835
833
836 self.strdispatchers = {}
834 self.strdispatchers = {}
837
835
838 # Set all default hooks, defined in the IPython.hooks module.
836 # Set all default hooks, defined in the IPython.hooks module.
839 hooks = IPython.core.hooks
837 hooks = IPython.core.hooks
840 for hook_name in hooks.__all__:
838 for hook_name in hooks.__all__:
841 # default hooks have priority 100, i.e. low; user hooks should have
839 # default hooks have priority 100, i.e. low; user hooks should have
842 # 0-100 priority
840 # 0-100 priority
843 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
841 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
844
842
845 if self.display_page:
843 if self.display_page:
846 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
844 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
847
845
848 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
846 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
849 _warn_deprecated=True):
847 _warn_deprecated=True):
850 """set_hook(name,hook) -> sets an internal IPython hook.
848 """set_hook(name,hook) -> sets an internal IPython hook.
851
849
852 IPython exposes some of its internal API as user-modifiable hooks. By
850 IPython exposes some of its internal API as user-modifiable hooks. By
853 adding your function to one of these hooks, you can modify IPython's
851 adding your function to one of these hooks, you can modify IPython's
854 behavior to call at runtime your own routines."""
852 behavior to call at runtime your own routines."""
855
853
856 # At some point in the future, this should validate the hook before it
854 # At some point in the future, this should validate the hook before it
857 # accepts it. Probably at least check that the hook takes the number
855 # accepts it. Probably at least check that the hook takes the number
858 # of args it's supposed to.
856 # of args it's supposed to.
859
857
860 f = types.MethodType(hook,self)
858 f = types.MethodType(hook,self)
861
859
862 # check if the hook is for strdispatcher first
860 # check if the hook is for strdispatcher first
863 if str_key is not None:
861 if str_key is not None:
864 sdp = self.strdispatchers.get(name, StrDispatch())
862 sdp = self.strdispatchers.get(name, StrDispatch())
865 sdp.add_s(str_key, f, priority )
863 sdp.add_s(str_key, f, priority )
866 self.strdispatchers[name] = sdp
864 self.strdispatchers[name] = sdp
867 return
865 return
868 if re_key is not None:
866 if re_key is not None:
869 sdp = self.strdispatchers.get(name, StrDispatch())
867 sdp = self.strdispatchers.get(name, StrDispatch())
870 sdp.add_re(re.compile(re_key), f, priority )
868 sdp.add_re(re.compile(re_key), f, priority )
871 self.strdispatchers[name] = sdp
869 self.strdispatchers[name] = sdp
872 return
870 return
873
871
874 dp = getattr(self.hooks, name, None)
872 dp = getattr(self.hooks, name, None)
875 if name not in IPython.core.hooks.__all__:
873 if name not in IPython.core.hooks.__all__:
876 print("Warning! Hook '%s' is not one of %s" % \
874 print("Warning! Hook '%s' is not one of %s" % \
877 (name, IPython.core.hooks.__all__ ))
875 (name, IPython.core.hooks.__all__ ))
878
876
879 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
877 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
880 alternative = IPython.core.hooks.deprecated[name]
878 alternative = IPython.core.hooks.deprecated[name]
881 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
879 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative))
882
880
883 if not dp:
881 if not dp:
884 dp = IPython.core.hooks.CommandChainDispatcher()
882 dp = IPython.core.hooks.CommandChainDispatcher()
885
883
886 try:
884 try:
887 dp.add(f,priority)
885 dp.add(f,priority)
888 except AttributeError:
886 except AttributeError:
889 # it was not commandchain, plain old func - replace
887 # it was not commandchain, plain old func - replace
890 dp = f
888 dp = f
891
889
892 setattr(self.hooks,name, dp)
890 setattr(self.hooks,name, dp)
893
891
894 #-------------------------------------------------------------------------
892 #-------------------------------------------------------------------------
895 # Things related to events
893 # Things related to events
896 #-------------------------------------------------------------------------
894 #-------------------------------------------------------------------------
897
895
898 def init_events(self):
896 def init_events(self):
899 self.events = EventManager(self, available_events)
897 self.events = EventManager(self, available_events)
900
898
901 self.events.register("pre_execute", self._clear_warning_registry)
899 self.events.register("pre_execute", self._clear_warning_registry)
902
900
903 def register_post_execute(self, func):
901 def register_post_execute(self, func):
904 """DEPRECATED: Use ip.events.register('post_run_cell', func)
902 """DEPRECATED: Use ip.events.register('post_run_cell', func)
905
903
906 Register a function for calling after code execution.
904 Register a function for calling after code execution.
907 """
905 """
908 warn("ip.register_post_execute is deprecated, use "
906 warn("ip.register_post_execute is deprecated, use "
909 "ip.events.register('post_run_cell', func) instead.")
907 "ip.events.register('post_run_cell', func) instead.")
910 self.events.register('post_run_cell', func)
908 self.events.register('post_run_cell', func)
911
909
912 def _clear_warning_registry(self):
910 def _clear_warning_registry(self):
913 # clear the warning registry, so that different code blocks with
911 # clear the warning registry, so that different code blocks with
914 # overlapping line number ranges don't cause spurious suppression of
912 # overlapping line number ranges don't cause spurious suppression of
915 # warnings (see gh-6611 for details)
913 # warnings (see gh-6611 for details)
916 if "__warningregistry__" in self.user_global_ns:
914 if "__warningregistry__" in self.user_global_ns:
917 del self.user_global_ns["__warningregistry__"]
915 del self.user_global_ns["__warningregistry__"]
918
916
919 #-------------------------------------------------------------------------
917 #-------------------------------------------------------------------------
920 # Things related to the "main" module
918 # Things related to the "main" module
921 #-------------------------------------------------------------------------
919 #-------------------------------------------------------------------------
922
920
923 def new_main_mod(self, filename, modname):
921 def new_main_mod(self, filename, modname):
924 """Return a new 'main' module object for user code execution.
922 """Return a new 'main' module object for user code execution.
925
923
926 ``filename`` should be the path of the script which will be run in the
924 ``filename`` should be the path of the script which will be run in the
927 module. Requests with the same filename will get the same module, with
925 module. Requests with the same filename will get the same module, with
928 its namespace cleared.
926 its namespace cleared.
929
927
930 ``modname`` should be the module name - normally either '__main__' or
928 ``modname`` should be the module name - normally either '__main__' or
931 the basename of the file without the extension.
929 the basename of the file without the extension.
932
930
933 When scripts are executed via %run, we must keep a reference to their
931 When scripts are executed via %run, we must keep a reference to their
934 __main__ module around so that Python doesn't
932 __main__ module around so that Python doesn't
935 clear it, rendering references to module globals useless.
933 clear it, rendering references to module globals useless.
936
934
937 This method keeps said reference in a private dict, keyed by the
935 This method keeps said reference in a private dict, keyed by the
938 absolute path of the script. This way, for multiple executions of the
936 absolute path of the script. This way, for multiple executions of the
939 same script we only keep one copy of the namespace (the last one),
937 same script we only keep one copy of the namespace (the last one),
940 thus preventing memory leaks from old references while allowing the
938 thus preventing memory leaks from old references while allowing the
941 objects from the last execution to be accessible.
939 objects from the last execution to be accessible.
942 """
940 """
943 filename = os.path.abspath(filename)
941 filename = os.path.abspath(filename)
944 try:
942 try:
945 main_mod = self._main_mod_cache[filename]
943 main_mod = self._main_mod_cache[filename]
946 except KeyError:
944 except KeyError:
947 main_mod = self._main_mod_cache[filename] = types.ModuleType(
945 main_mod = self._main_mod_cache[filename] = types.ModuleType(
948 py3compat.cast_bytes_py2(modname),
946 py3compat.cast_bytes_py2(modname),
949 doc="Module created for script run in IPython")
947 doc="Module created for script run in IPython")
950 else:
948 else:
951 main_mod.__dict__.clear()
949 main_mod.__dict__.clear()
952 main_mod.__name__ = modname
950 main_mod.__name__ = modname
953
951
954 main_mod.__file__ = filename
952 main_mod.__file__ = filename
955 # It seems pydoc (and perhaps others) needs any module instance to
953 # It seems pydoc (and perhaps others) needs any module instance to
956 # implement a __nonzero__ method
954 # implement a __nonzero__ method
957 main_mod.__nonzero__ = lambda : True
955 main_mod.__nonzero__ = lambda : True
958
956
959 return main_mod
957 return main_mod
960
958
961 def clear_main_mod_cache(self):
959 def clear_main_mod_cache(self):
962 """Clear the cache of main modules.
960 """Clear the cache of main modules.
963
961
964 Mainly for use by utilities like %reset.
962 Mainly for use by utilities like %reset.
965
963
966 Examples
964 Examples
967 --------
965 --------
968
966
969 In [15]: import IPython
967 In [15]: import IPython
970
968
971 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
969 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
972
970
973 In [17]: len(_ip._main_mod_cache) > 0
971 In [17]: len(_ip._main_mod_cache) > 0
974 Out[17]: True
972 Out[17]: True
975
973
976 In [18]: _ip.clear_main_mod_cache()
974 In [18]: _ip.clear_main_mod_cache()
977
975
978 In [19]: len(_ip._main_mod_cache) == 0
976 In [19]: len(_ip._main_mod_cache) == 0
979 Out[19]: True
977 Out[19]: True
980 """
978 """
981 self._main_mod_cache.clear()
979 self._main_mod_cache.clear()
982
980
983 #-------------------------------------------------------------------------
981 #-------------------------------------------------------------------------
984 # Things related to debugging
982 # Things related to debugging
985 #-------------------------------------------------------------------------
983 #-------------------------------------------------------------------------
986
984
987 def init_pdb(self):
985 def init_pdb(self):
988 # Set calling of pdb on exceptions
986 # Set calling of pdb on exceptions
989 # self.call_pdb is a property
987 # self.call_pdb is a property
990 self.call_pdb = self.pdb
988 self.call_pdb = self.pdb
991
989
992 def _get_call_pdb(self):
990 def _get_call_pdb(self):
993 return self._call_pdb
991 return self._call_pdb
994
992
995 def _set_call_pdb(self,val):
993 def _set_call_pdb(self,val):
996
994
997 if val not in (0,1,False,True):
995 if val not in (0,1,False,True):
998 raise ValueError('new call_pdb value must be boolean')
996 raise ValueError('new call_pdb value must be boolean')
999
997
1000 # store value in instance
998 # store value in instance
1001 self._call_pdb = val
999 self._call_pdb = val
1002
1000
1003 # notify the actual exception handlers
1001 # notify the actual exception handlers
1004 self.InteractiveTB.call_pdb = val
1002 self.InteractiveTB.call_pdb = val
1005
1003
1006 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1004 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1007 'Control auto-activation of pdb at exceptions')
1005 'Control auto-activation of pdb at exceptions')
1008
1006
1009 def debugger(self,force=False):
1007 def debugger(self,force=False):
1010 """Call the pdb debugger.
1008 """Call the pdb debugger.
1011
1009
1012 Keywords:
1010 Keywords:
1013
1011
1014 - force(False): by default, this routine checks the instance call_pdb
1012 - force(False): by default, this routine checks the instance call_pdb
1015 flag and does not actually invoke the debugger if the flag is false.
1013 flag and does not actually invoke the debugger if the flag is false.
1016 The 'force' option forces the debugger to activate even if the flag
1014 The 'force' option forces the debugger to activate even if the flag
1017 is false.
1015 is false.
1018 """
1016 """
1019
1017
1020 if not (force or self.call_pdb):
1018 if not (force or self.call_pdb):
1021 return
1019 return
1022
1020
1023 if not hasattr(sys,'last_traceback'):
1021 if not hasattr(sys,'last_traceback'):
1024 error('No traceback has been produced, nothing to debug.')
1022 error('No traceback has been produced, nothing to debug.')
1025 return
1023 return
1026
1024
1027
1025
1028 with self.readline_no_record:
1026 with self.readline_no_record:
1029 self.InteractiveTB.debugger(force=True)
1027 self.InteractiveTB.debugger(force=True)
1030
1028
1031 #-------------------------------------------------------------------------
1029 #-------------------------------------------------------------------------
1032 # Things related to IPython's various namespaces
1030 # Things related to IPython's various namespaces
1033 #-------------------------------------------------------------------------
1031 #-------------------------------------------------------------------------
1034 default_user_namespaces = True
1032 default_user_namespaces = True
1035
1033
1036 def init_create_namespaces(self, user_module=None, user_ns=None):
1034 def init_create_namespaces(self, user_module=None, user_ns=None):
1037 # Create the namespace where the user will operate. user_ns is
1035 # Create the namespace where the user will operate. user_ns is
1038 # normally the only one used, and it is passed to the exec calls as
1036 # normally the only one used, and it is passed to the exec calls as
1039 # the locals argument. But we do carry a user_global_ns namespace
1037 # the locals argument. But we do carry a user_global_ns namespace
1040 # given as the exec 'globals' argument, This is useful in embedding
1038 # given as the exec 'globals' argument, This is useful in embedding
1041 # situations where the ipython shell opens in a context where the
1039 # situations where the ipython shell opens in a context where the
1042 # distinction between locals and globals is meaningful. For
1040 # distinction between locals and globals is meaningful. For
1043 # non-embedded contexts, it is just the same object as the user_ns dict.
1041 # non-embedded contexts, it is just the same object as the user_ns dict.
1044
1042
1045 # FIXME. For some strange reason, __builtins__ is showing up at user
1043 # FIXME. For some strange reason, __builtins__ is showing up at user
1046 # level as a dict instead of a module. This is a manual fix, but I
1044 # level as a dict instead of a module. This is a manual fix, but I
1047 # should really track down where the problem is coming from. Alex
1045 # should really track down where the problem is coming from. Alex
1048 # Schmolck reported this problem first.
1046 # Schmolck reported this problem first.
1049
1047
1050 # A useful post by Alex Martelli on this topic:
1048 # A useful post by Alex Martelli on this topic:
1051 # Re: inconsistent value from __builtins__
1049 # Re: inconsistent value from __builtins__
1052 # Von: Alex Martelli <aleaxit@yahoo.com>
1050 # Von: Alex Martelli <aleaxit@yahoo.com>
1053 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1051 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1054 # Gruppen: comp.lang.python
1052 # Gruppen: comp.lang.python
1055
1053
1056 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1054 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1057 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1055 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1058 # > <type 'dict'>
1056 # > <type 'dict'>
1059 # > >>> print type(__builtins__)
1057 # > >>> print type(__builtins__)
1060 # > <type 'module'>
1058 # > <type 'module'>
1061 # > Is this difference in return value intentional?
1059 # > Is this difference in return value intentional?
1062
1060
1063 # Well, it's documented that '__builtins__' can be either a dictionary
1061 # Well, it's documented that '__builtins__' can be either a dictionary
1064 # or a module, and it's been that way for a long time. Whether it's
1062 # or a module, and it's been that way for a long time. Whether it's
1065 # intentional (or sensible), I don't know. In any case, the idea is
1063 # intentional (or sensible), I don't know. In any case, the idea is
1066 # that if you need to access the built-in namespace directly, you
1064 # that if you need to access the built-in namespace directly, you
1067 # should start with "import __builtin__" (note, no 's') which will
1065 # should start with "import __builtin__" (note, no 's') which will
1068 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1066 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1069
1067
1070 # These routines return a properly built module and dict as needed by
1068 # These routines return a properly built module and dict as needed by
1071 # the rest of the code, and can also be used by extension writers to
1069 # the rest of the code, and can also be used by extension writers to
1072 # generate properly initialized namespaces.
1070 # generate properly initialized namespaces.
1073 if (user_ns is not None) or (user_module is not None):
1071 if (user_ns is not None) or (user_module is not None):
1074 self.default_user_namespaces = False
1072 self.default_user_namespaces = False
1075 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1073 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1076
1074
1077 # A record of hidden variables we have added to the user namespace, so
1075 # A record of hidden variables we have added to the user namespace, so
1078 # we can list later only variables defined in actual interactive use.
1076 # we can list later only variables defined in actual interactive use.
1079 self.user_ns_hidden = {}
1077 self.user_ns_hidden = {}
1080
1078
1081 # Now that FakeModule produces a real module, we've run into a nasty
1079 # Now that FakeModule produces a real module, we've run into a nasty
1082 # problem: after script execution (via %run), the module where the user
1080 # problem: after script execution (via %run), the module where the user
1083 # code ran is deleted. Now that this object is a true module (needed
1081 # code ran is deleted. Now that this object is a true module (needed
1084 # so doctest and other tools work correctly), the Python module
1082 # so doctest and other tools work correctly), the Python module
1085 # teardown mechanism runs over it, and sets to None every variable
1083 # teardown mechanism runs over it, and sets to None every variable
1086 # present in that module. Top-level references to objects from the
1084 # present in that module. Top-level references to objects from the
1087 # script survive, because the user_ns is updated with them. However,
1085 # script survive, because the user_ns is updated with them. However,
1088 # calling functions defined in the script that use other things from
1086 # calling functions defined in the script that use other things from
1089 # the script will fail, because the function's closure had references
1087 # the script will fail, because the function's closure had references
1090 # to the original objects, which are now all None. So we must protect
1088 # to the original objects, which are now all None. So we must protect
1091 # these modules from deletion by keeping a cache.
1089 # these modules from deletion by keeping a cache.
1092 #
1090 #
1093 # To avoid keeping stale modules around (we only need the one from the
1091 # To avoid keeping stale modules around (we only need the one from the
1094 # last run), we use a dict keyed with the full path to the script, so
1092 # last run), we use a dict keyed with the full path to the script, so
1095 # only the last version of the module is held in the cache. Note,
1093 # only the last version of the module is held in the cache. Note,
1096 # however, that we must cache the module *namespace contents* (their
1094 # however, that we must cache the module *namespace contents* (their
1097 # __dict__). Because if we try to cache the actual modules, old ones
1095 # __dict__). Because if we try to cache the actual modules, old ones
1098 # (uncached) could be destroyed while still holding references (such as
1096 # (uncached) could be destroyed while still holding references (such as
1099 # those held by GUI objects that tend to be long-lived)>
1097 # those held by GUI objects that tend to be long-lived)>
1100 #
1098 #
1101 # The %reset command will flush this cache. See the cache_main_mod()
1099 # The %reset command will flush this cache. See the cache_main_mod()
1102 # and clear_main_mod_cache() methods for details on use.
1100 # and clear_main_mod_cache() methods for details on use.
1103
1101
1104 # This is the cache used for 'main' namespaces
1102 # This is the cache used for 'main' namespaces
1105 self._main_mod_cache = {}
1103 self._main_mod_cache = {}
1106
1104
1107 # A table holding all the namespaces IPython deals with, so that
1105 # A table holding all the namespaces IPython deals with, so that
1108 # introspection facilities can search easily.
1106 # introspection facilities can search easily.
1109 self.ns_table = {'user_global':self.user_module.__dict__,
1107 self.ns_table = {'user_global':self.user_module.__dict__,
1110 'user_local':self.user_ns,
1108 'user_local':self.user_ns,
1111 'builtin':builtin_mod.__dict__
1109 'builtin':builtin_mod.__dict__
1112 }
1110 }
1113
1111
1114 @property
1112 @property
1115 def user_global_ns(self):
1113 def user_global_ns(self):
1116 return self.user_module.__dict__
1114 return self.user_module.__dict__
1117
1115
1118 def prepare_user_module(self, user_module=None, user_ns=None):
1116 def prepare_user_module(self, user_module=None, user_ns=None):
1119 """Prepare the module and namespace in which user code will be run.
1117 """Prepare the module and namespace in which user code will be run.
1120
1118
1121 When IPython is started normally, both parameters are None: a new module
1119 When IPython is started normally, both parameters are None: a new module
1122 is created automatically, and its __dict__ used as the namespace.
1120 is created automatically, and its __dict__ used as the namespace.
1123
1121
1124 If only user_module is provided, its __dict__ is used as the namespace.
1122 If only user_module is provided, its __dict__ is used as the namespace.
1125 If only user_ns is provided, a dummy module is created, and user_ns
1123 If only user_ns is provided, a dummy module is created, and user_ns
1126 becomes the global namespace. If both are provided (as they may be
1124 becomes the global namespace. If both are provided (as they may be
1127 when embedding), user_ns is the local namespace, and user_module
1125 when embedding), user_ns is the local namespace, and user_module
1128 provides the global namespace.
1126 provides the global namespace.
1129
1127
1130 Parameters
1128 Parameters
1131 ----------
1129 ----------
1132 user_module : module, optional
1130 user_module : module, optional
1133 The current user module in which IPython is being run. If None,
1131 The current user module in which IPython is being run. If None,
1134 a clean module will be created.
1132 a clean module will be created.
1135 user_ns : dict, optional
1133 user_ns : dict, optional
1136 A namespace in which to run interactive commands.
1134 A namespace in which to run interactive commands.
1137
1135
1138 Returns
1136 Returns
1139 -------
1137 -------
1140 A tuple of user_module and user_ns, each properly initialised.
1138 A tuple of user_module and user_ns, each properly initialised.
1141 """
1139 """
1142 if user_module is None and user_ns is not None:
1140 if user_module is None and user_ns is not None:
1143 user_ns.setdefault("__name__", "__main__")
1141 user_ns.setdefault("__name__", "__main__")
1144 user_module = DummyMod()
1142 user_module = DummyMod()
1145 user_module.__dict__ = user_ns
1143 user_module.__dict__ = user_ns
1146
1144
1147 if user_module is None:
1145 if user_module is None:
1148 user_module = types.ModuleType("__main__",
1146 user_module = types.ModuleType("__main__",
1149 doc="Automatically created module for IPython interactive environment")
1147 doc="Automatically created module for IPython interactive environment")
1150
1148
1151 # We must ensure that __builtin__ (without the final 's') is always
1149 # We must ensure that __builtin__ (without the final 's') is always
1152 # available and pointing to the __builtin__ *module*. For more details:
1150 # available and pointing to the __builtin__ *module*. For more details:
1153 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1151 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1154 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1152 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1155 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1153 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1156
1154
1157 if user_ns is None:
1155 if user_ns is None:
1158 user_ns = user_module.__dict__
1156 user_ns = user_module.__dict__
1159
1157
1160 return user_module, user_ns
1158 return user_module, user_ns
1161
1159
1162 def init_sys_modules(self):
1160 def init_sys_modules(self):
1163 # We need to insert into sys.modules something that looks like a
1161 # We need to insert into sys.modules something that looks like a
1164 # module but which accesses the IPython namespace, for shelve and
1162 # module but which accesses the IPython namespace, for shelve and
1165 # pickle to work interactively. Normally they rely on getting
1163 # pickle to work interactively. Normally they rely on getting
1166 # everything out of __main__, but for embedding purposes each IPython
1164 # everything out of __main__, but for embedding purposes each IPython
1167 # instance has its own private namespace, so we can't go shoving
1165 # instance has its own private namespace, so we can't go shoving
1168 # everything into __main__.
1166 # everything into __main__.
1169
1167
1170 # note, however, that we should only do this for non-embedded
1168 # note, however, that we should only do this for non-embedded
1171 # ipythons, which really mimic the __main__.__dict__ with their own
1169 # ipythons, which really mimic the __main__.__dict__ with their own
1172 # namespace. Embedded instances, on the other hand, should not do
1170 # namespace. Embedded instances, on the other hand, should not do
1173 # this because they need to manage the user local/global namespaces
1171 # this because they need to manage the user local/global namespaces
1174 # only, but they live within a 'normal' __main__ (meaning, they
1172 # only, but they live within a 'normal' __main__ (meaning, they
1175 # shouldn't overtake the execution environment of the script they're
1173 # shouldn't overtake the execution environment of the script they're
1176 # embedded in).
1174 # embedded in).
1177
1175
1178 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1176 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1179 main_name = self.user_module.__name__
1177 main_name = self.user_module.__name__
1180 sys.modules[main_name] = self.user_module
1178 sys.modules[main_name] = self.user_module
1181
1179
1182 def init_user_ns(self):
1180 def init_user_ns(self):
1183 """Initialize all user-visible namespaces to their minimum defaults.
1181 """Initialize all user-visible namespaces to their minimum defaults.
1184
1182
1185 Certain history lists are also initialized here, as they effectively
1183 Certain history lists are also initialized here, as they effectively
1186 act as user namespaces.
1184 act as user namespaces.
1187
1185
1188 Notes
1186 Notes
1189 -----
1187 -----
1190 All data structures here are only filled in, they are NOT reset by this
1188 All data structures here are only filled in, they are NOT reset by this
1191 method. If they were not empty before, data will simply be added to
1189 method. If they were not empty before, data will simply be added to
1192 therm.
1190 therm.
1193 """
1191 """
1194 # This function works in two parts: first we put a few things in
1192 # This function works in two parts: first we put a few things in
1195 # user_ns, and we sync that contents into user_ns_hidden so that these
1193 # user_ns, and we sync that contents into user_ns_hidden so that these
1196 # initial variables aren't shown by %who. After the sync, we add the
1194 # initial variables aren't shown by %who. After the sync, we add the
1197 # rest of what we *do* want the user to see with %who even on a new
1195 # rest of what we *do* want the user to see with %who even on a new
1198 # session (probably nothing, so they really only see their own stuff)
1196 # session (probably nothing, so they really only see their own stuff)
1199
1197
1200 # The user dict must *always* have a __builtin__ reference to the
1198 # The user dict must *always* have a __builtin__ reference to the
1201 # Python standard __builtin__ namespace, which must be imported.
1199 # Python standard __builtin__ namespace, which must be imported.
1202 # This is so that certain operations in prompt evaluation can be
1200 # This is so that certain operations in prompt evaluation can be
1203 # reliably executed with builtins. Note that we can NOT use
1201 # reliably executed with builtins. Note that we can NOT use
1204 # __builtins__ (note the 's'), because that can either be a dict or a
1202 # __builtins__ (note the 's'), because that can either be a dict or a
1205 # module, and can even mutate at runtime, depending on the context
1203 # module, and can even mutate at runtime, depending on the context
1206 # (Python makes no guarantees on it). In contrast, __builtin__ is
1204 # (Python makes no guarantees on it). In contrast, __builtin__ is
1207 # always a module object, though it must be explicitly imported.
1205 # always a module object, though it must be explicitly imported.
1208
1206
1209 # For more details:
1207 # For more details:
1210 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1208 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1211 ns = dict()
1209 ns = dict()
1212
1210
1213 # make global variables for user access to the histories
1211 # make global variables for user access to the histories
1214 ns['_ih'] = self.history_manager.input_hist_parsed
1212 ns['_ih'] = self.history_manager.input_hist_parsed
1215 ns['_oh'] = self.history_manager.output_hist
1213 ns['_oh'] = self.history_manager.output_hist
1216 ns['_dh'] = self.history_manager.dir_hist
1214 ns['_dh'] = self.history_manager.dir_hist
1217
1215
1218 ns['_sh'] = shadowns
1216 ns['_sh'] = shadowns
1219
1217
1220 # user aliases to input and output histories. These shouldn't show up
1218 # user aliases to input and output histories. These shouldn't show up
1221 # in %who, as they can have very large reprs.
1219 # in %who, as they can have very large reprs.
1222 ns['In'] = self.history_manager.input_hist_parsed
1220 ns['In'] = self.history_manager.input_hist_parsed
1223 ns['Out'] = self.history_manager.output_hist
1221 ns['Out'] = self.history_manager.output_hist
1224
1222
1225 # Store myself as the public api!!!
1223 # Store myself as the public api!!!
1226 ns['get_ipython'] = self.get_ipython
1224 ns['get_ipython'] = self.get_ipython
1227
1225
1228 ns['exit'] = self.exiter
1226 ns['exit'] = self.exiter
1229 ns['quit'] = self.exiter
1227 ns['quit'] = self.exiter
1230
1228
1231 # Sync what we've added so far to user_ns_hidden so these aren't seen
1229 # Sync what we've added so far to user_ns_hidden so these aren't seen
1232 # by %who
1230 # by %who
1233 self.user_ns_hidden.update(ns)
1231 self.user_ns_hidden.update(ns)
1234
1232
1235 # Anything put into ns now would show up in %who. Think twice before
1233 # Anything put into ns now would show up in %who. Think twice before
1236 # putting anything here, as we really want %who to show the user their
1234 # putting anything here, as we really want %who to show the user their
1237 # stuff, not our variables.
1235 # stuff, not our variables.
1238
1236
1239 # Finally, update the real user's namespace
1237 # Finally, update the real user's namespace
1240 self.user_ns.update(ns)
1238 self.user_ns.update(ns)
1241
1239
1242 @property
1240 @property
1243 def all_ns_refs(self):
1241 def all_ns_refs(self):
1244 """Get a list of references to all the namespace dictionaries in which
1242 """Get a list of references to all the namespace dictionaries in which
1245 IPython might store a user-created object.
1243 IPython might store a user-created object.
1246
1244
1247 Note that this does not include the displayhook, which also caches
1245 Note that this does not include the displayhook, which also caches
1248 objects from the output."""
1246 objects from the output."""
1249 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1247 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1250 [m.__dict__ for m in self._main_mod_cache.values()]
1248 [m.__dict__ for m in self._main_mod_cache.values()]
1251
1249
1252 def reset(self, new_session=True):
1250 def reset(self, new_session=True):
1253 """Clear all internal namespaces, and attempt to release references to
1251 """Clear all internal namespaces, and attempt to release references to
1254 user objects.
1252 user objects.
1255
1253
1256 If new_session is True, a new history session will be opened.
1254 If new_session is True, a new history session will be opened.
1257 """
1255 """
1258 # Clear histories
1256 # Clear histories
1259 self.history_manager.reset(new_session)
1257 self.history_manager.reset(new_session)
1260 # Reset counter used to index all histories
1258 # Reset counter used to index all histories
1261 if new_session:
1259 if new_session:
1262 self.execution_count = 1
1260 self.execution_count = 1
1263
1261
1264 # Flush cached output items
1262 # Flush cached output items
1265 if self.displayhook.do_full_cache:
1263 if self.displayhook.do_full_cache:
1266 self.displayhook.flush()
1264 self.displayhook.flush()
1267
1265
1268 # The main execution namespaces must be cleared very carefully,
1266 # The main execution namespaces must be cleared very carefully,
1269 # skipping the deletion of the builtin-related keys, because doing so
1267 # skipping the deletion of the builtin-related keys, because doing so
1270 # would cause errors in many object's __del__ methods.
1268 # would cause errors in many object's __del__ methods.
1271 if self.user_ns is not self.user_global_ns:
1269 if self.user_ns is not self.user_global_ns:
1272 self.user_ns.clear()
1270 self.user_ns.clear()
1273 ns = self.user_global_ns
1271 ns = self.user_global_ns
1274 drop_keys = set(ns.keys())
1272 drop_keys = set(ns.keys())
1275 drop_keys.discard('__builtin__')
1273 drop_keys.discard('__builtin__')
1276 drop_keys.discard('__builtins__')
1274 drop_keys.discard('__builtins__')
1277 drop_keys.discard('__name__')
1275 drop_keys.discard('__name__')
1278 for k in drop_keys:
1276 for k in drop_keys:
1279 del ns[k]
1277 del ns[k]
1280
1278
1281 self.user_ns_hidden.clear()
1279 self.user_ns_hidden.clear()
1282
1280
1283 # Restore the user namespaces to minimal usability
1281 # Restore the user namespaces to minimal usability
1284 self.init_user_ns()
1282 self.init_user_ns()
1285
1283
1286 # Restore the default and user aliases
1284 # Restore the default and user aliases
1287 self.alias_manager.clear_aliases()
1285 self.alias_manager.clear_aliases()
1288 self.alias_manager.init_aliases()
1286 self.alias_manager.init_aliases()
1289
1287
1290 # Flush the private list of module references kept for script
1288 # Flush the private list of module references kept for script
1291 # execution protection
1289 # execution protection
1292 self.clear_main_mod_cache()
1290 self.clear_main_mod_cache()
1293
1291
1294 def del_var(self, varname, by_name=False):
1292 def del_var(self, varname, by_name=False):
1295 """Delete a variable from the various namespaces, so that, as
1293 """Delete a variable from the various namespaces, so that, as
1296 far as possible, we're not keeping any hidden references to it.
1294 far as possible, we're not keeping any hidden references to it.
1297
1295
1298 Parameters
1296 Parameters
1299 ----------
1297 ----------
1300 varname : str
1298 varname : str
1301 The name of the variable to delete.
1299 The name of the variable to delete.
1302 by_name : bool
1300 by_name : bool
1303 If True, delete variables with the given name in each
1301 If True, delete variables with the given name in each
1304 namespace. If False (default), find the variable in the user
1302 namespace. If False (default), find the variable in the user
1305 namespace, and delete references to it.
1303 namespace, and delete references to it.
1306 """
1304 """
1307 if varname in ('__builtin__', '__builtins__'):
1305 if varname in ('__builtin__', '__builtins__'):
1308 raise ValueError("Refusing to delete %s" % varname)
1306 raise ValueError("Refusing to delete %s" % varname)
1309
1307
1310 ns_refs = self.all_ns_refs
1308 ns_refs = self.all_ns_refs
1311
1309
1312 if by_name: # Delete by name
1310 if by_name: # Delete by name
1313 for ns in ns_refs:
1311 for ns in ns_refs:
1314 try:
1312 try:
1315 del ns[varname]
1313 del ns[varname]
1316 except KeyError:
1314 except KeyError:
1317 pass
1315 pass
1318 else: # Delete by object
1316 else: # Delete by object
1319 try:
1317 try:
1320 obj = self.user_ns[varname]
1318 obj = self.user_ns[varname]
1321 except KeyError:
1319 except KeyError:
1322 raise NameError("name '%s' is not defined" % varname)
1320 raise NameError("name '%s' is not defined" % varname)
1323 # Also check in output history
1321 # Also check in output history
1324 ns_refs.append(self.history_manager.output_hist)
1322 ns_refs.append(self.history_manager.output_hist)
1325 for ns in ns_refs:
1323 for ns in ns_refs:
1326 to_delete = [n for n, o in iteritems(ns) if o is obj]
1324 to_delete = [n for n, o in iteritems(ns) if o is obj]
1327 for name in to_delete:
1325 for name in to_delete:
1328 del ns[name]
1326 del ns[name]
1329
1327
1330 # displayhook keeps extra references, but not in a dictionary
1328 # displayhook keeps extra references, but not in a dictionary
1331 for name in ('_', '__', '___'):
1329 for name in ('_', '__', '___'):
1332 if getattr(self.displayhook, name) is obj:
1330 if getattr(self.displayhook, name) is obj:
1333 setattr(self.displayhook, name, None)
1331 setattr(self.displayhook, name, None)
1334
1332
1335 def reset_selective(self, regex=None):
1333 def reset_selective(self, regex=None):
1336 """Clear selective variables from internal namespaces based on a
1334 """Clear selective variables from internal namespaces based on a
1337 specified regular expression.
1335 specified regular expression.
1338
1336
1339 Parameters
1337 Parameters
1340 ----------
1338 ----------
1341 regex : string or compiled pattern, optional
1339 regex : string or compiled pattern, optional
1342 A regular expression pattern that will be used in searching
1340 A regular expression pattern that will be used in searching
1343 variable names in the users namespaces.
1341 variable names in the users namespaces.
1344 """
1342 """
1345 if regex is not None:
1343 if regex is not None:
1346 try:
1344 try:
1347 m = re.compile(regex)
1345 m = re.compile(regex)
1348 except TypeError:
1346 except TypeError:
1349 raise TypeError('regex must be a string or compiled pattern')
1347 raise TypeError('regex must be a string or compiled pattern')
1350 # Search for keys in each namespace that match the given regex
1348 # Search for keys in each namespace that match the given regex
1351 # If a match is found, delete the key/value pair.
1349 # If a match is found, delete the key/value pair.
1352 for ns in self.all_ns_refs:
1350 for ns in self.all_ns_refs:
1353 for var in ns:
1351 for var in ns:
1354 if m.search(var):
1352 if m.search(var):
1355 del ns[var]
1353 del ns[var]
1356
1354
1357 def push(self, variables, interactive=True):
1355 def push(self, variables, interactive=True):
1358 """Inject a group of variables into the IPython user namespace.
1356 """Inject a group of variables into the IPython user namespace.
1359
1357
1360 Parameters
1358 Parameters
1361 ----------
1359 ----------
1362 variables : dict, str or list/tuple of str
1360 variables : dict, str or list/tuple of str
1363 The variables to inject into the user's namespace. If a dict, a
1361 The variables to inject into the user's namespace. If a dict, a
1364 simple update is done. If a str, the string is assumed to have
1362 simple update is done. If a str, the string is assumed to have
1365 variable names separated by spaces. A list/tuple of str can also
1363 variable names separated by spaces. A list/tuple of str can also
1366 be used to give the variable names. If just the variable names are
1364 be used to give the variable names. If just the variable names are
1367 give (list/tuple/str) then the variable values looked up in the
1365 give (list/tuple/str) then the variable values looked up in the
1368 callers frame.
1366 callers frame.
1369 interactive : bool
1367 interactive : bool
1370 If True (default), the variables will be listed with the ``who``
1368 If True (default), the variables will be listed with the ``who``
1371 magic.
1369 magic.
1372 """
1370 """
1373 vdict = None
1371 vdict = None
1374
1372
1375 # We need a dict of name/value pairs to do namespace updates.
1373 # We need a dict of name/value pairs to do namespace updates.
1376 if isinstance(variables, dict):
1374 if isinstance(variables, dict):
1377 vdict = variables
1375 vdict = variables
1378 elif isinstance(variables, string_types+(list, tuple)):
1376 elif isinstance(variables, string_types+(list, tuple)):
1379 if isinstance(variables, string_types):
1377 if isinstance(variables, string_types):
1380 vlist = variables.split()
1378 vlist = variables.split()
1381 else:
1379 else:
1382 vlist = variables
1380 vlist = variables
1383 vdict = {}
1381 vdict = {}
1384 cf = sys._getframe(1)
1382 cf = sys._getframe(1)
1385 for name in vlist:
1383 for name in vlist:
1386 try:
1384 try:
1387 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1385 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1388 except:
1386 except:
1389 print('Could not get variable %s from %s' %
1387 print('Could not get variable %s from %s' %
1390 (name,cf.f_code.co_name))
1388 (name,cf.f_code.co_name))
1391 else:
1389 else:
1392 raise ValueError('variables must be a dict/str/list/tuple')
1390 raise ValueError('variables must be a dict/str/list/tuple')
1393
1391
1394 # Propagate variables to user namespace
1392 # Propagate variables to user namespace
1395 self.user_ns.update(vdict)
1393 self.user_ns.update(vdict)
1396
1394
1397 # And configure interactive visibility
1395 # And configure interactive visibility
1398 user_ns_hidden = self.user_ns_hidden
1396 user_ns_hidden = self.user_ns_hidden
1399 if interactive:
1397 if interactive:
1400 for name in vdict:
1398 for name in vdict:
1401 user_ns_hidden.pop(name, None)
1399 user_ns_hidden.pop(name, None)
1402 else:
1400 else:
1403 user_ns_hidden.update(vdict)
1401 user_ns_hidden.update(vdict)
1404
1402
1405 def drop_by_id(self, variables):
1403 def drop_by_id(self, variables):
1406 """Remove a dict of variables from the user namespace, if they are the
1404 """Remove a dict of variables from the user namespace, if they are the
1407 same as the values in the dictionary.
1405 same as the values in the dictionary.
1408
1406
1409 This is intended for use by extensions: variables that they've added can
1407 This is intended for use by extensions: variables that they've added can
1410 be taken back out if they are unloaded, without removing any that the
1408 be taken back out if they are unloaded, without removing any that the
1411 user has overwritten.
1409 user has overwritten.
1412
1410
1413 Parameters
1411 Parameters
1414 ----------
1412 ----------
1415 variables : dict
1413 variables : dict
1416 A dictionary mapping object names (as strings) to the objects.
1414 A dictionary mapping object names (as strings) to the objects.
1417 """
1415 """
1418 for name, obj in iteritems(variables):
1416 for name, obj in iteritems(variables):
1419 if name in self.user_ns and self.user_ns[name] is obj:
1417 if name in self.user_ns and self.user_ns[name] is obj:
1420 del self.user_ns[name]
1418 del self.user_ns[name]
1421 self.user_ns_hidden.pop(name, None)
1419 self.user_ns_hidden.pop(name, None)
1422
1420
1423 #-------------------------------------------------------------------------
1421 #-------------------------------------------------------------------------
1424 # Things related to object introspection
1422 # Things related to object introspection
1425 #-------------------------------------------------------------------------
1423 #-------------------------------------------------------------------------
1426
1424
1427 def _ofind(self, oname, namespaces=None):
1425 def _ofind(self, oname, namespaces=None):
1428 """Find an object in the available namespaces.
1426 """Find an object in the available namespaces.
1429
1427
1430 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1428 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1431
1429
1432 Has special code to detect magic functions.
1430 Has special code to detect magic functions.
1433 """
1431 """
1434 oname = oname.strip()
1432 oname = oname.strip()
1435 #print '1- oname: <%r>' % oname # dbg
1433 #print '1- oname: <%r>' % oname # dbg
1436 if not oname.startswith(ESC_MAGIC) and \
1434 if not oname.startswith(ESC_MAGIC) and \
1437 not oname.startswith(ESC_MAGIC2) and \
1435 not oname.startswith(ESC_MAGIC2) and \
1438 not py3compat.isidentifier(oname, dotted=True):
1436 not py3compat.isidentifier(oname, dotted=True):
1439 return dict(found=False)
1437 return dict(found=False)
1440
1438
1441 if namespaces is None:
1439 if namespaces is None:
1442 # Namespaces to search in:
1440 # Namespaces to search in:
1443 # Put them in a list. The order is important so that we
1441 # Put them in a list. The order is important so that we
1444 # find things in the same order that Python finds them.
1442 # find things in the same order that Python finds them.
1445 namespaces = [ ('Interactive', self.user_ns),
1443 namespaces = [ ('Interactive', self.user_ns),
1446 ('Interactive (global)', self.user_global_ns),
1444 ('Interactive (global)', self.user_global_ns),
1447 ('Python builtin', builtin_mod.__dict__),
1445 ('Python builtin', builtin_mod.__dict__),
1448 ]
1446 ]
1449
1447
1450 # initialize results to 'null'
1448 # initialize results to 'null'
1451 found = False; obj = None; ospace = None;
1449 found = False; obj = None; ospace = None;
1452 ismagic = False; isalias = False; parent = None
1450 ismagic = False; isalias = False; parent = None
1453
1451
1454 # We need to special-case 'print', which as of python2.6 registers as a
1452 # We need to special-case 'print', which as of python2.6 registers as a
1455 # function but should only be treated as one if print_function was
1453 # function but should only be treated as one if print_function was
1456 # loaded with a future import. In this case, just bail.
1454 # loaded with a future import. In this case, just bail.
1457 if (oname == 'print' and not py3compat.PY3 and not \
1455 if (oname == 'print' and not py3compat.PY3 and not \
1458 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1456 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1459 return {'found':found, 'obj':obj, 'namespace':ospace,
1457 return {'found':found, 'obj':obj, 'namespace':ospace,
1460 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1458 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1461
1459
1462 # Look for the given name by splitting it in parts. If the head is
1460 # Look for the given name by splitting it in parts. If the head is
1463 # found, then we look for all the remaining parts as members, and only
1461 # found, then we look for all the remaining parts as members, and only
1464 # declare success if we can find them all.
1462 # declare success if we can find them all.
1465 oname_parts = oname.split('.')
1463 oname_parts = oname.split('.')
1466 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1464 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1467 for nsname,ns in namespaces:
1465 for nsname,ns in namespaces:
1468 try:
1466 try:
1469 obj = ns[oname_head]
1467 obj = ns[oname_head]
1470 except KeyError:
1468 except KeyError:
1471 continue
1469 continue
1472 else:
1470 else:
1473 #print 'oname_rest:', oname_rest # dbg
1471 #print 'oname_rest:', oname_rest # dbg
1474 for idx, part in enumerate(oname_rest):
1472 for idx, part in enumerate(oname_rest):
1475 try:
1473 try:
1476 parent = obj
1474 parent = obj
1477 # The last part is looked up in a special way to avoid
1475 # The last part is looked up in a special way to avoid
1478 # descriptor invocation as it may raise or have side
1476 # descriptor invocation as it may raise or have side
1479 # effects.
1477 # effects.
1480 if idx == len(oname_rest) - 1:
1478 if idx == len(oname_rest) - 1:
1481 obj = self._getattr_property(obj, part)
1479 obj = self._getattr_property(obj, part)
1482 else:
1480 else:
1483 obj = getattr(obj, part)
1481 obj = getattr(obj, part)
1484 except:
1482 except:
1485 # Blanket except b/c some badly implemented objects
1483 # Blanket except b/c some badly implemented objects
1486 # allow __getattr__ to raise exceptions other than
1484 # allow __getattr__ to raise exceptions other than
1487 # AttributeError, which then crashes IPython.
1485 # AttributeError, which then crashes IPython.
1488 break
1486 break
1489 else:
1487 else:
1490 # If we finish the for loop (no break), we got all members
1488 # If we finish the for loop (no break), we got all members
1491 found = True
1489 found = True
1492 ospace = nsname
1490 ospace = nsname
1493 break # namespace loop
1491 break # namespace loop
1494
1492
1495 # Try to see if it's magic
1493 # Try to see if it's magic
1496 if not found:
1494 if not found:
1497 obj = None
1495 obj = None
1498 if oname.startswith(ESC_MAGIC2):
1496 if oname.startswith(ESC_MAGIC2):
1499 oname = oname.lstrip(ESC_MAGIC2)
1497 oname = oname.lstrip(ESC_MAGIC2)
1500 obj = self.find_cell_magic(oname)
1498 obj = self.find_cell_magic(oname)
1501 elif oname.startswith(ESC_MAGIC):
1499 elif oname.startswith(ESC_MAGIC):
1502 oname = oname.lstrip(ESC_MAGIC)
1500 oname = oname.lstrip(ESC_MAGIC)
1503 obj = self.find_line_magic(oname)
1501 obj = self.find_line_magic(oname)
1504 else:
1502 else:
1505 # search without prefix, so run? will find %run?
1503 # search without prefix, so run? will find %run?
1506 obj = self.find_line_magic(oname)
1504 obj = self.find_line_magic(oname)
1507 if obj is None:
1505 if obj is None:
1508 obj = self.find_cell_magic(oname)
1506 obj = self.find_cell_magic(oname)
1509 if obj is not None:
1507 if obj is not None:
1510 found = True
1508 found = True
1511 ospace = 'IPython internal'
1509 ospace = 'IPython internal'
1512 ismagic = True
1510 ismagic = True
1513 isalias = isinstance(obj, Alias)
1511 isalias = isinstance(obj, Alias)
1514
1512
1515 # Last try: special-case some literals like '', [], {}, etc:
1513 # Last try: special-case some literals like '', [], {}, etc:
1516 if not found and oname_head in ["''",'""','[]','{}','()']:
1514 if not found and oname_head in ["''",'""','[]','{}','()']:
1517 obj = eval(oname_head)
1515 obj = eval(oname_head)
1518 found = True
1516 found = True
1519 ospace = 'Interactive'
1517 ospace = 'Interactive'
1520
1518
1521 return {'found':found, 'obj':obj, 'namespace':ospace,
1519 return {'found':found, 'obj':obj, 'namespace':ospace,
1522 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1520 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1523
1521
1524 @staticmethod
1522 @staticmethod
1525 def _getattr_property(obj, attrname):
1523 def _getattr_property(obj, attrname):
1526 """Property-aware getattr to use in object finding.
1524 """Property-aware getattr to use in object finding.
1527
1525
1528 If attrname represents a property, return it unevaluated (in case it has
1526 If attrname represents a property, return it unevaluated (in case it has
1529 side effects or raises an error.
1527 side effects or raises an error.
1530
1528
1531 """
1529 """
1532 if not isinstance(obj, type):
1530 if not isinstance(obj, type):
1533 try:
1531 try:
1534 # `getattr(type(obj), attrname)` is not guaranteed to return
1532 # `getattr(type(obj), attrname)` is not guaranteed to return
1535 # `obj`, but does so for property:
1533 # `obj`, but does so for property:
1536 #
1534 #
1537 # property.__get__(self, None, cls) -> self
1535 # property.__get__(self, None, cls) -> self
1538 #
1536 #
1539 # The universal alternative is to traverse the mro manually
1537 # The universal alternative is to traverse the mro manually
1540 # searching for attrname in class dicts.
1538 # searching for attrname in class dicts.
1541 attr = getattr(type(obj), attrname)
1539 attr = getattr(type(obj), attrname)
1542 except AttributeError:
1540 except AttributeError:
1543 pass
1541 pass
1544 else:
1542 else:
1545 # This relies on the fact that data descriptors (with both
1543 # This relies on the fact that data descriptors (with both
1546 # __get__ & __set__ magic methods) take precedence over
1544 # __get__ & __set__ magic methods) take precedence over
1547 # instance-level attributes:
1545 # instance-level attributes:
1548 #
1546 #
1549 # class A(object):
1547 # class A(object):
1550 # @property
1548 # @property
1551 # def foobar(self): return 123
1549 # def foobar(self): return 123
1552 # a = A()
1550 # a = A()
1553 # a.__dict__['foobar'] = 345
1551 # a.__dict__['foobar'] = 345
1554 # a.foobar # == 123
1552 # a.foobar # == 123
1555 #
1553 #
1556 # So, a property may be returned right away.
1554 # So, a property may be returned right away.
1557 if isinstance(attr, property):
1555 if isinstance(attr, property):
1558 return attr
1556 return attr
1559
1557
1560 # Nothing helped, fall back.
1558 # Nothing helped, fall back.
1561 return getattr(obj, attrname)
1559 return getattr(obj, attrname)
1562
1560
1563 def _object_find(self, oname, namespaces=None):
1561 def _object_find(self, oname, namespaces=None):
1564 """Find an object and return a struct with info about it."""
1562 """Find an object and return a struct with info about it."""
1565 return Struct(self._ofind(oname, namespaces))
1563 return Struct(self._ofind(oname, namespaces))
1566
1564
1567 def _inspect(self, meth, oname, namespaces=None, **kw):
1565 def _inspect(self, meth, oname, namespaces=None, **kw):
1568 """Generic interface to the inspector system.
1566 """Generic interface to the inspector system.
1569
1567
1570 This function is meant to be called by pdef, pdoc & friends.
1568 This function is meant to be called by pdef, pdoc & friends.
1571 """
1569 """
1572 info = self._object_find(oname, namespaces)
1570 info = self._object_find(oname, namespaces)
1573 docformat = sphinxify if self.sphinxify_docstring else None
1571 docformat = sphinxify if self.sphinxify_docstring else None
1574 if info.found:
1572 if info.found:
1575 pmethod = getattr(self.inspector, meth)
1573 pmethod = getattr(self.inspector, meth)
1576 # TODO: only apply format_screen to the plain/text repr of the mime
1574 # TODO: only apply format_screen to the plain/text repr of the mime
1577 # bundle.
1575 # bundle.
1578 formatter = format_screen if info.ismagic else docformat
1576 formatter = format_screen if info.ismagic else docformat
1579 if meth == 'pdoc':
1577 if meth == 'pdoc':
1580 pmethod(info.obj, oname, formatter)
1578 pmethod(info.obj, oname, formatter)
1581 elif meth == 'pinfo':
1579 elif meth == 'pinfo':
1582 pmethod(info.obj, oname, formatter, info,
1580 pmethod(info.obj, oname, formatter, info,
1583 enable_html_pager=self.enable_html_pager, **kw)
1581 enable_html_pager=self.enable_html_pager, **kw)
1584 else:
1582 else:
1585 pmethod(info.obj, oname)
1583 pmethod(info.obj, oname)
1586 else:
1584 else:
1587 print('Object `%s` not found.' % oname)
1585 print('Object `%s` not found.' % oname)
1588 return 'not found' # so callers can take other action
1586 return 'not found' # so callers can take other action
1589
1587
1590 def object_inspect(self, oname, detail_level=0):
1588 def object_inspect(self, oname, detail_level=0):
1591 """Get object info about oname"""
1589 """Get object info about oname"""
1592 with self.builtin_trap:
1590 with self.builtin_trap:
1593 info = self._object_find(oname)
1591 info = self._object_find(oname)
1594 if info.found:
1592 if info.found:
1595 return self.inspector.info(info.obj, oname, info=info,
1593 return self.inspector.info(info.obj, oname, info=info,
1596 detail_level=detail_level
1594 detail_level=detail_level
1597 )
1595 )
1598 else:
1596 else:
1599 return oinspect.object_info(name=oname, found=False)
1597 return oinspect.object_info(name=oname, found=False)
1600
1598
1601 def object_inspect_text(self, oname, detail_level=0):
1599 def object_inspect_text(self, oname, detail_level=0):
1602 """Get object info as formatted text"""
1600 """Get object info as formatted text"""
1603 return self.object_inspect_mime(oname, detail_level)['text/plain']
1601 return self.object_inspect_mime(oname, detail_level)['text/plain']
1604
1602
1605 def object_inspect_mime(self, oname, detail_level=0):
1603 def object_inspect_mime(self, oname, detail_level=0):
1606 """Get object info as a mimebundle of formatted representations.
1604 """Get object info as a mimebundle of formatted representations.
1607
1605
1608 A mimebundle is a dictionary, keyed by mime-type.
1606 A mimebundle is a dictionary, keyed by mime-type.
1609 It must always have the key `'text/plain'`.
1607 It must always have the key `'text/plain'`.
1610 """
1608 """
1611 with self.builtin_trap:
1609 with self.builtin_trap:
1612 info = self._object_find(oname)
1610 info = self._object_find(oname)
1613 if info.found:
1611 if info.found:
1614 return self.inspector._get_info(info.obj, oname, info=info,
1612 return self.inspector._get_info(info.obj, oname, info=info,
1615 detail_level=detail_level
1613 detail_level=detail_level
1616 )
1614 )
1617 else:
1615 else:
1618 raise KeyError(oname)
1616 raise KeyError(oname)
1619
1617
1620 #-------------------------------------------------------------------------
1618 #-------------------------------------------------------------------------
1621 # Things related to history management
1619 # Things related to history management
1622 #-------------------------------------------------------------------------
1620 #-------------------------------------------------------------------------
1623
1621
1624 def init_history(self):
1622 def init_history(self):
1625 """Sets up the command history, and starts regular autosaves."""
1623 """Sets up the command history, and starts regular autosaves."""
1626 self.history_manager = HistoryManager(shell=self, parent=self)
1624 self.history_manager = HistoryManager(shell=self, parent=self)
1627 self.configurables.append(self.history_manager)
1625 self.configurables.append(self.history_manager)
1628
1626
1629 #-------------------------------------------------------------------------
1627 #-------------------------------------------------------------------------
1630 # Things related to exception handling and tracebacks (not debugging)
1628 # Things related to exception handling and tracebacks (not debugging)
1631 #-------------------------------------------------------------------------
1629 #-------------------------------------------------------------------------
1632
1630
1633 debugger_cls = Pdb
1631 debugger_cls = Pdb
1634
1632
1635 def init_traceback_handlers(self, custom_exceptions):
1633 def init_traceback_handlers(self, custom_exceptions):
1636 # Syntax error handler.
1634 # Syntax error handler.
1637 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1635 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1638
1636
1639 # The interactive one is initialized with an offset, meaning we always
1637 # The interactive one is initialized with an offset, meaning we always
1640 # want to remove the topmost item in the traceback, which is our own
1638 # want to remove the topmost item in the traceback, which is our own
1641 # internal code. Valid modes: ['Plain','Context','Verbose']
1639 # internal code. Valid modes: ['Plain','Context','Verbose']
1642 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1640 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1643 color_scheme='NoColor',
1641 color_scheme='NoColor',
1644 tb_offset = 1,
1642 tb_offset = 1,
1645 check_cache=check_linecache_ipython,
1643 check_cache=check_linecache_ipython,
1646 debugger_cls=self.debugger_cls)
1644 debugger_cls=self.debugger_cls)
1647
1645
1648 # The instance will store a pointer to the system-wide exception hook,
1646 # The instance will store a pointer to the system-wide exception hook,
1649 # so that runtime code (such as magics) can access it. This is because
1647 # so that runtime code (such as magics) can access it. This is because
1650 # during the read-eval loop, it may get temporarily overwritten.
1648 # during the read-eval loop, it may get temporarily overwritten.
1651 self.sys_excepthook = sys.excepthook
1649 self.sys_excepthook = sys.excepthook
1652
1650
1653 # and add any custom exception handlers the user may have specified
1651 # and add any custom exception handlers the user may have specified
1654 self.set_custom_exc(*custom_exceptions)
1652 self.set_custom_exc(*custom_exceptions)
1655
1653
1656 # Set the exception mode
1654 # Set the exception mode
1657 self.InteractiveTB.set_mode(mode=self.xmode)
1655 self.InteractiveTB.set_mode(mode=self.xmode)
1658
1656
1659 def set_custom_exc(self, exc_tuple, handler):
1657 def set_custom_exc(self, exc_tuple, handler):
1660 """set_custom_exc(exc_tuple, handler)
1658 """set_custom_exc(exc_tuple, handler)
1661
1659
1662 Set a custom exception handler, which will be called if any of the
1660 Set a custom exception handler, which will be called if any of the
1663 exceptions in exc_tuple occur in the mainloop (specifically, in the
1661 exceptions in exc_tuple occur in the mainloop (specifically, in the
1664 run_code() method).
1662 run_code() method).
1665
1663
1666 Parameters
1664 Parameters
1667 ----------
1665 ----------
1668
1666
1669 exc_tuple : tuple of exception classes
1667 exc_tuple : tuple of exception classes
1670 A *tuple* of exception classes, for which to call the defined
1668 A *tuple* of exception classes, for which to call the defined
1671 handler. It is very important that you use a tuple, and NOT A
1669 handler. It is very important that you use a tuple, and NOT A
1672 LIST here, because of the way Python's except statement works. If
1670 LIST here, because of the way Python's except statement works. If
1673 you only want to trap a single exception, use a singleton tuple::
1671 you only want to trap a single exception, use a singleton tuple::
1674
1672
1675 exc_tuple == (MyCustomException,)
1673 exc_tuple == (MyCustomException,)
1676
1674
1677 handler : callable
1675 handler : callable
1678 handler must have the following signature::
1676 handler must have the following signature::
1679
1677
1680 def my_handler(self, etype, value, tb, tb_offset=None):
1678 def my_handler(self, etype, value, tb, tb_offset=None):
1681 ...
1679 ...
1682 return structured_traceback
1680 return structured_traceback
1683
1681
1684 Your handler must return a structured traceback (a list of strings),
1682 Your handler must return a structured traceback (a list of strings),
1685 or None.
1683 or None.
1686
1684
1687 This will be made into an instance method (via types.MethodType)
1685 This will be made into an instance method (via types.MethodType)
1688 of IPython itself, and it will be called if any of the exceptions
1686 of IPython itself, and it will be called if any of the exceptions
1689 listed in the exc_tuple are caught. If the handler is None, an
1687 listed in the exc_tuple are caught. If the handler is None, an
1690 internal basic one is used, which just prints basic info.
1688 internal basic one is used, which just prints basic info.
1691
1689
1692 To protect IPython from crashes, if your handler ever raises an
1690 To protect IPython from crashes, if your handler ever raises an
1693 exception or returns an invalid result, it will be immediately
1691 exception or returns an invalid result, it will be immediately
1694 disabled.
1692 disabled.
1695
1693
1696 WARNING: by putting in your own exception handler into IPython's main
1694 WARNING: by putting in your own exception handler into IPython's main
1697 execution loop, you run a very good chance of nasty crashes. This
1695 execution loop, you run a very good chance of nasty crashes. This
1698 facility should only be used if you really know what you are doing."""
1696 facility should only be used if you really know what you are doing."""
1699
1697
1700 assert type(exc_tuple)==type(()) , \
1698 assert type(exc_tuple)==type(()) , \
1701 "The custom exceptions must be given AS A TUPLE."
1699 "The custom exceptions must be given AS A TUPLE."
1702
1700
1703 def dummy_handler(self, etype, value, tb, tb_offset=None):
1701 def dummy_handler(self, etype, value, tb, tb_offset=None):
1704 print('*** Simple custom exception handler ***')
1702 print('*** Simple custom exception handler ***')
1705 print('Exception type :',etype)
1703 print('Exception type :',etype)
1706 print('Exception value:',value)
1704 print('Exception value:',value)
1707 print('Traceback :',tb)
1705 print('Traceback :',tb)
1708 #print 'Source code :','\n'.join(self.buffer)
1706 #print 'Source code :','\n'.join(self.buffer)
1709
1707
1710 def validate_stb(stb):
1708 def validate_stb(stb):
1711 """validate structured traceback return type
1709 """validate structured traceback return type
1712
1710
1713 return type of CustomTB *should* be a list of strings, but allow
1711 return type of CustomTB *should* be a list of strings, but allow
1714 single strings or None, which are harmless.
1712 single strings or None, which are harmless.
1715
1713
1716 This function will *always* return a list of strings,
1714 This function will *always* return a list of strings,
1717 and will raise a TypeError if stb is inappropriate.
1715 and will raise a TypeError if stb is inappropriate.
1718 """
1716 """
1719 msg = "CustomTB must return list of strings, not %r" % stb
1717 msg = "CustomTB must return list of strings, not %r" % stb
1720 if stb is None:
1718 if stb is None:
1721 return []
1719 return []
1722 elif isinstance(stb, string_types):
1720 elif isinstance(stb, string_types):
1723 return [stb]
1721 return [stb]
1724 elif not isinstance(stb, list):
1722 elif not isinstance(stb, list):
1725 raise TypeError(msg)
1723 raise TypeError(msg)
1726 # it's a list
1724 # it's a list
1727 for line in stb:
1725 for line in stb:
1728 # check every element
1726 # check every element
1729 if not isinstance(line, string_types):
1727 if not isinstance(line, string_types):
1730 raise TypeError(msg)
1728 raise TypeError(msg)
1731 return stb
1729 return stb
1732
1730
1733 if handler is None:
1731 if handler is None:
1734 wrapped = dummy_handler
1732 wrapped = dummy_handler
1735 else:
1733 else:
1736 def wrapped(self,etype,value,tb,tb_offset=None):
1734 def wrapped(self,etype,value,tb,tb_offset=None):
1737 """wrap CustomTB handler, to protect IPython from user code
1735 """wrap CustomTB handler, to protect IPython from user code
1738
1736
1739 This makes it harder (but not impossible) for custom exception
1737 This makes it harder (but not impossible) for custom exception
1740 handlers to crash IPython.
1738 handlers to crash IPython.
1741 """
1739 """
1742 try:
1740 try:
1743 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1741 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1744 return validate_stb(stb)
1742 return validate_stb(stb)
1745 except:
1743 except:
1746 # clear custom handler immediately
1744 # clear custom handler immediately
1747 self.set_custom_exc((), None)
1745 self.set_custom_exc((), None)
1748 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1746 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1749 # show the exception in handler first
1747 # show the exception in handler first
1750 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1748 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1751 print(self.InteractiveTB.stb2text(stb))
1749 print(self.InteractiveTB.stb2text(stb))
1752 print("The original exception:")
1750 print("The original exception:")
1753 stb = self.InteractiveTB.structured_traceback(
1751 stb = self.InteractiveTB.structured_traceback(
1754 (etype,value,tb), tb_offset=tb_offset
1752 (etype,value,tb), tb_offset=tb_offset
1755 )
1753 )
1756 return stb
1754 return stb
1757
1755
1758 self.CustomTB = types.MethodType(wrapped,self)
1756 self.CustomTB = types.MethodType(wrapped,self)
1759 self.custom_exceptions = exc_tuple
1757 self.custom_exceptions = exc_tuple
1760
1758
1761 def excepthook(self, etype, value, tb):
1759 def excepthook(self, etype, value, tb):
1762 """One more defense for GUI apps that call sys.excepthook.
1760 """One more defense for GUI apps that call sys.excepthook.
1763
1761
1764 GUI frameworks like wxPython trap exceptions and call
1762 GUI frameworks like wxPython trap exceptions and call
1765 sys.excepthook themselves. I guess this is a feature that
1763 sys.excepthook themselves. I guess this is a feature that
1766 enables them to keep running after exceptions that would
1764 enables them to keep running after exceptions that would
1767 otherwise kill their mainloop. This is a bother for IPython
1765 otherwise kill their mainloop. This is a bother for IPython
1768 which excepts to catch all of the program exceptions with a try:
1766 which excepts to catch all of the program exceptions with a try:
1769 except: statement.
1767 except: statement.
1770
1768
1771 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1769 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1772 any app directly invokes sys.excepthook, it will look to the user like
1770 any app directly invokes sys.excepthook, it will look to the user like
1773 IPython crashed. In order to work around this, we can disable the
1771 IPython crashed. In order to work around this, we can disable the
1774 CrashHandler and replace it with this excepthook instead, which prints a
1772 CrashHandler and replace it with this excepthook instead, which prints a
1775 regular traceback using our InteractiveTB. In this fashion, apps which
1773 regular traceback using our InteractiveTB. In this fashion, apps which
1776 call sys.excepthook will generate a regular-looking exception from
1774 call sys.excepthook will generate a regular-looking exception from
1777 IPython, and the CrashHandler will only be triggered by real IPython
1775 IPython, and the CrashHandler will only be triggered by real IPython
1778 crashes.
1776 crashes.
1779
1777
1780 This hook should be used sparingly, only in places which are not likely
1778 This hook should be used sparingly, only in places which are not likely
1781 to be true IPython errors.
1779 to be true IPython errors.
1782 """
1780 """
1783 self.showtraceback((etype, value, tb), tb_offset=0)
1781 self.showtraceback((etype, value, tb), tb_offset=0)
1784
1782
1785 def _get_exc_info(self, exc_tuple=None):
1783 def _get_exc_info(self, exc_tuple=None):
1786 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1784 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1787
1785
1788 Ensures sys.last_type,value,traceback hold the exc_info we found,
1786 Ensures sys.last_type,value,traceback hold the exc_info we found,
1789 from whichever source.
1787 from whichever source.
1790
1788
1791 raises ValueError if none of these contain any information
1789 raises ValueError if none of these contain any information
1792 """
1790 """
1793 if exc_tuple is None:
1791 if exc_tuple is None:
1794 etype, value, tb = sys.exc_info()
1792 etype, value, tb = sys.exc_info()
1795 else:
1793 else:
1796 etype, value, tb = exc_tuple
1794 etype, value, tb = exc_tuple
1797
1795
1798 if etype is None:
1796 if etype is None:
1799 if hasattr(sys, 'last_type'):
1797 if hasattr(sys, 'last_type'):
1800 etype, value, tb = sys.last_type, sys.last_value, \
1798 etype, value, tb = sys.last_type, sys.last_value, \
1801 sys.last_traceback
1799 sys.last_traceback
1802
1800
1803 if etype is None:
1801 if etype is None:
1804 raise ValueError("No exception to find")
1802 raise ValueError("No exception to find")
1805
1803
1806 # Now store the exception info in sys.last_type etc.
1804 # Now store the exception info in sys.last_type etc.
1807 # WARNING: these variables are somewhat deprecated and not
1805 # WARNING: these variables are somewhat deprecated and not
1808 # necessarily safe to use in a threaded environment, but tools
1806 # necessarily safe to use in a threaded environment, but tools
1809 # like pdb depend on their existence, so let's set them. If we
1807 # like pdb depend on their existence, so let's set them. If we
1810 # find problems in the field, we'll need to revisit their use.
1808 # find problems in the field, we'll need to revisit their use.
1811 sys.last_type = etype
1809 sys.last_type = etype
1812 sys.last_value = value
1810 sys.last_value = value
1813 sys.last_traceback = tb
1811 sys.last_traceback = tb
1814
1812
1815 return etype, value, tb
1813 return etype, value, tb
1816
1814
1817 def show_usage_error(self, exc):
1815 def show_usage_error(self, exc):
1818 """Show a short message for UsageErrors
1816 """Show a short message for UsageErrors
1819
1817
1820 These are special exceptions that shouldn't show a traceback.
1818 These are special exceptions that shouldn't show a traceback.
1821 """
1819 """
1822 print("UsageError: %s" % exc, file=sys.stderr)
1820 print("UsageError: %s" % exc, file=sys.stderr)
1823
1821
1824 def get_exception_only(self, exc_tuple=None):
1822 def get_exception_only(self, exc_tuple=None):
1825 """
1823 """
1826 Return as a string (ending with a newline) the exception that
1824 Return as a string (ending with a newline) the exception that
1827 just occurred, without any traceback.
1825 just occurred, without any traceback.
1828 """
1826 """
1829 etype, value, tb = self._get_exc_info(exc_tuple)
1827 etype, value, tb = self._get_exc_info(exc_tuple)
1830 msg = traceback.format_exception_only(etype, value)
1828 msg = traceback.format_exception_only(etype, value)
1831 return ''.join(msg)
1829 return ''.join(msg)
1832
1830
1833 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1831 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1834 exception_only=False):
1832 exception_only=False):
1835 """Display the exception that just occurred.
1833 """Display the exception that just occurred.
1836
1834
1837 If nothing is known about the exception, this is the method which
1835 If nothing is known about the exception, this is the method which
1838 should be used throughout the code for presenting user tracebacks,
1836 should be used throughout the code for presenting user tracebacks,
1839 rather than directly invoking the InteractiveTB object.
1837 rather than directly invoking the InteractiveTB object.
1840
1838
1841 A specific showsyntaxerror() also exists, but this method can take
1839 A specific showsyntaxerror() also exists, but this method can take
1842 care of calling it if needed, so unless you are explicitly catching a
1840 care of calling it if needed, so unless you are explicitly catching a
1843 SyntaxError exception, don't try to analyze the stack manually and
1841 SyntaxError exception, don't try to analyze the stack manually and
1844 simply call this method."""
1842 simply call this method."""
1845
1843
1846 try:
1844 try:
1847 try:
1845 try:
1848 etype, value, tb = self._get_exc_info(exc_tuple)
1846 etype, value, tb = self._get_exc_info(exc_tuple)
1849 except ValueError:
1847 except ValueError:
1850 print('No traceback available to show.', file=sys.stderr)
1848 print('No traceback available to show.', file=sys.stderr)
1851 return
1849 return
1852
1850
1853 if issubclass(etype, SyntaxError):
1851 if issubclass(etype, SyntaxError):
1854 # Though this won't be called by syntax errors in the input
1852 # Though this won't be called by syntax errors in the input
1855 # line, there may be SyntaxError cases with imported code.
1853 # line, there may be SyntaxError cases with imported code.
1856 self.showsyntaxerror(filename)
1854 self.showsyntaxerror(filename)
1857 elif etype is UsageError:
1855 elif etype is UsageError:
1858 self.show_usage_error(value)
1856 self.show_usage_error(value)
1859 else:
1857 else:
1860 if exception_only:
1858 if exception_only:
1861 stb = ['An exception has occurred, use %tb to see '
1859 stb = ['An exception has occurred, use %tb to see '
1862 'the full traceback.\n']
1860 'the full traceback.\n']
1863 stb.extend(self.InteractiveTB.get_exception_only(etype,
1861 stb.extend(self.InteractiveTB.get_exception_only(etype,
1864 value))
1862 value))
1865 else:
1863 else:
1866 try:
1864 try:
1867 # Exception classes can customise their traceback - we
1865 # Exception classes can customise their traceback - we
1868 # use this in IPython.parallel for exceptions occurring
1866 # use this in IPython.parallel for exceptions occurring
1869 # in the engines. This should return a list of strings.
1867 # in the engines. This should return a list of strings.
1870 stb = value._render_traceback_()
1868 stb = value._render_traceback_()
1871 except Exception:
1869 except Exception:
1872 stb = self.InteractiveTB.structured_traceback(etype,
1870 stb = self.InteractiveTB.structured_traceback(etype,
1873 value, tb, tb_offset=tb_offset)
1871 value, tb, tb_offset=tb_offset)
1874
1872
1875 self._showtraceback(etype, value, stb)
1873 self._showtraceback(etype, value, stb)
1876 if self.call_pdb:
1874 if self.call_pdb:
1877 # drop into debugger
1875 # drop into debugger
1878 self.debugger(force=True)
1876 self.debugger(force=True)
1879 return
1877 return
1880
1878
1881 # Actually show the traceback
1879 # Actually show the traceback
1882 self._showtraceback(etype, value, stb)
1880 self._showtraceback(etype, value, stb)
1883
1881
1884 except KeyboardInterrupt:
1882 except KeyboardInterrupt:
1885 print('\n' + self.get_exception_only(), file=sys.stderr)
1883 print('\n' + self.get_exception_only(), file=sys.stderr)
1886
1884
1887 def _showtraceback(self, etype, evalue, stb):
1885 def _showtraceback(self, etype, evalue, stb):
1888 """Actually show a traceback.
1886 """Actually show a traceback.
1889
1887
1890 Subclasses may override this method to put the traceback on a different
1888 Subclasses may override this method to put the traceback on a different
1891 place, like a side channel.
1889 place, like a side channel.
1892 """
1890 """
1893 print(self.InteractiveTB.stb2text(stb))
1891 print(self.InteractiveTB.stb2text(stb))
1894
1892
1895 def showsyntaxerror(self, filename=None):
1893 def showsyntaxerror(self, filename=None):
1896 """Display the syntax error that just occurred.
1894 """Display the syntax error that just occurred.
1897
1895
1898 This doesn't display a stack trace because there isn't one.
1896 This doesn't display a stack trace because there isn't one.
1899
1897
1900 If a filename is given, it is stuffed in the exception instead
1898 If a filename is given, it is stuffed in the exception instead
1901 of what was there before (because Python's parser always uses
1899 of what was there before (because Python's parser always uses
1902 "<string>" when reading from a string).
1900 "<string>" when reading from a string).
1903 """
1901 """
1904 etype, value, last_traceback = self._get_exc_info()
1902 etype, value, last_traceback = self._get_exc_info()
1905
1903
1906 if filename and issubclass(etype, SyntaxError):
1904 if filename and issubclass(etype, SyntaxError):
1907 try:
1905 try:
1908 value.filename = filename
1906 value.filename = filename
1909 except:
1907 except:
1910 # Not the format we expect; leave it alone
1908 # Not the format we expect; leave it alone
1911 pass
1909 pass
1912
1910
1913 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1911 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1914 self._showtraceback(etype, value, stb)
1912 self._showtraceback(etype, value, stb)
1915
1913
1916 # This is overridden in TerminalInteractiveShell to show a message about
1914 # This is overridden in TerminalInteractiveShell to show a message about
1917 # the %paste magic.
1915 # the %paste magic.
1918 def showindentationerror(self):
1916 def showindentationerror(self):
1919 """Called by run_cell when there's an IndentationError in code entered
1917 """Called by run_cell when there's an IndentationError in code entered
1920 at the prompt.
1918 at the prompt.
1921
1919
1922 This is overridden in TerminalInteractiveShell to show a message about
1920 This is overridden in TerminalInteractiveShell to show a message about
1923 the %paste magic."""
1921 the %paste magic."""
1924 self.showsyntaxerror()
1922 self.showsyntaxerror()
1925
1923
1926 #-------------------------------------------------------------------------
1924 #-------------------------------------------------------------------------
1927 # Things related to readline
1925 # Things related to readline
1928 #-------------------------------------------------------------------------
1926 #-------------------------------------------------------------------------
1929
1927
1930 def init_readline(self):
1928 def init_readline(self):
1931 """Moved to terminal subclass, here only to simplify the init logic."""
1929 """Moved to terminal subclass, here only to simplify the init logic."""
1932 self.readline = None
1930 self.readline = None
1933 # Set a number of methods that depend on readline to be no-op
1931 # Set a number of methods that depend on readline to be no-op
1934 self.readline_no_record = NoOpContext()
1932 self.readline_no_record = NoOpContext()
1935 self.set_readline_completer = no_op
1933 self.set_readline_completer = no_op
1936 self.set_custom_completer = no_op
1934 self.set_custom_completer = no_op
1937
1935
1938 @skip_doctest
1936 @skip_doctest
1939 def set_next_input(self, s, replace=False):
1937 def set_next_input(self, s, replace=False):
1940 """ Sets the 'default' input string for the next command line.
1938 """ Sets the 'default' input string for the next command line.
1941
1939
1942 Example::
1940 Example::
1943
1941
1944 In [1]: _ip.set_next_input("Hello Word")
1942 In [1]: _ip.set_next_input("Hello Word")
1945 In [2]: Hello Word_ # cursor is here
1943 In [2]: Hello Word_ # cursor is here
1946 """
1944 """
1947 self.rl_next_input = py3compat.cast_bytes_py2(s)
1945 self.rl_next_input = py3compat.cast_bytes_py2(s)
1948
1946
1949 def _indent_current_str(self):
1947 def _indent_current_str(self):
1950 """return the current level of indentation as a string"""
1948 """return the current level of indentation as a string"""
1951 return self.input_splitter.indent_spaces * ' '
1949 return self.input_splitter.indent_spaces * ' '
1952
1950
1953 #-------------------------------------------------------------------------
1951 #-------------------------------------------------------------------------
1954 # Things related to text completion
1952 # Things related to text completion
1955 #-------------------------------------------------------------------------
1953 #-------------------------------------------------------------------------
1956
1954
1957 def init_completer(self):
1955 def init_completer(self):
1958 """Initialize the completion machinery.
1956 """Initialize the completion machinery.
1959
1957
1960 This creates completion machinery that can be used by client code,
1958 This creates completion machinery that can be used by client code,
1961 either interactively in-process (typically triggered by the readline
1959 either interactively in-process (typically triggered by the readline
1962 library), programmatically (such as in test suites) or out-of-process
1960 library), programmatically (such as in test suites) or out-of-process
1963 (typically over the network by remote frontends).
1961 (typically over the network by remote frontends).
1964 """
1962 """
1965 from IPython.core.completer import IPCompleter
1963 from IPython.core.completer import IPCompleter
1966 from IPython.core.completerlib import (module_completer,
1964 from IPython.core.completerlib import (module_completer,
1967 magic_run_completer, cd_completer, reset_completer)
1965 magic_run_completer, cd_completer, reset_completer)
1968
1966
1969 self.Completer = IPCompleter(shell=self,
1967 self.Completer = IPCompleter(shell=self,
1970 namespace=self.user_ns,
1968 namespace=self.user_ns,
1971 global_namespace=self.user_global_ns,
1969 global_namespace=self.user_global_ns,
1972 use_readline=self.has_readline,
1970 use_readline=self.has_readline,
1973 parent=self,
1971 parent=self,
1974 )
1972 )
1975 self.configurables.append(self.Completer)
1973 self.configurables.append(self.Completer)
1976
1974
1977 # Add custom completers to the basic ones built into IPCompleter
1975 # Add custom completers to the basic ones built into IPCompleter
1978 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1976 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1979 self.strdispatchers['complete_command'] = sdisp
1977 self.strdispatchers['complete_command'] = sdisp
1980 self.Completer.custom_completers = sdisp
1978 self.Completer.custom_completers = sdisp
1981
1979
1982 self.set_hook('complete_command', module_completer, str_key = 'import')
1980 self.set_hook('complete_command', module_completer, str_key = 'import')
1983 self.set_hook('complete_command', module_completer, str_key = 'from')
1981 self.set_hook('complete_command', module_completer, str_key = 'from')
1984 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1982 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1985 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1983 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1986 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1984 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1987 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1985 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1988
1986
1989
1987
1990 @skip_doctest_py2
1988 @skip_doctest_py2
1991 def complete(self, text, line=None, cursor_pos=None):
1989 def complete(self, text, line=None, cursor_pos=None):
1992 """Return the completed text and a list of completions.
1990 """Return the completed text and a list of completions.
1993
1991
1994 Parameters
1992 Parameters
1995 ----------
1993 ----------
1996
1994
1997 text : string
1995 text : string
1998 A string of text to be completed on. It can be given as empty and
1996 A string of text to be completed on. It can be given as empty and
1999 instead a line/position pair are given. In this case, the
1997 instead a line/position pair are given. In this case, the
2000 completer itself will split the line like readline does.
1998 completer itself will split the line like readline does.
2001
1999
2002 line : string, optional
2000 line : string, optional
2003 The complete line that text is part of.
2001 The complete line that text is part of.
2004
2002
2005 cursor_pos : int, optional
2003 cursor_pos : int, optional
2006 The position of the cursor on the input line.
2004 The position of the cursor on the input line.
2007
2005
2008 Returns
2006 Returns
2009 -------
2007 -------
2010 text : string
2008 text : string
2011 The actual text that was completed.
2009 The actual text that was completed.
2012
2010
2013 matches : list
2011 matches : list
2014 A sorted list with all possible completions.
2012 A sorted list with all possible completions.
2015
2013
2016 The optional arguments allow the completion to take more context into
2014 The optional arguments allow the completion to take more context into
2017 account, and are part of the low-level completion API.
2015 account, and are part of the low-level completion API.
2018
2016
2019 This is a wrapper around the completion mechanism, similar to what
2017 This is a wrapper around the completion mechanism, similar to what
2020 readline does at the command line when the TAB key is hit. By
2018 readline does at the command line when the TAB key is hit. By
2021 exposing it as a method, it can be used by other non-readline
2019 exposing it as a method, it can be used by other non-readline
2022 environments (such as GUIs) for text completion.
2020 environments (such as GUIs) for text completion.
2023
2021
2024 Simple usage example:
2022 Simple usage example:
2025
2023
2026 In [1]: x = 'hello'
2024 In [1]: x = 'hello'
2027
2025
2028 In [2]: _ip.complete('x.l')
2026 In [2]: _ip.complete('x.l')
2029 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2027 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2030 """
2028 """
2031
2029
2032 # Inject names into __builtin__ so we can complete on the added names.
2030 # Inject names into __builtin__ so we can complete on the added names.
2033 with self.builtin_trap:
2031 with self.builtin_trap:
2034 return self.Completer.complete(text, line, cursor_pos)
2032 return self.Completer.complete(text, line, cursor_pos)
2035
2033
2036 def set_custom_completer(self, completer, pos=0):
2034 def set_custom_completer(self, completer, pos=0):
2037 """Adds a new custom completer function.
2035 """Adds a new custom completer function.
2038
2036
2039 The position argument (defaults to 0) is the index in the completers
2037 The position argument (defaults to 0) is the index in the completers
2040 list where you want the completer to be inserted."""
2038 list where you want the completer to be inserted."""
2041
2039
2042 newcomp = types.MethodType(completer,self.Completer)
2040 newcomp = types.MethodType(completer,self.Completer)
2043 self.Completer.matchers.insert(pos,newcomp)
2041 self.Completer.matchers.insert(pos,newcomp)
2044
2042
2045 def set_completer_frame(self, frame=None):
2043 def set_completer_frame(self, frame=None):
2046 """Set the frame of the completer."""
2044 """Set the frame of the completer."""
2047 if frame:
2045 if frame:
2048 self.Completer.namespace = frame.f_locals
2046 self.Completer.namespace = frame.f_locals
2049 self.Completer.global_namespace = frame.f_globals
2047 self.Completer.global_namespace = frame.f_globals
2050 else:
2048 else:
2051 self.Completer.namespace = self.user_ns
2049 self.Completer.namespace = self.user_ns
2052 self.Completer.global_namespace = self.user_global_ns
2050 self.Completer.global_namespace = self.user_global_ns
2053
2051
2054 #-------------------------------------------------------------------------
2052 #-------------------------------------------------------------------------
2055 # Things related to magics
2053 # Things related to magics
2056 #-------------------------------------------------------------------------
2054 #-------------------------------------------------------------------------
2057
2055
2058 def init_magics(self):
2056 def init_magics(self):
2059 from IPython.core import magics as m
2057 from IPython.core import magics as m
2060 self.magics_manager = magic.MagicsManager(shell=self,
2058 self.magics_manager = magic.MagicsManager(shell=self,
2061 parent=self,
2059 parent=self,
2062 user_magics=m.UserMagics(self))
2060 user_magics=m.UserMagics(self))
2063 self.configurables.append(self.magics_manager)
2061 self.configurables.append(self.magics_manager)
2064
2062
2065 # Expose as public API from the magics manager
2063 # Expose as public API from the magics manager
2066 self.register_magics = self.magics_manager.register
2064 self.register_magics = self.magics_manager.register
2067
2065
2068 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2066 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2069 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2067 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2070 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2068 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2071 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2069 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2072 )
2070 )
2073
2071
2074 # Register Magic Aliases
2072 # Register Magic Aliases
2075 mman = self.magics_manager
2073 mman = self.magics_manager
2076 # FIXME: magic aliases should be defined by the Magics classes
2074 # FIXME: magic aliases should be defined by the Magics classes
2077 # or in MagicsManager, not here
2075 # or in MagicsManager, not here
2078 mman.register_alias('ed', 'edit')
2076 mman.register_alias('ed', 'edit')
2079 mman.register_alias('hist', 'history')
2077 mman.register_alias('hist', 'history')
2080 mman.register_alias('rep', 'recall')
2078 mman.register_alias('rep', 'recall')
2081 mman.register_alias('SVG', 'svg', 'cell')
2079 mman.register_alias('SVG', 'svg', 'cell')
2082 mman.register_alias('HTML', 'html', 'cell')
2080 mman.register_alias('HTML', 'html', 'cell')
2083 mman.register_alias('file', 'writefile', 'cell')
2081 mman.register_alias('file', 'writefile', 'cell')
2084
2082
2085 # FIXME: Move the color initialization to the DisplayHook, which
2083 # FIXME: Move the color initialization to the DisplayHook, which
2086 # should be split into a prompt manager and displayhook. We probably
2084 # should be split into a prompt manager and displayhook. We probably
2087 # even need a centralize colors management object.
2085 # even need a centralize colors management object.
2088 self.magic('colors %s' % self.colors)
2086 self.magic('colors %s' % self.colors)
2089
2087
2090 # Defined here so that it's included in the documentation
2088 # Defined here so that it's included in the documentation
2091 @functools.wraps(magic.MagicsManager.register_function)
2089 @functools.wraps(magic.MagicsManager.register_function)
2092 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2090 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2093 self.magics_manager.register_function(func,
2091 self.magics_manager.register_function(func,
2094 magic_kind=magic_kind, magic_name=magic_name)
2092 magic_kind=magic_kind, magic_name=magic_name)
2095
2093
2096 def run_line_magic(self, magic_name, line):
2094 def run_line_magic(self, magic_name, line):
2097 """Execute the given line magic.
2095 """Execute the given line magic.
2098
2096
2099 Parameters
2097 Parameters
2100 ----------
2098 ----------
2101 magic_name : str
2099 magic_name : str
2102 Name of the desired magic function, without '%' prefix.
2100 Name of the desired magic function, without '%' prefix.
2103
2101
2104 line : str
2102 line : str
2105 The rest of the input line as a single string.
2103 The rest of the input line as a single string.
2106 """
2104 """
2107 fn = self.find_line_magic(magic_name)
2105 fn = self.find_line_magic(magic_name)
2108 if fn is None:
2106 if fn is None:
2109 cm = self.find_cell_magic(magic_name)
2107 cm = self.find_cell_magic(magic_name)
2110 etpl = "Line magic function `%%%s` not found%s."
2108 etpl = "Line magic function `%%%s` not found%s."
2111 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2109 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2112 'did you mean that instead?)' % magic_name )
2110 'did you mean that instead?)' % magic_name )
2113 error(etpl % (magic_name, extra))
2111 error(etpl % (magic_name, extra))
2114 else:
2112 else:
2115 # Note: this is the distance in the stack to the user's frame.
2113 # Note: this is the distance in the stack to the user's frame.
2116 # This will need to be updated if the internal calling logic gets
2114 # This will need to be updated if the internal calling logic gets
2117 # refactored, or else we'll be expanding the wrong variables.
2115 # refactored, or else we'll be expanding the wrong variables.
2118 stack_depth = 2
2116 stack_depth = 2
2119 magic_arg_s = self.var_expand(line, stack_depth)
2117 magic_arg_s = self.var_expand(line, stack_depth)
2120 # Put magic args in a list so we can call with f(*a) syntax
2118 # Put magic args in a list so we can call with f(*a) syntax
2121 args = [magic_arg_s]
2119 args = [magic_arg_s]
2122 kwargs = {}
2120 kwargs = {}
2123 # Grab local namespace if we need it:
2121 # Grab local namespace if we need it:
2124 if getattr(fn, "needs_local_scope", False):
2122 if getattr(fn, "needs_local_scope", False):
2125 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2123 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2126 with self.builtin_trap:
2124 with self.builtin_trap:
2127 result = fn(*args,**kwargs)
2125 result = fn(*args,**kwargs)
2128 return result
2126 return result
2129
2127
2130 def run_cell_magic(self, magic_name, line, cell):
2128 def run_cell_magic(self, magic_name, line, cell):
2131 """Execute the given cell magic.
2129 """Execute the given cell magic.
2132
2130
2133 Parameters
2131 Parameters
2134 ----------
2132 ----------
2135 magic_name : str
2133 magic_name : str
2136 Name of the desired magic function, without '%' prefix.
2134 Name of the desired magic function, without '%' prefix.
2137
2135
2138 line : str
2136 line : str
2139 The rest of the first input line as a single string.
2137 The rest of the first input line as a single string.
2140
2138
2141 cell : str
2139 cell : str
2142 The body of the cell as a (possibly multiline) string.
2140 The body of the cell as a (possibly multiline) string.
2143 """
2141 """
2144 fn = self.find_cell_magic(magic_name)
2142 fn = self.find_cell_magic(magic_name)
2145 if fn is None:
2143 if fn is None:
2146 lm = self.find_line_magic(magic_name)
2144 lm = self.find_line_magic(magic_name)
2147 etpl = "Cell magic `%%{0}` not found{1}."
2145 etpl = "Cell magic `%%{0}` not found{1}."
2148 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2146 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2149 'did you mean that instead?)'.format(magic_name))
2147 'did you mean that instead?)'.format(magic_name))
2150 error(etpl.format(magic_name, extra))
2148 error(etpl.format(magic_name, extra))
2151 elif cell == '':
2149 elif cell == '':
2152 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2150 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2153 if self.find_line_magic(magic_name) is not None:
2151 if self.find_line_magic(magic_name) is not None:
2154 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2152 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2155 raise UsageError(message)
2153 raise UsageError(message)
2156 else:
2154 else:
2157 # Note: this is the distance in the stack to the user's frame.
2155 # Note: this is the distance in the stack to the user's frame.
2158 # This will need to be updated if the internal calling logic gets
2156 # This will need to be updated if the internal calling logic gets
2159 # refactored, or else we'll be expanding the wrong variables.
2157 # refactored, or else we'll be expanding the wrong variables.
2160 stack_depth = 2
2158 stack_depth = 2
2161 magic_arg_s = self.var_expand(line, stack_depth)
2159 magic_arg_s = self.var_expand(line, stack_depth)
2162 with self.builtin_trap:
2160 with self.builtin_trap:
2163 result = fn(magic_arg_s, cell)
2161 result = fn(magic_arg_s, cell)
2164 return result
2162 return result
2165
2163
2166 def find_line_magic(self, magic_name):
2164 def find_line_magic(self, magic_name):
2167 """Find and return a line magic by name.
2165 """Find and return a line magic by name.
2168
2166
2169 Returns None if the magic isn't found."""
2167 Returns None if the magic isn't found."""
2170 return self.magics_manager.magics['line'].get(magic_name)
2168 return self.magics_manager.magics['line'].get(magic_name)
2171
2169
2172 def find_cell_magic(self, magic_name):
2170 def find_cell_magic(self, magic_name):
2173 """Find and return a cell magic by name.
2171 """Find and return a cell magic by name.
2174
2172
2175 Returns None if the magic isn't found."""
2173 Returns None if the magic isn't found."""
2176 return self.magics_manager.magics['cell'].get(magic_name)
2174 return self.magics_manager.magics['cell'].get(magic_name)
2177
2175
2178 def find_magic(self, magic_name, magic_kind='line'):
2176 def find_magic(self, magic_name, magic_kind='line'):
2179 """Find and return a magic of the given type by name.
2177 """Find and return a magic of the given type by name.
2180
2178
2181 Returns None if the magic isn't found."""
2179 Returns None if the magic isn't found."""
2182 return self.magics_manager.magics[magic_kind].get(magic_name)
2180 return self.magics_manager.magics[magic_kind].get(magic_name)
2183
2181
2184 def magic(self, arg_s):
2182 def magic(self, arg_s):
2185 """DEPRECATED. Use run_line_magic() instead.
2183 """DEPRECATED. Use run_line_magic() instead.
2186
2184
2187 Call a magic function by name.
2185 Call a magic function by name.
2188
2186
2189 Input: a string containing the name of the magic function to call and
2187 Input: a string containing the name of the magic function to call and
2190 any additional arguments to be passed to the magic.
2188 any additional arguments to be passed to the magic.
2191
2189
2192 magic('name -opt foo bar') is equivalent to typing at the ipython
2190 magic('name -opt foo bar') is equivalent to typing at the ipython
2193 prompt:
2191 prompt:
2194
2192
2195 In[1]: %name -opt foo bar
2193 In[1]: %name -opt foo bar
2196
2194
2197 To call a magic without arguments, simply use magic('name').
2195 To call a magic without arguments, simply use magic('name').
2198
2196
2199 This provides a proper Python function to call IPython's magics in any
2197 This provides a proper Python function to call IPython's magics in any
2200 valid Python code you can type at the interpreter, including loops and
2198 valid Python code you can type at the interpreter, including loops and
2201 compound statements.
2199 compound statements.
2202 """
2200 """
2203 # TODO: should we issue a loud deprecation warning here?
2201 # TODO: should we issue a loud deprecation warning here?
2204 magic_name, _, magic_arg_s = arg_s.partition(' ')
2202 magic_name, _, magic_arg_s = arg_s.partition(' ')
2205 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2203 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2206 return self.run_line_magic(magic_name, magic_arg_s)
2204 return self.run_line_magic(magic_name, magic_arg_s)
2207
2205
2208 #-------------------------------------------------------------------------
2206 #-------------------------------------------------------------------------
2209 # Things related to macros
2207 # Things related to macros
2210 #-------------------------------------------------------------------------
2208 #-------------------------------------------------------------------------
2211
2209
2212 def define_macro(self, name, themacro):
2210 def define_macro(self, name, themacro):
2213 """Define a new macro
2211 """Define a new macro
2214
2212
2215 Parameters
2213 Parameters
2216 ----------
2214 ----------
2217 name : str
2215 name : str
2218 The name of the macro.
2216 The name of the macro.
2219 themacro : str or Macro
2217 themacro : str or Macro
2220 The action to do upon invoking the macro. If a string, a new
2218 The action to do upon invoking the macro. If a string, a new
2221 Macro object is created by passing the string to it.
2219 Macro object is created by passing the string to it.
2222 """
2220 """
2223
2221
2224 from IPython.core import macro
2222 from IPython.core import macro
2225
2223
2226 if isinstance(themacro, string_types):
2224 if isinstance(themacro, string_types):
2227 themacro = macro.Macro(themacro)
2225 themacro = macro.Macro(themacro)
2228 if not isinstance(themacro, macro.Macro):
2226 if not isinstance(themacro, macro.Macro):
2229 raise ValueError('A macro must be a string or a Macro instance.')
2227 raise ValueError('A macro must be a string or a Macro instance.')
2230 self.user_ns[name] = themacro
2228 self.user_ns[name] = themacro
2231
2229
2232 #-------------------------------------------------------------------------
2230 #-------------------------------------------------------------------------
2233 # Things related to the running of system commands
2231 # Things related to the running of system commands
2234 #-------------------------------------------------------------------------
2232 #-------------------------------------------------------------------------
2235
2233
2236 def system_piped(self, cmd):
2234 def system_piped(self, cmd):
2237 """Call the given cmd in a subprocess, piping stdout/err
2235 """Call the given cmd in a subprocess, piping stdout/err
2238
2236
2239 Parameters
2237 Parameters
2240 ----------
2238 ----------
2241 cmd : str
2239 cmd : str
2242 Command to execute (can not end in '&', as background processes are
2240 Command to execute (can not end in '&', as background processes are
2243 not supported. Should not be a command that expects input
2241 not supported. Should not be a command that expects input
2244 other than simple text.
2242 other than simple text.
2245 """
2243 """
2246 if cmd.rstrip().endswith('&'):
2244 if cmd.rstrip().endswith('&'):
2247 # this is *far* from a rigorous test
2245 # this is *far* from a rigorous test
2248 # We do not support backgrounding processes because we either use
2246 # We do not support backgrounding processes because we either use
2249 # pexpect or pipes to read from. Users can always just call
2247 # pexpect or pipes to read from. Users can always just call
2250 # os.system() or use ip.system=ip.system_raw
2248 # os.system() or use ip.system=ip.system_raw
2251 # if they really want a background process.
2249 # if they really want a background process.
2252 raise OSError("Background processes not supported.")
2250 raise OSError("Background processes not supported.")
2253
2251
2254 # we explicitly do NOT return the subprocess status code, because
2252 # we explicitly do NOT return the subprocess status code, because
2255 # a non-None value would trigger :func:`sys.displayhook` calls.
2253 # a non-None value would trigger :func:`sys.displayhook` calls.
2256 # Instead, we store the exit_code in user_ns.
2254 # Instead, we store the exit_code in user_ns.
2257 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2255 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2258
2256
2259 def system_raw(self, cmd):
2257 def system_raw(self, cmd):
2260 """Call the given cmd in a subprocess using os.system on Windows or
2258 """Call the given cmd in a subprocess using os.system on Windows or
2261 subprocess.call using the system shell on other platforms.
2259 subprocess.call using the system shell on other platforms.
2262
2260
2263 Parameters
2261 Parameters
2264 ----------
2262 ----------
2265 cmd : str
2263 cmd : str
2266 Command to execute.
2264 Command to execute.
2267 """
2265 """
2268 cmd = self.var_expand(cmd, depth=1)
2266 cmd = self.var_expand(cmd, depth=1)
2269 # protect os.system from UNC paths on Windows, which it can't handle:
2267 # protect os.system from UNC paths on Windows, which it can't handle:
2270 if sys.platform == 'win32':
2268 if sys.platform == 'win32':
2271 from IPython.utils._process_win32 import AvoidUNCPath
2269 from IPython.utils._process_win32 import AvoidUNCPath
2272 with AvoidUNCPath() as path:
2270 with AvoidUNCPath() as path:
2273 if path is not None:
2271 if path is not None:
2274 cmd = '"pushd %s &&"%s' % (path, cmd)
2272 cmd = '"pushd %s &&"%s' % (path, cmd)
2275 cmd = py3compat.unicode_to_str(cmd)
2273 cmd = py3compat.unicode_to_str(cmd)
2276 try:
2274 try:
2277 ec = os.system(cmd)
2275 ec = os.system(cmd)
2278 except KeyboardInterrupt:
2276 except KeyboardInterrupt:
2279 print('\n' + self.get_exception_only(), file=sys.stderr)
2277 print('\n' + self.get_exception_only(), file=sys.stderr)
2280 ec = -2
2278 ec = -2
2281 else:
2279 else:
2282 cmd = py3compat.unicode_to_str(cmd)
2280 cmd = py3compat.unicode_to_str(cmd)
2283 # For posix the result of the subprocess.call() below is an exit
2281 # For posix the result of the subprocess.call() below is an exit
2284 # code, which by convention is zero for success, positive for
2282 # code, which by convention is zero for success, positive for
2285 # program failure. Exit codes above 128 are reserved for signals,
2283 # program failure. Exit codes above 128 are reserved for signals,
2286 # and the formula for converting a signal to an exit code is usually
2284 # and the formula for converting a signal to an exit code is usually
2287 # signal_number+128. To more easily differentiate between exit
2285 # signal_number+128. To more easily differentiate between exit
2288 # codes and signals, ipython uses negative numbers. For instance
2286 # codes and signals, ipython uses negative numbers. For instance
2289 # since control-c is signal 2 but exit code 130, ipython's
2287 # since control-c is signal 2 but exit code 130, ipython's
2290 # _exit_code variable will read -2. Note that some shells like
2288 # _exit_code variable will read -2. Note that some shells like
2291 # csh and fish don't follow sh/bash conventions for exit codes.
2289 # csh and fish don't follow sh/bash conventions for exit codes.
2292 executable = os.environ.get('SHELL', None)
2290 executable = os.environ.get('SHELL', None)
2293 try:
2291 try:
2294 # Use env shell instead of default /bin/sh
2292 # Use env shell instead of default /bin/sh
2295 ec = subprocess.call(cmd, shell=True, executable=executable)
2293 ec = subprocess.call(cmd, shell=True, executable=executable)
2296 except KeyboardInterrupt:
2294 except KeyboardInterrupt:
2297 # intercept control-C; a long traceback is not useful here
2295 # intercept control-C; a long traceback is not useful here
2298 print('\n' + self.get_exception_only(), file=sys.stderr)
2296 print('\n' + self.get_exception_only(), file=sys.stderr)
2299 ec = 130
2297 ec = 130
2300 if ec > 128:
2298 if ec > 128:
2301 ec = -(ec - 128)
2299 ec = -(ec - 128)
2302
2300
2303 # We explicitly do NOT return the subprocess status code, because
2301 # We explicitly do NOT return the subprocess status code, because
2304 # a non-None value would trigger :func:`sys.displayhook` calls.
2302 # a non-None value would trigger :func:`sys.displayhook` calls.
2305 # Instead, we store the exit_code in user_ns. Note the semantics
2303 # Instead, we store the exit_code in user_ns. Note the semantics
2306 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2304 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2307 # but raising SystemExit(_exit_code) will give status 254!
2305 # but raising SystemExit(_exit_code) will give status 254!
2308 self.user_ns['_exit_code'] = ec
2306 self.user_ns['_exit_code'] = ec
2309
2307
2310 # use piped system by default, because it is better behaved
2308 # use piped system by default, because it is better behaved
2311 system = system_piped
2309 system = system_piped
2312
2310
2313 def getoutput(self, cmd, split=True, depth=0):
2311 def getoutput(self, cmd, split=True, depth=0):
2314 """Get output (possibly including stderr) from a subprocess.
2312 """Get output (possibly including stderr) from a subprocess.
2315
2313
2316 Parameters
2314 Parameters
2317 ----------
2315 ----------
2318 cmd : str
2316 cmd : str
2319 Command to execute (can not end in '&', as background processes are
2317 Command to execute (can not end in '&', as background processes are
2320 not supported.
2318 not supported.
2321 split : bool, optional
2319 split : bool, optional
2322 If True, split the output into an IPython SList. Otherwise, an
2320 If True, split the output into an IPython SList. Otherwise, an
2323 IPython LSString is returned. These are objects similar to normal
2321 IPython LSString is returned. These are objects similar to normal
2324 lists and strings, with a few convenience attributes for easier
2322 lists and strings, with a few convenience attributes for easier
2325 manipulation of line-based output. You can use '?' on them for
2323 manipulation of line-based output. You can use '?' on them for
2326 details.
2324 details.
2327 depth : int, optional
2325 depth : int, optional
2328 How many frames above the caller are the local variables which should
2326 How many frames above the caller are the local variables which should
2329 be expanded in the command string? The default (0) assumes that the
2327 be expanded in the command string? The default (0) assumes that the
2330 expansion variables are in the stack frame calling this function.
2328 expansion variables are in the stack frame calling this function.
2331 """
2329 """
2332 if cmd.rstrip().endswith('&'):
2330 if cmd.rstrip().endswith('&'):
2333 # this is *far* from a rigorous test
2331 # this is *far* from a rigorous test
2334 raise OSError("Background processes not supported.")
2332 raise OSError("Background processes not supported.")
2335 out = getoutput(self.var_expand(cmd, depth=depth+1))
2333 out = getoutput(self.var_expand(cmd, depth=depth+1))
2336 if split:
2334 if split:
2337 out = SList(out.splitlines())
2335 out = SList(out.splitlines())
2338 else:
2336 else:
2339 out = LSString(out)
2337 out = LSString(out)
2340 return out
2338 return out
2341
2339
2342 #-------------------------------------------------------------------------
2340 #-------------------------------------------------------------------------
2343 # Things related to aliases
2341 # Things related to aliases
2344 #-------------------------------------------------------------------------
2342 #-------------------------------------------------------------------------
2345
2343
2346 def init_alias(self):
2344 def init_alias(self):
2347 self.alias_manager = AliasManager(shell=self, parent=self)
2345 self.alias_manager = AliasManager(shell=self, parent=self)
2348 self.configurables.append(self.alias_manager)
2346 self.configurables.append(self.alias_manager)
2349
2347
2350 #-------------------------------------------------------------------------
2348 #-------------------------------------------------------------------------
2351 # Things related to extensions
2349 # Things related to extensions
2352 #-------------------------------------------------------------------------
2350 #-------------------------------------------------------------------------
2353
2351
2354 def init_extension_manager(self):
2352 def init_extension_manager(self):
2355 self.extension_manager = ExtensionManager(shell=self, parent=self)
2353 self.extension_manager = ExtensionManager(shell=self, parent=self)
2356 self.configurables.append(self.extension_manager)
2354 self.configurables.append(self.extension_manager)
2357
2355
2358 #-------------------------------------------------------------------------
2356 #-------------------------------------------------------------------------
2359 # Things related to payloads
2357 # Things related to payloads
2360 #-------------------------------------------------------------------------
2358 #-------------------------------------------------------------------------
2361
2359
2362 def init_payload(self):
2360 def init_payload(self):
2363 self.payload_manager = PayloadManager(parent=self)
2361 self.payload_manager = PayloadManager(parent=self)
2364 self.configurables.append(self.payload_manager)
2362 self.configurables.append(self.payload_manager)
2365
2363
2366 #-------------------------------------------------------------------------
2364 #-------------------------------------------------------------------------
2367 # Things related to the prefilter
2365 # Things related to the prefilter
2368 #-------------------------------------------------------------------------
2366 #-------------------------------------------------------------------------
2369
2367
2370 def init_prefilter(self):
2368 def init_prefilter(self):
2371 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2369 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2372 self.configurables.append(self.prefilter_manager)
2370 self.configurables.append(self.prefilter_manager)
2373 # Ultimately this will be refactored in the new interpreter code, but
2371 # Ultimately this will be refactored in the new interpreter code, but
2374 # for now, we should expose the main prefilter method (there's legacy
2372 # for now, we should expose the main prefilter method (there's legacy
2375 # code out there that may rely on this).
2373 # code out there that may rely on this).
2376 self.prefilter = self.prefilter_manager.prefilter_lines
2374 self.prefilter = self.prefilter_manager.prefilter_lines
2377
2375
2378 def auto_rewrite_input(self, cmd):
2376 def auto_rewrite_input(self, cmd):
2379 """Print to the screen the rewritten form of the user's command.
2377 """Print to the screen the rewritten form of the user's command.
2380
2378
2381 This shows visual feedback by rewriting input lines that cause
2379 This shows visual feedback by rewriting input lines that cause
2382 automatic calling to kick in, like::
2380 automatic calling to kick in, like::
2383
2381
2384 /f x
2382 /f x
2385
2383
2386 into::
2384 into::
2387
2385
2388 ------> f(x)
2386 ------> f(x)
2389
2387
2390 after the user's input prompt. This helps the user understand that the
2388 after the user's input prompt. This helps the user understand that the
2391 input line was transformed automatically by IPython.
2389 input line was transformed automatically by IPython.
2392 """
2390 """
2393 if not self.show_rewritten_input:
2391 if not self.show_rewritten_input:
2394 return
2392 return
2395
2393
2396 # This is overridden in TerminalInteractiveShell to use fancy prompts
2394 # This is overridden in TerminalInteractiveShell to use fancy prompts
2397 print("------> " + cmd)
2395 print("------> " + cmd)
2398
2396
2399 #-------------------------------------------------------------------------
2397 #-------------------------------------------------------------------------
2400 # Things related to extracting values/expressions from kernel and user_ns
2398 # Things related to extracting values/expressions from kernel and user_ns
2401 #-------------------------------------------------------------------------
2399 #-------------------------------------------------------------------------
2402
2400
2403 def _user_obj_error(self):
2401 def _user_obj_error(self):
2404 """return simple exception dict
2402 """return simple exception dict
2405
2403
2406 for use in user_expressions
2404 for use in user_expressions
2407 """
2405 """
2408
2406
2409 etype, evalue, tb = self._get_exc_info()
2407 etype, evalue, tb = self._get_exc_info()
2410 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2408 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2411
2409
2412 exc_info = {
2410 exc_info = {
2413 u'status' : 'error',
2411 u'status' : 'error',
2414 u'traceback' : stb,
2412 u'traceback' : stb,
2415 u'ename' : unicode_type(etype.__name__),
2413 u'ename' : unicode_type(etype.__name__),
2416 u'evalue' : py3compat.safe_unicode(evalue),
2414 u'evalue' : py3compat.safe_unicode(evalue),
2417 }
2415 }
2418
2416
2419 return exc_info
2417 return exc_info
2420
2418
2421 def _format_user_obj(self, obj):
2419 def _format_user_obj(self, obj):
2422 """format a user object to display dict
2420 """format a user object to display dict
2423
2421
2424 for use in user_expressions
2422 for use in user_expressions
2425 """
2423 """
2426
2424
2427 data, md = self.display_formatter.format(obj)
2425 data, md = self.display_formatter.format(obj)
2428 value = {
2426 value = {
2429 'status' : 'ok',
2427 'status' : 'ok',
2430 'data' : data,
2428 'data' : data,
2431 'metadata' : md,
2429 'metadata' : md,
2432 }
2430 }
2433 return value
2431 return value
2434
2432
2435 def user_expressions(self, expressions):
2433 def user_expressions(self, expressions):
2436 """Evaluate a dict of expressions in the user's namespace.
2434 """Evaluate a dict of expressions in the user's namespace.
2437
2435
2438 Parameters
2436 Parameters
2439 ----------
2437 ----------
2440 expressions : dict
2438 expressions : dict
2441 A dict with string keys and string values. The expression values
2439 A dict with string keys and string values. The expression values
2442 should be valid Python expressions, each of which will be evaluated
2440 should be valid Python expressions, each of which will be evaluated
2443 in the user namespace.
2441 in the user namespace.
2444
2442
2445 Returns
2443 Returns
2446 -------
2444 -------
2447 A dict, keyed like the input expressions dict, with the rich mime-typed
2445 A dict, keyed like the input expressions dict, with the rich mime-typed
2448 display_data of each value.
2446 display_data of each value.
2449 """
2447 """
2450 out = {}
2448 out = {}
2451 user_ns = self.user_ns
2449 user_ns = self.user_ns
2452 global_ns = self.user_global_ns
2450 global_ns = self.user_global_ns
2453
2451
2454 for key, expr in iteritems(expressions):
2452 for key, expr in iteritems(expressions):
2455 try:
2453 try:
2456 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2454 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2457 except:
2455 except:
2458 value = self._user_obj_error()
2456 value = self._user_obj_error()
2459 out[key] = value
2457 out[key] = value
2460 return out
2458 return out
2461
2459
2462 #-------------------------------------------------------------------------
2460 #-------------------------------------------------------------------------
2463 # Things related to the running of code
2461 # Things related to the running of code
2464 #-------------------------------------------------------------------------
2462 #-------------------------------------------------------------------------
2465
2463
2466 def ex(self, cmd):
2464 def ex(self, cmd):
2467 """Execute a normal python statement in user namespace."""
2465 """Execute a normal python statement in user namespace."""
2468 with self.builtin_trap:
2466 with self.builtin_trap:
2469 exec(cmd, self.user_global_ns, self.user_ns)
2467 exec(cmd, self.user_global_ns, self.user_ns)
2470
2468
2471 def ev(self, expr):
2469 def ev(self, expr):
2472 """Evaluate python expression expr in user namespace.
2470 """Evaluate python expression expr in user namespace.
2473
2471
2474 Returns the result of evaluation
2472 Returns the result of evaluation
2475 """
2473 """
2476 with self.builtin_trap:
2474 with self.builtin_trap:
2477 return eval(expr, self.user_global_ns, self.user_ns)
2475 return eval(expr, self.user_global_ns, self.user_ns)
2478
2476
2479 def safe_execfile(self, fname, *where, **kw):
2477 def safe_execfile(self, fname, *where, **kw):
2480 """A safe version of the builtin execfile().
2478 """A safe version of the builtin execfile().
2481
2479
2482 This version will never throw an exception, but instead print
2480 This version will never throw an exception, but instead print
2483 helpful error messages to the screen. This only works on pure
2481 helpful error messages to the screen. This only works on pure
2484 Python files with the .py extension.
2482 Python files with the .py extension.
2485
2483
2486 Parameters
2484 Parameters
2487 ----------
2485 ----------
2488 fname : string
2486 fname : string
2489 The name of the file to be executed.
2487 The name of the file to be executed.
2490 where : tuple
2488 where : tuple
2491 One or two namespaces, passed to execfile() as (globals,locals).
2489 One or two namespaces, passed to execfile() as (globals,locals).
2492 If only one is given, it is passed as both.
2490 If only one is given, it is passed as both.
2493 exit_ignore : bool (False)
2491 exit_ignore : bool (False)
2494 If True, then silence SystemExit for non-zero status (it is always
2492 If True, then silence SystemExit for non-zero status (it is always
2495 silenced for zero status, as it is so common).
2493 silenced for zero status, as it is so common).
2496 raise_exceptions : bool (False)
2494 raise_exceptions : bool (False)
2497 If True raise exceptions everywhere. Meant for testing.
2495 If True raise exceptions everywhere. Meant for testing.
2498 shell_futures : bool (False)
2496 shell_futures : bool (False)
2499 If True, the code will share future statements with the interactive
2497 If True, the code will share future statements with the interactive
2500 shell. It will both be affected by previous __future__ imports, and
2498 shell. It will both be affected by previous __future__ imports, and
2501 any __future__ imports in the code will affect the shell. If False,
2499 any __future__ imports in the code will affect the shell. If False,
2502 __future__ imports are not shared in either direction.
2500 __future__ imports are not shared in either direction.
2503
2501
2504 """
2502 """
2505 kw.setdefault('exit_ignore', False)
2503 kw.setdefault('exit_ignore', False)
2506 kw.setdefault('raise_exceptions', False)
2504 kw.setdefault('raise_exceptions', False)
2507 kw.setdefault('shell_futures', False)
2505 kw.setdefault('shell_futures', False)
2508
2506
2509 fname = os.path.abspath(os.path.expanduser(fname))
2507 fname = os.path.abspath(os.path.expanduser(fname))
2510
2508
2511 # Make sure we can open the file
2509 # Make sure we can open the file
2512 try:
2510 try:
2513 with open(fname):
2511 with open(fname):
2514 pass
2512 pass
2515 except:
2513 except:
2516 warn('Could not open file <%s> for safe execution.' % fname)
2514 warn('Could not open file <%s> for safe execution.' % fname)
2517 return
2515 return
2518
2516
2519 # Find things also in current directory. This is needed to mimic the
2517 # Find things also in current directory. This is needed to mimic the
2520 # behavior of running a script from the system command line, where
2518 # behavior of running a script from the system command line, where
2521 # Python inserts the script's directory into sys.path
2519 # Python inserts the script's directory into sys.path
2522 dname = os.path.dirname(fname)
2520 dname = os.path.dirname(fname)
2523
2521
2524 with prepended_to_syspath(dname):
2522 with prepended_to_syspath(dname):
2525 try:
2523 try:
2526 glob, loc = (where + (None, ))[:2]
2524 glob, loc = (where + (None, ))[:2]
2527 py3compat.execfile(
2525 py3compat.execfile(
2528 fname, glob, loc,
2526 fname, glob, loc,
2529 self.compile if kw['shell_futures'] else None)
2527 self.compile if kw['shell_futures'] else None)
2530 except SystemExit as status:
2528 except SystemExit as status:
2531 # If the call was made with 0 or None exit status (sys.exit(0)
2529 # If the call was made with 0 or None exit status (sys.exit(0)
2532 # or sys.exit() ), don't bother showing a traceback, as both of
2530 # or sys.exit() ), don't bother showing a traceback, as both of
2533 # these are considered normal by the OS:
2531 # these are considered normal by the OS:
2534 # > python -c'import sys;sys.exit(0)'; echo $?
2532 # > python -c'import sys;sys.exit(0)'; echo $?
2535 # 0
2533 # 0
2536 # > python -c'import sys;sys.exit()'; echo $?
2534 # > python -c'import sys;sys.exit()'; echo $?
2537 # 0
2535 # 0
2538 # For other exit status, we show the exception unless
2536 # For other exit status, we show the exception unless
2539 # explicitly silenced, but only in short form.
2537 # explicitly silenced, but only in short form.
2540 if status.code:
2538 if status.code:
2541 if kw['raise_exceptions']:
2539 if kw['raise_exceptions']:
2542 raise
2540 raise
2543 if not kw['exit_ignore']:
2541 if not kw['exit_ignore']:
2544 self.showtraceback(exception_only=True)
2542 self.showtraceback(exception_only=True)
2545 except:
2543 except:
2546 if kw['raise_exceptions']:
2544 if kw['raise_exceptions']:
2547 raise
2545 raise
2548 # tb offset is 2 because we wrap execfile
2546 # tb offset is 2 because we wrap execfile
2549 self.showtraceback(tb_offset=2)
2547 self.showtraceback(tb_offset=2)
2550
2548
2551 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2549 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2552 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2550 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2553
2551
2554 Parameters
2552 Parameters
2555 ----------
2553 ----------
2556 fname : str
2554 fname : str
2557 The name of the file to execute. The filename must have a
2555 The name of the file to execute. The filename must have a
2558 .ipy or .ipynb extension.
2556 .ipy or .ipynb extension.
2559 shell_futures : bool (False)
2557 shell_futures : bool (False)
2560 If True, the code will share future statements with the interactive
2558 If True, the code will share future statements with the interactive
2561 shell. It will both be affected by previous __future__ imports, and
2559 shell. It will both be affected by previous __future__ imports, and
2562 any __future__ imports in the code will affect the shell. If False,
2560 any __future__ imports in the code will affect the shell. If False,
2563 __future__ imports are not shared in either direction.
2561 __future__ imports are not shared in either direction.
2564 raise_exceptions : bool (False)
2562 raise_exceptions : bool (False)
2565 If True raise exceptions everywhere. Meant for testing.
2563 If True raise exceptions everywhere. Meant for testing.
2566 """
2564 """
2567 fname = os.path.abspath(os.path.expanduser(fname))
2565 fname = os.path.abspath(os.path.expanduser(fname))
2568
2566
2569 # Make sure we can open the file
2567 # Make sure we can open the file
2570 try:
2568 try:
2571 with open(fname):
2569 with open(fname):
2572 pass
2570 pass
2573 except:
2571 except:
2574 warn('Could not open file <%s> for safe execution.' % fname)
2572 warn('Could not open file <%s> for safe execution.' % fname)
2575 return
2573 return
2576
2574
2577 # Find things also in current directory. This is needed to mimic the
2575 # Find things also in current directory. This is needed to mimic the
2578 # behavior of running a script from the system command line, where
2576 # behavior of running a script from the system command line, where
2579 # Python inserts the script's directory into sys.path
2577 # Python inserts the script's directory into sys.path
2580 dname = os.path.dirname(fname)
2578 dname = os.path.dirname(fname)
2581
2579
2582 def get_cells():
2580 def get_cells():
2583 """generator for sequence of code blocks to run"""
2581 """generator for sequence of code blocks to run"""
2584 if fname.endswith('.ipynb'):
2582 if fname.endswith('.ipynb'):
2585 from nbformat import read
2583 from nbformat import read
2586 with io_open(fname) as f:
2584 with io_open(fname) as f:
2587 nb = read(f, as_version=4)
2585 nb = read(f, as_version=4)
2588 if not nb.cells:
2586 if not nb.cells:
2589 return
2587 return
2590 for cell in nb.cells:
2588 for cell in nb.cells:
2591 if cell.cell_type == 'code':
2589 if cell.cell_type == 'code':
2592 yield cell.source
2590 yield cell.source
2593 else:
2591 else:
2594 with open(fname) as f:
2592 with open(fname) as f:
2595 yield f.read()
2593 yield f.read()
2596
2594
2597 with prepended_to_syspath(dname):
2595 with prepended_to_syspath(dname):
2598 try:
2596 try:
2599 for cell in get_cells():
2597 for cell in get_cells():
2600 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2598 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2601 if raise_exceptions:
2599 if raise_exceptions:
2602 result.raise_error()
2600 result.raise_error()
2603 elif not result.success:
2601 elif not result.success:
2604 break
2602 break
2605 except:
2603 except:
2606 if raise_exceptions:
2604 if raise_exceptions:
2607 raise
2605 raise
2608 self.showtraceback()
2606 self.showtraceback()
2609 warn('Unknown failure executing file: <%s>' % fname)
2607 warn('Unknown failure executing file: <%s>' % fname)
2610
2608
2611 def safe_run_module(self, mod_name, where):
2609 def safe_run_module(self, mod_name, where):
2612 """A safe version of runpy.run_module().
2610 """A safe version of runpy.run_module().
2613
2611
2614 This version will never throw an exception, but instead print
2612 This version will never throw an exception, but instead print
2615 helpful error messages to the screen.
2613 helpful error messages to the screen.
2616
2614
2617 `SystemExit` exceptions with status code 0 or None are ignored.
2615 `SystemExit` exceptions with status code 0 or None are ignored.
2618
2616
2619 Parameters
2617 Parameters
2620 ----------
2618 ----------
2621 mod_name : string
2619 mod_name : string
2622 The name of the module to be executed.
2620 The name of the module to be executed.
2623 where : dict
2621 where : dict
2624 The globals namespace.
2622 The globals namespace.
2625 """
2623 """
2626 try:
2624 try:
2627 try:
2625 try:
2628 where.update(
2626 where.update(
2629 runpy.run_module(str(mod_name), run_name="__main__",
2627 runpy.run_module(str(mod_name), run_name="__main__",
2630 alter_sys=True)
2628 alter_sys=True)
2631 )
2629 )
2632 except SystemExit as status:
2630 except SystemExit as status:
2633 if status.code:
2631 if status.code:
2634 raise
2632 raise
2635 except:
2633 except:
2636 self.showtraceback()
2634 self.showtraceback()
2637 warn('Unknown failure executing module: <%s>' % mod_name)
2635 warn('Unknown failure executing module: <%s>' % mod_name)
2638
2636
2639 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2637 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2640 """Run a complete IPython cell.
2638 """Run a complete IPython cell.
2641
2639
2642 Parameters
2640 Parameters
2643 ----------
2641 ----------
2644 raw_cell : str
2642 raw_cell : str
2645 The code (including IPython code such as %magic functions) to run.
2643 The code (including IPython code such as %magic functions) to run.
2646 store_history : bool
2644 store_history : bool
2647 If True, the raw and translated cell will be stored in IPython's
2645 If True, the raw and translated cell will be stored in IPython's
2648 history. For user code calling back into IPython's machinery, this
2646 history. For user code calling back into IPython's machinery, this
2649 should be set to False.
2647 should be set to False.
2650 silent : bool
2648 silent : bool
2651 If True, avoid side-effects, such as implicit displayhooks and
2649 If True, avoid side-effects, such as implicit displayhooks and
2652 and logging. silent=True forces store_history=False.
2650 and logging. silent=True forces store_history=False.
2653 shell_futures : bool
2651 shell_futures : bool
2654 If True, the code will share future statements with the interactive
2652 If True, the code will share future statements with the interactive
2655 shell. It will both be affected by previous __future__ imports, and
2653 shell. It will both be affected by previous __future__ imports, and
2656 any __future__ imports in the code will affect the shell. If False,
2654 any __future__ imports in the code will affect the shell. If False,
2657 __future__ imports are not shared in either direction.
2655 __future__ imports are not shared in either direction.
2658
2656
2659 Returns
2657 Returns
2660 -------
2658 -------
2661 result : :class:`ExecutionResult`
2659 result : :class:`ExecutionResult`
2662 """
2660 """
2663 result = ExecutionResult()
2661 result = ExecutionResult()
2664
2662
2665 if (not raw_cell) or raw_cell.isspace():
2663 if (not raw_cell) or raw_cell.isspace():
2666 self.last_execution_succeeded = True
2664 self.last_execution_succeeded = True
2667 return result
2665 return result
2668
2666
2669 if silent:
2667 if silent:
2670 store_history = False
2668 store_history = False
2671
2669
2672 if store_history:
2670 if store_history:
2673 result.execution_count = self.execution_count
2671 result.execution_count = self.execution_count
2674
2672
2675 def error_before_exec(value):
2673 def error_before_exec(value):
2676 result.error_before_exec = value
2674 result.error_before_exec = value
2677 self.last_execution_succeeded = False
2675 self.last_execution_succeeded = False
2678 return result
2676 return result
2679
2677
2680 self.events.trigger('pre_execute')
2678 self.events.trigger('pre_execute')
2681 if not silent:
2679 if not silent:
2682 self.events.trigger('pre_run_cell')
2680 self.events.trigger('pre_run_cell')
2683
2681
2684 # If any of our input transformation (input_transformer_manager or
2682 # If any of our input transformation (input_transformer_manager or
2685 # prefilter_manager) raises an exception, we store it in this variable
2683 # prefilter_manager) raises an exception, we store it in this variable
2686 # so that we can display the error after logging the input and storing
2684 # so that we can display the error after logging the input and storing
2687 # it in the history.
2685 # it in the history.
2688 preprocessing_exc_tuple = None
2686 preprocessing_exc_tuple = None
2689 try:
2687 try:
2690 # Static input transformations
2688 # Static input transformations
2691 cell = self.input_transformer_manager.transform_cell(raw_cell)
2689 cell = self.input_transformer_manager.transform_cell(raw_cell)
2692 except SyntaxError:
2690 except SyntaxError:
2693 preprocessing_exc_tuple = sys.exc_info()
2691 preprocessing_exc_tuple = sys.exc_info()
2694 cell = raw_cell # cell has to exist so it can be stored/logged
2692 cell = raw_cell # cell has to exist so it can be stored/logged
2695 else:
2693 else:
2696 if len(cell.splitlines()) == 1:
2694 if len(cell.splitlines()) == 1:
2697 # Dynamic transformations - only applied for single line commands
2695 # Dynamic transformations - only applied for single line commands
2698 with self.builtin_trap:
2696 with self.builtin_trap:
2699 try:
2697 try:
2700 # use prefilter_lines to handle trailing newlines
2698 # use prefilter_lines to handle trailing newlines
2701 # restore trailing newline for ast.parse
2699 # restore trailing newline for ast.parse
2702 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2700 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2703 except Exception:
2701 except Exception:
2704 # don't allow prefilter errors to crash IPython
2702 # don't allow prefilter errors to crash IPython
2705 preprocessing_exc_tuple = sys.exc_info()
2703 preprocessing_exc_tuple = sys.exc_info()
2706
2704
2707 # Store raw and processed history
2705 # Store raw and processed history
2708 if store_history:
2706 if store_history:
2709 self.history_manager.store_inputs(self.execution_count,
2707 self.history_manager.store_inputs(self.execution_count,
2710 cell, raw_cell)
2708 cell, raw_cell)
2711 if not silent:
2709 if not silent:
2712 self.logger.log(cell, raw_cell)
2710 self.logger.log(cell, raw_cell)
2713
2711
2714 # Display the exception if input processing failed.
2712 # Display the exception if input processing failed.
2715 if preprocessing_exc_tuple is not None:
2713 if preprocessing_exc_tuple is not None:
2716 self.showtraceback(preprocessing_exc_tuple)
2714 self.showtraceback(preprocessing_exc_tuple)
2717 if store_history:
2715 if store_history:
2718 self.execution_count += 1
2716 self.execution_count += 1
2719 return error_before_exec(preprocessing_exc_tuple[2])
2717 return error_before_exec(preprocessing_exc_tuple[2])
2720
2718
2721 # Our own compiler remembers the __future__ environment. If we want to
2719 # Our own compiler remembers the __future__ environment. If we want to
2722 # run code with a separate __future__ environment, use the default
2720 # run code with a separate __future__ environment, use the default
2723 # compiler
2721 # compiler
2724 compiler = self.compile if shell_futures else CachingCompiler()
2722 compiler = self.compile if shell_futures else CachingCompiler()
2725
2723
2726 with self.builtin_trap:
2724 with self.builtin_trap:
2727 cell_name = self.compile.cache(cell, self.execution_count)
2725 cell_name = self.compile.cache(cell, self.execution_count)
2728
2726
2729 with self.display_trap:
2727 with self.display_trap:
2730 # Compile to bytecode
2728 # Compile to bytecode
2731 try:
2729 try:
2732 code_ast = compiler.ast_parse(cell, filename=cell_name)
2730 code_ast = compiler.ast_parse(cell, filename=cell_name)
2733 except self.custom_exceptions as e:
2731 except self.custom_exceptions as e:
2734 etype, value, tb = sys.exc_info()
2732 etype, value, tb = sys.exc_info()
2735 self.CustomTB(etype, value, tb)
2733 self.CustomTB(etype, value, tb)
2736 return error_before_exec(e)
2734 return error_before_exec(e)
2737 except IndentationError as e:
2735 except IndentationError as e:
2738 self.showindentationerror()
2736 self.showindentationerror()
2739 if store_history:
2737 if store_history:
2740 self.execution_count += 1
2738 self.execution_count += 1
2741 return error_before_exec(e)
2739 return error_before_exec(e)
2742 except (OverflowError, SyntaxError, ValueError, TypeError,
2740 except (OverflowError, SyntaxError, ValueError, TypeError,
2743 MemoryError) as e:
2741 MemoryError) as e:
2744 self.showsyntaxerror()
2742 self.showsyntaxerror()
2745 if store_history:
2743 if store_history:
2746 self.execution_count += 1
2744 self.execution_count += 1
2747 return error_before_exec(e)
2745 return error_before_exec(e)
2748
2746
2749 # Apply AST transformations
2747 # Apply AST transformations
2750 try:
2748 try:
2751 code_ast = self.transform_ast(code_ast)
2749 code_ast = self.transform_ast(code_ast)
2752 except InputRejected as e:
2750 except InputRejected as e:
2753 self.showtraceback()
2751 self.showtraceback()
2754 if store_history:
2752 if store_history:
2755 self.execution_count += 1
2753 self.execution_count += 1
2756 return error_before_exec(e)
2754 return error_before_exec(e)
2757
2755
2758 # Give the displayhook a reference to our ExecutionResult so it
2756 # Give the displayhook a reference to our ExecutionResult so it
2759 # can fill in the output value.
2757 # can fill in the output value.
2760 self.displayhook.exec_result = result
2758 self.displayhook.exec_result = result
2761
2759
2762 # Execute the user code
2760 # Execute the user code
2763 interactivity = "none" if silent else self.ast_node_interactivity
2761 interactivity = "none" if silent else self.ast_node_interactivity
2764 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2762 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2765 interactivity=interactivity, compiler=compiler, result=result)
2763 interactivity=interactivity, compiler=compiler, result=result)
2766
2764
2767 self.last_execution_succeeded = not has_raised
2765 self.last_execution_succeeded = not has_raised
2768
2766
2769 # Reset this so later displayed values do not modify the
2767 # Reset this so later displayed values do not modify the
2770 # ExecutionResult
2768 # ExecutionResult
2771 self.displayhook.exec_result = None
2769 self.displayhook.exec_result = None
2772
2770
2773 self.events.trigger('post_execute')
2771 self.events.trigger('post_execute')
2774 if not silent:
2772 if not silent:
2775 self.events.trigger('post_run_cell')
2773 self.events.trigger('post_run_cell')
2776
2774
2777 if store_history:
2775 if store_history:
2778 # Write output to the database. Does nothing unless
2776 # Write output to the database. Does nothing unless
2779 # history output logging is enabled.
2777 # history output logging is enabled.
2780 self.history_manager.store_output(self.execution_count)
2778 self.history_manager.store_output(self.execution_count)
2781 # Each cell is a *single* input, regardless of how many lines it has
2779 # Each cell is a *single* input, regardless of how many lines it has
2782 self.execution_count += 1
2780 self.execution_count += 1
2783
2781
2784 return result
2782 return result
2785
2783
2786 def transform_ast(self, node):
2784 def transform_ast(self, node):
2787 """Apply the AST transformations from self.ast_transformers
2785 """Apply the AST transformations from self.ast_transformers
2788
2786
2789 Parameters
2787 Parameters
2790 ----------
2788 ----------
2791 node : ast.Node
2789 node : ast.Node
2792 The root node to be transformed. Typically called with the ast.Module
2790 The root node to be transformed. Typically called with the ast.Module
2793 produced by parsing user input.
2791 produced by parsing user input.
2794
2792
2795 Returns
2793 Returns
2796 -------
2794 -------
2797 An ast.Node corresponding to the node it was called with. Note that it
2795 An ast.Node corresponding to the node it was called with. Note that it
2798 may also modify the passed object, so don't rely on references to the
2796 may also modify the passed object, so don't rely on references to the
2799 original AST.
2797 original AST.
2800 """
2798 """
2801 for transformer in self.ast_transformers:
2799 for transformer in self.ast_transformers:
2802 try:
2800 try:
2803 node = transformer.visit(node)
2801 node = transformer.visit(node)
2804 except InputRejected:
2802 except InputRejected:
2805 # User-supplied AST transformers can reject an input by raising
2803 # User-supplied AST transformers can reject an input by raising
2806 # an InputRejected. Short-circuit in this case so that we
2804 # an InputRejected. Short-circuit in this case so that we
2807 # don't unregister the transform.
2805 # don't unregister the transform.
2808 raise
2806 raise
2809 except Exception:
2807 except Exception:
2810 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2808 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2811 self.ast_transformers.remove(transformer)
2809 self.ast_transformers.remove(transformer)
2812
2810
2813 if self.ast_transformers:
2811 if self.ast_transformers:
2814 ast.fix_missing_locations(node)
2812 ast.fix_missing_locations(node)
2815 return node
2813 return node
2816
2814
2817
2815
2818 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2816 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2819 compiler=compile, result=None):
2817 compiler=compile, result=None):
2820 """Run a sequence of AST nodes. The execution mode depends on the
2818 """Run a sequence of AST nodes. The execution mode depends on the
2821 interactivity parameter.
2819 interactivity parameter.
2822
2820
2823 Parameters
2821 Parameters
2824 ----------
2822 ----------
2825 nodelist : list
2823 nodelist : list
2826 A sequence of AST nodes to run.
2824 A sequence of AST nodes to run.
2827 cell_name : str
2825 cell_name : str
2828 Will be passed to the compiler as the filename of the cell. Typically
2826 Will be passed to the compiler as the filename of the cell. Typically
2829 the value returned by ip.compile.cache(cell).
2827 the value returned by ip.compile.cache(cell).
2830 interactivity : str
2828 interactivity : str
2831 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2829 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2832 run interactively (displaying output from expressions). 'last_expr'
2830 run interactively (displaying output from expressions). 'last_expr'
2833 will run the last node interactively only if it is an expression (i.e.
2831 will run the last node interactively only if it is an expression (i.e.
2834 expressions in loops or other blocks are not displayed. Other values
2832 expressions in loops or other blocks are not displayed. Other values
2835 for this parameter will raise a ValueError.
2833 for this parameter will raise a ValueError.
2836 compiler : callable
2834 compiler : callable
2837 A function with the same interface as the built-in compile(), to turn
2835 A function with the same interface as the built-in compile(), to turn
2838 the AST nodes into code objects. Default is the built-in compile().
2836 the AST nodes into code objects. Default is the built-in compile().
2839 result : ExecutionResult, optional
2837 result : ExecutionResult, optional
2840 An object to store exceptions that occur during execution.
2838 An object to store exceptions that occur during execution.
2841
2839
2842 Returns
2840 Returns
2843 -------
2841 -------
2844 True if an exception occurred while running code, False if it finished
2842 True if an exception occurred while running code, False if it finished
2845 running.
2843 running.
2846 """
2844 """
2847 if not nodelist:
2845 if not nodelist:
2848 return
2846 return
2849
2847
2850 if interactivity == 'last_expr':
2848 if interactivity == 'last_expr':
2851 if isinstance(nodelist[-1], ast.Expr):
2849 if isinstance(nodelist[-1], ast.Expr):
2852 interactivity = "last"
2850 interactivity = "last"
2853 else:
2851 else:
2854 interactivity = "none"
2852 interactivity = "none"
2855
2853
2856 if interactivity == 'none':
2854 if interactivity == 'none':
2857 to_run_exec, to_run_interactive = nodelist, []
2855 to_run_exec, to_run_interactive = nodelist, []
2858 elif interactivity == 'last':
2856 elif interactivity == 'last':
2859 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2857 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2860 elif interactivity == 'all':
2858 elif interactivity == 'all':
2861 to_run_exec, to_run_interactive = [], nodelist
2859 to_run_exec, to_run_interactive = [], nodelist
2862 else:
2860 else:
2863 raise ValueError("Interactivity was %r" % interactivity)
2861 raise ValueError("Interactivity was %r" % interactivity)
2864
2862
2865 try:
2863 try:
2866 for i, node in enumerate(to_run_exec):
2864 for i, node in enumerate(to_run_exec):
2867 mod = ast.Module([node])
2865 mod = ast.Module([node])
2868 code = compiler(mod, cell_name, "exec")
2866 code = compiler(mod, cell_name, "exec")
2869 if self.run_code(code, result):
2867 if self.run_code(code, result):
2870 return True
2868 return True
2871
2869
2872 for i, node in enumerate(to_run_interactive):
2870 for i, node in enumerate(to_run_interactive):
2873 mod = ast.Interactive([node])
2871 mod = ast.Interactive([node])
2874 code = compiler(mod, cell_name, "single")
2872 code = compiler(mod, cell_name, "single")
2875 if self.run_code(code, result):
2873 if self.run_code(code, result):
2876 return True
2874 return True
2877
2875
2878 # Flush softspace
2876 # Flush softspace
2879 if softspace(sys.stdout, 0):
2877 if softspace(sys.stdout, 0):
2880 print()
2878 print()
2881
2879
2882 except:
2880 except:
2883 # It's possible to have exceptions raised here, typically by
2881 # It's possible to have exceptions raised here, typically by
2884 # compilation of odd code (such as a naked 'return' outside a
2882 # compilation of odd code (such as a naked 'return' outside a
2885 # function) that did parse but isn't valid. Typically the exception
2883 # function) that did parse but isn't valid. Typically the exception
2886 # is a SyntaxError, but it's safest just to catch anything and show
2884 # is a SyntaxError, but it's safest just to catch anything and show
2887 # the user a traceback.
2885 # the user a traceback.
2888
2886
2889 # We do only one try/except outside the loop to minimize the impact
2887 # We do only one try/except outside the loop to minimize the impact
2890 # on runtime, and also because if any node in the node list is
2888 # on runtime, and also because if any node in the node list is
2891 # broken, we should stop execution completely.
2889 # broken, we should stop execution completely.
2892 if result:
2890 if result:
2893 result.error_before_exec = sys.exc_info()[1]
2891 result.error_before_exec = sys.exc_info()[1]
2894 self.showtraceback()
2892 self.showtraceback()
2895 return True
2893 return True
2896
2894
2897 return False
2895 return False
2898
2896
2899 def run_code(self, code_obj, result=None):
2897 def run_code(self, code_obj, result=None):
2900 """Execute a code object.
2898 """Execute a code object.
2901
2899
2902 When an exception occurs, self.showtraceback() is called to display a
2900 When an exception occurs, self.showtraceback() is called to display a
2903 traceback.
2901 traceback.
2904
2902
2905 Parameters
2903 Parameters
2906 ----------
2904 ----------
2907 code_obj : code object
2905 code_obj : code object
2908 A compiled code object, to be executed
2906 A compiled code object, to be executed
2909 result : ExecutionResult, optional
2907 result : ExecutionResult, optional
2910 An object to store exceptions that occur during execution.
2908 An object to store exceptions that occur during execution.
2911
2909
2912 Returns
2910 Returns
2913 -------
2911 -------
2914 False : successful execution.
2912 False : successful execution.
2915 True : an error occurred.
2913 True : an error occurred.
2916 """
2914 """
2917 # Set our own excepthook in case the user code tries to call it
2915 # Set our own excepthook in case the user code tries to call it
2918 # directly, so that the IPython crash handler doesn't get triggered
2916 # directly, so that the IPython crash handler doesn't get triggered
2919 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2917 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2920
2918
2921 # we save the original sys.excepthook in the instance, in case config
2919 # we save the original sys.excepthook in the instance, in case config
2922 # code (such as magics) needs access to it.
2920 # code (such as magics) needs access to it.
2923 self.sys_excepthook = old_excepthook
2921 self.sys_excepthook = old_excepthook
2924 outflag = 1 # happens in more places, so it's easier as default
2922 outflag = 1 # happens in more places, so it's easier as default
2925 try:
2923 try:
2926 try:
2924 try:
2927 self.hooks.pre_run_code_hook()
2925 self.hooks.pre_run_code_hook()
2928 #rprint('Running code', repr(code_obj)) # dbg
2926 #rprint('Running code', repr(code_obj)) # dbg
2929 exec(code_obj, self.user_global_ns, self.user_ns)
2927 exec(code_obj, self.user_global_ns, self.user_ns)
2930 finally:
2928 finally:
2931 # Reset our crash handler in place
2929 # Reset our crash handler in place
2932 sys.excepthook = old_excepthook
2930 sys.excepthook = old_excepthook
2933 except SystemExit as e:
2931 except SystemExit as e:
2934 if result is not None:
2932 if result is not None:
2935 result.error_in_exec = e
2933 result.error_in_exec = e
2936 self.showtraceback(exception_only=True)
2934 self.showtraceback(exception_only=True)
2937 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2935 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2938 except self.custom_exceptions:
2936 except self.custom_exceptions:
2939 etype, value, tb = sys.exc_info()
2937 etype, value, tb = sys.exc_info()
2940 if result is not None:
2938 if result is not None:
2941 result.error_in_exec = value
2939 result.error_in_exec = value
2942 self.CustomTB(etype, value, tb)
2940 self.CustomTB(etype, value, tb)
2943 except:
2941 except:
2944 if result is not None:
2942 if result is not None:
2945 result.error_in_exec = sys.exc_info()[1]
2943 result.error_in_exec = sys.exc_info()[1]
2946 self.showtraceback()
2944 self.showtraceback()
2947 else:
2945 else:
2948 outflag = 0
2946 outflag = 0
2949 return outflag
2947 return outflag
2950
2948
2951 # For backwards compatibility
2949 # For backwards compatibility
2952 runcode = run_code
2950 runcode = run_code
2953
2951
2954 #-------------------------------------------------------------------------
2952 #-------------------------------------------------------------------------
2955 # Things related to GUI support and pylab
2953 # Things related to GUI support and pylab
2956 #-------------------------------------------------------------------------
2954 #-------------------------------------------------------------------------
2957
2955
2958 def enable_gui(self, gui=None):
2956 def enable_gui(self, gui=None):
2959 raise NotImplementedError('Implement enable_gui in a subclass')
2957 raise NotImplementedError('Implement enable_gui in a subclass')
2960
2958
2961 def enable_matplotlib(self, gui=None):
2959 def enable_matplotlib(self, gui=None):
2962 """Enable interactive matplotlib and inline figure support.
2960 """Enable interactive matplotlib and inline figure support.
2963
2961
2964 This takes the following steps:
2962 This takes the following steps:
2965
2963
2966 1. select the appropriate eventloop and matplotlib backend
2964 1. select the appropriate eventloop and matplotlib backend
2967 2. set up matplotlib for interactive use with that backend
2965 2. set up matplotlib for interactive use with that backend
2968 3. configure formatters for inline figure display
2966 3. configure formatters for inline figure display
2969 4. enable the selected gui eventloop
2967 4. enable the selected gui eventloop
2970
2968
2971 Parameters
2969 Parameters
2972 ----------
2970 ----------
2973 gui : optional, string
2971 gui : optional, string
2974 If given, dictates the choice of matplotlib GUI backend to use
2972 If given, dictates the choice of matplotlib GUI backend to use
2975 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2973 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2976 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2974 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2977 matplotlib (as dictated by the matplotlib build-time options plus the
2975 matplotlib (as dictated by the matplotlib build-time options plus the
2978 user's matplotlibrc configuration file). Note that not all backends
2976 user's matplotlibrc configuration file). Note that not all backends
2979 make sense in all contexts, for example a terminal ipython can't
2977 make sense in all contexts, for example a terminal ipython can't
2980 display figures inline.
2978 display figures inline.
2981 """
2979 """
2982 from IPython.core import pylabtools as pt
2980 from IPython.core import pylabtools as pt
2983 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2981 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2984
2982
2985 if gui != 'inline':
2983 if gui != 'inline':
2986 # If we have our first gui selection, store it
2984 # If we have our first gui selection, store it
2987 if self.pylab_gui_select is None:
2985 if self.pylab_gui_select is None:
2988 self.pylab_gui_select = gui
2986 self.pylab_gui_select = gui
2989 # Otherwise if they are different
2987 # Otherwise if they are different
2990 elif gui != self.pylab_gui_select:
2988 elif gui != self.pylab_gui_select:
2991 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2989 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2992 ' Using %s instead.' % (gui, self.pylab_gui_select))
2990 ' Using %s instead.' % (gui, self.pylab_gui_select))
2993 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2991 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2994
2992
2995 pt.activate_matplotlib(backend)
2993 pt.activate_matplotlib(backend)
2996 pt.configure_inline_support(self, backend)
2994 pt.configure_inline_support(self, backend)
2997
2995
2998 # Now we must activate the gui pylab wants to use, and fix %run to take
2996 # Now we must activate the gui pylab wants to use, and fix %run to take
2999 # plot updates into account
2997 # plot updates into account
3000 self.enable_gui(gui)
2998 self.enable_gui(gui)
3001 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2999 self.magics_manager.registry['ExecutionMagics'].default_runner = \
3002 pt.mpl_runner(self.safe_execfile)
3000 pt.mpl_runner(self.safe_execfile)
3003
3001
3004 return gui, backend
3002 return gui, backend
3005
3003
3006 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3004 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
3007 """Activate pylab support at runtime.
3005 """Activate pylab support at runtime.
3008
3006
3009 This turns on support for matplotlib, preloads into the interactive
3007 This turns on support for matplotlib, preloads into the interactive
3010 namespace all of numpy and pylab, and configures IPython to correctly
3008 namespace all of numpy and pylab, and configures IPython to correctly
3011 interact with the GUI event loop. The GUI backend to be used can be
3009 interact with the GUI event loop. The GUI backend to be used can be
3012 optionally selected with the optional ``gui`` argument.
3010 optionally selected with the optional ``gui`` argument.
3013
3011
3014 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3012 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
3015
3013
3016 Parameters
3014 Parameters
3017 ----------
3015 ----------
3018 gui : optional, string
3016 gui : optional, string
3019 If given, dictates the choice of matplotlib GUI backend to use
3017 If given, dictates the choice of matplotlib GUI backend to use
3020 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3018 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
3021 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3019 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
3022 matplotlib (as dictated by the matplotlib build-time options plus the
3020 matplotlib (as dictated by the matplotlib build-time options plus the
3023 user's matplotlibrc configuration file). Note that not all backends
3021 user's matplotlibrc configuration file). Note that not all backends
3024 make sense in all contexts, for example a terminal ipython can't
3022 make sense in all contexts, for example a terminal ipython can't
3025 display figures inline.
3023 display figures inline.
3026 import_all : optional, bool, default: True
3024 import_all : optional, bool, default: True
3027 Whether to do `from numpy import *` and `from pylab import *`
3025 Whether to do `from numpy import *` and `from pylab import *`
3028 in addition to module imports.
3026 in addition to module imports.
3029 welcome_message : deprecated
3027 welcome_message : deprecated
3030 This argument is ignored, no welcome message will be displayed.
3028 This argument is ignored, no welcome message will be displayed.
3031 """
3029 """
3032 from IPython.core.pylabtools import import_pylab
3030 from IPython.core.pylabtools import import_pylab
3033
3031
3034 gui, backend = self.enable_matplotlib(gui)
3032 gui, backend = self.enable_matplotlib(gui)
3035
3033
3036 # We want to prevent the loading of pylab to pollute the user's
3034 # We want to prevent the loading of pylab to pollute the user's
3037 # namespace as shown by the %who* magics, so we execute the activation
3035 # namespace as shown by the %who* magics, so we execute the activation
3038 # code in an empty namespace, and we update *both* user_ns and
3036 # code in an empty namespace, and we update *both* user_ns and
3039 # user_ns_hidden with this information.
3037 # user_ns_hidden with this information.
3040 ns = {}
3038 ns = {}
3041 import_pylab(ns, import_all)
3039 import_pylab(ns, import_all)
3042 # warn about clobbered names
3040 # warn about clobbered names
3043 ignored = {"__builtins__"}
3041 ignored = {"__builtins__"}
3044 both = set(ns).intersection(self.user_ns).difference(ignored)
3042 both = set(ns).intersection(self.user_ns).difference(ignored)
3045 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3043 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3046 self.user_ns.update(ns)
3044 self.user_ns.update(ns)
3047 self.user_ns_hidden.update(ns)
3045 self.user_ns_hidden.update(ns)
3048 return gui, backend, clobbered
3046 return gui, backend, clobbered
3049
3047
3050 #-------------------------------------------------------------------------
3048 #-------------------------------------------------------------------------
3051 # Utilities
3049 # Utilities
3052 #-------------------------------------------------------------------------
3050 #-------------------------------------------------------------------------
3053
3051
3054 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3052 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3055 """Expand python variables in a string.
3053 """Expand python variables in a string.
3056
3054
3057 The depth argument indicates how many frames above the caller should
3055 The depth argument indicates how many frames above the caller should
3058 be walked to look for the local namespace where to expand variables.
3056 be walked to look for the local namespace where to expand variables.
3059
3057
3060 The global namespace for expansion is always the user's interactive
3058 The global namespace for expansion is always the user's interactive
3061 namespace.
3059 namespace.
3062 """
3060 """
3063 ns = self.user_ns.copy()
3061 ns = self.user_ns.copy()
3064 try:
3062 try:
3065 frame = sys._getframe(depth+1)
3063 frame = sys._getframe(depth+1)
3066 except ValueError:
3064 except ValueError:
3067 # This is thrown if there aren't that many frames on the stack,
3065 # This is thrown if there aren't that many frames on the stack,
3068 # e.g. if a script called run_line_magic() directly.
3066 # e.g. if a script called run_line_magic() directly.
3069 pass
3067 pass
3070 else:
3068 else:
3071 ns.update(frame.f_locals)
3069 ns.update(frame.f_locals)
3072
3070
3073 try:
3071 try:
3074 # We have to use .vformat() here, because 'self' is a valid and common
3072 # We have to use .vformat() here, because 'self' is a valid and common
3075 # name, and expanding **ns for .format() would make it collide with
3073 # name, and expanding **ns for .format() would make it collide with
3076 # the 'self' argument of the method.
3074 # the 'self' argument of the method.
3077 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3075 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3078 except Exception:
3076 except Exception:
3079 # if formatter couldn't format, just let it go untransformed
3077 # if formatter couldn't format, just let it go untransformed
3080 pass
3078 pass
3081 return cmd
3079 return cmd
3082
3080
3083 def mktempfile(self, data=None, prefix='ipython_edit_'):
3081 def mktempfile(self, data=None, prefix='ipython_edit_'):
3084 """Make a new tempfile and return its filename.
3082 """Make a new tempfile and return its filename.
3085
3083
3086 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3084 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3087 but it registers the created filename internally so ipython cleans it up
3085 but it registers the created filename internally so ipython cleans it up
3088 at exit time.
3086 at exit time.
3089
3087
3090 Optional inputs:
3088 Optional inputs:
3091
3089
3092 - data(None): if data is given, it gets written out to the temp file
3090 - data(None): if data is given, it gets written out to the temp file
3093 immediately, and the file is closed again."""
3091 immediately, and the file is closed again."""
3094
3092
3095 dirname = tempfile.mkdtemp(prefix=prefix)
3093 dirname = tempfile.mkdtemp(prefix=prefix)
3096 self.tempdirs.append(dirname)
3094 self.tempdirs.append(dirname)
3097
3095
3098 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3096 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3099 os.close(handle) # On Windows, there can only be one open handle on a file
3097 os.close(handle) # On Windows, there can only be one open handle on a file
3100 self.tempfiles.append(filename)
3098 self.tempfiles.append(filename)
3101
3099
3102 if data:
3100 if data:
3103 tmp_file = open(filename,'w')
3101 tmp_file = open(filename,'w')
3104 tmp_file.write(data)
3102 tmp_file.write(data)
3105 tmp_file.close()
3103 tmp_file.close()
3106 return filename
3104 return filename
3107
3105
3108 @undoc
3106 @undoc
3109 def write(self,data):
3107 def write(self,data):
3110 """DEPRECATED: Write a string to the default output"""
3108 """DEPRECATED: Write a string to the default output"""
3111 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3109 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3112 DeprecationWarning, stacklevel=2)
3110 DeprecationWarning, stacklevel=2)
3113 sys.stdout.write(data)
3111 sys.stdout.write(data)
3114
3112
3115 @undoc
3113 @undoc
3116 def write_err(self,data):
3114 def write_err(self,data):
3117 """DEPRECATED: Write a string to the default error output"""
3115 """DEPRECATED: Write a string to the default error output"""
3118 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3116 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3119 DeprecationWarning, stacklevel=2)
3117 DeprecationWarning, stacklevel=2)
3120 sys.stderr.write(data)
3118 sys.stderr.write(data)
3121
3119
3122 def ask_yes_no(self, prompt, default=None, interrupt=None):
3120 def ask_yes_no(self, prompt, default=None, interrupt=None):
3123 if self.quiet:
3121 if self.quiet:
3124 return True
3122 return True
3125 return ask_yes_no(prompt,default,interrupt)
3123 return ask_yes_no(prompt,default,interrupt)
3126
3124
3127 def show_usage(self):
3125 def show_usage(self):
3128 """Show a usage message"""
3126 """Show a usage message"""
3129 page.page(IPython.core.usage.interactive_usage)
3127 page.page(IPython.core.usage.interactive_usage)
3130
3128
3131 def extract_input_lines(self, range_str, raw=False):
3129 def extract_input_lines(self, range_str, raw=False):
3132 """Return as a string a set of input history slices.
3130 """Return as a string a set of input history slices.
3133
3131
3134 Parameters
3132 Parameters
3135 ----------
3133 ----------
3136 range_str : string
3134 range_str : string
3137 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3135 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3138 since this function is for use by magic functions which get their
3136 since this function is for use by magic functions which get their
3139 arguments as strings. The number before the / is the session
3137 arguments as strings. The number before the / is the session
3140 number: ~n goes n back from the current session.
3138 number: ~n goes n back from the current session.
3141
3139
3142 raw : bool, optional
3140 raw : bool, optional
3143 By default, the processed input is used. If this is true, the raw
3141 By default, the processed input is used. If this is true, the raw
3144 input history is used instead.
3142 input history is used instead.
3145
3143
3146 Notes
3144 Notes
3147 -----
3145 -----
3148
3146
3149 Slices can be described with two notations:
3147 Slices can be described with two notations:
3150
3148
3151 * ``N:M`` -> standard python form, means including items N...(M-1).
3149 * ``N:M`` -> standard python form, means including items N...(M-1).
3152 * ``N-M`` -> include items N..M (closed endpoint).
3150 * ``N-M`` -> include items N..M (closed endpoint).
3153 """
3151 """
3154 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3152 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3155 return "\n".join(x for _, _, x in lines)
3153 return "\n".join(x for _, _, x in lines)
3156
3154
3157 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3155 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3158 """Get a code string from history, file, url, or a string or macro.
3156 """Get a code string from history, file, url, or a string or macro.
3159
3157
3160 This is mainly used by magic functions.
3158 This is mainly used by magic functions.
3161
3159
3162 Parameters
3160 Parameters
3163 ----------
3161 ----------
3164
3162
3165 target : str
3163 target : str
3166
3164
3167 A string specifying code to retrieve. This will be tried respectively
3165 A string specifying code to retrieve. This will be tried respectively
3168 as: ranges of input history (see %history for syntax), url,
3166 as: ranges of input history (see %history for syntax), url,
3169 corresponding .py file, filename, or an expression evaluating to a
3167 corresponding .py file, filename, or an expression evaluating to a
3170 string or Macro in the user namespace.
3168 string or Macro in the user namespace.
3171
3169
3172 raw : bool
3170 raw : bool
3173 If true (default), retrieve raw history. Has no effect on the other
3171 If true (default), retrieve raw history. Has no effect on the other
3174 retrieval mechanisms.
3172 retrieval mechanisms.
3175
3173
3176 py_only : bool (default False)
3174 py_only : bool (default False)
3177 Only try to fetch python code, do not try alternative methods to decode file
3175 Only try to fetch python code, do not try alternative methods to decode file
3178 if unicode fails.
3176 if unicode fails.
3179
3177
3180 Returns
3178 Returns
3181 -------
3179 -------
3182 A string of code.
3180 A string of code.
3183
3181
3184 ValueError is raised if nothing is found, and TypeError if it evaluates
3182 ValueError is raised if nothing is found, and TypeError if it evaluates
3185 to an object of another type. In each case, .args[0] is a printable
3183 to an object of another type. In each case, .args[0] is a printable
3186 message.
3184 message.
3187 """
3185 """
3188 code = self.extract_input_lines(target, raw=raw) # Grab history
3186 code = self.extract_input_lines(target, raw=raw) # Grab history
3189 if code:
3187 if code:
3190 return code
3188 return code
3191 try:
3189 try:
3192 if target.startswith(('http://', 'https://')):
3190 if target.startswith(('http://', 'https://')):
3193 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3191 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3194 except UnicodeDecodeError:
3192 except UnicodeDecodeError:
3195 if not py_only :
3193 if not py_only :
3196 # Deferred import
3194 # Deferred import
3197 try:
3195 try:
3198 from urllib.request import urlopen # Py3
3196 from urllib.request import urlopen # Py3
3199 except ImportError:
3197 except ImportError:
3200 from urllib import urlopen
3198 from urllib import urlopen
3201 response = urlopen(target)
3199 response = urlopen(target)
3202 return response.read().decode('latin1')
3200 return response.read().decode('latin1')
3203 raise ValueError(("'%s' seem to be unreadable.") % target)
3201 raise ValueError(("'%s' seem to be unreadable.") % target)
3204
3202
3205 potential_target = [target]
3203 potential_target = [target]
3206 try :
3204 try :
3207 potential_target.insert(0,get_py_filename(target))
3205 potential_target.insert(0,get_py_filename(target))
3208 except IOError:
3206 except IOError:
3209 pass
3207 pass
3210
3208
3211 for tgt in potential_target :
3209 for tgt in potential_target :
3212 if os.path.isfile(tgt): # Read file
3210 if os.path.isfile(tgt): # Read file
3213 try :
3211 try :
3214 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3212 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3215 except UnicodeDecodeError :
3213 except UnicodeDecodeError :
3216 if not py_only :
3214 if not py_only :
3217 with io_open(tgt,'r', encoding='latin1') as f :
3215 with io_open(tgt,'r', encoding='latin1') as f :
3218 return f.read()
3216 return f.read()
3219 raise ValueError(("'%s' seem to be unreadable.") % target)
3217 raise ValueError(("'%s' seem to be unreadable.") % target)
3220 elif os.path.isdir(os.path.expanduser(tgt)):
3218 elif os.path.isdir(os.path.expanduser(tgt)):
3221 raise ValueError("'%s' is a directory, not a regular file." % target)
3219 raise ValueError("'%s' is a directory, not a regular file." % target)
3222
3220
3223 if search_ns:
3221 if search_ns:
3224 # Inspect namespace to load object source
3222 # Inspect namespace to load object source
3225 object_info = self.object_inspect(target, detail_level=1)
3223 object_info = self.object_inspect(target, detail_level=1)
3226 if object_info['found'] and object_info['source']:
3224 if object_info['found'] and object_info['source']:
3227 return object_info['source']
3225 return object_info['source']
3228
3226
3229 try: # User namespace
3227 try: # User namespace
3230 codeobj = eval(target, self.user_ns)
3228 codeobj = eval(target, self.user_ns)
3231 except Exception:
3229 except Exception:
3232 raise ValueError(("'%s' was not found in history, as a file, url, "
3230 raise ValueError(("'%s' was not found in history, as a file, url, "
3233 "nor in the user namespace.") % target)
3231 "nor in the user namespace.") % target)
3234
3232
3235 if isinstance(codeobj, string_types):
3233 if isinstance(codeobj, string_types):
3236 return codeobj
3234 return codeobj
3237 elif isinstance(codeobj, Macro):
3235 elif isinstance(codeobj, Macro):
3238 return codeobj.value
3236 return codeobj.value
3239
3237
3240 raise TypeError("%s is neither a string nor a macro." % target,
3238 raise TypeError("%s is neither a string nor a macro." % target,
3241 codeobj)
3239 codeobj)
3242
3240
3243 #-------------------------------------------------------------------------
3241 #-------------------------------------------------------------------------
3244 # Things related to IPython exiting
3242 # Things related to IPython exiting
3245 #-------------------------------------------------------------------------
3243 #-------------------------------------------------------------------------
3246 def atexit_operations(self):
3244 def atexit_operations(self):
3247 """This will be executed at the time of exit.
3245 """This will be executed at the time of exit.
3248
3246
3249 Cleanup operations and saving of persistent data that is done
3247 Cleanup operations and saving of persistent data that is done
3250 unconditionally by IPython should be performed here.
3248 unconditionally by IPython should be performed here.
3251
3249
3252 For things that may depend on startup flags or platform specifics (such
3250 For things that may depend on startup flags or platform specifics (such
3253 as having readline or not), register a separate atexit function in the
3251 as having readline or not), register a separate atexit function in the
3254 code that has the appropriate information, rather than trying to
3252 code that has the appropriate information, rather than trying to
3255 clutter
3253 clutter
3256 """
3254 """
3257 # Close the history session (this stores the end time and line count)
3255 # Close the history session (this stores the end time and line count)
3258 # this must be *before* the tempfile cleanup, in case of temporary
3256 # this must be *before* the tempfile cleanup, in case of temporary
3259 # history db
3257 # history db
3260 self.history_manager.end_session()
3258 self.history_manager.end_session()
3261
3259
3262 # Cleanup all tempfiles and folders left around
3260 # Cleanup all tempfiles and folders left around
3263 for tfile in self.tempfiles:
3261 for tfile in self.tempfiles:
3264 try:
3262 try:
3265 os.unlink(tfile)
3263 os.unlink(tfile)
3266 except OSError:
3264 except OSError:
3267 pass
3265 pass
3268
3266
3269 for tdir in self.tempdirs:
3267 for tdir in self.tempdirs:
3270 try:
3268 try:
3271 os.rmdir(tdir)
3269 os.rmdir(tdir)
3272 except OSError:
3270 except OSError:
3273 pass
3271 pass
3274
3272
3275 # Clear all user namespaces to release all references cleanly.
3273 # Clear all user namespaces to release all references cleanly.
3276 self.reset(new_session=False)
3274 self.reset(new_session=False)
3277
3275
3278 # Run user hooks
3276 # Run user hooks
3279 self.hooks.shutdown_hook()
3277 self.hooks.shutdown_hook()
3280
3278
3281 def cleanup(self):
3279 def cleanup(self):
3282 self.restore_sys_module_state()
3280 self.restore_sys_module_state()
3283
3281
3284
3282
3285 # Overridden in terminal subclass to change prompts
3283 # Overridden in terminal subclass to change prompts
3286 def switch_doctest_mode(self, mode):
3284 def switch_doctest_mode(self, mode):
3287 pass
3285 pass
3288
3286
3289
3287
3290 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3288 class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
3291 """An abstract base class for InteractiveShell."""
3289 """An abstract base class for InteractiveShell."""
3292
3290
3293 InteractiveShellABC.register(InteractiveShell)
3291 InteractiveShellABC.register(InteractiveShell)
@@ -1,599 +1,599 b''
1 """Implementation of basic magic functions."""
1 """Implementation of basic magic functions."""
2
2
3 from __future__ import print_function
3 from __future__ import print_function
4 from __future__ import absolute_import
4 from __future__ import absolute_import
5
5
6 import io
6 import io
7 import sys
7 import sys
8 from pprint import pformat
8 from pprint import pformat
9
9
10 from IPython.core import magic_arguments, page
10 from IPython.core import magic_arguments, page
11 from IPython.core.error import UsageError
11 from IPython.core.error import UsageError
12 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
12 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
13 from IPython.utils.text import format_screen, dedent, indent
13 from IPython.utils.text import format_screen, dedent, indent
14 from IPython.testing.skipdoctest import skip_doctest
14 from IPython.testing.skipdoctest import skip_doctest
15 from IPython.utils.ipstruct import Struct
15 from IPython.utils.ipstruct import Struct
16 from IPython.utils.py3compat import unicode_type
16 from IPython.utils.py3compat import unicode_type
17 from warnings import warn
17 from warnings import warn
18 from logging import error
18 from logging import error
19
19
20
20
21 class MagicsDisplay(object):
21 class MagicsDisplay(object):
22 def __init__(self, magics_manager):
22 def __init__(self, magics_manager):
23 self.magics_manager = magics_manager
23 self.magics_manager = magics_manager
24
24
25 def _lsmagic(self):
25 def _lsmagic(self):
26 """The main implementation of the %lsmagic"""
26 """The main implementation of the %lsmagic"""
27 mesc = magic_escapes['line']
27 mesc = magic_escapes['line']
28 cesc = magic_escapes['cell']
28 cesc = magic_escapes['cell']
29 mman = self.magics_manager
29 mman = self.magics_manager
30 magics = mman.lsmagic()
30 magics = mman.lsmagic()
31 out = ['Available line magics:',
31 out = ['Available line magics:',
32 mesc + (' '+mesc).join(sorted(magics['line'])),
32 mesc + (' '+mesc).join(sorted(magics['line'])),
33 '',
33 '',
34 'Available cell magics:',
34 'Available cell magics:',
35 cesc + (' '+cesc).join(sorted(magics['cell'])),
35 cesc + (' '+cesc).join(sorted(magics['cell'])),
36 '',
36 '',
37 mman.auto_status()]
37 mman.auto_status()]
38 return '\n'.join(out)
38 return '\n'.join(out)
39
39
40 def _repr_pretty_(self, p, cycle):
40 def _repr_pretty_(self, p, cycle):
41 p.text(self._lsmagic())
41 p.text(self._lsmagic())
42
42
43 def __str__(self):
43 def __str__(self):
44 return self._lsmagic()
44 return self._lsmagic()
45
45
46 def _jsonable(self):
46 def _jsonable(self):
47 """turn magics dict into jsonable dict of the same structure
47 """turn magics dict into jsonable dict of the same structure
48
48
49 replaces object instances with their class names as strings
49 replaces object instances with their class names as strings
50 """
50 """
51 magic_dict = {}
51 magic_dict = {}
52 mman = self.magics_manager
52 mman = self.magics_manager
53 magics = mman.lsmagic()
53 magics = mman.lsmagic()
54 for key, subdict in magics.items():
54 for key, subdict in magics.items():
55 d = {}
55 d = {}
56 magic_dict[key] = d
56 magic_dict[key] = d
57 for name, obj in subdict.items():
57 for name, obj in subdict.items():
58 try:
58 try:
59 classname = obj.__self__.__class__.__name__
59 classname = obj.__self__.__class__.__name__
60 except AttributeError:
60 except AttributeError:
61 classname = 'Other'
61 classname = 'Other'
62
62
63 d[name] = classname
63 d[name] = classname
64 return magic_dict
64 return magic_dict
65
65
66 def _repr_json_(self):
66 def _repr_json_(self):
67 return self._jsonable()
67 return self._jsonable()
68
68
69
69
70 @magics_class
70 @magics_class
71 class BasicMagics(Magics):
71 class BasicMagics(Magics):
72 """Magics that provide central IPython functionality.
72 """Magics that provide central IPython functionality.
73
73
74 These are various magics that don't fit into specific categories but that
74 These are various magics that don't fit into specific categories but that
75 are all part of the base 'IPython experience'."""
75 are all part of the base 'IPython experience'."""
76
76
77 @magic_arguments.magic_arguments()
77 @magic_arguments.magic_arguments()
78 @magic_arguments.argument(
78 @magic_arguments.argument(
79 '-l', '--line', action='store_true',
79 '-l', '--line', action='store_true',
80 help="""Create a line magic alias."""
80 help="""Create a line magic alias."""
81 )
81 )
82 @magic_arguments.argument(
82 @magic_arguments.argument(
83 '-c', '--cell', action='store_true',
83 '-c', '--cell', action='store_true',
84 help="""Create a cell magic alias."""
84 help="""Create a cell magic alias."""
85 )
85 )
86 @magic_arguments.argument(
86 @magic_arguments.argument(
87 'name',
87 'name',
88 help="""Name of the magic to be created."""
88 help="""Name of the magic to be created."""
89 )
89 )
90 @magic_arguments.argument(
90 @magic_arguments.argument(
91 'target',
91 'target',
92 help="""Name of the existing line or cell magic."""
92 help="""Name of the existing line or cell magic."""
93 )
93 )
94 @line_magic
94 @line_magic
95 def alias_magic(self, line=''):
95 def alias_magic(self, line=''):
96 """Create an alias for an existing line or cell magic.
96 """Create an alias for an existing line or cell magic.
97
97
98 Examples
98 Examples
99 --------
99 --------
100 ::
100 ::
101
101
102 In [1]: %alias_magic t timeit
102 In [1]: %alias_magic t timeit
103 Created `%t` as an alias for `%timeit`.
103 Created `%t` as an alias for `%timeit`.
104 Created `%%t` as an alias for `%%timeit`.
104 Created `%%t` as an alias for `%%timeit`.
105
105
106 In [2]: %t -n1 pass
106 In [2]: %t -n1 pass
107 1 loops, best of 3: 954 ns per loop
107 1 loops, best of 3: 954 ns per loop
108
108
109 In [3]: %%t -n1
109 In [3]: %%t -n1
110 ...: pass
110 ...: pass
111 ...:
111 ...:
112 1 loops, best of 3: 954 ns per loop
112 1 loops, best of 3: 954 ns per loop
113
113
114 In [4]: %alias_magic --cell whereami pwd
114 In [4]: %alias_magic --cell whereami pwd
115 UsageError: Cell magic function `%%pwd` not found.
115 UsageError: Cell magic function `%%pwd` not found.
116 In [5]: %alias_magic --line whereami pwd
116 In [5]: %alias_magic --line whereami pwd
117 Created `%whereami` as an alias for `%pwd`.
117 Created `%whereami` as an alias for `%pwd`.
118
118
119 In [6]: %whereami
119 In [6]: %whereami
120 Out[6]: u'/home/testuser'
120 Out[6]: u'/home/testuser'
121 """
121 """
122 args = magic_arguments.parse_argstring(self.alias_magic, line)
122 args = magic_arguments.parse_argstring(self.alias_magic, line)
123 shell = self.shell
123 shell = self.shell
124 mman = self.shell.magics_manager
124 mman = self.shell.magics_manager
125 escs = ''.join(magic_escapes.values())
125 escs = ''.join(magic_escapes.values())
126
126
127 target = args.target.lstrip(escs)
127 target = args.target.lstrip(escs)
128 name = args.name.lstrip(escs)
128 name = args.name.lstrip(escs)
129
129
130 # Find the requested magics.
130 # Find the requested magics.
131 m_line = shell.find_magic(target, 'line')
131 m_line = shell.find_magic(target, 'line')
132 m_cell = shell.find_magic(target, 'cell')
132 m_cell = shell.find_magic(target, 'cell')
133 if args.line and m_line is None:
133 if args.line and m_line is None:
134 raise UsageError('Line magic function `%s%s` not found.' %
134 raise UsageError('Line magic function `%s%s` not found.' %
135 (magic_escapes['line'], target))
135 (magic_escapes['line'], target))
136 if args.cell and m_cell is None:
136 if args.cell and m_cell is None:
137 raise UsageError('Cell magic function `%s%s` not found.' %
137 raise UsageError('Cell magic function `%s%s` not found.' %
138 (magic_escapes['cell'], target))
138 (magic_escapes['cell'], target))
139
139
140 # If --line and --cell are not specified, default to the ones
140 # If --line and --cell are not specified, default to the ones
141 # that are available.
141 # that are available.
142 if not args.line and not args.cell:
142 if not args.line and not args.cell:
143 if not m_line and not m_cell:
143 if not m_line and not m_cell:
144 raise UsageError(
144 raise UsageError(
145 'No line or cell magic with name `%s` found.' % target
145 'No line or cell magic with name `%s` found.' % target
146 )
146 )
147 args.line = bool(m_line)
147 args.line = bool(m_line)
148 args.cell = bool(m_cell)
148 args.cell = bool(m_cell)
149
149
150 if args.line:
150 if args.line:
151 mman.register_alias(name, target, 'line')
151 mman.register_alias(name, target, 'line')
152 print('Created `%s%s` as an alias for `%s%s`.' % (
152 print('Created `%s%s` as an alias for `%s%s`.' % (
153 magic_escapes['line'], name,
153 magic_escapes['line'], name,
154 magic_escapes['line'], target))
154 magic_escapes['line'], target))
155
155
156 if args.cell:
156 if args.cell:
157 mman.register_alias(name, target, 'cell')
157 mman.register_alias(name, target, 'cell')
158 print('Created `%s%s` as an alias for `%s%s`.' % (
158 print('Created `%s%s` as an alias for `%s%s`.' % (
159 magic_escapes['cell'], name,
159 magic_escapes['cell'], name,
160 magic_escapes['cell'], target))
160 magic_escapes['cell'], target))
161
161
162 @line_magic
162 @line_magic
163 def lsmagic(self, parameter_s=''):
163 def lsmagic(self, parameter_s=''):
164 """List currently available magic functions."""
164 """List currently available magic functions."""
165 return MagicsDisplay(self.shell.magics_manager)
165 return MagicsDisplay(self.shell.magics_manager)
166
166
167 def _magic_docs(self, brief=False, rest=False):
167 def _magic_docs(self, brief=False, rest=False):
168 """Return docstrings from magic functions."""
168 """Return docstrings from magic functions."""
169 mman = self.shell.magics_manager
169 mman = self.shell.magics_manager
170 docs = mman.lsmagic_docs(brief, missing='No documentation')
170 docs = mman.lsmagic_docs(brief, missing='No documentation')
171
171
172 if rest:
172 if rest:
173 format_string = '**%s%s**::\n\n%s\n\n'
173 format_string = '**%s%s**::\n\n%s\n\n'
174 else:
174 else:
175 format_string = '%s%s:\n%s\n'
175 format_string = '%s%s:\n%s\n'
176
176
177 return ''.join(
177 return ''.join(
178 [format_string % (magic_escapes['line'], fname,
178 [format_string % (magic_escapes['line'], fname,
179 indent(dedent(fndoc)))
179 indent(dedent(fndoc)))
180 for fname, fndoc in sorted(docs['line'].items())]
180 for fname, fndoc in sorted(docs['line'].items())]
181 +
181 +
182 [format_string % (magic_escapes['cell'], fname,
182 [format_string % (magic_escapes['cell'], fname,
183 indent(dedent(fndoc)))
183 indent(dedent(fndoc)))
184 for fname, fndoc in sorted(docs['cell'].items())]
184 for fname, fndoc in sorted(docs['cell'].items())]
185 )
185 )
186
186
187 @line_magic
187 @line_magic
188 def magic(self, parameter_s=''):
188 def magic(self, parameter_s=''):
189 """Print information about the magic function system.
189 """Print information about the magic function system.
190
190
191 Supported formats: -latex, -brief, -rest
191 Supported formats: -latex, -brief, -rest
192 """
192 """
193
193
194 mode = ''
194 mode = ''
195 try:
195 try:
196 mode = parameter_s.split()[0][1:]
196 mode = parameter_s.split()[0][1:]
197 except IndexError:
197 except IndexError:
198 pass
198 pass
199
199
200 brief = (mode == 'brief')
200 brief = (mode == 'brief')
201 rest = (mode == 'rest')
201 rest = (mode == 'rest')
202 magic_docs = self._magic_docs(brief, rest)
202 magic_docs = self._magic_docs(brief, rest)
203
203
204 if mode == 'latex':
204 if mode == 'latex':
205 print(self.format_latex(magic_docs))
205 print(self.format_latex(magic_docs))
206 return
206 return
207 else:
207 else:
208 magic_docs = format_screen(magic_docs)
208 magic_docs = format_screen(magic_docs)
209
209
210 out = ["""
210 out = ["""
211 IPython's 'magic' functions
211 IPython's 'magic' functions
212 ===========================
212 ===========================
213
213
214 The magic function system provides a series of functions which allow you to
214 The magic function system provides a series of functions which allow you to
215 control the behavior of IPython itself, plus a lot of system-type
215 control the behavior of IPython itself, plus a lot of system-type
216 features. There are two kinds of magics, line-oriented and cell-oriented.
216 features. There are two kinds of magics, line-oriented and cell-oriented.
217
217
218 Line magics are prefixed with the % character and work much like OS
218 Line magics are prefixed with the % character and work much like OS
219 command-line calls: they get as an argument the rest of the line, where
219 command-line calls: they get as an argument the rest of the line, where
220 arguments are passed without parentheses or quotes. For example, this will
220 arguments are passed without parentheses or quotes. For example, this will
221 time the given statement::
221 time the given statement::
222
222
223 %timeit range(1000)
223 %timeit range(1000)
224
224
225 Cell magics are prefixed with a double %%, and they are functions that get as
225 Cell magics are prefixed with a double %%, and they are functions that get as
226 an argument not only the rest of the line, but also the lines below it in a
226 an argument not only the rest of the line, but also the lines below it in a
227 separate argument. These magics are called with two arguments: the rest of the
227 separate argument. These magics are called with two arguments: the rest of the
228 call line and the body of the cell, consisting of the lines below the first.
228 call line and the body of the cell, consisting of the lines below the first.
229 For example::
229 For example::
230
230
231 %%timeit x = numpy.random.randn((100, 100))
231 %%timeit x = numpy.random.randn((100, 100))
232 numpy.linalg.svd(x)
232 numpy.linalg.svd(x)
233
233
234 will time the execution of the numpy svd routine, running the assignment of x
234 will time the execution of the numpy svd routine, running the assignment of x
235 as part of the setup phase, which is not timed.
235 as part of the setup phase, which is not timed.
236
236
237 In a line-oriented client (the terminal or Qt console IPython), starting a new
237 In a line-oriented client (the terminal or Qt console IPython), starting a new
238 input with %% will automatically enter cell mode, and IPython will continue
238 input with %% will automatically enter cell mode, and IPython will continue
239 reading input until a blank line is given. In the notebook, simply type the
239 reading input until a blank line is given. In the notebook, simply type the
240 whole cell as one entity, but keep in mind that the %% escape can only be at
240 whole cell as one entity, but keep in mind that the %% escape can only be at
241 the very start of the cell.
241 the very start of the cell.
242
242
243 NOTE: If you have 'automagic' enabled (via the command line option or with the
243 NOTE: If you have 'automagic' enabled (via the command line option or with the
244 %automagic function), you don't need to type in the % explicitly for line
244 %automagic function), you don't need to type in the % explicitly for line
245 magics; cell magics always require an explicit '%%' escape. By default,
245 magics; cell magics always require an explicit '%%' escape. By default,
246 IPython ships with automagic on, so you should only rarely need the % escape.
246 IPython ships with automagic on, so you should only rarely need the % escape.
247
247
248 Example: typing '%cd mydir' (without the quotes) changes your working directory
248 Example: typing '%cd mydir' (without the quotes) changes your working directory
249 to 'mydir', if it exists.
249 to 'mydir', if it exists.
250
250
251 For a list of the available magic functions, use %lsmagic. For a description
251 For a list of the available magic functions, use %lsmagic. For a description
252 of any of them, type %magic_name?, e.g. '%cd?'.
252 of any of them, type %magic_name?, e.g. '%cd?'.
253
253
254 Currently the magic system has the following functions:""",
254 Currently the magic system has the following functions:""",
255 magic_docs,
255 magic_docs,
256 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
256 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
257 str(self.lsmagic()),
257 str(self.lsmagic()),
258 ]
258 ]
259 page.page('\n'.join(out))
259 page.page('\n'.join(out))
260
260
261
261
262 @line_magic
262 @line_magic
263 def page(self, parameter_s=''):
263 def page(self, parameter_s=''):
264 """Pretty print the object and display it through a pager.
264 """Pretty print the object and display it through a pager.
265
265
266 %page [options] OBJECT
266 %page [options] OBJECT
267
267
268 If no object is given, use _ (last output).
268 If no object is given, use _ (last output).
269
269
270 Options:
270 Options:
271
271
272 -r: page str(object), don't pretty-print it."""
272 -r: page str(object), don't pretty-print it."""
273
273
274 # After a function contributed by Olivier Aubert, slightly modified.
274 # After a function contributed by Olivier Aubert, slightly modified.
275
275
276 # Process options/args
276 # Process options/args
277 opts, args = self.parse_options(parameter_s, 'r')
277 opts, args = self.parse_options(parameter_s, 'r')
278 raw = 'r' in opts
278 raw = 'r' in opts
279
279
280 oname = args and args or '_'
280 oname = args and args or '_'
281 info = self.shell._ofind(oname)
281 info = self.shell._ofind(oname)
282 if info['found']:
282 if info['found']:
283 txt = (raw and str or pformat)( info['obj'] )
283 txt = (raw and str or pformat)( info['obj'] )
284 page.page(txt)
284 page.page(txt)
285 else:
285 else:
286 print('Object `%s` not found' % oname)
286 print('Object `%s` not found' % oname)
287
287
288 @line_magic
288 @line_magic
289 def profile(self, parameter_s=''):
289 def profile(self, parameter_s=''):
290 """Print your currently active IPython profile.
290 """Print your currently active IPython profile.
291
291
292 See Also
292 See Also
293 --------
293 --------
294 prun : run code using the Python profiler
294 prun : run code using the Python profiler
295 (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`)
295 (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`)
296 """
296 """
297 warn("%profile is now deprecated. Please use get_ipython().profile instead.")
297 warn("%profile is now deprecated. Please use get_ipython().profile instead.")
298 from IPython.core.application import BaseIPythonApplication
298 from IPython.core.application import BaseIPythonApplication
299 if BaseIPythonApplication.initialized():
299 if BaseIPythonApplication.initialized():
300 print(BaseIPythonApplication.instance().profile)
300 print(BaseIPythonApplication.instance().profile)
301 else:
301 else:
302 error("profile is an application-level value, but you don't appear to be in an IPython application")
302 error("profile is an application-level value, but you don't appear to be in an IPython application")
303
303
304 @line_magic
304 @line_magic
305 def pprint(self, parameter_s=''):
305 def pprint(self, parameter_s=''):
306 """Toggle pretty printing on/off."""
306 """Toggle pretty printing on/off."""
307 ptformatter = self.shell.display_formatter.formatters['text/plain']
307 ptformatter = self.shell.display_formatter.formatters['text/plain']
308 ptformatter.pprint = bool(1 - ptformatter.pprint)
308 ptformatter.pprint = bool(1 - ptformatter.pprint)
309 print('Pretty printing has been turned',
309 print('Pretty printing has been turned',
310 ['OFF','ON'][ptformatter.pprint])
310 ['OFF','ON'][ptformatter.pprint])
311
311
312 @line_magic
312 @line_magic
313 def colors(self, parameter_s=''):
313 def colors(self, parameter_s=''):
314 """Switch color scheme for prompts, info system and exception handlers.
314 """Switch color scheme for prompts, info system and exception handlers.
315
315
316 Currently implemented schemes: NoColor, Linux, LightBG.
316 Currently implemented schemes: NoColor, Linux, LightBG.
317
317
318 Color scheme names are not case-sensitive.
318 Color scheme names are not case-sensitive.
319
319
320 Examples
320 Examples
321 --------
321 --------
322 To get a plain black and white terminal::
322 To get a plain black and white terminal::
323
323
324 %colors nocolor
324 %colors nocolor
325 """
325 """
326 def color_switch_err(name):
326 def color_switch_err(name):
327 warn('Error changing %s color schemes.\n%s' %
327 warn('Error changing %s color schemes.\n%s' %
328 (name, sys.exc_info()[1]))
328 (name, sys.exc_info()[1]), stacklevel=2)
329
329
330
330
331 new_scheme = parameter_s.strip()
331 new_scheme = parameter_s.strip()
332 if not new_scheme:
332 if not new_scheme:
333 raise UsageError(
333 raise UsageError(
334 "%colors: you must specify a color scheme. See '%colors?'")
334 "%colors: you must specify a color scheme. See '%colors?'")
335 # local shortcut
335 # local shortcut
336 shell = self.shell
336 shell = self.shell
337
337
338
338
339
339
340 if not shell.colors_force:
340 if not shell.colors_force:
341 if sys.platform in {'win32', 'cli'}:
341 if sys.platform in {'win32', 'cli'}:
342 import IPython.utils.rlineimpl as readline
342 import IPython.utils.rlineimpl as readline
343 if not readline.have_readline:
343 if not readline.have_readline:
344 msg = """\
344 msg = """\
345 Proper color support under MS Windows requires the pyreadline library.
345 Proper color support under MS Windows requires the pyreadline library.
346 You can find it at:
346 You can find it at:
347 http://ipython.org/pyreadline.html
347 http://ipython.org/pyreadline.html
348
348
349 Defaulting color scheme to 'NoColor'"""
349 Defaulting color scheme to 'NoColor'"""
350 new_scheme = 'NoColor'
350 new_scheme = 'NoColor'
351 warn(msg)
351 warn(msg)
352
352
353 elif not shell.has_readline:
353 elif not shell.has_readline:
354 # Coloured prompts get messed up without readline
354 # Coloured prompts get messed up without readline
355 # Will remove this check after switching to prompt_toolkit
355 # Will remove this check after switching to prompt_toolkit
356 new_scheme = 'NoColor'
356 new_scheme = 'NoColor'
357
357
358 # Set exception colors
358 # Set exception colors
359 try:
359 try:
360 shell.InteractiveTB.set_colors(scheme = new_scheme)
360 shell.InteractiveTB.set_colors(scheme = new_scheme)
361 shell.colors = new_scheme
361 shell.colors = new_scheme
362 shell.refresh_style()
362 shell.refresh_style()
363 shell.SyntaxTB.set_colors(scheme = new_scheme)
363 shell.SyntaxTB.set_colors(scheme = new_scheme)
364 except:
364 except:
365 color_switch_err('exception')
365 color_switch_err('exception')
366
366
367 # Set info (for 'object?') colors
367 # Set info (for 'object?') colors
368 if shell.color_info:
368 if shell.color_info:
369 try:
369 try:
370 shell.inspector.set_active_scheme(new_scheme)
370 shell.inspector.set_active_scheme(new_scheme)
371 except:
371 except:
372 color_switch_err('object inspector')
372 color_switch_err('object inspector')
373 else:
373 else:
374 shell.inspector.set_active_scheme('NoColor')
374 shell.inspector.set_active_scheme('NoColor')
375
375
376 @line_magic
376 @line_magic
377 def xmode(self, parameter_s=''):
377 def xmode(self, parameter_s=''):
378 """Switch modes for the exception handlers.
378 """Switch modes for the exception handlers.
379
379
380 Valid modes: Plain, Context and Verbose.
380 Valid modes: Plain, Context and Verbose.
381
381
382 If called without arguments, acts as a toggle."""
382 If called without arguments, acts as a toggle."""
383
383
384 def xmode_switch_err(name):
384 def xmode_switch_err(name):
385 warn('Error changing %s exception modes.\n%s' %
385 warn('Error changing %s exception modes.\n%s' %
386 (name,sys.exc_info()[1]))
386 (name,sys.exc_info()[1]))
387
387
388 shell = self.shell
388 shell = self.shell
389 new_mode = parameter_s.strip().capitalize()
389 new_mode = parameter_s.strip().capitalize()
390 try:
390 try:
391 shell.InteractiveTB.set_mode(mode=new_mode)
391 shell.InteractiveTB.set_mode(mode=new_mode)
392 print('Exception reporting mode:',shell.InteractiveTB.mode)
392 print('Exception reporting mode:',shell.InteractiveTB.mode)
393 except:
393 except:
394 xmode_switch_err('user')
394 xmode_switch_err('user')
395
395
396 @line_magic
396 @line_magic
397 def quickref(self,arg):
397 def quickref(self,arg):
398 """ Show a quick reference sheet """
398 """ Show a quick reference sheet """
399 from IPython.core.usage import quick_reference
399 from IPython.core.usage import quick_reference
400 qr = quick_reference + self._magic_docs(brief=True)
400 qr = quick_reference + self._magic_docs(brief=True)
401 page.page(qr)
401 page.page(qr)
402
402
403 @line_magic
403 @line_magic
404 def doctest_mode(self, parameter_s=''):
404 def doctest_mode(self, parameter_s=''):
405 """Toggle doctest mode on and off.
405 """Toggle doctest mode on and off.
406
406
407 This mode is intended to make IPython behave as much as possible like a
407 This mode is intended to make IPython behave as much as possible like a
408 plain Python shell, from the perspective of how its prompts, exceptions
408 plain Python shell, from the perspective of how its prompts, exceptions
409 and output look. This makes it easy to copy and paste parts of a
409 and output look. This makes it easy to copy and paste parts of a
410 session into doctests. It does so by:
410 session into doctests. It does so by:
411
411
412 - Changing the prompts to the classic ``>>>`` ones.
412 - Changing the prompts to the classic ``>>>`` ones.
413 - Changing the exception reporting mode to 'Plain'.
413 - Changing the exception reporting mode to 'Plain'.
414 - Disabling pretty-printing of output.
414 - Disabling pretty-printing of output.
415
415
416 Note that IPython also supports the pasting of code snippets that have
416 Note that IPython also supports the pasting of code snippets that have
417 leading '>>>' and '...' prompts in them. This means that you can paste
417 leading '>>>' and '...' prompts in them. This means that you can paste
418 doctests from files or docstrings (even if they have leading
418 doctests from files or docstrings (even if they have leading
419 whitespace), and the code will execute correctly. You can then use
419 whitespace), and the code will execute correctly. You can then use
420 '%history -t' to see the translated history; this will give you the
420 '%history -t' to see the translated history; this will give you the
421 input after removal of all the leading prompts and whitespace, which
421 input after removal of all the leading prompts and whitespace, which
422 can be pasted back into an editor.
422 can be pasted back into an editor.
423
423
424 With these features, you can switch into this mode easily whenever you
424 With these features, you can switch into this mode easily whenever you
425 need to do testing and changes to doctests, without having to leave
425 need to do testing and changes to doctests, without having to leave
426 your existing IPython session.
426 your existing IPython session.
427 """
427 """
428
428
429 # Shorthands
429 # Shorthands
430 shell = self.shell
430 shell = self.shell
431 meta = shell.meta
431 meta = shell.meta
432 disp_formatter = self.shell.display_formatter
432 disp_formatter = self.shell.display_formatter
433 ptformatter = disp_formatter.formatters['text/plain']
433 ptformatter = disp_formatter.formatters['text/plain']
434 # dstore is a data store kept in the instance metadata bag to track any
434 # dstore is a data store kept in the instance metadata bag to track any
435 # changes we make, so we can undo them later.
435 # changes we make, so we can undo them later.
436 dstore = meta.setdefault('doctest_mode',Struct())
436 dstore = meta.setdefault('doctest_mode',Struct())
437 save_dstore = dstore.setdefault
437 save_dstore = dstore.setdefault
438
438
439 # save a few values we'll need to recover later
439 # save a few values we'll need to recover later
440 mode = save_dstore('mode',False)
440 mode = save_dstore('mode',False)
441 save_dstore('rc_pprint',ptformatter.pprint)
441 save_dstore('rc_pprint',ptformatter.pprint)
442 save_dstore('xmode',shell.InteractiveTB.mode)
442 save_dstore('xmode',shell.InteractiveTB.mode)
443 save_dstore('rc_separate_out',shell.separate_out)
443 save_dstore('rc_separate_out',shell.separate_out)
444 save_dstore('rc_separate_out2',shell.separate_out2)
444 save_dstore('rc_separate_out2',shell.separate_out2)
445 save_dstore('rc_separate_in',shell.separate_in)
445 save_dstore('rc_separate_in',shell.separate_in)
446 save_dstore('rc_active_types',disp_formatter.active_types)
446 save_dstore('rc_active_types',disp_formatter.active_types)
447
447
448 if not mode:
448 if not mode:
449 # turn on
449 # turn on
450
450
451 # Prompt separators like plain python
451 # Prompt separators like plain python
452 shell.separate_in = ''
452 shell.separate_in = ''
453 shell.separate_out = ''
453 shell.separate_out = ''
454 shell.separate_out2 = ''
454 shell.separate_out2 = ''
455
455
456
456
457 ptformatter.pprint = False
457 ptformatter.pprint = False
458 disp_formatter.active_types = ['text/plain']
458 disp_formatter.active_types = ['text/plain']
459
459
460 shell.magic('xmode Plain')
460 shell.magic('xmode Plain')
461 else:
461 else:
462 # turn off
462 # turn off
463 shell.separate_in = dstore.rc_separate_in
463 shell.separate_in = dstore.rc_separate_in
464
464
465 shell.separate_out = dstore.rc_separate_out
465 shell.separate_out = dstore.rc_separate_out
466 shell.separate_out2 = dstore.rc_separate_out2
466 shell.separate_out2 = dstore.rc_separate_out2
467
467
468 ptformatter.pprint = dstore.rc_pprint
468 ptformatter.pprint = dstore.rc_pprint
469 disp_formatter.active_types = dstore.rc_active_types
469 disp_formatter.active_types = dstore.rc_active_types
470
470
471 shell.magic('xmode ' + dstore.xmode)
471 shell.magic('xmode ' + dstore.xmode)
472
472
473 # mode here is the state before we switch; switch_doctest_mode takes
473 # mode here is the state before we switch; switch_doctest_mode takes
474 # the mode we're switching to.
474 # the mode we're switching to.
475 shell.switch_doctest_mode(not mode)
475 shell.switch_doctest_mode(not mode)
476
476
477 # Store new mode and inform
477 # Store new mode and inform
478 dstore.mode = bool(not mode)
478 dstore.mode = bool(not mode)
479 mode_label = ['OFF','ON'][dstore.mode]
479 mode_label = ['OFF','ON'][dstore.mode]
480 print('Doctest mode is:', mode_label)
480 print('Doctest mode is:', mode_label)
481
481
482 @line_magic
482 @line_magic
483 def gui(self, parameter_s=''):
483 def gui(self, parameter_s=''):
484 """Enable or disable IPython GUI event loop integration.
484 """Enable or disable IPython GUI event loop integration.
485
485
486 %gui [GUINAME]
486 %gui [GUINAME]
487
487
488 This magic replaces IPython's threaded shells that were activated
488 This magic replaces IPython's threaded shells that were activated
489 using the (pylab/wthread/etc.) command line flags. GUI toolkits
489 using the (pylab/wthread/etc.) command line flags. GUI toolkits
490 can now be enabled at runtime and keyboard
490 can now be enabled at runtime and keyboard
491 interrupts should work without any problems. The following toolkits
491 interrupts should work without any problems. The following toolkits
492 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
492 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
493
493
494 %gui wx # enable wxPython event loop integration
494 %gui wx # enable wxPython event loop integration
495 %gui qt4|qt # enable PyQt4 event loop integration
495 %gui qt4|qt # enable PyQt4 event loop integration
496 %gui qt5 # enable PyQt5 event loop integration
496 %gui qt5 # enable PyQt5 event loop integration
497 %gui gtk # enable PyGTK event loop integration
497 %gui gtk # enable PyGTK event loop integration
498 %gui gtk3 # enable Gtk3 event loop integration
498 %gui gtk3 # enable Gtk3 event loop integration
499 %gui tk # enable Tk event loop integration
499 %gui tk # enable Tk event loop integration
500 %gui osx # enable Cocoa event loop integration
500 %gui osx # enable Cocoa event loop integration
501 # (requires %matplotlib 1.1)
501 # (requires %matplotlib 1.1)
502 %gui # disable all event loop integration
502 %gui # disable all event loop integration
503
503
504 WARNING: after any of these has been called you can simply create
504 WARNING: after any of these has been called you can simply create
505 an application object, but DO NOT start the event loop yourself, as
505 an application object, but DO NOT start the event loop yourself, as
506 we have already handled that.
506 we have already handled that.
507 """
507 """
508 opts, arg = self.parse_options(parameter_s, '')
508 opts, arg = self.parse_options(parameter_s, '')
509 if arg=='': arg = None
509 if arg=='': arg = None
510 try:
510 try:
511 return self.shell.enable_gui(arg)
511 return self.shell.enable_gui(arg)
512 except Exception as e:
512 except Exception as e:
513 # print simple error message, rather than traceback if we can't
513 # print simple error message, rather than traceback if we can't
514 # hook up the GUI
514 # hook up the GUI
515 error(str(e))
515 error(str(e))
516
516
517 @skip_doctest
517 @skip_doctest
518 @line_magic
518 @line_magic
519 def precision(self, s=''):
519 def precision(self, s=''):
520 """Set floating point precision for pretty printing.
520 """Set floating point precision for pretty printing.
521
521
522 Can set either integer precision or a format string.
522 Can set either integer precision or a format string.
523
523
524 If numpy has been imported and precision is an int,
524 If numpy has been imported and precision is an int,
525 numpy display precision will also be set, via ``numpy.set_printoptions``.
525 numpy display precision will also be set, via ``numpy.set_printoptions``.
526
526
527 If no argument is given, defaults will be restored.
527 If no argument is given, defaults will be restored.
528
528
529 Examples
529 Examples
530 --------
530 --------
531 ::
531 ::
532
532
533 In [1]: from math import pi
533 In [1]: from math import pi
534
534
535 In [2]: %precision 3
535 In [2]: %precision 3
536 Out[2]: u'%.3f'
536 Out[2]: u'%.3f'
537
537
538 In [3]: pi
538 In [3]: pi
539 Out[3]: 3.142
539 Out[3]: 3.142
540
540
541 In [4]: %precision %i
541 In [4]: %precision %i
542 Out[4]: u'%i'
542 Out[4]: u'%i'
543
543
544 In [5]: pi
544 In [5]: pi
545 Out[5]: 3
545 Out[5]: 3
546
546
547 In [6]: %precision %e
547 In [6]: %precision %e
548 Out[6]: u'%e'
548 Out[6]: u'%e'
549
549
550 In [7]: pi**10
550 In [7]: pi**10
551 Out[7]: 9.364805e+04
551 Out[7]: 9.364805e+04
552
552
553 In [8]: %precision
553 In [8]: %precision
554 Out[8]: u'%r'
554 Out[8]: u'%r'
555
555
556 In [9]: pi**10
556 In [9]: pi**10
557 Out[9]: 93648.047476082982
557 Out[9]: 93648.047476082982
558 """
558 """
559 ptformatter = self.shell.display_formatter.formatters['text/plain']
559 ptformatter = self.shell.display_formatter.formatters['text/plain']
560 ptformatter.float_precision = s
560 ptformatter.float_precision = s
561 return ptformatter.float_format
561 return ptformatter.float_format
562
562
563 @magic_arguments.magic_arguments()
563 @magic_arguments.magic_arguments()
564 @magic_arguments.argument(
564 @magic_arguments.argument(
565 '-e', '--export', action='store_true', default=False,
565 '-e', '--export', action='store_true', default=False,
566 help='Export IPython history as a notebook. The filename argument '
566 help='Export IPython history as a notebook. The filename argument '
567 'is used to specify the notebook name and format. For example '
567 'is used to specify the notebook name and format. For example '
568 'a filename of notebook.ipynb will result in a notebook name '
568 'a filename of notebook.ipynb will result in a notebook name '
569 'of "notebook" and a format of "json". Likewise using a ".py" '
569 'of "notebook" and a format of "json". Likewise using a ".py" '
570 'file extension will write the notebook as a Python script'
570 'file extension will write the notebook as a Python script'
571 )
571 )
572 @magic_arguments.argument(
572 @magic_arguments.argument(
573 'filename', type=unicode_type,
573 'filename', type=unicode_type,
574 help='Notebook name or filename'
574 help='Notebook name or filename'
575 )
575 )
576 @line_magic
576 @line_magic
577 def notebook(self, s):
577 def notebook(self, s):
578 """Export and convert IPython notebooks.
578 """Export and convert IPython notebooks.
579
579
580 This function can export the current IPython history to a notebook file.
580 This function can export the current IPython history to a notebook file.
581 For example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
581 For example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
582 To export the history to "foo.py" do "%notebook -e foo.py".
582 To export the history to "foo.py" do "%notebook -e foo.py".
583 """
583 """
584 args = magic_arguments.parse_argstring(self.notebook, s)
584 args = magic_arguments.parse_argstring(self.notebook, s)
585
585
586 from nbformat import write, v4
586 from nbformat import write, v4
587 if args.export:
587 if args.export:
588 cells = []
588 cells = []
589 hist = list(self.shell.history_manager.get_range())
589 hist = list(self.shell.history_manager.get_range())
590 if(len(hist)<=1):
590 if(len(hist)<=1):
591 raise ValueError('History is empty, cannot export')
591 raise ValueError('History is empty, cannot export')
592 for session, execution_count, source in hist[:-1]:
592 for session, execution_count, source in hist[:-1]:
593 cells.append(v4.new_code_cell(
593 cells.append(v4.new_code_cell(
594 execution_count=execution_count,
594 execution_count=execution_count,
595 source=source
595 source=source
596 ))
596 ))
597 nb = v4.new_notebook(cells=cells)
597 nb = v4.new_notebook(cells=cells)
598 with io.open(args.filename, 'w', encoding='utf-8') as f:
598 with io.open(args.filename, 'w', encoding='utf-8') as f:
599 write(nb, f, version=4)
599 write(nb, f, version=4)
@@ -1,1492 +1,1495 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
71 dark background
72
70 You can implement other color schemes easily, the syntax is fairly
73 You can implement other color schemes easily, the syntax is fairly
71 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
72 possible inclusion in future releases.
75 possible inclusion in future releases.
73
76
74 Inheritance diagram:
77 Inheritance diagram:
75
78
76 .. inheritance-diagram:: IPython.core.ultratb
79 .. inheritance-diagram:: IPython.core.ultratb
77 :parts: 3
80 :parts: 3
78 """
81 """
79
82
80 #*****************************************************************************
83 #*****************************************************************************
81 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
84 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
82 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
85 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
83 #
86 #
84 # 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
85 # the file COPYING, distributed as part of this software.
88 # the file COPYING, distributed as part of this software.
86 #*****************************************************************************
89 #*****************************************************************************
87
90
88 from __future__ import absolute_import
91 from __future__ import absolute_import
89 from __future__ import unicode_literals
92 from __future__ import unicode_literals
90 from __future__ import print_function
93 from __future__ import print_function
91
94
92 import dis
95 import dis
93 import inspect
96 import inspect
94 import keyword
97 import keyword
95 import linecache
98 import linecache
96 import os
99 import os
97 import pydoc
100 import pydoc
98 import re
101 import re
99 import sys
102 import sys
100 import time
103 import time
101 import tokenize
104 import tokenize
102 import traceback
105 import traceback
103 import types
106 import types
104
107
105 try: # Python 2
108 try: # Python 2
106 generate_tokens = tokenize.generate_tokens
109 generate_tokens = tokenize.generate_tokens
107 except AttributeError: # Python 3
110 except AttributeError: # Python 3
108 generate_tokens = tokenize.tokenize
111 generate_tokens = tokenize.tokenize
109
112
110 # For purposes of monkeypatching inspect to fix a bug in it.
113 # For purposes of monkeypatching inspect to fix a bug in it.
111 from inspect import getsourcefile, getfile, getmodule, \
114 from inspect import getsourcefile, getfile, getmodule, \
112 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
115 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
113
116
114 # IPython's own modules
117 # IPython's own modules
115 # Modified pdb which doesn't damage IPython's readline handling
118 # Modified pdb which doesn't damage IPython's readline handling
116 from IPython import get_ipython
119 from IPython import get_ipython
117 from IPython.core import debugger
120 from IPython.core import debugger
118 from IPython.core.display_trap import DisplayTrap
121 from IPython.core.display_trap import DisplayTrap
119 from IPython.core.excolors import exception_colors
122 from IPython.core.excolors import exception_colors
120 from IPython.utils import PyColorize
123 from IPython.utils import PyColorize
121 from IPython.utils import openpy
124 from IPython.utils import openpy
122 from IPython.utils import path as util_path
125 from IPython.utils import path as util_path
123 from IPython.utils import py3compat
126 from IPython.utils import py3compat
124 from IPython.utils import ulinecache
127 from IPython.utils import ulinecache
125 from IPython.utils.data import uniq_stable
128 from IPython.utils.data import uniq_stable
126 from IPython.utils.terminal import get_terminal_size
129 from IPython.utils.terminal import get_terminal_size
127 from logging import info, error
130 from logging import info, error
128
131
129 import IPython.utils.colorable as colorable
132 import IPython.utils.colorable as colorable
130
133
131 # Globals
134 # Globals
132 # amount of space to put line numbers before verbose tracebacks
135 # amount of space to put line numbers before verbose tracebacks
133 INDENT_SIZE = 8
136 INDENT_SIZE = 8
134
137
135 # Default color scheme. This is used, for example, by the traceback
138 # Default color scheme. This is used, for example, by the traceback
136 # formatter. When running in an actual IPython instance, the user's rc.colors
139 # formatter. When running in an actual IPython instance, the user's rc.colors
137 # value is used, but having a module global makes this functionality available
140 # value is used, but having a module global makes this functionality available
138 # to users of ultratb who are NOT running inside ipython.
141 # to users of ultratb who are NOT running inside ipython.
139 DEFAULT_SCHEME = 'NoColor'
142 DEFAULT_SCHEME = 'NoColor'
140
143
141 # ---------------------------------------------------------------------------
144 # ---------------------------------------------------------------------------
142 # Code begins
145 # Code begins
143
146
144 # Utility functions
147 # Utility functions
145 def inspect_error():
148 def inspect_error():
146 """Print a message about internal inspect errors.
149 """Print a message about internal inspect errors.
147
150
148 These are unfortunately quite common."""
151 These are unfortunately quite common."""
149
152
150 error('Internal Python error in the inspect module.\n'
153 error('Internal Python error in the inspect module.\n'
151 'Below is the traceback from this internal error.\n')
154 'Below is the traceback from this internal error.\n')
152
155
153
156
154 # This function is a monkeypatch we apply to the Python inspect module. We have
157 # This function is a monkeypatch we apply to the Python inspect module. We have
155 # now found when it's needed (see discussion on issue gh-1456), and we have a
158 # now found when it's needed (see discussion on issue gh-1456), and we have a
156 # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
159 # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if
157 # the monkeypatch is not applied. TK, Aug 2012.
160 # the monkeypatch is not applied. TK, Aug 2012.
158 def findsource(object):
161 def findsource(object):
159 """Return the entire source file and starting line number for an object.
162 """Return the entire source file and starting line number for an object.
160
163
161 The argument may be a module, class, method, function, traceback, frame,
164 The argument may be a module, class, method, function, traceback, frame,
162 or code object. The source code is returned as a list of all the lines
165 or code object. The source code is returned as a list of all the lines
163 in the file and the line number indexes a line in that list. An IOError
166 in the file and the line number indexes a line in that list. An IOError
164 is raised if the source code cannot be retrieved.
167 is raised if the source code cannot be retrieved.
165
168
166 FIXED version with which we monkeypatch the stdlib to work around a bug."""
169 FIXED version with which we monkeypatch the stdlib to work around a bug."""
167
170
168 file = getsourcefile(object) or getfile(object)
171 file = getsourcefile(object) or getfile(object)
169 # If the object is a frame, then trying to get the globals dict from its
172 # If the object is a frame, then trying to get the globals dict from its
170 # module won't work. Instead, the frame object itself has the globals
173 # module won't work. Instead, the frame object itself has the globals
171 # dictionary.
174 # dictionary.
172 globals_dict = None
175 globals_dict = None
173 if inspect.isframe(object):
176 if inspect.isframe(object):
174 # XXX: can this ever be false?
177 # XXX: can this ever be false?
175 globals_dict = object.f_globals
178 globals_dict = object.f_globals
176 else:
179 else:
177 module = getmodule(object, file)
180 module = getmodule(object, file)
178 if module:
181 if module:
179 globals_dict = module.__dict__
182 globals_dict = module.__dict__
180 lines = linecache.getlines(file, globals_dict)
183 lines = linecache.getlines(file, globals_dict)
181 if not lines:
184 if not lines:
182 raise IOError('could not get source code')
185 raise IOError('could not get source code')
183
186
184 if ismodule(object):
187 if ismodule(object):
185 return lines, 0
188 return lines, 0
186
189
187 if isclass(object):
190 if isclass(object):
188 name = object.__name__
191 name = object.__name__
189 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
192 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
190 # make some effort to find the best matching class definition:
193 # make some effort to find the best matching class definition:
191 # use the one with the least indentation, which is the one
194 # use the one with the least indentation, which is the one
192 # that's most probably not inside a function definition.
195 # that's most probably not inside a function definition.
193 candidates = []
196 candidates = []
194 for i in range(len(lines)):
197 for i in range(len(lines)):
195 match = pat.match(lines[i])
198 match = pat.match(lines[i])
196 if match:
199 if match:
197 # if it's at toplevel, it's already the best one
200 # if it's at toplevel, it's already the best one
198 if lines[i][0] == 'c':
201 if lines[i][0] == 'c':
199 return lines, i
202 return lines, i
200 # else add whitespace to candidate list
203 # else add whitespace to candidate list
201 candidates.append((match.group(1), i))
204 candidates.append((match.group(1), i))
202 if candidates:
205 if candidates:
203 # this will sort by whitespace, and by line number,
206 # this will sort by whitespace, and by line number,
204 # less whitespace first
207 # less whitespace first
205 candidates.sort()
208 candidates.sort()
206 return lines, candidates[0][1]
209 return lines, candidates[0][1]
207 else:
210 else:
208 raise IOError('could not find class definition')
211 raise IOError('could not find class definition')
209
212
210 if ismethod(object):
213 if ismethod(object):
211 object = object.__func__
214 object = object.__func__
212 if isfunction(object):
215 if isfunction(object):
213 object = object.__code__
216 object = object.__code__
214 if istraceback(object):
217 if istraceback(object):
215 object = object.tb_frame
218 object = object.tb_frame
216 if isframe(object):
219 if isframe(object):
217 object = object.f_code
220 object = object.f_code
218 if iscode(object):
221 if iscode(object):
219 if not hasattr(object, 'co_firstlineno'):
222 if not hasattr(object, 'co_firstlineno'):
220 raise IOError('could not find function definition')
223 raise IOError('could not find function definition')
221 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
224 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
222 pmatch = pat.match
225 pmatch = pat.match
223 # fperez - fix: sometimes, co_firstlineno can give a number larger than
226 # fperez - fix: sometimes, co_firstlineno can give a number larger than
224 # the length of lines, which causes an error. Safeguard against that.
227 # the length of lines, which causes an error. Safeguard against that.
225 lnum = min(object.co_firstlineno, len(lines)) - 1
228 lnum = min(object.co_firstlineno, len(lines)) - 1
226 while lnum > 0:
229 while lnum > 0:
227 if pmatch(lines[lnum]):
230 if pmatch(lines[lnum]):
228 break
231 break
229 lnum -= 1
232 lnum -= 1
230
233
231 return lines, lnum
234 return lines, lnum
232 raise IOError('could not find code object')
235 raise IOError('could not find code object')
233
236
234
237
235 # This is a patched version of inspect.getargs that applies the (unmerged)
238 # This is a patched version of inspect.getargs that applies the (unmerged)
236 # patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes
239 # patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes
237 # https://github.com/ipython/ipython/issues/8205 and
240 # https://github.com/ipython/ipython/issues/8205 and
238 # https://github.com/ipython/ipython/issues/8293
241 # https://github.com/ipython/ipython/issues/8293
239 def getargs(co):
242 def getargs(co):
240 """Get information about the arguments accepted by a code object.
243 """Get information about the arguments accepted by a code object.
241
244
242 Three things are returned: (args, varargs, varkw), where 'args' is
245 Three things are returned: (args, varargs, varkw), where 'args' is
243 a list of argument names (possibly containing nested lists), and
246 a list of argument names (possibly containing nested lists), and
244 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
247 'varargs' and 'varkw' are the names of the * and ** arguments or None."""
245 if not iscode(co):
248 if not iscode(co):
246 raise TypeError('{!r} is not a code object'.format(co))
249 raise TypeError('{!r} is not a code object'.format(co))
247
250
248 nargs = co.co_argcount
251 nargs = co.co_argcount
249 names = co.co_varnames
252 names = co.co_varnames
250 args = list(names[:nargs])
253 args = list(names[:nargs])
251 step = 0
254 step = 0
252
255
253 # The following acrobatics are for anonymous (tuple) arguments.
256 # The following acrobatics are for anonymous (tuple) arguments.
254 for i in range(nargs):
257 for i in range(nargs):
255 if args[i][:1] in ('', '.'):
258 if args[i][:1] in ('', '.'):
256 stack, remain, count = [], [], []
259 stack, remain, count = [], [], []
257 while step < len(co.co_code):
260 while step < len(co.co_code):
258 op = ord(co.co_code[step])
261 op = ord(co.co_code[step])
259 step = step + 1
262 step = step + 1
260 if op >= dis.HAVE_ARGUMENT:
263 if op >= dis.HAVE_ARGUMENT:
261 opname = dis.opname[op]
264 opname = dis.opname[op]
262 value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256
265 value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256
263 step = step + 2
266 step = step + 2
264 if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
267 if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'):
265 remain.append(value)
268 remain.append(value)
266 count.append(value)
269 count.append(value)
267 elif opname in ('STORE_FAST', 'STORE_DEREF'):
270 elif opname in ('STORE_FAST', 'STORE_DEREF'):
268 if op in dis.haslocal:
271 if op in dis.haslocal:
269 stack.append(co.co_varnames[value])
272 stack.append(co.co_varnames[value])
270 elif op in dis.hasfree:
273 elif op in dis.hasfree:
271 stack.append((co.co_cellvars + co.co_freevars)[value])
274 stack.append((co.co_cellvars + co.co_freevars)[value])
272 # Special case for sublists of length 1: def foo((bar))
275 # Special case for sublists of length 1: def foo((bar))
273 # doesn't generate the UNPACK_TUPLE bytecode, so if
276 # doesn't generate the UNPACK_TUPLE bytecode, so if
274 # `remain` is empty here, we have such a sublist.
277 # `remain` is empty here, we have such a sublist.
275 if not remain:
278 if not remain:
276 stack[0] = [stack[0]]
279 stack[0] = [stack[0]]
277 break
280 break
278 else:
281 else:
279 remain[-1] = remain[-1] - 1
282 remain[-1] = remain[-1] - 1
280 while remain[-1] == 0:
283 while remain[-1] == 0:
281 remain.pop()
284 remain.pop()
282 size = count.pop()
285 size = count.pop()
283 stack[-size:] = [stack[-size:]]
286 stack[-size:] = [stack[-size:]]
284 if not remain:
287 if not remain:
285 break
288 break
286 remain[-1] = remain[-1] - 1
289 remain[-1] = remain[-1] - 1
287 if not remain:
290 if not remain:
288 break
291 break
289 args[i] = stack[0]
292 args[i] = stack[0]
290
293
291 varargs = None
294 varargs = None
292 if co.co_flags & inspect.CO_VARARGS:
295 if co.co_flags & inspect.CO_VARARGS:
293 varargs = co.co_varnames[nargs]
296 varargs = co.co_varnames[nargs]
294 nargs = nargs + 1
297 nargs = nargs + 1
295 varkw = None
298 varkw = None
296 if co.co_flags & inspect.CO_VARKEYWORDS:
299 if co.co_flags & inspect.CO_VARKEYWORDS:
297 varkw = co.co_varnames[nargs]
300 varkw = co.co_varnames[nargs]
298 return inspect.Arguments(args, varargs, varkw)
301 return inspect.Arguments(args, varargs, varkw)
299
302
300
303
301 # Monkeypatch inspect to apply our bugfix.
304 # Monkeypatch inspect to apply our bugfix.
302 def with_patch_inspect(f):
305 def with_patch_inspect(f):
303 """decorator for monkeypatching inspect.findsource"""
306 """decorator for monkeypatching inspect.findsource"""
304
307
305 def wrapped(*args, **kwargs):
308 def wrapped(*args, **kwargs):
306 save_findsource = inspect.findsource
309 save_findsource = inspect.findsource
307 save_getargs = inspect.getargs
310 save_getargs = inspect.getargs
308 inspect.findsource = findsource
311 inspect.findsource = findsource
309 inspect.getargs = getargs
312 inspect.getargs = getargs
310 try:
313 try:
311 return f(*args, **kwargs)
314 return f(*args, **kwargs)
312 finally:
315 finally:
313 inspect.findsource = save_findsource
316 inspect.findsource = save_findsource
314 inspect.getargs = save_getargs
317 inspect.getargs = save_getargs
315
318
316 return wrapped
319 return wrapped
317
320
318
321
319 if py3compat.PY3:
322 if py3compat.PY3:
320 fixed_getargvalues = inspect.getargvalues
323 fixed_getargvalues = inspect.getargvalues
321 else:
324 else:
322 # Fixes for https://github.com/ipython/ipython/issues/8293
325 # Fixes for https://github.com/ipython/ipython/issues/8293
323 # and https://github.com/ipython/ipython/issues/8205.
326 # and https://github.com/ipython/ipython/issues/8205.
324 # The relevant bug is caused by failure to correctly handle anonymous tuple
327 # The relevant bug is caused by failure to correctly handle anonymous tuple
325 # unpacking, which only exists in Python 2.
328 # unpacking, which only exists in Python 2.
326 fixed_getargvalues = with_patch_inspect(inspect.getargvalues)
329 fixed_getargvalues = with_patch_inspect(inspect.getargvalues)
327
330
328
331
329 def fix_frame_records_filenames(records):
332 def fix_frame_records_filenames(records):
330 """Try to fix the filenames in each record from inspect.getinnerframes().
333 """Try to fix the filenames in each record from inspect.getinnerframes().
331
334
332 Particularly, modules loaded from within zip files have useless filenames
335 Particularly, modules loaded from within zip files have useless filenames
333 attached to their code object, and inspect.getinnerframes() just uses it.
336 attached to their code object, and inspect.getinnerframes() just uses it.
334 """
337 """
335 fixed_records = []
338 fixed_records = []
336 for frame, filename, line_no, func_name, lines, index in records:
339 for frame, filename, line_no, func_name, lines, index in records:
337 # Look inside the frame's globals dictionary for __file__,
340 # Look inside the frame's globals dictionary for __file__,
338 # which should be better. However, keep Cython filenames since
341 # which should be better. However, keep Cython filenames since
339 # we prefer the source filenames over the compiled .so file.
342 # we prefer the source filenames over the compiled .so file.
340 filename = py3compat.cast_unicode_py2(filename, "utf-8")
343 filename = py3compat.cast_unicode_py2(filename, "utf-8")
341 if not filename.endswith(('.pyx', '.pxd', '.pxi')):
344 if not filename.endswith(('.pyx', '.pxd', '.pxi')):
342 better_fn = frame.f_globals.get('__file__', None)
345 better_fn = frame.f_globals.get('__file__', None)
343 if isinstance(better_fn, str):
346 if isinstance(better_fn, str):
344 # Check the type just in case someone did something weird with
347 # Check the type just in case someone did something weird with
345 # __file__. It might also be None if the error occurred during
348 # __file__. It might also be None if the error occurred during
346 # import.
349 # import.
347 filename = better_fn
350 filename = better_fn
348 fixed_records.append((frame, filename, line_no, func_name, lines, index))
351 fixed_records.append((frame, filename, line_no, func_name, lines, index))
349 return fixed_records
352 return fixed_records
350
353
351
354
352 @with_patch_inspect
355 @with_patch_inspect
353 def _fixed_getinnerframes(etb, context=1, tb_offset=0):
356 def _fixed_getinnerframes(etb, context=1, tb_offset=0):
354 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
357 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
355
358
356 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
359 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
357 # If the error is at the console, don't build any context, since it would
360 # If the error is at the console, don't build any context, since it would
358 # otherwise produce 5 blank lines printed out (there is no file at the
361 # otherwise produce 5 blank lines printed out (there is no file at the
359 # console)
362 # console)
360 rec_check = records[tb_offset:]
363 rec_check = records[tb_offset:]
361 try:
364 try:
362 rname = rec_check[0][1]
365 rname = rec_check[0][1]
363 if rname == '<ipython console>' or rname.endswith('<string>'):
366 if rname == '<ipython console>' or rname.endswith('<string>'):
364 return rec_check
367 return rec_check
365 except IndexError:
368 except IndexError:
366 pass
369 pass
367
370
368 aux = traceback.extract_tb(etb)
371 aux = traceback.extract_tb(etb)
369 assert len(records) == len(aux)
372 assert len(records) == len(aux)
370 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
373 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
371 maybeStart = lnum - 1 - context // 2
374 maybeStart = lnum - 1 - context // 2
372 start = max(maybeStart, 0)
375 start = max(maybeStart, 0)
373 end = start + context
376 end = start + context
374 lines = ulinecache.getlines(file)[start:end]
377 lines = ulinecache.getlines(file)[start:end]
375 buf = list(records[i])
378 buf = list(records[i])
376 buf[LNUM_POS] = lnum
379 buf[LNUM_POS] = lnum
377 buf[INDEX_POS] = lnum - 1 - start
380 buf[INDEX_POS] = lnum - 1 - start
378 buf[LINES_POS] = lines
381 buf[LINES_POS] = lines
379 records[i] = tuple(buf)
382 records[i] = tuple(buf)
380 return records[tb_offset:]
383 return records[tb_offset:]
381
384
382 # Helper function -- largely belongs to VerboseTB, but we need the same
385 # Helper function -- largely belongs to VerboseTB, but we need the same
383 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
386 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
384 # can be recognized properly by ipython.el's py-traceback-line-re
387 # can be recognized properly by ipython.el's py-traceback-line-re
385 # (SyntaxErrors have to be treated specially because they have no traceback)
388 # (SyntaxErrors have to be treated specially because they have no traceback)
386
389
387 _parser = PyColorize.Parser()
390 _parser = PyColorize.Parser()
388
391
389
392
390 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None, scheme=None):
393 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None, scheme=None):
391 numbers_width = INDENT_SIZE - 1
394 numbers_width = INDENT_SIZE - 1
392 res = []
395 res = []
393 i = lnum - index
396 i = lnum - index
394
397
395 # This lets us get fully syntax-highlighted tracebacks.
398 # This lets us get fully syntax-highlighted tracebacks.
396 if scheme is None:
399 if scheme is None:
397 ipinst = get_ipython()
400 ipinst = get_ipython()
398 if ipinst is not None:
401 if ipinst is not None:
399 scheme = ipinst.colors
402 scheme = ipinst.colors
400 else:
403 else:
401 scheme = DEFAULT_SCHEME
404 scheme = DEFAULT_SCHEME
402
405
403 _line_format = _parser.format2
406 _line_format = _parser.format2
404
407
405 for line in lines:
408 for line in lines:
406 line = py3compat.cast_unicode(line)
409 line = py3compat.cast_unicode(line)
407
410
408 new_line, err = _line_format(line, 'str', scheme)
411 new_line, err = _line_format(line, 'str', scheme)
409 if not err: line = new_line
412 if not err: line = new_line
410
413
411 if i == lnum:
414 if i == lnum:
412 # This is the line with the error
415 # This is the line with the error
413 pad = numbers_width - len(str(i))
416 pad = numbers_width - len(str(i))
414 num = '%s%s' % (debugger.make_arrow(pad), str(lnum))
417 num = '%s%s' % (debugger.make_arrow(pad), str(lnum))
415 line = '%s%s%s %s%s' % (Colors.linenoEm, num,
418 line = '%s%s%s %s%s' % (Colors.linenoEm, num,
416 Colors.line, line, Colors.Normal)
419 Colors.line, line, Colors.Normal)
417 else:
420 else:
418 num = '%*s' % (numbers_width, i)
421 num = '%*s' % (numbers_width, i)
419 line = '%s%s%s %s' % (Colors.lineno, num,
422 line = '%s%s%s %s' % (Colors.lineno, num,
420 Colors.Normal, line)
423 Colors.Normal, line)
421
424
422 res.append(line)
425 res.append(line)
423 if lvals and i == lnum:
426 if lvals and i == lnum:
424 res.append(lvals + '\n')
427 res.append(lvals + '\n')
425 i = i + 1
428 i = i + 1
426 return res
429 return res
427
430
428 def is_recursion_error(etype, value, records):
431 def is_recursion_error(etype, value, records):
429 try:
432 try:
430 # RecursionError is new in Python 3.5
433 # RecursionError is new in Python 3.5
431 recursion_error_type = RecursionError
434 recursion_error_type = RecursionError
432 except NameError:
435 except NameError:
433 recursion_error_type = RuntimeError
436 recursion_error_type = RuntimeError
434
437
435 # The default recursion limit is 1000, but some of that will be taken up
438 # The default recursion limit is 1000, but some of that will be taken up
436 # by stack frames in IPython itself. >500 frames probably indicates
439 # by stack frames in IPython itself. >500 frames probably indicates
437 # a recursion error.
440 # a recursion error.
438 return (etype is recursion_error_type) \
441 return (etype is recursion_error_type) \
439 and "recursion" in str(value).lower() \
442 and "recursion" in str(value).lower() \
440 and len(records) > 500
443 and len(records) > 500
441
444
442 def find_recursion(etype, value, records):
445 def find_recursion(etype, value, records):
443 """Identify the repeating stack frames from a RecursionError traceback
446 """Identify the repeating stack frames from a RecursionError traceback
444
447
445 'records' is a list as returned by VerboseTB.get_records()
448 'records' is a list as returned by VerboseTB.get_records()
446
449
447 Returns (last_unique, repeat_length)
450 Returns (last_unique, repeat_length)
448 """
451 """
449 # This involves a bit of guesswork - we want to show enough of the traceback
452 # This involves a bit of guesswork - we want to show enough of the traceback
450 # to indicate where the recursion is occurring. We guess that the innermost
453 # to indicate where the recursion is occurring. We guess that the innermost
451 # quarter of the traceback (250 frames by default) is repeats, and find the
454 # quarter of the traceback (250 frames by default) is repeats, and find the
452 # first frame (from in to out) that looks different.
455 # first frame (from in to out) that looks different.
453 if not is_recursion_error(etype, value, records):
456 if not is_recursion_error(etype, value, records):
454 return len(records), 0
457 return len(records), 0
455
458
456 # Select filename, lineno, func_name to track frames with
459 # Select filename, lineno, func_name to track frames with
457 records = [r[1:4] for r in records]
460 records = [r[1:4] for r in records]
458 inner_frames = records[-(len(records)//4):]
461 inner_frames = records[-(len(records)//4):]
459 frames_repeated = set(inner_frames)
462 frames_repeated = set(inner_frames)
460
463
461 last_seen_at = {}
464 last_seen_at = {}
462 longest_repeat = 0
465 longest_repeat = 0
463 i = len(records)
466 i = len(records)
464 for frame in reversed(records):
467 for frame in reversed(records):
465 i -= 1
468 i -= 1
466 if frame not in frames_repeated:
469 if frame not in frames_repeated:
467 last_unique = i
470 last_unique = i
468 break
471 break
469
472
470 if frame in last_seen_at:
473 if frame in last_seen_at:
471 distance = last_seen_at[frame] - i
474 distance = last_seen_at[frame] - i
472 longest_repeat = max(longest_repeat, distance)
475 longest_repeat = max(longest_repeat, distance)
473
476
474 last_seen_at[frame] = i
477 last_seen_at[frame] = i
475 else:
478 else:
476 last_unique = 0 # The whole traceback was recursion
479 last_unique = 0 # The whole traceback was recursion
477
480
478 return last_unique, longest_repeat
481 return last_unique, longest_repeat
479
482
480 #---------------------------------------------------------------------------
483 #---------------------------------------------------------------------------
481 # Module classes
484 # Module classes
482 class TBTools(colorable.Colorable):
485 class TBTools(colorable.Colorable):
483 """Basic tools used by all traceback printer classes."""
486 """Basic tools used by all traceback printer classes."""
484
487
485 # Number of frames to skip when reporting tracebacks
488 # Number of frames to skip when reporting tracebacks
486 tb_offset = 0
489 tb_offset = 0
487
490
488 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
491 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
489 # Whether to call the interactive pdb debugger after printing
492 # Whether to call the interactive pdb debugger after printing
490 # tracebacks or not
493 # tracebacks or not
491 super(TBTools, self).__init__(parent=parent, config=config)
494 super(TBTools, self).__init__(parent=parent, config=config)
492 self.call_pdb = call_pdb
495 self.call_pdb = call_pdb
493
496
494 # Output stream to write to. Note that we store the original value in
497 # Output stream to write to. Note that we store the original value in
495 # a private attribute and then make the public ostream a property, so
498 # a private attribute and then make the public ostream a property, so
496 # that we can delay accessing io.stdout until runtime. The way
499 # that we can delay accessing io.stdout until runtime. The way
497 # things are written now, the io.stdout object is dynamically managed
500 # things are written now, the io.stdout object is dynamically managed
498 # so a reference to it should NEVER be stored statically. This
501 # so a reference to it should NEVER be stored statically. This
499 # property approach confines this detail to a single location, and all
502 # property approach confines this detail to a single location, and all
500 # subclasses can simply access self.ostream for writing.
503 # subclasses can simply access self.ostream for writing.
501 self._ostream = ostream
504 self._ostream = ostream
502
505
503 # Create color table
506 # Create color table
504 self.color_scheme_table = exception_colors()
507 self.color_scheme_table = exception_colors()
505
508
506 self.set_colors(color_scheme)
509 self.set_colors(color_scheme)
507 self.old_scheme = color_scheme # save initial value for toggles
510 self.old_scheme = color_scheme # save initial value for toggles
508
511
509 if call_pdb:
512 if call_pdb:
510 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
513 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
511 else:
514 else:
512 self.pdb = None
515 self.pdb = None
513
516
514 def _get_ostream(self):
517 def _get_ostream(self):
515 """Output stream that exceptions are written to.
518 """Output stream that exceptions are written to.
516
519
517 Valid values are:
520 Valid values are:
518
521
519 - None: the default, which means that IPython will dynamically resolve
522 - None: the default, which means that IPython will dynamically resolve
520 to io.stdout. This ensures compatibility with most tools, including
523 to io.stdout. This ensures compatibility with most tools, including
521 Windows (where plain stdout doesn't recognize ANSI escapes).
524 Windows (where plain stdout doesn't recognize ANSI escapes).
522
525
523 - Any object with 'write' and 'flush' attributes.
526 - Any object with 'write' and 'flush' attributes.
524 """
527 """
525 return sys.stdout if self._ostream is None else self._ostream
528 return sys.stdout if self._ostream is None else self._ostream
526
529
527 def _set_ostream(self, val):
530 def _set_ostream(self, val):
528 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
531 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
529 self._ostream = val
532 self._ostream = val
530
533
531 ostream = property(_get_ostream, _set_ostream)
534 ostream = property(_get_ostream, _set_ostream)
532
535
533 def set_colors(self, *args, **kw):
536 def set_colors(self, *args, **kw):
534 """Shorthand access to the color table scheme selector method."""
537 """Shorthand access to the color table scheme selector method."""
535
538
536 # Set own color table
539 # Set own color table
537 self.color_scheme_table.set_active_scheme(*args, **kw)
540 self.color_scheme_table.set_active_scheme(*args, **kw)
538 # for convenience, set Colors to the active scheme
541 # for convenience, set Colors to the active scheme
539 self.Colors = self.color_scheme_table.active_colors
542 self.Colors = self.color_scheme_table.active_colors
540 # Also set colors of debugger
543 # Also set colors of debugger
541 if hasattr(self, 'pdb') and self.pdb is not None:
544 if hasattr(self, 'pdb') and self.pdb is not None:
542 self.pdb.set_colors(*args, **kw)
545 self.pdb.set_colors(*args, **kw)
543
546
544 def color_toggle(self):
547 def color_toggle(self):
545 """Toggle between the currently active color scheme and NoColor."""
548 """Toggle between the currently active color scheme and NoColor."""
546
549
547 if self.color_scheme_table.active_scheme_name == 'NoColor':
550 if self.color_scheme_table.active_scheme_name == 'NoColor':
548 self.color_scheme_table.set_active_scheme(self.old_scheme)
551 self.color_scheme_table.set_active_scheme(self.old_scheme)
549 self.Colors = self.color_scheme_table.active_colors
552 self.Colors = self.color_scheme_table.active_colors
550 else:
553 else:
551 self.old_scheme = self.color_scheme_table.active_scheme_name
554 self.old_scheme = self.color_scheme_table.active_scheme_name
552 self.color_scheme_table.set_active_scheme('NoColor')
555 self.color_scheme_table.set_active_scheme('NoColor')
553 self.Colors = self.color_scheme_table.active_colors
556 self.Colors = self.color_scheme_table.active_colors
554
557
555 def stb2text(self, stb):
558 def stb2text(self, stb):
556 """Convert a structured traceback (a list) to a string."""
559 """Convert a structured traceback (a list) to a string."""
557 return '\n'.join(stb)
560 return '\n'.join(stb)
558
561
559 def text(self, etype, value, tb, tb_offset=None, context=5):
562 def text(self, etype, value, tb, tb_offset=None, context=5):
560 """Return formatted traceback.
563 """Return formatted traceback.
561
564
562 Subclasses may override this if they add extra arguments.
565 Subclasses may override this if they add extra arguments.
563 """
566 """
564 tb_list = self.structured_traceback(etype, value, tb,
567 tb_list = self.structured_traceback(etype, value, tb,
565 tb_offset, context)
568 tb_offset, context)
566 return self.stb2text(tb_list)
569 return self.stb2text(tb_list)
567
570
568 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
571 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
569 context=5, mode=None):
572 context=5, mode=None):
570 """Return a list of traceback frames.
573 """Return a list of traceback frames.
571
574
572 Must be implemented by each class.
575 Must be implemented by each class.
573 """
576 """
574 raise NotImplementedError()
577 raise NotImplementedError()
575
578
576
579
577 #---------------------------------------------------------------------------
580 #---------------------------------------------------------------------------
578 class ListTB(TBTools):
581 class ListTB(TBTools):
579 """Print traceback information from a traceback list, with optional color.
582 """Print traceback information from a traceback list, with optional color.
580
583
581 Calling requires 3 arguments: (etype, evalue, elist)
584 Calling requires 3 arguments: (etype, evalue, elist)
582 as would be obtained by::
585 as would be obtained by::
583
586
584 etype, evalue, tb = sys.exc_info()
587 etype, evalue, tb = sys.exc_info()
585 if tb:
588 if tb:
586 elist = traceback.extract_tb(tb)
589 elist = traceback.extract_tb(tb)
587 else:
590 else:
588 elist = None
591 elist = None
589
592
590 It can thus be used by programs which need to process the traceback before
593 It can thus be used by programs which need to process the traceback before
591 printing (such as console replacements based on the code module from the
594 printing (such as console replacements based on the code module from the
592 standard library).
595 standard library).
593
596
594 Because they are meant to be called without a full traceback (only a
597 Because they are meant to be called without a full traceback (only a
595 list), instances of this class can't call the interactive pdb debugger."""
598 list), instances of this class can't call the interactive pdb debugger."""
596
599
597 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None):
600 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None):
598 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
601 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
599 ostream=ostream, parent=parent)
602 ostream=ostream, parent=parent)
600
603
601 def __call__(self, etype, value, elist):
604 def __call__(self, etype, value, elist):
602 self.ostream.flush()
605 self.ostream.flush()
603 self.ostream.write(self.text(etype, value, elist))
606 self.ostream.write(self.text(etype, value, elist))
604 self.ostream.write('\n')
607 self.ostream.write('\n')
605
608
606 def structured_traceback(self, etype, value, elist, tb_offset=None,
609 def structured_traceback(self, etype, value, elist, tb_offset=None,
607 context=5):
610 context=5):
608 """Return a color formatted string with the traceback info.
611 """Return a color formatted string with the traceback info.
609
612
610 Parameters
613 Parameters
611 ----------
614 ----------
612 etype : exception type
615 etype : exception type
613 Type of the exception raised.
616 Type of the exception raised.
614
617
615 value : object
618 value : object
616 Data stored in the exception
619 Data stored in the exception
617
620
618 elist : list
621 elist : list
619 List of frames, see class docstring for details.
622 List of frames, see class docstring for details.
620
623
621 tb_offset : int, optional
624 tb_offset : int, optional
622 Number of frames in the traceback to skip. If not given, the
625 Number of frames in the traceback to skip. If not given, the
623 instance value is used (set in constructor).
626 instance value is used (set in constructor).
624
627
625 context : int, optional
628 context : int, optional
626 Number of lines of context information to print.
629 Number of lines of context information to print.
627
630
628 Returns
631 Returns
629 -------
632 -------
630 String with formatted exception.
633 String with formatted exception.
631 """
634 """
632 tb_offset = self.tb_offset if tb_offset is None else tb_offset
635 tb_offset = self.tb_offset if tb_offset is None else tb_offset
633 Colors = self.Colors
636 Colors = self.Colors
634 out_list = []
637 out_list = []
635 if elist:
638 if elist:
636
639
637 if tb_offset and len(elist) > tb_offset:
640 if tb_offset and len(elist) > tb_offset:
638 elist = elist[tb_offset:]
641 elist = elist[tb_offset:]
639
642
640 out_list.append('Traceback %s(most recent call last)%s:' %
643 out_list.append('Traceback %s(most recent call last)%s:' %
641 (Colors.normalEm, Colors.Normal) + '\n')
644 (Colors.normalEm, Colors.Normal) + '\n')
642 out_list.extend(self._format_list(elist))
645 out_list.extend(self._format_list(elist))
643 # The exception info should be a single entry in the list.
646 # The exception info should be a single entry in the list.
644 lines = ''.join(self._format_exception_only(etype, value))
647 lines = ''.join(self._format_exception_only(etype, value))
645 out_list.append(lines)
648 out_list.append(lines)
646
649
647 # Note: this code originally read:
650 # Note: this code originally read:
648
651
649 ## for line in lines[:-1]:
652 ## for line in lines[:-1]:
650 ## out_list.append(" "+line)
653 ## out_list.append(" "+line)
651 ## out_list.append(lines[-1])
654 ## out_list.append(lines[-1])
652
655
653 # This means it was indenting everything but the last line by a little
656 # This means it was indenting everything but the last line by a little
654 # bit. I've disabled this for now, but if we see ugliness somewhere we
657 # bit. I've disabled this for now, but if we see ugliness somewhere we
655 # can restore it.
658 # can restore it.
656
659
657 return out_list
660 return out_list
658
661
659 def _format_list(self, extracted_list):
662 def _format_list(self, extracted_list):
660 """Format a list of traceback entry tuples for printing.
663 """Format a list of traceback entry tuples for printing.
661
664
662 Given a list of tuples as returned by extract_tb() or
665 Given a list of tuples as returned by extract_tb() or
663 extract_stack(), return a list of strings ready for printing.
666 extract_stack(), return a list of strings ready for printing.
664 Each string in the resulting list corresponds to the item with the
667 Each string in the resulting list corresponds to the item with the
665 same index in the argument list. Each string ends in a newline;
668 same index in the argument list. Each string ends in a newline;
666 the strings may contain internal newlines as well, for those items
669 the strings may contain internal newlines as well, for those items
667 whose source text line is not None.
670 whose source text line is not None.
668
671
669 Lifted almost verbatim from traceback.py
672 Lifted almost verbatim from traceback.py
670 """
673 """
671
674
672 Colors = self.Colors
675 Colors = self.Colors
673 list = []
676 list = []
674 for filename, lineno, name, line in extracted_list[:-1]:
677 for filename, lineno, name, line in extracted_list[:-1]:
675 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
678 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
676 (Colors.filename, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.Normal,
679 (Colors.filename, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.Normal,
677 Colors.lineno, lineno, Colors.Normal,
680 Colors.lineno, lineno, Colors.Normal,
678 Colors.name, py3compat.cast_unicode_py2(name, "utf-8"), Colors.Normal)
681 Colors.name, py3compat.cast_unicode_py2(name, "utf-8"), Colors.Normal)
679 if line:
682 if line:
680 item += ' %s\n' % line.strip()
683 item += ' %s\n' % line.strip()
681 list.append(item)
684 list.append(item)
682 # Emphasize the last entry
685 # Emphasize the last entry
683 filename, lineno, name, line = extracted_list[-1]
686 filename, lineno, name, line = extracted_list[-1]
684 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
687 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
685 (Colors.normalEm,
688 (Colors.normalEm,
686 Colors.filenameEm, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.normalEm,
689 Colors.filenameEm, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.normalEm,
687 Colors.linenoEm, lineno, Colors.normalEm,
690 Colors.linenoEm, lineno, Colors.normalEm,
688 Colors.nameEm, py3compat.cast_unicode_py2(name, "utf-8"), Colors.normalEm,
691 Colors.nameEm, py3compat.cast_unicode_py2(name, "utf-8"), Colors.normalEm,
689 Colors.Normal)
692 Colors.Normal)
690 if line:
693 if line:
691 item += '%s %s%s\n' % (Colors.line, line.strip(),
694 item += '%s %s%s\n' % (Colors.line, line.strip(),
692 Colors.Normal)
695 Colors.Normal)
693 list.append(item)
696 list.append(item)
694 return list
697 return list
695
698
696 def _format_exception_only(self, etype, value):
699 def _format_exception_only(self, etype, value):
697 """Format the exception part of a traceback.
700 """Format the exception part of a traceback.
698
701
699 The arguments are the exception type and value such as given by
702 The arguments are the exception type and value such as given by
700 sys.exc_info()[:2]. The return value is a list of strings, each ending
703 sys.exc_info()[:2]. The return value is a list of strings, each ending
701 in a newline. Normally, the list contains a single string; however,
704 in a newline. Normally, the list contains a single string; however,
702 for SyntaxError exceptions, it contains several lines that (when
705 for SyntaxError exceptions, it contains several lines that (when
703 printed) display detailed information about where the syntax error
706 printed) display detailed information about where the syntax error
704 occurred. The message indicating which exception occurred is the
707 occurred. The message indicating which exception occurred is the
705 always last string in the list.
708 always last string in the list.
706
709
707 Also lifted nearly verbatim from traceback.py
710 Also lifted nearly verbatim from traceback.py
708 """
711 """
709 have_filedata = False
712 have_filedata = False
710 Colors = self.Colors
713 Colors = self.Colors
711 list = []
714 list = []
712 stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
715 stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
713 if value is None:
716 if value is None:
714 # Not sure if this can still happen in Python 2.6 and above
717 # Not sure if this can still happen in Python 2.6 and above
715 list.append(stype + '\n')
718 list.append(stype + '\n')
716 else:
719 else:
717 if issubclass(etype, SyntaxError):
720 if issubclass(etype, SyntaxError):
718 have_filedata = True
721 have_filedata = True
719 if not value.filename: value.filename = "<string>"
722 if not value.filename: value.filename = "<string>"
720 if value.lineno:
723 if value.lineno:
721 lineno = value.lineno
724 lineno = value.lineno
722 textline = ulinecache.getline(value.filename, value.lineno)
725 textline = ulinecache.getline(value.filename, value.lineno)
723 else:
726 else:
724 lineno = 'unknown'
727 lineno = 'unknown'
725 textline = ''
728 textline = ''
726 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
729 list.append('%s File %s"%s"%s, line %s%s%s\n' % \
727 (Colors.normalEm,
730 (Colors.normalEm,
728 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
731 Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm,
729 Colors.linenoEm, lineno, Colors.Normal ))
732 Colors.linenoEm, lineno, Colors.Normal ))
730 if textline == '':
733 if textline == '':
731 textline = py3compat.cast_unicode(value.text, "utf-8")
734 textline = py3compat.cast_unicode(value.text, "utf-8")
732
735
733 if textline is not None:
736 if textline is not None:
734 i = 0
737 i = 0
735 while i < len(textline) and textline[i].isspace():
738 while i < len(textline) and textline[i].isspace():
736 i += 1
739 i += 1
737 list.append('%s %s%s\n' % (Colors.line,
740 list.append('%s %s%s\n' % (Colors.line,
738 textline.strip(),
741 textline.strip(),
739 Colors.Normal))
742 Colors.Normal))
740 if value.offset is not None:
743 if value.offset is not None:
741 s = ' '
744 s = ' '
742 for c in textline[i:value.offset - 1]:
745 for c in textline[i:value.offset - 1]:
743 if c.isspace():
746 if c.isspace():
744 s += c
747 s += c
745 else:
748 else:
746 s += ' '
749 s += ' '
747 list.append('%s%s^%s\n' % (Colors.caret, s,
750 list.append('%s%s^%s\n' % (Colors.caret, s,
748 Colors.Normal))
751 Colors.Normal))
749
752
750 try:
753 try:
751 s = value.msg
754 s = value.msg
752 except Exception:
755 except Exception:
753 s = self._some_str(value)
756 s = self._some_str(value)
754 if s:
757 if s:
755 list.append('%s%s:%s %s\n' % (stype, Colors.excName,
758 list.append('%s%s:%s %s\n' % (stype, Colors.excName,
756 Colors.Normal, s))
759 Colors.Normal, s))
757 else:
760 else:
758 list.append('%s\n' % stype)
761 list.append('%s\n' % stype)
759
762
760 # sync with user hooks
763 # sync with user hooks
761 if have_filedata:
764 if have_filedata:
762 ipinst = get_ipython()
765 ipinst = get_ipython()
763 if ipinst is not None:
766 if ipinst is not None:
764 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
767 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
765
768
766 return list
769 return list
767
770
768 def get_exception_only(self, etype, value):
771 def get_exception_only(self, etype, value):
769 """Only print the exception type and message, without a traceback.
772 """Only print the exception type and message, without a traceback.
770
773
771 Parameters
774 Parameters
772 ----------
775 ----------
773 etype : exception type
776 etype : exception type
774 value : exception value
777 value : exception value
775 """
778 """
776 return ListTB.structured_traceback(self, etype, value, [])
779 return ListTB.structured_traceback(self, etype, value, [])
777
780
778 def show_exception_only(self, etype, evalue):
781 def show_exception_only(self, etype, evalue):
779 """Only print the exception type and message, without a traceback.
782 """Only print the exception type and message, without a traceback.
780
783
781 Parameters
784 Parameters
782 ----------
785 ----------
783 etype : exception type
786 etype : exception type
784 value : exception value
787 value : exception value
785 """
788 """
786 # This method needs to use __call__ from *this* class, not the one from
789 # This method needs to use __call__ from *this* class, not the one from
787 # a subclass whose signature or behavior may be different
790 # a subclass whose signature or behavior may be different
788 ostream = self.ostream
791 ostream = self.ostream
789 ostream.flush()
792 ostream.flush()
790 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
793 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
791 ostream.flush()
794 ostream.flush()
792
795
793 def _some_str(self, value):
796 def _some_str(self, value):
794 # Lifted from traceback.py
797 # Lifted from traceback.py
795 try:
798 try:
796 return py3compat.cast_unicode(str(value))
799 return py3compat.cast_unicode(str(value))
797 except:
800 except:
798 return u'<unprintable %s object>' % type(value).__name__
801 return u'<unprintable %s object>' % type(value).__name__
799
802
800
803
801 #----------------------------------------------------------------------------
804 #----------------------------------------------------------------------------
802 class VerboseTB(TBTools):
805 class VerboseTB(TBTools):
803 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
806 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
804 of HTML. Requires inspect and pydoc. Crazy, man.
807 of HTML. Requires inspect and pydoc. Crazy, man.
805
808
806 Modified version which optionally strips the topmost entries from the
809 Modified version which optionally strips the topmost entries from the
807 traceback, to be used with alternate interpreters (because their own code
810 traceback, to be used with alternate interpreters (because their own code
808 would appear in the traceback)."""
811 would appear in the traceback)."""
809
812
810 def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
813 def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
811 tb_offset=0, long_header=False, include_vars=True,
814 tb_offset=0, long_header=False, include_vars=True,
812 check_cache=None, debugger_cls = None):
815 check_cache=None, debugger_cls = None):
813 """Specify traceback offset, headers and color scheme.
816 """Specify traceback offset, headers and color scheme.
814
817
815 Define how many frames to drop from the tracebacks. Calling it with
818 Define how many frames to drop from the tracebacks. Calling it with
816 tb_offset=1 allows use of this handler in interpreters which will have
819 tb_offset=1 allows use of this handler in interpreters which will have
817 their own code at the top of the traceback (VerboseTB will first
820 their own code at the top of the traceback (VerboseTB will first
818 remove that frame before printing the traceback info)."""
821 remove that frame before printing the traceback info)."""
819 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
822 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
820 ostream=ostream)
823 ostream=ostream)
821 self.tb_offset = tb_offset
824 self.tb_offset = tb_offset
822 self.long_header = long_header
825 self.long_header = long_header
823 self.include_vars = include_vars
826 self.include_vars = include_vars
824 # By default we use linecache.checkcache, but the user can provide a
827 # By default we use linecache.checkcache, but the user can provide a
825 # different check_cache implementation. This is used by the IPython
828 # different check_cache implementation. This is used by the IPython
826 # kernel to provide tracebacks for interactive code that is cached,
829 # kernel to provide tracebacks for interactive code that is cached,
827 # by a compiler instance that flushes the linecache but preserves its
830 # by a compiler instance that flushes the linecache but preserves its
828 # own code cache.
831 # own code cache.
829 if check_cache is None:
832 if check_cache is None:
830 check_cache = linecache.checkcache
833 check_cache = linecache.checkcache
831 self.check_cache = check_cache
834 self.check_cache = check_cache
832
835
833 self.debugger_cls = debugger_cls or debugger.Pdb
836 self.debugger_cls = debugger_cls or debugger.Pdb
834
837
835 def format_records(self, records, last_unique, recursion_repeat):
838 def format_records(self, records, last_unique, recursion_repeat):
836 """Format the stack frames of the traceback"""
839 """Format the stack frames of the traceback"""
837 frames = []
840 frames = []
838 for r in records[:last_unique+recursion_repeat+1]:
841 for r in records[:last_unique+recursion_repeat+1]:
839 #print '*** record:',file,lnum,func,lines,index # dbg
842 #print '*** record:',file,lnum,func,lines,index # dbg
840 frames.append(self.format_record(*r))
843 frames.append(self.format_record(*r))
841
844
842 if recursion_repeat:
845 if recursion_repeat:
843 frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat)
846 frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat)
844 frames.append(self.format_record(*records[last_unique+recursion_repeat+1]))
847 frames.append(self.format_record(*records[last_unique+recursion_repeat+1]))
845
848
846 return frames
849 return frames
847
850
848 def format_record(self, frame, file, lnum, func, lines, index):
851 def format_record(self, frame, file, lnum, func, lines, index):
849 """Format a single stack frame"""
852 """Format a single stack frame"""
850 Colors = self.Colors # just a shorthand + quicker name lookup
853 Colors = self.Colors # just a shorthand + quicker name lookup
851 ColorsNormal = Colors.Normal # used a lot
854 ColorsNormal = Colors.Normal # used a lot
852 col_scheme = self.color_scheme_table.active_scheme_name
855 col_scheme = self.color_scheme_table.active_scheme_name
853 indent = ' ' * INDENT_SIZE
856 indent = ' ' * INDENT_SIZE
854 em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
857 em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal)
855 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
858 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
856 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
859 tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal)
857 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
860 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
858 ColorsNormal)
861 ColorsNormal)
859 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
862 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
860 (Colors.vName, Colors.valEm, ColorsNormal)
863 (Colors.vName, Colors.valEm, ColorsNormal)
861 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
864 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
862 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
865 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
863 Colors.vName, ColorsNormal)
866 Colors.vName, ColorsNormal)
864 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
867 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
865
868
866 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
869 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
867 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm, Colors.line,
870 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm, Colors.line,
868 ColorsNormal)
871 ColorsNormal)
869
872
870 abspath = os.path.abspath
873 abspath = os.path.abspath
871
874
872
875
873 if not file:
876 if not file:
874 file = '?'
877 file = '?'
875 elif file.startswith(str("<")) and file.endswith(str(">")):
878 elif file.startswith(str("<")) and file.endswith(str(">")):
876 # Not a real filename, no problem...
879 # Not a real filename, no problem...
877 pass
880 pass
878 elif not os.path.isabs(file):
881 elif not os.path.isabs(file):
879 # Try to make the filename absolute by trying all
882 # Try to make the filename absolute by trying all
880 # sys.path entries (which is also what linecache does)
883 # sys.path entries (which is also what linecache does)
881 for dirname in sys.path:
884 for dirname in sys.path:
882 try:
885 try:
883 fullname = os.path.join(dirname, file)
886 fullname = os.path.join(dirname, file)
884 if os.path.isfile(fullname):
887 if os.path.isfile(fullname):
885 file = os.path.abspath(fullname)
888 file = os.path.abspath(fullname)
886 break
889 break
887 except Exception:
890 except Exception:
888 # Just in case that sys.path contains very
891 # Just in case that sys.path contains very
889 # strange entries...
892 # strange entries...
890 pass
893 pass
891
894
892 file = py3compat.cast_unicode(file, util_path.fs_encoding)
895 file = py3compat.cast_unicode(file, util_path.fs_encoding)
893 link = tpl_link % file
896 link = tpl_link % file
894 args, varargs, varkw, locals = fixed_getargvalues(frame)
897 args, varargs, varkw, locals = fixed_getargvalues(frame)
895
898
896 if func == '?':
899 if func == '?':
897 call = ''
900 call = ''
898 else:
901 else:
899 # Decide whether to include variable details or not
902 # Decide whether to include variable details or not
900 var_repr = self.include_vars and eqrepr or nullrepr
903 var_repr = self.include_vars and eqrepr or nullrepr
901 try:
904 try:
902 call = tpl_call % (func, inspect.formatargvalues(args,
905 call = tpl_call % (func, inspect.formatargvalues(args,
903 varargs, varkw,
906 varargs, varkw,
904 locals, formatvalue=var_repr))
907 locals, formatvalue=var_repr))
905 except KeyError:
908 except KeyError:
906 # This happens in situations like errors inside generator
909 # This happens in situations like errors inside generator
907 # expressions, where local variables are listed in the
910 # expressions, where local variables are listed in the
908 # line, but can't be extracted from the frame. I'm not
911 # line, but can't be extracted from the frame. I'm not
909 # 100% sure this isn't actually a bug in inspect itself,
912 # 100% sure this isn't actually a bug in inspect itself,
910 # but since there's no info for us to compute with, the
913 # but since there's no info for us to compute with, the
911 # best we can do is report the failure and move on. Here
914 # best we can do is report the failure and move on. Here
912 # we must *not* call any traceback construction again,
915 # we must *not* call any traceback construction again,
913 # because that would mess up use of %debug later on. So we
916 # because that would mess up use of %debug later on. So we
914 # simply report the failure and move on. The only
917 # simply report the failure and move on. The only
915 # limitation will be that this frame won't have locals
918 # limitation will be that this frame won't have locals
916 # listed in the call signature. Quite subtle problem...
919 # listed in the call signature. Quite subtle problem...
917 # I can't think of a good way to validate this in a unit
920 # I can't think of a good way to validate this in a unit
918 # test, but running a script consisting of:
921 # test, but running a script consisting of:
919 # dict( (k,v.strip()) for (k,v) in range(10) )
922 # dict( (k,v.strip()) for (k,v) in range(10) )
920 # will illustrate the error, if this exception catch is
923 # will illustrate the error, if this exception catch is
921 # disabled.
924 # disabled.
922 call = tpl_call_fail % func
925 call = tpl_call_fail % func
923
926
924 # Don't attempt to tokenize binary files.
927 # Don't attempt to tokenize binary files.
925 if file.endswith(('.so', '.pyd', '.dll')):
928 if file.endswith(('.so', '.pyd', '.dll')):
926 return '%s %s\n' % (link, call)
929 return '%s %s\n' % (link, call)
927
930
928 elif file.endswith(('.pyc', '.pyo')):
931 elif file.endswith(('.pyc', '.pyo')):
929 # Look up the corresponding source file.
932 # Look up the corresponding source file.
930 try:
933 try:
931 file = openpy.source_from_cache(file)
934 file = openpy.source_from_cache(file)
932 except ValueError:
935 except ValueError:
933 # Failed to get the source file for some reason
936 # Failed to get the source file for some reason
934 # E.g. https://github.com/ipython/ipython/issues/9486
937 # E.g. https://github.com/ipython/ipython/issues/9486
935 return '%s %s\n' % (link, call)
938 return '%s %s\n' % (link, call)
936
939
937 def linereader(file=file, lnum=[lnum], getline=ulinecache.getline):
940 def linereader(file=file, lnum=[lnum], getline=ulinecache.getline):
938 line = getline(file, lnum[0])
941 line = getline(file, lnum[0])
939 lnum[0] += 1
942 lnum[0] += 1
940 return line
943 return line
941
944
942 # Build the list of names on this line of code where the exception
945 # Build the list of names on this line of code where the exception
943 # occurred.
946 # occurred.
944 try:
947 try:
945 names = []
948 names = []
946 name_cont = False
949 name_cont = False
947
950
948 for token_type, token, start, end, line in generate_tokens(linereader):
951 for token_type, token, start, end, line in generate_tokens(linereader):
949 # build composite names
952 # build composite names
950 if token_type == tokenize.NAME and token not in keyword.kwlist:
953 if token_type == tokenize.NAME and token not in keyword.kwlist:
951 if name_cont:
954 if name_cont:
952 # Continuation of a dotted name
955 # Continuation of a dotted name
953 try:
956 try:
954 names[-1].append(token)
957 names[-1].append(token)
955 except IndexError:
958 except IndexError:
956 names.append([token])
959 names.append([token])
957 name_cont = False
960 name_cont = False
958 else:
961 else:
959 # Regular new names. We append everything, the caller
962 # Regular new names. We append everything, the caller
960 # will be responsible for pruning the list later. It's
963 # will be responsible for pruning the list later. It's
961 # very tricky to try to prune as we go, b/c composite
964 # very tricky to try to prune as we go, b/c composite
962 # names can fool us. The pruning at the end is easy
965 # names can fool us. The pruning at the end is easy
963 # to do (or the caller can print a list with repeated
966 # to do (or the caller can print a list with repeated
964 # names if so desired.
967 # names if so desired.
965 names.append([token])
968 names.append([token])
966 elif token == '.':
969 elif token == '.':
967 name_cont = True
970 name_cont = True
968 elif token_type == tokenize.NEWLINE:
971 elif token_type == tokenize.NEWLINE:
969 break
972 break
970
973
971 except (IndexError, UnicodeDecodeError, SyntaxError):
974 except (IndexError, UnicodeDecodeError, SyntaxError):
972 # signals exit of tokenizer
975 # signals exit of tokenizer
973 # SyntaxError can occur if the file is not actually Python
976 # SyntaxError can occur if the file is not actually Python
974 # - see gh-6300
977 # - see gh-6300
975 pass
978 pass
976 except tokenize.TokenError as msg:
979 except tokenize.TokenError as msg:
977 _m = ("An unexpected error occurred while tokenizing input\n"
980 _m = ("An unexpected error occurred while tokenizing input\n"
978 "The following traceback may be corrupted or invalid\n"
981 "The following traceback may be corrupted or invalid\n"
979 "The error message is: %s\n" % msg)
982 "The error message is: %s\n" % msg)
980 error(_m)
983 error(_m)
981
984
982 # Join composite names (e.g. "dict.fromkeys")
985 # Join composite names (e.g. "dict.fromkeys")
983 names = ['.'.join(n) for n in names]
986 names = ['.'.join(n) for n in names]
984 # prune names list of duplicates, but keep the right order
987 # prune names list of duplicates, but keep the right order
985 unique_names = uniq_stable(names)
988 unique_names = uniq_stable(names)
986
989
987 # Start loop over vars
990 # Start loop over vars
988 lvals = []
991 lvals = []
989 if self.include_vars:
992 if self.include_vars:
990 for name_full in unique_names:
993 for name_full in unique_names:
991 name_base = name_full.split('.', 1)[0]
994 name_base = name_full.split('.', 1)[0]
992 if name_base in frame.f_code.co_varnames:
995 if name_base in frame.f_code.co_varnames:
993 if name_base in locals:
996 if name_base in locals:
994 try:
997 try:
995 value = repr(eval(name_full, locals))
998 value = repr(eval(name_full, locals))
996 except:
999 except:
997 value = undefined
1000 value = undefined
998 else:
1001 else:
999 value = undefined
1002 value = undefined
1000 name = tpl_local_var % name_full
1003 name = tpl_local_var % name_full
1001 else:
1004 else:
1002 if name_base in frame.f_globals:
1005 if name_base in frame.f_globals:
1003 try:
1006 try:
1004 value = repr(eval(name_full, frame.f_globals))
1007 value = repr(eval(name_full, frame.f_globals))
1005 except:
1008 except:
1006 value = undefined
1009 value = undefined
1007 else:
1010 else:
1008 value = undefined
1011 value = undefined
1009 name = tpl_global_var % name_full
1012 name = tpl_global_var % name_full
1010 lvals.append(tpl_name_val % (name, value))
1013 lvals.append(tpl_name_val % (name, value))
1011 if lvals:
1014 if lvals:
1012 lvals = '%s%s' % (indent, em_normal.join(lvals))
1015 lvals = '%s%s' % (indent, em_normal.join(lvals))
1013 else:
1016 else:
1014 lvals = ''
1017 lvals = ''
1015
1018
1016 level = '%s %s\n' % (link, call)
1019 level = '%s %s\n' % (link, call)
1017
1020
1018 if index is None:
1021 if index is None:
1019 return level
1022 return level
1020 else:
1023 else:
1021 return '%s%s' % (level, ''.join(
1024 return '%s%s' % (level, ''.join(
1022 _format_traceback_lines(lnum, index, lines, Colors, lvals,
1025 _format_traceback_lines(lnum, index, lines, Colors, lvals,
1023 col_scheme)))
1026 col_scheme)))
1024
1027
1025 def prepare_chained_exception_message(self, cause):
1028 def prepare_chained_exception_message(self, cause):
1026 direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
1029 direct_cause = "\nThe above exception was the direct cause of the following exception:\n"
1027 exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
1030 exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n"
1028
1031
1029 if cause:
1032 if cause:
1030 message = [[direct_cause]]
1033 message = [[direct_cause]]
1031 else:
1034 else:
1032 message = [[exception_during_handling]]
1035 message = [[exception_during_handling]]
1033 return message
1036 return message
1034
1037
1035 def prepare_header(self, etype, long_version=False):
1038 def prepare_header(self, etype, long_version=False):
1036 colors = self.Colors # just a shorthand + quicker name lookup
1039 colors = self.Colors # just a shorthand + quicker name lookup
1037 colorsnormal = colors.Normal # used a lot
1040 colorsnormal = colors.Normal # used a lot
1038 exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
1041 exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
1039 width = min(75, get_terminal_size()[0])
1042 width = min(75, get_terminal_size()[0])
1040 if long_version:
1043 if long_version:
1041 # Header with the exception type, python version, and date
1044 # Header with the exception type, python version, and date
1042 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
1045 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
1043 date = time.ctime(time.time())
1046 date = time.ctime(time.time())
1044
1047
1045 head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
1048 head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
1046 exc, ' ' * (width - len(str(etype)) - len(pyver)),
1049 exc, ' ' * (width - len(str(etype)) - len(pyver)),
1047 pyver, date.rjust(width) )
1050 pyver, date.rjust(width) )
1048 head += "\nA problem occurred executing Python code. Here is the sequence of function" \
1051 head += "\nA problem occurred executing Python code. Here is the sequence of function" \
1049 "\ncalls leading up to the error, with the most recent (innermost) call last."
1052 "\ncalls leading up to the error, with the most recent (innermost) call last."
1050 else:
1053 else:
1051 # Simplified header
1054 # Simplified header
1052 head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
1055 head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
1053 rjust(width - len(str(etype))) )
1056 rjust(width - len(str(etype))) )
1054
1057
1055 return head
1058 return head
1056
1059
1057 def format_exception(self, etype, evalue):
1060 def format_exception(self, etype, evalue):
1058 colors = self.Colors # just a shorthand + quicker name lookup
1061 colors = self.Colors # just a shorthand + quicker name lookup
1059 colorsnormal = colors.Normal # used a lot
1062 colorsnormal = colors.Normal # used a lot
1060 indent = ' ' * INDENT_SIZE
1063 indent = ' ' * INDENT_SIZE
1061 # Get (safely) a string form of the exception info
1064 # Get (safely) a string form of the exception info
1062 try:
1065 try:
1063 etype_str, evalue_str = map(str, (etype, evalue))
1066 etype_str, evalue_str = map(str, (etype, evalue))
1064 except:
1067 except:
1065 # User exception is improperly defined.
1068 # User exception is improperly defined.
1066 etype, evalue = str, sys.exc_info()[:2]
1069 etype, evalue = str, sys.exc_info()[:2]
1067 etype_str, evalue_str = map(str, (etype, evalue))
1070 etype_str, evalue_str = map(str, (etype, evalue))
1068 # ... and format it
1071 # ... and format it
1069 exception = ['%s%s%s: %s' % (colors.excName, etype_str,
1072 exception = ['%s%s%s: %s' % (colors.excName, etype_str,
1070 colorsnormal, py3compat.cast_unicode(evalue_str))]
1073 colorsnormal, py3compat.cast_unicode(evalue_str))]
1071
1074
1072 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
1075 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
1073 try:
1076 try:
1074 names = [w for w in dir(evalue) if isinstance(w, py3compat.string_types)]
1077 names = [w for w in dir(evalue) if isinstance(w, py3compat.string_types)]
1075 except:
1078 except:
1076 # Every now and then, an object with funny internals blows up
1079 # Every now and then, an object with funny internals blows up
1077 # when dir() is called on it. We do the best we can to report
1080 # when dir() is called on it. We do the best we can to report
1078 # the problem and continue
1081 # the problem and continue
1079 _m = '%sException reporting error (object with broken dir())%s:'
1082 _m = '%sException reporting error (object with broken dir())%s:'
1080 exception.append(_m % (colors.excName, colorsnormal))
1083 exception.append(_m % (colors.excName, colorsnormal))
1081 etype_str, evalue_str = map(str, sys.exc_info()[:2])
1084 etype_str, evalue_str = map(str, sys.exc_info()[:2])
1082 exception.append('%s%s%s: %s' % (colors.excName, etype_str,
1085 exception.append('%s%s%s: %s' % (colors.excName, etype_str,
1083 colorsnormal, py3compat.cast_unicode(evalue_str)))
1086 colorsnormal, py3compat.cast_unicode(evalue_str)))
1084 names = []
1087 names = []
1085 for name in names:
1088 for name in names:
1086 value = text_repr(getattr(evalue, name))
1089 value = text_repr(getattr(evalue, name))
1087 exception.append('\n%s%s = %s' % (indent, name, value))
1090 exception.append('\n%s%s = %s' % (indent, name, value))
1088
1091
1089 return exception
1092 return exception
1090
1093
1091 def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
1094 def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset):
1092 """Formats the header, traceback and exception message for a single exception.
1095 """Formats the header, traceback and exception message for a single exception.
1093
1096
1094 This may be called multiple times by Python 3 exception chaining
1097 This may be called multiple times by Python 3 exception chaining
1095 (PEP 3134).
1098 (PEP 3134).
1096 """
1099 """
1097 # some locals
1100 # some locals
1098 orig_etype = etype
1101 orig_etype = etype
1099 try:
1102 try:
1100 etype = etype.__name__
1103 etype = etype.__name__
1101 except AttributeError:
1104 except AttributeError:
1102 pass
1105 pass
1103
1106
1104 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1107 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1105 head = self.prepare_header(etype, self.long_header)
1108 head = self.prepare_header(etype, self.long_header)
1106 records = self.get_records(etb, number_of_lines_of_context, tb_offset)
1109 records = self.get_records(etb, number_of_lines_of_context, tb_offset)
1107
1110
1108 if records is None:
1111 if records is None:
1109 return ""
1112 return ""
1110
1113
1111 last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
1114 last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records)
1112
1115
1113 frames = self.format_records(records, last_unique, recursion_repeat)
1116 frames = self.format_records(records, last_unique, recursion_repeat)
1114
1117
1115 formatted_exception = self.format_exception(etype, evalue)
1118 formatted_exception = self.format_exception(etype, evalue)
1116 if records:
1119 if records:
1117 filepath, lnum = records[-1][1:3]
1120 filepath, lnum = records[-1][1:3]
1118 filepath = os.path.abspath(filepath)
1121 filepath = os.path.abspath(filepath)
1119 ipinst = get_ipython()
1122 ipinst = get_ipython()
1120 if ipinst is not None:
1123 if ipinst is not None:
1121 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
1124 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
1122
1125
1123 return [[head] + frames + [''.join(formatted_exception[0])]]
1126 return [[head] + frames + [''.join(formatted_exception[0])]]
1124
1127
1125 def get_records(self, etb, number_of_lines_of_context, tb_offset):
1128 def get_records(self, etb, number_of_lines_of_context, tb_offset):
1126 try:
1129 try:
1127 # Try the default getinnerframes and Alex's: Alex's fixes some
1130 # Try the default getinnerframes and Alex's: Alex's fixes some
1128 # problems, but it generates empty tracebacks for console errors
1131 # problems, but it generates empty tracebacks for console errors
1129 # (5 blanks lines) where none should be returned.
1132 # (5 blanks lines) where none should be returned.
1130 return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
1133 return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
1131 except:
1134 except:
1132 # FIXME: I've been getting many crash reports from python 2.3
1135 # FIXME: I've been getting many crash reports from python 2.3
1133 # users, traceable to inspect.py. If I can find a small test-case
1136 # users, traceable to inspect.py. If I can find a small test-case
1134 # to reproduce this, I should either write a better workaround or
1137 # to reproduce this, I should either write a better workaround or
1135 # file a bug report against inspect (if that's the real problem).
1138 # file a bug report against inspect (if that's the real problem).
1136 # So far, I haven't been able to find an isolated example to
1139 # So far, I haven't been able to find an isolated example to
1137 # reproduce the problem.
1140 # reproduce the problem.
1138 inspect_error()
1141 inspect_error()
1139 traceback.print_exc(file=self.ostream)
1142 traceback.print_exc(file=self.ostream)
1140 info('\nUnfortunately, your original traceback can not be constructed.\n')
1143 info('\nUnfortunately, your original traceback can not be constructed.\n')
1141 return None
1144 return None
1142
1145
1143 def get_parts_of_chained_exception(self, evalue):
1146 def get_parts_of_chained_exception(self, evalue):
1144 def get_chained_exception(exception_value):
1147 def get_chained_exception(exception_value):
1145 cause = getattr(exception_value, '__cause__', None)
1148 cause = getattr(exception_value, '__cause__', None)
1146 if cause:
1149 if cause:
1147 return cause
1150 return cause
1148 if getattr(exception_value, '__suppress_context__', False):
1151 if getattr(exception_value, '__suppress_context__', False):
1149 return None
1152 return None
1150 return getattr(exception_value, '__context__', None)
1153 return getattr(exception_value, '__context__', None)
1151
1154
1152 chained_evalue = get_chained_exception(evalue)
1155 chained_evalue = get_chained_exception(evalue)
1153
1156
1154 if chained_evalue:
1157 if chained_evalue:
1155 return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
1158 return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__
1156
1159
1157 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
1160 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
1158 number_of_lines_of_context=5):
1161 number_of_lines_of_context=5):
1159 """Return a nice text document describing the traceback."""
1162 """Return a nice text document describing the traceback."""
1160
1163
1161 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
1164 formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
1162 tb_offset)
1165 tb_offset)
1163
1166
1164 colors = self.Colors # just a shorthand + quicker name lookup
1167 colors = self.Colors # just a shorthand + quicker name lookup
1165 colorsnormal = colors.Normal # used a lot
1168 colorsnormal = colors.Normal # used a lot
1166 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
1169 head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
1167 structured_traceback_parts = [head]
1170 structured_traceback_parts = [head]
1168 if py3compat.PY3:
1171 if py3compat.PY3:
1169 chained_exceptions_tb_offset = 0
1172 chained_exceptions_tb_offset = 0
1170 lines_of_context = 3
1173 lines_of_context = 3
1171 formatted_exceptions = formatted_exception
1174 formatted_exceptions = formatted_exception
1172 exception = self.get_parts_of_chained_exception(evalue)
1175 exception = self.get_parts_of_chained_exception(evalue)
1173 if exception:
1176 if exception:
1174 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1177 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1175 etype, evalue, etb = exception
1178 etype, evalue, etb = exception
1176 else:
1179 else:
1177 evalue = None
1180 evalue = None
1178 chained_exc_ids = set()
1181 chained_exc_ids = set()
1179 while evalue:
1182 while evalue:
1180 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
1183 formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context,
1181 chained_exceptions_tb_offset)
1184 chained_exceptions_tb_offset)
1182 exception = self.get_parts_of_chained_exception(evalue)
1185 exception = self.get_parts_of_chained_exception(evalue)
1183
1186
1184 if exception and not id(exception[1]) in chained_exc_ids:
1187 if exception and not id(exception[1]) in chained_exc_ids:
1185 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
1188 chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop
1186 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1189 formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__)
1187 etype, evalue, etb = exception
1190 etype, evalue, etb = exception
1188 else:
1191 else:
1189 evalue = None
1192 evalue = None
1190
1193
1191 # we want to see exceptions in a reversed order:
1194 # we want to see exceptions in a reversed order:
1192 # the first exception should be on top
1195 # the first exception should be on top
1193 for formatted_exception in reversed(formatted_exceptions):
1196 for formatted_exception in reversed(formatted_exceptions):
1194 structured_traceback_parts += formatted_exception
1197 structured_traceback_parts += formatted_exception
1195 else:
1198 else:
1196 structured_traceback_parts += formatted_exception[0]
1199 structured_traceback_parts += formatted_exception[0]
1197
1200
1198 return structured_traceback_parts
1201 return structured_traceback_parts
1199
1202
1200 def debugger(self, force=False):
1203 def debugger(self, force=False):
1201 """Call up the pdb debugger if desired, always clean up the tb
1204 """Call up the pdb debugger if desired, always clean up the tb
1202 reference.
1205 reference.
1203
1206
1204 Keywords:
1207 Keywords:
1205
1208
1206 - force(False): by default, this routine checks the instance call_pdb
1209 - force(False): by default, this routine checks the instance call_pdb
1207 flag and does not actually invoke the debugger if the flag is false.
1210 flag and does not actually invoke the debugger if the flag is false.
1208 The 'force' option forces the debugger to activate even if the flag
1211 The 'force' option forces the debugger to activate even if the flag
1209 is false.
1212 is false.
1210
1213
1211 If the call_pdb flag is set, the pdb interactive debugger is
1214 If the call_pdb flag is set, the pdb interactive debugger is
1212 invoked. In all cases, the self.tb reference to the current traceback
1215 invoked. In all cases, the self.tb reference to the current traceback
1213 is deleted to prevent lingering references which hamper memory
1216 is deleted to prevent lingering references which hamper memory
1214 management.
1217 management.
1215
1218
1216 Note that each call to pdb() does an 'import readline', so if your app
1219 Note that each call to pdb() does an 'import readline', so if your app
1217 requires a special setup for the readline completers, you'll have to
1220 requires a special setup for the readline completers, you'll have to
1218 fix that by hand after invoking the exception handler."""
1221 fix that by hand after invoking the exception handler."""
1219
1222
1220 if force or self.call_pdb:
1223 if force or self.call_pdb:
1221 if self.pdb is None:
1224 if self.pdb is None:
1222 self.pdb = self.debugger_cls(
1225 self.pdb = self.debugger_cls(
1223 self.color_scheme_table.active_scheme_name)
1226 self.color_scheme_table.active_scheme_name)
1224 # the system displayhook may have changed, restore the original
1227 # the system displayhook may have changed, restore the original
1225 # for pdb
1228 # for pdb
1226 display_trap = DisplayTrap(hook=sys.__displayhook__)
1229 display_trap = DisplayTrap(hook=sys.__displayhook__)
1227 with display_trap:
1230 with display_trap:
1228 self.pdb.reset()
1231 self.pdb.reset()
1229 # Find the right frame so we don't pop up inside ipython itself
1232 # Find the right frame so we don't pop up inside ipython itself
1230 if hasattr(self, 'tb') and self.tb is not None:
1233 if hasattr(self, 'tb') and self.tb is not None:
1231 etb = self.tb
1234 etb = self.tb
1232 else:
1235 else:
1233 etb = self.tb = sys.last_traceback
1236 etb = self.tb = sys.last_traceback
1234 while self.tb is not None and self.tb.tb_next is not None:
1237 while self.tb is not None and self.tb.tb_next is not None:
1235 self.tb = self.tb.tb_next
1238 self.tb = self.tb.tb_next
1236 if etb and etb.tb_next:
1239 if etb and etb.tb_next:
1237 etb = etb.tb_next
1240 etb = etb.tb_next
1238 self.pdb.botframe = etb.tb_frame
1241 self.pdb.botframe = etb.tb_frame
1239 self.pdb.interaction(self.tb.tb_frame, self.tb)
1242 self.pdb.interaction(self.tb.tb_frame, self.tb)
1240
1243
1241 if hasattr(self, 'tb'):
1244 if hasattr(self, 'tb'):
1242 del self.tb
1245 del self.tb
1243
1246
1244 def handler(self, info=None):
1247 def handler(self, info=None):
1245 (etype, evalue, etb) = info or sys.exc_info()
1248 (etype, evalue, etb) = info or sys.exc_info()
1246 self.tb = etb
1249 self.tb = etb
1247 ostream = self.ostream
1250 ostream = self.ostream
1248 ostream.flush()
1251 ostream.flush()
1249 ostream.write(self.text(etype, evalue, etb))
1252 ostream.write(self.text(etype, evalue, etb))
1250 ostream.write('\n')
1253 ostream.write('\n')
1251 ostream.flush()
1254 ostream.flush()
1252
1255
1253 # Changed so an instance can just be called as VerboseTB_inst() and print
1256 # Changed so an instance can just be called as VerboseTB_inst() and print
1254 # out the right info on its own.
1257 # out the right info on its own.
1255 def __call__(self, etype=None, evalue=None, etb=None):
1258 def __call__(self, etype=None, evalue=None, etb=None):
1256 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1259 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1257 if etb is None:
1260 if etb is None:
1258 self.handler()
1261 self.handler()
1259 else:
1262 else:
1260 self.handler((etype, evalue, etb))
1263 self.handler((etype, evalue, etb))
1261 try:
1264 try:
1262 self.debugger()
1265 self.debugger()
1263 except KeyboardInterrupt:
1266 except KeyboardInterrupt:
1264 print("\nKeyboardInterrupt")
1267 print("\nKeyboardInterrupt")
1265
1268
1266
1269
1267 #----------------------------------------------------------------------------
1270 #----------------------------------------------------------------------------
1268 class FormattedTB(VerboseTB, ListTB):
1271 class FormattedTB(VerboseTB, ListTB):
1269 """Subclass ListTB but allow calling with a traceback.
1272 """Subclass ListTB but allow calling with a traceback.
1270
1273
1271 It can thus be used as a sys.excepthook for Python > 2.1.
1274 It can thus be used as a sys.excepthook for Python > 2.1.
1272
1275
1273 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1276 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1274
1277
1275 Allows a tb_offset to be specified. This is useful for situations where
1278 Allows a tb_offset to be specified. This is useful for situations where
1276 one needs to remove a number of topmost frames from the traceback (such as
1279 one needs to remove a number of topmost frames from the traceback (such as
1277 occurs with python programs that themselves execute other python code,
1280 occurs with python programs that themselves execute other python code,
1278 like Python shells). """
1281 like Python shells). """
1279
1282
1280 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1283 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1281 ostream=None,
1284 ostream=None,
1282 tb_offset=0, long_header=False, include_vars=False,
1285 tb_offset=0, long_header=False, include_vars=False,
1283 check_cache=None, debugger_cls=None):
1286 check_cache=None, debugger_cls=None):
1284
1287
1285 # NEVER change the order of this list. Put new modes at the end:
1288 # NEVER change the order of this list. Put new modes at the end:
1286 self.valid_modes = ['Plain', 'Context', 'Verbose']
1289 self.valid_modes = ['Plain', 'Context', 'Verbose']
1287 self.verbose_modes = self.valid_modes[1:3]
1290 self.verbose_modes = self.valid_modes[1:3]
1288
1291
1289 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1292 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1290 ostream=ostream, tb_offset=tb_offset,
1293 ostream=ostream, tb_offset=tb_offset,
1291 long_header=long_header, include_vars=include_vars,
1294 long_header=long_header, include_vars=include_vars,
1292 check_cache=check_cache, debugger_cls=debugger_cls)
1295 check_cache=check_cache, debugger_cls=debugger_cls)
1293
1296
1294 # Different types of tracebacks are joined with different separators to
1297 # Different types of tracebacks are joined with different separators to
1295 # form a single string. They are taken from this dict
1298 # form a single string. They are taken from this dict
1296 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1299 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1297 # set_mode also sets the tb_join_char attribute
1300 # set_mode also sets the tb_join_char attribute
1298 self.set_mode(mode)
1301 self.set_mode(mode)
1299
1302
1300 def _extract_tb(self, tb):
1303 def _extract_tb(self, tb):
1301 if tb:
1304 if tb:
1302 return traceback.extract_tb(tb)
1305 return traceback.extract_tb(tb)
1303 else:
1306 else:
1304 return None
1307 return None
1305
1308
1306 def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
1309 def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5):
1307 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1310 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1308 mode = self.mode
1311 mode = self.mode
1309 if mode in self.verbose_modes:
1312 if mode in self.verbose_modes:
1310 # Verbose modes need a full traceback
1313 # Verbose modes need a full traceback
1311 return VerboseTB.structured_traceback(
1314 return VerboseTB.structured_traceback(
1312 self, etype, value, tb, tb_offset, number_of_lines_of_context
1315 self, etype, value, tb, tb_offset, number_of_lines_of_context
1313 )
1316 )
1314 else:
1317 else:
1315 # We must check the source cache because otherwise we can print
1318 # We must check the source cache because otherwise we can print
1316 # out-of-date source code.
1319 # out-of-date source code.
1317 self.check_cache()
1320 self.check_cache()
1318 # Now we can extract and format the exception
1321 # Now we can extract and format the exception
1319 elist = self._extract_tb(tb)
1322 elist = self._extract_tb(tb)
1320 return ListTB.structured_traceback(
1323 return ListTB.structured_traceback(
1321 self, etype, value, elist, tb_offset, number_of_lines_of_context
1324 self, etype, value, elist, tb_offset, number_of_lines_of_context
1322 )
1325 )
1323
1326
1324 def stb2text(self, stb):
1327 def stb2text(self, stb):
1325 """Convert a structured traceback (a list) to a string."""
1328 """Convert a structured traceback (a list) to a string."""
1326 return self.tb_join_char.join(stb)
1329 return self.tb_join_char.join(stb)
1327
1330
1328
1331
1329 def set_mode(self, mode=None):
1332 def set_mode(self, mode=None):
1330 """Switch to the desired mode.
1333 """Switch to the desired mode.
1331
1334
1332 If mode is not specified, cycles through the available modes."""
1335 If mode is not specified, cycles through the available modes."""
1333
1336
1334 if not mode:
1337 if not mode:
1335 new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
1338 new_idx = (self.valid_modes.index(self.mode) + 1 ) % \
1336 len(self.valid_modes)
1339 len(self.valid_modes)
1337 self.mode = self.valid_modes[new_idx]
1340 self.mode = self.valid_modes[new_idx]
1338 elif mode not in self.valid_modes:
1341 elif mode not in self.valid_modes:
1339 raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
1342 raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n'
1340 'Valid modes: ' + str(self.valid_modes))
1343 'Valid modes: ' + str(self.valid_modes))
1341 else:
1344 else:
1342 self.mode = mode
1345 self.mode = mode
1343 # include variable details only in 'Verbose' mode
1346 # include variable details only in 'Verbose' mode
1344 self.include_vars = (self.mode == self.valid_modes[2])
1347 self.include_vars = (self.mode == self.valid_modes[2])
1345 # Set the join character for generating text tracebacks
1348 # Set the join character for generating text tracebacks
1346 self.tb_join_char = self._join_chars[self.mode]
1349 self.tb_join_char = self._join_chars[self.mode]
1347
1350
1348 # some convenient shortcuts
1351 # some convenient shortcuts
1349 def plain(self):
1352 def plain(self):
1350 self.set_mode(self.valid_modes[0])
1353 self.set_mode(self.valid_modes[0])
1351
1354
1352 def context(self):
1355 def context(self):
1353 self.set_mode(self.valid_modes[1])
1356 self.set_mode(self.valid_modes[1])
1354
1357
1355 def verbose(self):
1358 def verbose(self):
1356 self.set_mode(self.valid_modes[2])
1359 self.set_mode(self.valid_modes[2])
1357
1360
1358
1361
1359 #----------------------------------------------------------------------------
1362 #----------------------------------------------------------------------------
1360 class AutoFormattedTB(FormattedTB):
1363 class AutoFormattedTB(FormattedTB):
1361 """A traceback printer which can be called on the fly.
1364 """A traceback printer which can be called on the fly.
1362
1365
1363 It will find out about exceptions by itself.
1366 It will find out about exceptions by itself.
1364
1367
1365 A brief example::
1368 A brief example::
1366
1369
1367 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1370 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1368 try:
1371 try:
1369 ...
1372 ...
1370 except:
1373 except:
1371 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1374 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1372 """
1375 """
1373
1376
1374 def __call__(self, etype=None, evalue=None, etb=None,
1377 def __call__(self, etype=None, evalue=None, etb=None,
1375 out=None, tb_offset=None):
1378 out=None, tb_offset=None):
1376 """Print out a formatted exception traceback.
1379 """Print out a formatted exception traceback.
1377
1380
1378 Optional arguments:
1381 Optional arguments:
1379 - out: an open file-like object to direct output to.
1382 - out: an open file-like object to direct output to.
1380
1383
1381 - tb_offset: the number of frames to skip over in the stack, on a
1384 - tb_offset: the number of frames to skip over in the stack, on a
1382 per-call basis (this overrides temporarily the instance's tb_offset
1385 per-call basis (this overrides temporarily the instance's tb_offset
1383 given at initialization time. """
1386 given at initialization time. """
1384
1387
1385 if out is None:
1388 if out is None:
1386 out = self.ostream
1389 out = self.ostream
1387 out.flush()
1390 out.flush()
1388 out.write(self.text(etype, evalue, etb, tb_offset))
1391 out.write(self.text(etype, evalue, etb, tb_offset))
1389 out.write('\n')
1392 out.write('\n')
1390 out.flush()
1393 out.flush()
1391 # FIXME: we should remove the auto pdb behavior from here and leave
1394 # FIXME: we should remove the auto pdb behavior from here and leave
1392 # that to the clients.
1395 # that to the clients.
1393 try:
1396 try:
1394 self.debugger()
1397 self.debugger()
1395 except KeyboardInterrupt:
1398 except KeyboardInterrupt:
1396 print("\nKeyboardInterrupt")
1399 print("\nKeyboardInterrupt")
1397
1400
1398 def structured_traceback(self, etype=None, value=None, tb=None,
1401 def structured_traceback(self, etype=None, value=None, tb=None,
1399 tb_offset=None, number_of_lines_of_context=5):
1402 tb_offset=None, number_of_lines_of_context=5):
1400 if etype is None:
1403 if etype is None:
1401 etype, value, tb = sys.exc_info()
1404 etype, value, tb = sys.exc_info()
1402 self.tb = tb
1405 self.tb = tb
1403 return FormattedTB.structured_traceback(
1406 return FormattedTB.structured_traceback(
1404 self, etype, value, tb, tb_offset, number_of_lines_of_context)
1407 self, etype, value, tb, tb_offset, number_of_lines_of_context)
1405
1408
1406
1409
1407 #---------------------------------------------------------------------------
1410 #---------------------------------------------------------------------------
1408
1411
1409 # A simple class to preserve Nathan's original functionality.
1412 # A simple class to preserve Nathan's original functionality.
1410 class ColorTB(FormattedTB):
1413 class ColorTB(FormattedTB):
1411 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1414 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1412
1415
1413 def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
1416 def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs):
1414 FormattedTB.__init__(self, color_scheme=color_scheme,
1417 FormattedTB.__init__(self, color_scheme=color_scheme,
1415 call_pdb=call_pdb, **kwargs)
1418 call_pdb=call_pdb, **kwargs)
1416
1419
1417
1420
1418 class SyntaxTB(ListTB):
1421 class SyntaxTB(ListTB):
1419 """Extension which holds some state: the last exception value"""
1422 """Extension which holds some state: the last exception value"""
1420
1423
1421 def __init__(self, color_scheme='NoColor'):
1424 def __init__(self, color_scheme='NoColor'):
1422 ListTB.__init__(self, color_scheme)
1425 ListTB.__init__(self, color_scheme)
1423 self.last_syntax_error = None
1426 self.last_syntax_error = None
1424
1427
1425 def __call__(self, etype, value, elist):
1428 def __call__(self, etype, value, elist):
1426 self.last_syntax_error = value
1429 self.last_syntax_error = value
1427
1430
1428 ListTB.__call__(self, etype, value, elist)
1431 ListTB.__call__(self, etype, value, elist)
1429
1432
1430 def structured_traceback(self, etype, value, elist, tb_offset=None,
1433 def structured_traceback(self, etype, value, elist, tb_offset=None,
1431 context=5):
1434 context=5):
1432 # If the source file has been edited, the line in the syntax error can
1435 # If the source file has been edited, the line in the syntax error can
1433 # be wrong (retrieved from an outdated cache). This replaces it with
1436 # be wrong (retrieved from an outdated cache). This replaces it with
1434 # the current value.
1437 # the current value.
1435 if isinstance(value, SyntaxError) \
1438 if isinstance(value, SyntaxError) \
1436 and isinstance(value.filename, py3compat.string_types) \
1439 and isinstance(value.filename, py3compat.string_types) \
1437 and isinstance(value.lineno, int):
1440 and isinstance(value.lineno, int):
1438 linecache.checkcache(value.filename)
1441 linecache.checkcache(value.filename)
1439 newtext = ulinecache.getline(value.filename, value.lineno)
1442 newtext = ulinecache.getline(value.filename, value.lineno)
1440 if newtext:
1443 if newtext:
1441 value.text = newtext
1444 value.text = newtext
1442 self.last_syntax_error = value
1445 self.last_syntax_error = value
1443 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1446 return super(SyntaxTB, self).structured_traceback(etype, value, elist,
1444 tb_offset=tb_offset, context=context)
1447 tb_offset=tb_offset, context=context)
1445
1448
1446 def clear_err_state(self):
1449 def clear_err_state(self):
1447 """Return the current error state and clear it"""
1450 """Return the current error state and clear it"""
1448 e = self.last_syntax_error
1451 e = self.last_syntax_error
1449 self.last_syntax_error = None
1452 self.last_syntax_error = None
1450 return e
1453 return e
1451
1454
1452 def stb2text(self, stb):
1455 def stb2text(self, stb):
1453 """Convert a structured traceback (a list) to a string."""
1456 """Convert a structured traceback (a list) to a string."""
1454 return ''.join(stb)
1457 return ''.join(stb)
1455
1458
1456
1459
1457 # some internal-use functions
1460 # some internal-use functions
1458 def text_repr(value):
1461 def text_repr(value):
1459 """Hopefully pretty robust repr equivalent."""
1462 """Hopefully pretty robust repr equivalent."""
1460 # this is pretty horrible but should always return *something*
1463 # this is pretty horrible but should always return *something*
1461 try:
1464 try:
1462 return pydoc.text.repr(value)
1465 return pydoc.text.repr(value)
1463 except KeyboardInterrupt:
1466 except KeyboardInterrupt:
1464 raise
1467 raise
1465 except:
1468 except:
1466 try:
1469 try:
1467 return repr(value)
1470 return repr(value)
1468 except KeyboardInterrupt:
1471 except KeyboardInterrupt:
1469 raise
1472 raise
1470 except:
1473 except:
1471 try:
1474 try:
1472 # all still in an except block so we catch
1475 # all still in an except block so we catch
1473 # getattr raising
1476 # getattr raising
1474 name = getattr(value, '__name__', None)
1477 name = getattr(value, '__name__', None)
1475 if name:
1478 if name:
1476 # ick, recursion
1479 # ick, recursion
1477 return text_repr(name)
1480 return text_repr(name)
1478 klass = getattr(value, '__class__', None)
1481 klass = getattr(value, '__class__', None)
1479 if klass:
1482 if klass:
1480 return '%s instance' % text_repr(klass)
1483 return '%s instance' % text_repr(klass)
1481 except KeyboardInterrupt:
1484 except KeyboardInterrupt:
1482 raise
1485 raise
1483 except:
1486 except:
1484 return 'UNRECOVERABLE REPR FAILURE'
1487 return 'UNRECOVERABLE REPR FAILURE'
1485
1488
1486
1489
1487 def eqrepr(value, repr=text_repr):
1490 def eqrepr(value, repr=text_repr):
1488 return '=%s' % repr(value)
1491 return '=%s' % repr(value)
1489
1492
1490
1493
1491 def nullrepr(value, repr=text_repr):
1494 def nullrepr(value, repr=text_repr):
1492 return ''
1495 return ''
@@ -1,571 +1,578 b''
1 """IPython terminal interface using prompt_toolkit"""
1 """IPython terminal interface using prompt_toolkit"""
2 from __future__ import print_function
2 from __future__ import print_function
3
3
4 import os
4 import os
5 import sys
5 import sys
6 import signal
6 import signal
7 from warnings import warn
7 from warnings import warn
8
8
9 from IPython.core.error import TryNext
9 from IPython.core.error import TryNext
10 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
10 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
11 from IPython.utils.py3compat import PY3, cast_unicode_py2, input
11 from IPython.utils.py3compat import PY3, cast_unicode_py2, input
12 from IPython.utils.terminal import toggle_set_term_title, set_term_title
12 from IPython.utils.terminal import toggle_set_term_title, set_term_title
13 from IPython.utils.process import abbrev_cwd
13 from IPython.utils.process import abbrev_cwd
14 from traitlets import Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum
14 from traitlets import Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum
15
15
16 from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER, EditingMode
16 from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER, EditingMode
17 from prompt_toolkit.filters import (HasFocus, HasSelection, Condition,
17 from prompt_toolkit.filters import (HasFocus, HasSelection, Condition,
18 ViInsertMode, EmacsInsertMode, IsDone, HasCompletions)
18 ViInsertMode, EmacsInsertMode, IsDone, HasCompletions)
19 from prompt_toolkit.filters.cli import ViMode
19 from prompt_toolkit.filters.cli import ViMode
20 from prompt_toolkit.history import InMemoryHistory
20 from prompt_toolkit.history import InMemoryHistory
21 from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop, create_prompt_layout
21 from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop, create_prompt_layout
22 from prompt_toolkit.interface import CommandLineInterface
22 from prompt_toolkit.interface import CommandLineInterface
23 from prompt_toolkit.key_binding.manager import KeyBindingManager
23 from prompt_toolkit.key_binding.manager import KeyBindingManager
24 from prompt_toolkit.keys import Keys
24 from prompt_toolkit.keys import Keys
25 from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
25 from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
26 from prompt_toolkit.styles import PygmentsStyle, DynamicStyle
26 from prompt_toolkit.styles import PygmentsStyle, DynamicStyle
27 from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
27 from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
28
28
29 from pygments.styles import get_style_by_name, get_all_styles
29 from pygments.styles import get_style_by_name, get_all_styles
30 from pygments.token import Token
30 from pygments.token import Token
31
31
32 from .debugger import TerminalPdb, Pdb
32 from .debugger import TerminalPdb, Pdb
33 from .magics import TerminalMagics
33 from .magics import TerminalMagics
34 from .pt_inputhooks import get_inputhook_func
34 from .pt_inputhooks import get_inputhook_func
35 from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
35 from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
36 from .ptutils import IPythonPTCompleter, IPythonPTLexer
36 from .ptutils import IPythonPTCompleter, IPythonPTLexer
37
37
38 DISPLAY_BANNER_DEPRECATED = object()
38 DISPLAY_BANNER_DEPRECATED = object()
39
39
40
40
41 from pygments.style import Style
41 from pygments.style import Style
42
42
43 class _NoStyle(Style): pass
43 class _NoStyle(Style): pass
44
44
45
45
46
46
47 _style_overrides_light_bg = {
47 _style_overrides_light_bg = {
48 Token.Prompt: '#0000ff',
48 Token.Prompt: '#0000ff',
49 Token.PromptNum: '#0000ee bold',
49 Token.PromptNum: '#0000ee bold',
50 Token.OutPrompt: '#cc0000',
50 Token.OutPrompt: '#cc0000',
51 Token.OutPromptNum: '#bb0000 bold',
51 Token.OutPromptNum: '#bb0000 bold',
52 }
52 }
53
53
54 _style_overrides_linux = {
54 _style_overrides_linux = {
55 Token.Prompt: '#00cc00',
55 Token.Prompt: '#00cc00',
56 Token.PromptNum: '#00bb00 bold',
56 Token.PromptNum: '#00bb00 bold',
57 Token.OutPrompt: '#cc0000',
57 Token.OutPrompt: '#cc0000',
58 Token.OutPromptNum: '#bb0000 bold',
58 Token.OutPromptNum: '#bb0000 bold',
59 }
59 }
60
60
61
61
62
62
63 def get_default_editor():
63 def get_default_editor():
64 try:
64 try:
65 ed = os.environ['EDITOR']
65 ed = os.environ['EDITOR']
66 if not PY3:
66 if not PY3:
67 ed = ed.decode()
67 ed = ed.decode()
68 return ed
68 return ed
69 except KeyError:
69 except KeyError:
70 pass
70 pass
71 except UnicodeError:
71 except UnicodeError:
72 warn("$EDITOR environment variable is not pure ASCII. Using platform "
72 warn("$EDITOR environment variable is not pure ASCII. Using platform "
73 "default editor.")
73 "default editor.")
74
74
75 if os.name == 'posix':
75 if os.name == 'posix':
76 return 'vi' # the only one guaranteed to be there!
76 return 'vi' # the only one guaranteed to be there!
77 else:
77 else:
78 return 'notepad' # same in Windows!
78 return 'notepad' # same in Windows!
79
79
80
80
81 if sys.stdin and sys.stdout and sys.stderr:
81 if sys.stdin and sys.stdout and sys.stderr:
82 _is_tty = (sys.stdin.isatty()) and (sys.stdout.isatty()) and (sys.stderr.isatty())
82 _is_tty = (sys.stdin.isatty()) and (sys.stdout.isatty()) and (sys.stderr.isatty())
83 else:
83 else:
84 _is_tty = False
84 _is_tty = False
85
85
86
86
87 _use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
87 _use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
88
88
89 class TerminalInteractiveShell(InteractiveShell):
89 class TerminalInteractiveShell(InteractiveShell):
90 colors_force = True
90 colors_force = True
91
91
92 space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
92 space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
93 'to reserve for the completion menu'
93 'to reserve for the completion menu'
94 ).tag(config=True)
94 ).tag(config=True)
95
95
96 def _space_for_menu_changed(self, old, new):
96 def _space_for_menu_changed(self, old, new):
97 self._update_layout()
97 self._update_layout()
98
98
99 pt_cli = None
99 pt_cli = None
100 debugger_history = None
100 debugger_history = None
101
101
102 simple_prompt = Bool(_use_simple_prompt,
102 simple_prompt = Bool(_use_simple_prompt,
103 help="""Use `raw_input` for the REPL, without completion, multiline input, and prompt colors.
103 help="""Use `raw_input` for the REPL, without completion, multiline input, and prompt colors.
104
104
105 Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
105 Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
106 IPython own testing machinery, and emacs inferior-shell integration through elpy.
106 IPython own testing machinery, and emacs inferior-shell integration through elpy.
107
107
108 This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
108 This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
109 environment variable is set, or the current terminal is not a tty.
109 environment variable is set, or the current terminal is not a tty.
110
110
111 """
111 """
112 ).tag(config=True)
112 ).tag(config=True)
113
113
114 @property
114 @property
115 def debugger_cls(self):
115 def debugger_cls(self):
116 return Pdb if self.simple_prompt else TerminalPdb
116 return Pdb if self.simple_prompt else TerminalPdb
117
117
118 confirm_exit = Bool(True,
118 confirm_exit = Bool(True,
119 help="""
119 help="""
120 Set to confirm when you try to exit IPython with an EOF (Control-D
120 Set to confirm when you try to exit IPython with an EOF (Control-D
121 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
121 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
122 you can force a direct exit without any confirmation.""",
122 you can force a direct exit without any confirmation.""",
123 ).tag(config=True)
123 ).tag(config=True)
124
124
125 editing_mode = Unicode('emacs',
125 editing_mode = Unicode('emacs',
126 help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
126 help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
127 ).tag(config=True)
127 ).tag(config=True)
128
128
129 mouse_support = Bool(False,
129 mouse_support = Bool(False,
130 help="Enable mouse support in the prompt"
130 help="Enable mouse support in the prompt"
131 ).tag(config=True)
131 ).tag(config=True)
132
132
133 highlighting_style = Unicode('legacy',
133 highlighting_style = Unicode('legacy',
134 help="The name of a Pygments style to use for syntax highlighting: \n %s" % ', '.join(get_all_styles())
134 help="The name of a Pygments style to use for syntax highlighting: \n %s" % ', '.join(get_all_styles())
135 ).tag(config=True)
135 ).tag(config=True)
136
136
137
137
138 @observe('highlighting_style')
138 @observe('highlighting_style')
139 @observe('colors')
139 @observe('colors')
140 def _highlighting_style_changed(self, change):
140 def _highlighting_style_changed(self, change):
141 self.refresh_style()
141 self.refresh_style()
142
142
143 def refresh_style(self):
143 def refresh_style(self):
144 self._style = self._make_style_from_name(self.highlighting_style)
144 self._style = self._make_style_from_name(self.highlighting_style)
145
145
146
146
147 highlighting_style_overrides = Dict(
147 highlighting_style_overrides = Dict(
148 help="Override highlighting format for specific tokens"
148 help="Override highlighting format for specific tokens"
149 ).tag(config=True)
149 ).tag(config=True)
150
150
151 editor = Unicode(get_default_editor(),
151 editor = Unicode(get_default_editor(),
152 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
152 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
153 ).tag(config=True)
153 ).tag(config=True)
154
154
155 prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
155 prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
156
156
157 prompts = Instance(Prompts)
157 prompts = Instance(Prompts)
158
158
159 @default('prompts')
159 @default('prompts')
160 def _prompts_default(self):
160 def _prompts_default(self):
161 return self.prompts_class(self)
161 return self.prompts_class(self)
162
162
163 @observe('prompts')
163 @observe('prompts')
164 def _(self, change):
164 def _(self, change):
165 self._update_layout()
165 self._update_layout()
166
166
167 @default('displayhook_class')
167 @default('displayhook_class')
168 def _displayhook_class_default(self):
168 def _displayhook_class_default(self):
169 return RichPromptDisplayHook
169 return RichPromptDisplayHook
170
170
171 term_title = Bool(True,
171 term_title = Bool(True,
172 help="Automatically set the terminal title"
172 help="Automatically set the terminal title"
173 ).tag(config=True)
173 ).tag(config=True)
174
174
175 # Leaving that for beta/rc tester, shoudl remove for 5.0.0 final.
175 # Leaving that for beta/rc tester, shoudl remove for 5.0.0 final.
176 display_completions_in_columns = Bool(None,
176 display_completions_in_columns = Bool(None,
177 help="DEPRECATED", allow_none=True
177 help="DEPRECATED", allow_none=True
178 ).tag(config=True)
178 ).tag(config=True)
179
179
180 @observe('display_completions_in_columns')
180 @observe('display_completions_in_columns')
181 def _display_completions_in_columns_changed(self, new):
181 def _display_completions_in_columns_changed(self, new):
182 raise DeprecationWarning("The `display_completions_in_columns` Boolean has been replaced by the enum `display_completions`"
182 raise DeprecationWarning("The `display_completions_in_columns` Boolean has been replaced by the enum `display_completions`"
183 "with the following acceptable value: 'column', 'multicolumn','readlinelike'. ")
183 "with the following acceptable value: 'column', 'multicolumn','readlinelike'. ")
184
184
185 display_completions = Enum(('column', 'multicolumn','readlinelike'), default_value='multicolumn').tag(config=True)
185 display_completions = Enum(('column', 'multicolumn','readlinelike'), default_value='multicolumn').tag(config=True)
186
186
187 highlight_matching_brackets = Bool(True,
187 highlight_matching_brackets = Bool(True,
188 help="Highlight matching brackets .",
188 help="Highlight matching brackets .",
189 ).tag(config=True)
189 ).tag(config=True)
190
190
191 @observe('term_title')
191 @observe('term_title')
192 def init_term_title(self, change=None):
192 def init_term_title(self, change=None):
193 # Enable or disable the terminal title.
193 # Enable or disable the terminal title.
194 if self.term_title:
194 if self.term_title:
195 toggle_set_term_title(True)
195 toggle_set_term_title(True)
196 set_term_title('IPython: ' + abbrev_cwd())
196 set_term_title('IPython: ' + abbrev_cwd())
197 else:
197 else:
198 toggle_set_term_title(False)
198 toggle_set_term_title(False)
199
199
200 def init_display_formatter(self):
200 def init_display_formatter(self):
201 super(TerminalInteractiveShell, self).init_display_formatter()
201 super(TerminalInteractiveShell, self).init_display_formatter()
202 # terminal only supports plain text
202 # terminal only supports plain text
203 self.display_formatter.active_types = ['text/plain']
203 self.display_formatter.active_types = ['text/plain']
204
204
205 def init_prompt_toolkit_cli(self):
205 def init_prompt_toolkit_cli(self):
206 self._app = None
206 self._app = None
207 if self.simple_prompt:
207 if self.simple_prompt:
208 # Fall back to plain non-interactive output for tests.
208 # Fall back to plain non-interactive output for tests.
209 # This is very limited, and only accepts a single line.
209 # This is very limited, and only accepts a single line.
210 def prompt():
210 def prompt():
211 return cast_unicode_py2(input('In [%d]: ' % self.execution_count))
211 return cast_unicode_py2(input('In [%d]: ' % self.execution_count))
212 self.prompt_for_code = prompt
212 self.prompt_for_code = prompt
213 return
213 return
214
214
215 kbmanager = KeyBindingManager.for_prompt()
215 kbmanager = KeyBindingManager.for_prompt()
216 insert_mode = ViInsertMode() | EmacsInsertMode()
216 insert_mode = ViInsertMode() | EmacsInsertMode()
217 # Ctrl+J == Enter, seemingly
217 # Ctrl+J == Enter, seemingly
218 @kbmanager.registry.add_binding(Keys.ControlJ,
218 @kbmanager.registry.add_binding(Keys.ControlJ,
219 filter=(HasFocus(DEFAULT_BUFFER)
219 filter=(HasFocus(DEFAULT_BUFFER)
220 & ~HasSelection()
220 & ~HasSelection()
221 & insert_mode
221 & insert_mode
222 ))
222 ))
223 def _(event):
223 def _(event):
224 b = event.current_buffer
224 b = event.current_buffer
225 d = b.document
225 d = b.document
226
226
227 if b.complete_state:
227 if b.complete_state:
228 cc = b.complete_state.current_completion
228 cc = b.complete_state.current_completion
229 if cc:
229 if cc:
230 b.apply_completion(cc)
230 b.apply_completion(cc)
231 else:
231 else:
232 b.cancel_completion()
232 b.cancel_completion()
233 return
233 return
234
234
235 if not (d.on_last_line or d.cursor_position_row >= d.line_count
235 if not (d.on_last_line or d.cursor_position_row >= d.line_count
236 - d.empty_line_count_at_the_end()):
236 - d.empty_line_count_at_the_end()):
237 b.newline()
237 b.newline()
238 return
238 return
239
239
240 status, indent = self.input_splitter.check_complete(d.text + '\n')
240 status, indent = self.input_splitter.check_complete(d.text + '\n')
241
241
242 if (status != 'incomplete') and b.accept_action.is_returnable:
242 if (status != 'incomplete') and b.accept_action.is_returnable:
243 b.accept_action.validate_and_handle(event.cli, b)
243 b.accept_action.validate_and_handle(event.cli, b)
244 else:
244 else:
245 b.insert_text('\n' + (' ' * (indent or 0)))
245 b.insert_text('\n' + (' ' * (indent or 0)))
246
246
247 @kbmanager.registry.add_binding(Keys.ControlP, filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)))
247 @kbmanager.registry.add_binding(Keys.ControlP, filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)))
248 def _previous_history_or_previous_completion(event):
248 def _previous_history_or_previous_completion(event):
249 """
249 """
250 Control-P in vi edit mode on readline is history next, unlike default prompt toolkit.
250 Control-P in vi edit mode on readline is history next, unlike default prompt toolkit.
251
251
252 If completer is open this still select previous completion.
252 If completer is open this still select previous completion.
253 """
253 """
254 event.current_buffer.auto_up()
254 event.current_buffer.auto_up()
255
255
256 @kbmanager.registry.add_binding(Keys.ControlN, filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)))
256 @kbmanager.registry.add_binding(Keys.ControlN, filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)))
257 def _next_history_or_next_completion(event):
257 def _next_history_or_next_completion(event):
258 """
258 """
259 Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit.
259 Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit.
260
260
261 If completer is open this still select next completion.
261 If completer is open this still select next completion.
262 """
262 """
263 event.current_buffer.auto_down()
263 event.current_buffer.auto_down()
264
264
265 @kbmanager.registry.add_binding(Keys.ControlG, filter=(
265 @kbmanager.registry.add_binding(Keys.ControlG, filter=(
266 HasFocus(DEFAULT_BUFFER) & HasCompletions()
266 HasFocus(DEFAULT_BUFFER) & HasCompletions()
267 ))
267 ))
268 def _dismiss_completion(event):
268 def _dismiss_completion(event):
269 b = event.current_buffer
269 b = event.current_buffer
270 if b.complete_state:
270 if b.complete_state:
271 b.cancel_completion()
271 b.cancel_completion()
272
272
273 @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER))
273 @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER))
274 def _reset_buffer(event):
274 def _reset_buffer(event):
275 b = event.current_buffer
275 b = event.current_buffer
276 if b.complete_state:
276 if b.complete_state:
277 b.cancel_completion()
277 b.cancel_completion()
278 else:
278 else:
279 b.reset()
279 b.reset()
280
280
281 @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(SEARCH_BUFFER))
281 @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(SEARCH_BUFFER))
282 def _reset_search_buffer(event):
282 def _reset_search_buffer(event):
283 if event.current_buffer.document.text:
283 if event.current_buffer.document.text:
284 event.current_buffer.reset()
284 event.current_buffer.reset()
285 else:
285 else:
286 event.cli.push_focus(DEFAULT_BUFFER)
286 event.cli.push_focus(DEFAULT_BUFFER)
287
287
288 supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP'))
288 supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP'))
289
289
290 @kbmanager.registry.add_binding(Keys.ControlZ, filter=supports_suspend)
290 @kbmanager.registry.add_binding(Keys.ControlZ, filter=supports_suspend)
291 def _suspend_to_bg(event):
291 def _suspend_to_bg(event):
292 event.cli.suspend_to_background()
292 event.cli.suspend_to_background()
293
293
294 @Condition
294 @Condition
295 def cursor_in_leading_ws(cli):
295 def cursor_in_leading_ws(cli):
296 before = cli.application.buffer.document.current_line_before_cursor
296 before = cli.application.buffer.document.current_line_before_cursor
297 return (not before) or before.isspace()
297 return (not before) or before.isspace()
298
298
299 # Ctrl+I == Tab
299 # Ctrl+I == Tab
300 @kbmanager.registry.add_binding(Keys.ControlI,
300 @kbmanager.registry.add_binding(Keys.ControlI,
301 filter=(HasFocus(DEFAULT_BUFFER)
301 filter=(HasFocus(DEFAULT_BUFFER)
302 & ~HasSelection()
302 & ~HasSelection()
303 & insert_mode
303 & insert_mode
304 & cursor_in_leading_ws
304 & cursor_in_leading_ws
305 ))
305 ))
306 def _indent_buffer(event):
306 def _indent_buffer(event):
307 event.current_buffer.insert_text(' ' * 4)
307 event.current_buffer.insert_text(' ' * 4)
308
308
309
309
310 if self.display_completions == 'readlinelike':
310 if self.display_completions == 'readlinelike':
311 @kbmanager.registry.add_binding(Keys.ControlI,
311 @kbmanager.registry.add_binding(Keys.ControlI,
312 filter=(HasFocus(DEFAULT_BUFFER)
312 filter=(HasFocus(DEFAULT_BUFFER)
313 & ~HasSelection()
313 & ~HasSelection()
314 & insert_mode
314 & insert_mode
315 & ~cursor_in_leading_ws
315 & ~cursor_in_leading_ws
316 ))
316 ))
317 def _disaply_compl(ev):
317 def _disaply_compl(ev):
318 display_completions_like_readline(ev)
318 display_completions_like_readline(ev)
319
319
320
320
321 if sys.platform == 'win32':
321 if sys.platform == 'win32':
322 from IPython.lib.clipboard import (ClipboardEmpty,
322 from IPython.lib.clipboard import (ClipboardEmpty,
323 win32_clipboard_get, tkinter_clipboard_get)
323 win32_clipboard_get, tkinter_clipboard_get)
324 @kbmanager.registry.add_binding(Keys.ControlV,
324 @kbmanager.registry.add_binding(Keys.ControlV,
325 filter=(HasFocus(DEFAULT_BUFFER) & ~ViMode()))
325 filter=(HasFocus(DEFAULT_BUFFER) & ~ViMode()))
326 def _paste(event):
326 def _paste(event):
327 try:
327 try:
328 text = win32_clipboard_get()
328 text = win32_clipboard_get()
329 except TryNext:
329 except TryNext:
330 try:
330 try:
331 text = tkinter_clipboard_get()
331 text = tkinter_clipboard_get()
332 except (TryNext, ClipboardEmpty):
332 except (TryNext, ClipboardEmpty):
333 return
333 return
334 except ClipboardEmpty:
334 except ClipboardEmpty:
335 return
335 return
336 event.current_buffer.insert_text(text.replace('\t', ' ' * 4))
336 event.current_buffer.insert_text(text.replace('\t', ' ' * 4))
337
337
338 # Pre-populate history from IPython's history database
338 # Pre-populate history from IPython's history database
339 history = InMemoryHistory()
339 history = InMemoryHistory()
340 last_cell = u""
340 last_cell = u""
341 for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
341 for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
342 include_latest=True):
342 include_latest=True):
343 # Ignore blank lines and consecutive duplicates
343 # Ignore blank lines and consecutive duplicates
344 cell = cell.rstrip()
344 cell = cell.rstrip()
345 if cell and (cell != last_cell):
345 if cell and (cell != last_cell):
346 history.append(cell)
346 history.append(cell)
347
347
348 self._style = self._make_style_from_name(self.highlighting_style)
348 self._style = self._make_style_from_name(self.highlighting_style)
349 style = DynamicStyle(lambda: self._style)
349 style = DynamicStyle(lambda: self._style)
350
350
351 editing_mode = getattr(EditingMode, self.editing_mode.upper())
351 editing_mode = getattr(EditingMode, self.editing_mode.upper())
352
352
353 self._app = create_prompt_application(
353 self._app = create_prompt_application(
354 editing_mode=editing_mode,
354 editing_mode=editing_mode,
355 key_bindings_registry=kbmanager.registry,
355 key_bindings_registry=kbmanager.registry,
356 history=history,
356 history=history,
357 completer=IPythonPTCompleter(self.Completer),
357 completer=IPythonPTCompleter(self.Completer),
358 enable_history_search=True,
358 enable_history_search=True,
359 style=style,
359 style=style,
360 mouse_support=self.mouse_support,
360 mouse_support=self.mouse_support,
361 **self._layout_options()
361 **self._layout_options()
362 )
362 )
363 self._eventloop = create_eventloop(self.inputhook)
363 self._eventloop = create_eventloop(self.inputhook)
364 self.pt_cli = CommandLineInterface(self._app, eventloop=self._eventloop)
364 self.pt_cli = CommandLineInterface(self._app, eventloop=self._eventloop)
365
365
366 def _make_style_from_name(self, name):
366 def _make_style_from_name(self, name):
367 """
367 """
368 Small wrapper that make an IPython compatible style from a style name
368 Small wrapper that make an IPython compatible style from a style name
369
369
370 We need that to add style for prompt ... etc.
370 We need that to add style for prompt ... etc.
371 """
371 """
372 style_overrides = {}
372 if name == 'legacy':
373 if name == 'legacy':
373 legacy = self.colors.lower()
374 legacy = self.colors.lower()
374 if legacy == 'linux':
375 if legacy == 'linux':
375 style_cls = get_style_by_name('monokai')
376 style_cls = get_style_by_name('monokai')
376 style_overrides = _style_overrides_linux
377 style_overrides = _style_overrides_linux
377 elif legacy == 'lightbg':
378 elif legacy == 'lightbg':
378 style_overrides = _style_overrides_light_bg
379 style_overrides = _style_overrides_light_bg
379 style_cls = get_style_by_name('default')
380 style_cls = get_style_by_name('pastie')
381 elif legacy == 'neutral':
380 # The default theme needs to be visible on both a dark background
382 # The default theme needs to be visible on both a dark background
381 # and a light background, because we can't tell what the terminal
383 # and a light background, because we can't tell what the terminal
382 # looks like. These tweaks to the default theme help with that.
384 # looks like. These tweaks to the default theme help with that.
385 style_cls = get_style_by_name('default')
383 style_overrides.update({
386 style_overrides.update({
384 Token.Number: '#007700',
387 Token.Number: '#007700',
385 Token.Operator: 'noinherit',
388 Token.Operator: 'noinherit',
386 Token.String: '#BB6622',
389 Token.String: '#BB6622',
387 Token.Name.Function: '#2080D0',
390 Token.Name.Function: '#2080D0',
388 Token.Name.Class: 'bold #2080D0',
391 Token.Name.Class: 'bold #2080D0',
389 Token.Name.Namespace: 'bold #2080D0',
392 Token.Name.Namespace: 'bold #2080D0',
393 Token.Prompt: '#009900',
394 Token.PromptNum: '#00ff00 bold',
395 Token.OutPrompt: '#990000',
396 Token.OutPromptNum: '#ff0000 bold',
390 })
397 })
391 elif legacy =='nocolor':
398 elif legacy =='nocolor':
392 style_cls=_NoStyle
399 style_cls=_NoStyle
393 style_overrides = {}
400 style_overrides = {}
394 else :
401 else :
395 raise ValueError('Got unknown colors: ', legacy)
402 raise ValueError('Got unknown colors: ', legacy)
396 else :
403 else :
397 style_cls = get_style_by_name(name)
404 style_cls = get_style_by_name(name)
398 style_overrides = {
405 style_overrides = {
399 Token.Prompt: '#009900',
406 Token.Prompt: '#009900',
400 Token.PromptNum: '#00ff00 bold',
407 Token.PromptNum: '#00ff00 bold',
401 Token.OutPrompt: '#990000',
408 Token.OutPrompt: '#990000',
402 Token.OutPromptNum: '#ff0000 bold',
409 Token.OutPromptNum: '#ff0000 bold',
403 }
410 }
404 style_overrides.update(self.highlighting_style_overrides)
411 style_overrides.update(self.highlighting_style_overrides)
405 style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
412 style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
406 style_dict=style_overrides)
413 style_dict=style_overrides)
407
414
408 return style
415 return style
409
416
410 def _layout_options(self):
417 def _layout_options(self):
411 """
418 """
412 Return the current layout option for the current Terminal InteractiveShell
419 Return the current layout option for the current Terminal InteractiveShell
413 """
420 """
414 return {
421 return {
415 'lexer':IPythonPTLexer(),
422 'lexer':IPythonPTLexer(),
416 'reserve_space_for_menu':self.space_for_menu,
423 'reserve_space_for_menu':self.space_for_menu,
417 'get_prompt_tokens':self.prompts.in_prompt_tokens,
424 'get_prompt_tokens':self.prompts.in_prompt_tokens,
418 'get_continuation_tokens':self.prompts.continuation_prompt_tokens,
425 'get_continuation_tokens':self.prompts.continuation_prompt_tokens,
419 'multiline':True,
426 'multiline':True,
420 'display_completions_in_columns': (self.display_completions == 'multicolumn'),
427 'display_completions_in_columns': (self.display_completions == 'multicolumn'),
421
428
422 # Highlight matching brackets, but only when this setting is
429 # Highlight matching brackets, but only when this setting is
423 # enabled, and only when the DEFAULT_BUFFER has the focus.
430 # enabled, and only when the DEFAULT_BUFFER has the focus.
424 'extra_input_processors': [ConditionalProcessor(
431 'extra_input_processors': [ConditionalProcessor(
425 processor=HighlightMatchingBracketProcessor(chars='[](){}'),
432 processor=HighlightMatchingBracketProcessor(chars='[](){}'),
426 filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
433 filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
427 Condition(lambda cli: self.highlight_matching_brackets))],
434 Condition(lambda cli: self.highlight_matching_brackets))],
428 }
435 }
429
436
430 def _update_layout(self):
437 def _update_layout(self):
431 """
438 """
432 Ask for a re computation of the application layout, if for example ,
439 Ask for a re computation of the application layout, if for example ,
433 some configuration options have changed.
440 some configuration options have changed.
434 """
441 """
435 if getattr(self, '._app', None):
442 if getattr(self, '._app', None):
436 self._app.layout = create_prompt_layout(**self._layout_options())
443 self._app.layout = create_prompt_layout(**self._layout_options())
437
444
438 def prompt_for_code(self):
445 def prompt_for_code(self):
439 document = self.pt_cli.run(
446 document = self.pt_cli.run(
440 pre_run=self.pre_prompt, reset_current_buffer=True)
447 pre_run=self.pre_prompt, reset_current_buffer=True)
441 return document.text
448 return document.text
442
449
443 def init_io(self):
450 def init_io(self):
444 if sys.platform not in {'win32', 'cli'}:
451 if sys.platform not in {'win32', 'cli'}:
445 return
452 return
446
453
447 import win_unicode_console
454 import win_unicode_console
448 import colorama
455 import colorama
449
456
450 win_unicode_console.enable()
457 win_unicode_console.enable()
451 colorama.init()
458 colorama.init()
452
459
453 # For some reason we make these wrappers around stdout/stderr.
460 # For some reason we make these wrappers around stdout/stderr.
454 # For now, we need to reset them so all output gets coloured.
461 # For now, we need to reset them so all output gets coloured.
455 # https://github.com/ipython/ipython/issues/8669
462 # https://github.com/ipython/ipython/issues/8669
456 from IPython.utils import io
463 from IPython.utils import io
457 io.stdout = io.IOStream(sys.stdout)
464 io.stdout = io.IOStream(sys.stdout)
458 io.stderr = io.IOStream(sys.stderr)
465 io.stderr = io.IOStream(sys.stderr)
459
466
460 def init_magics(self):
467 def init_magics(self):
461 super(TerminalInteractiveShell, self).init_magics()
468 super(TerminalInteractiveShell, self).init_magics()
462 self.register_magics(TerminalMagics)
469 self.register_magics(TerminalMagics)
463
470
464 def init_alias(self):
471 def init_alias(self):
465 # The parent class defines aliases that can be safely used with any
472 # The parent class defines aliases that can be safely used with any
466 # frontend.
473 # frontend.
467 super(TerminalInteractiveShell, self).init_alias()
474 super(TerminalInteractiveShell, self).init_alias()
468
475
469 # Now define aliases that only make sense on the terminal, because they
476 # Now define aliases that only make sense on the terminal, because they
470 # need direct access to the console in a way that we can't emulate in
477 # need direct access to the console in a way that we can't emulate in
471 # GUI or web frontend
478 # GUI or web frontend
472 if os.name == 'posix':
479 if os.name == 'posix':
473 for cmd in ['clear', 'more', 'less', 'man']:
480 for cmd in ['clear', 'more', 'less', 'man']:
474 self.alias_manager.soft_define_alias(cmd, cmd)
481 self.alias_manager.soft_define_alias(cmd, cmd)
475
482
476
483
477 def __init__(self, *args, **kwargs):
484 def __init__(self, *args, **kwargs):
478 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
485 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
479 self.init_prompt_toolkit_cli()
486 self.init_prompt_toolkit_cli()
480 self.init_term_title()
487 self.init_term_title()
481 self.keep_running = True
488 self.keep_running = True
482
489
483 self.debugger_history = InMemoryHistory()
490 self.debugger_history = InMemoryHistory()
484
491
485 def ask_exit(self):
492 def ask_exit(self):
486 self.keep_running = False
493 self.keep_running = False
487
494
488 rl_next_input = None
495 rl_next_input = None
489
496
490 def pre_prompt(self):
497 def pre_prompt(self):
491 if self.rl_next_input:
498 if self.rl_next_input:
492 self.pt_cli.application.buffer.text = cast_unicode_py2(self.rl_next_input)
499 self.pt_cli.application.buffer.text = cast_unicode_py2(self.rl_next_input)
493 self.rl_next_input = None
500 self.rl_next_input = None
494
501
495 def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
502 def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
496
503
497 if display_banner is not DISPLAY_BANNER_DEPRECATED:
504 if display_banner is not DISPLAY_BANNER_DEPRECATED:
498 warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
505 warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
499
506
500 while self.keep_running:
507 while self.keep_running:
501 print(self.separate_in, end='')
508 print(self.separate_in, end='')
502
509
503 try:
510 try:
504 code = self.prompt_for_code()
511 code = self.prompt_for_code()
505 except EOFError:
512 except EOFError:
506 if (not self.confirm_exit) \
513 if (not self.confirm_exit) \
507 or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
514 or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
508 self.ask_exit()
515 self.ask_exit()
509
516
510 else:
517 else:
511 if code:
518 if code:
512 self.run_cell(code, store_history=True)
519 self.run_cell(code, store_history=True)
513
520
514 def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
521 def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
515 # An extra layer of protection in case someone mashing Ctrl-C breaks
522 # An extra layer of protection in case someone mashing Ctrl-C breaks
516 # out of our internal code.
523 # out of our internal code.
517 if display_banner is not DISPLAY_BANNER_DEPRECATED:
524 if display_banner is not DISPLAY_BANNER_DEPRECATED:
518 warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
525 warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
519 while True:
526 while True:
520 try:
527 try:
521 self.interact()
528 self.interact()
522 break
529 break
523 except KeyboardInterrupt:
530 except KeyboardInterrupt:
524 print("\nKeyboardInterrupt escaped interact()\n")
531 print("\nKeyboardInterrupt escaped interact()\n")
525
532
526 if hasattr(self, '_eventloop'):
533 if hasattr(self, '_eventloop'):
527 self._eventloop.close()
534 self._eventloop.close()
528
535
529 _inputhook = None
536 _inputhook = None
530 def inputhook(self, context):
537 def inputhook(self, context):
531 if self._inputhook is not None:
538 if self._inputhook is not None:
532 self._inputhook(context)
539 self._inputhook(context)
533
540
534 def enable_gui(self, gui=None):
541 def enable_gui(self, gui=None):
535 if gui:
542 if gui:
536 self._inputhook = get_inputhook_func(gui)
543 self._inputhook = get_inputhook_func(gui)
537 else:
544 else:
538 self._inputhook = None
545 self._inputhook = None
539
546
540 # Run !system commands directly, not through pipes, so terminal programs
547 # Run !system commands directly, not through pipes, so terminal programs
541 # work correctly.
548 # work correctly.
542 system = InteractiveShell.system_raw
549 system = InteractiveShell.system_raw
543
550
544 def auto_rewrite_input(self, cmd):
551 def auto_rewrite_input(self, cmd):
545 """Overridden from the parent class to use fancy rewriting prompt"""
552 """Overridden from the parent class to use fancy rewriting prompt"""
546 if not self.show_rewritten_input:
553 if not self.show_rewritten_input:
547 return
554 return
548
555
549 tokens = self.prompts.rewrite_prompt_tokens()
556 tokens = self.prompts.rewrite_prompt_tokens()
550 if self.pt_cli:
557 if self.pt_cli:
551 self.pt_cli.print_tokens(tokens)
558 self.pt_cli.print_tokens(tokens)
552 print(cmd)
559 print(cmd)
553 else:
560 else:
554 prompt = ''.join(s for t, s in tokens)
561 prompt = ''.join(s for t, s in tokens)
555 print(prompt, cmd, sep='')
562 print(prompt, cmd, sep='')
556
563
557 _prompts_before = None
564 _prompts_before = None
558 def switch_doctest_mode(self, mode):
565 def switch_doctest_mode(self, mode):
559 """Switch prompts to classic for %doctest_mode"""
566 """Switch prompts to classic for %doctest_mode"""
560 if mode:
567 if mode:
561 self._prompts_before = self.prompts
568 self._prompts_before = self.prompts
562 self.prompts = ClassicPrompts(self)
569 self.prompts = ClassicPrompts(self)
563 elif self._prompts_before:
570 elif self._prompts_before:
564 self.prompts = self._prompts_before
571 self.prompts = self._prompts_before
565 self._prompts_before = None
572 self._prompts_before = None
566
573
567
574
568 InteractiveShellABC.register(TerminalInteractiveShell)
575 InteractiveShellABC.register(TerminalInteractiveShell)
569
576
570 if __name__ == '__main__':
577 if __name__ == '__main__':
571 TerminalInteractiveShell.instance().interact()
578 TerminalInteractiveShell.instance().interact()
@@ -1,347 +1,374 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(
126 'Neutral',{
127 'header' : Colors.Red,
128 token.NUMBER : Colors.Cyan,
129 token.OP : Colors.Blue,
130 token.STRING : Colors.Blue,
131 tokenize.COMMENT : Colors.Red,
132 token.NAME : Colors.Normal,
133 token.ERRORTOKEN : Colors.Red,
134
135 _KEYWORD : Colors.Green,
136 _TEXT : Colors.Blue,
137
138 'in_prompt' : InputTermColors.Blue,
139 'in_number' : InputTermColors.LightBlue,
140 'in_prompt2' : InputTermColors.Blue,
141 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
142
143 'out_prompt' : Colors.Red,
144 'out_number' : Colors.LightRed,
145
146 'normal' : Colors.Normal # color off (usu. Colors.Normal)
147 } )
148
149
150
125 LightBGColors = ColorScheme(
151 LightBGColors = ColorScheme(
126 'LightBG',{
152 'LightBG',{
127 'header' : Colors.Red,
153 'header' : Colors.Red,
128 token.NUMBER : Colors.Cyan,
154 token.NUMBER : Colors.Cyan,
129 token.OP : Colors.Blue,
155 token.OP : Colors.Blue,
130 token.STRING : Colors.Blue,
156 token.STRING : Colors.Blue,
131 tokenize.COMMENT : Colors.Red,
157 tokenize.COMMENT : Colors.Red,
132 token.NAME : Colors.Normal,
158 token.NAME : Colors.Normal,
133 token.ERRORTOKEN : Colors.Red,
159 token.ERRORTOKEN : Colors.Red,
134
160
161
135 _KEYWORD : Colors.Green,
162 _KEYWORD : Colors.Green,
136 _TEXT : Colors.Blue,
163 _TEXT : Colors.Blue,
137
164
138 'in_prompt' : InputTermColors.Blue,
165 'in_prompt' : InputTermColors.Blue,
139 'in_number' : InputTermColors.LightBlue,
166 'in_number' : InputTermColors.LightBlue,
140 'in_prompt2' : InputTermColors.Blue,
167 'in_prompt2' : InputTermColors.Blue,
141 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
168 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
142
169
143 'out_prompt' : Colors.Red,
170 'out_prompt' : Colors.Red,
144 'out_number' : Colors.LightRed,
171 'out_number' : Colors.LightRed,
145
172
146 'normal' : Colors.Normal # color off (usu. Colors.Normal)
173 'normal' : Colors.Normal # color off (usu. Colors.Normal)
147 } )
174 } )
148
175
149 # Build table of color schemes (needed by the parser)
176 # Build table of color schemes (needed by the parser)
150 ANSICodeColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors],
177 ANSICodeColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors, NeutralColors],
151 _scheme_default)
178 _scheme_default)
152
179
153 class Parser(Colorable):
180 class Parser(Colorable):
154 """ Format colored Python source.
181 """ Format colored Python source.
155 """
182 """
156
183
157 def __init__(self, color_table=None, out = sys.stdout, parent=None, style=None):
184 def __init__(self, color_table=None, out = sys.stdout, parent=None, style=None):
158 """ Create a parser with a specified color table and output channel.
185 """ Create a parser with a specified color table and output channel.
159
186
160 Call format() to process code.
187 Call format() to process code.
161 """
188 """
162
189
163 super(Parser, self).__init__(parent=parent)
190 super(Parser, self).__init__(parent=parent)
164
191
165 self.color_table = color_table and color_table or ANSICodeColors
192 self.color_table = color_table and color_table or ANSICodeColors
166 self.out = out
193 self.out = out
167
194
168 def format(self, raw, out = None, scheme = ''):
195 def format(self, raw, out = None, scheme = ''):
169 return self.format2(raw, out, scheme)[0]
196 return self.format2(raw, out, scheme)[0]
170
197
171 def format2(self, raw, out = None, scheme = ''):
198 def format2(self, raw, out = None, scheme = ''):
172 """ Parse and send the colored source.
199 """ Parse and send the colored source.
173
200
174 If out and scheme are not specified, the defaults (given to
201 If out and scheme are not specified, the defaults (given to
175 constructor) are used.
202 constructor) are used.
176
203
177 out should be a file-type object. Optionally, out can be given as the
204 out should be a file-type object. Optionally, out can be given as the
178 string 'str' and the parser will automatically return the output in a
205 string 'str' and the parser will automatically return the output in a
179 string."""
206 string."""
180
207
181 string_output = 0
208 string_output = 0
182 if out == 'str' or self.out == 'str' or \
209 if out == 'str' or self.out == 'str' or \
183 isinstance(self.out,StringIO):
210 isinstance(self.out,StringIO):
184 # XXX - I don't really like this state handling logic, but at this
211 # XXX - I don't really like this state handling logic, but at this
185 # point I don't want to make major changes, so adding the
212 # point I don't want to make major changes, so adding the
186 # isinstance() check is the simplest I can do to ensure correct
213 # isinstance() check is the simplest I can do to ensure correct
187 # behavior.
214 # behavior.
188 out_old = self.out
215 out_old = self.out
189 self.out = StringIO()
216 self.out = StringIO()
190 string_output = 1
217 string_output = 1
191 elif out is not None:
218 elif out is not None:
192 self.out = out
219 self.out = out
193
220
194 # Fast return of the unmodified input for NoColor scheme
221 # Fast return of the unmodified input for NoColor scheme
195 if scheme == 'NoColor':
222 if scheme == 'NoColor':
196 error = False
223 error = False
197 self.out.write(raw)
224 self.out.write(raw)
198 if string_output:
225 if string_output:
199 return raw,error
226 return raw,error
200 else:
227 else:
201 return None,error
228 return None,error
202
229
203 # local shorthands
230 # local shorthands
204 colors = self.color_table[scheme].colors
231 colors = self.color_table[scheme].colors
205 self.colors = colors # put in object so __call__ sees it
232 self.colors = colors # put in object so __call__ sees it
206
233
207 # Remove trailing whitespace and normalize tabs
234 # Remove trailing whitespace and normalize tabs
208 self.raw = raw.expandtabs().rstrip()
235 self.raw = raw.expandtabs().rstrip()
209
236
210 # store line offsets in self.lines
237 # store line offsets in self.lines
211 self.lines = [0, 0]
238 self.lines = [0, 0]
212 pos = 0
239 pos = 0
213 raw_find = self.raw.find
240 raw_find = self.raw.find
214 lines_append = self.lines.append
241 lines_append = self.lines.append
215 while 1:
242 while 1:
216 pos = raw_find('\n', pos) + 1
243 pos = raw_find('\n', pos) + 1
217 if not pos: break
244 if not pos: break
218 lines_append(pos)
245 lines_append(pos)
219 lines_append(len(self.raw))
246 lines_append(len(self.raw))
220
247
221 # parse the source and write it
248 # parse the source and write it
222 self.pos = 0
249 self.pos = 0
223 text = StringIO(self.raw)
250 text = StringIO(self.raw)
224
251
225 error = False
252 error = False
226 try:
253 try:
227 for atoken in generate_tokens(text.readline):
254 for atoken in generate_tokens(text.readline):
228 self(*atoken)
255 self(*atoken)
229 except tokenize.TokenError as ex:
256 except tokenize.TokenError as ex:
230 msg = ex.args[0]
257 msg = ex.args[0]
231 line = ex.args[1][0]
258 line = ex.args[1][0]
232 self.out.write("%s\n\n*** ERROR: %s%s%s\n" %
259 self.out.write("%s\n\n*** ERROR: %s%s%s\n" %
233 (colors[token.ERRORTOKEN],
260 (colors[token.ERRORTOKEN],
234 msg, self.raw[self.lines[line]:],
261 msg, self.raw[self.lines[line]:],
235 colors.normal)
262 colors.normal)
236 )
263 )
237 error = True
264 error = True
238 self.out.write(colors.normal+'\n')
265 self.out.write(colors.normal+'\n')
239 if string_output:
266 if string_output:
240 output = self.out.getvalue()
267 output = self.out.getvalue()
241 self.out = out_old
268 self.out = out_old
242 return (output, error)
269 return (output, error)
243 return (None, error)
270 return (None, error)
244
271
245 def __call__(self, toktype, toktext, start_pos, end_pos, line):
272 def __call__(self, toktype, toktext, start_pos, end_pos, line):
246 """ Token handler, with syntax highlighting."""
273 """ Token handler, with syntax highlighting."""
247 (srow,scol) = start_pos
274 (srow,scol) = start_pos
248 (erow,ecol) = end_pos
275 (erow,ecol) = end_pos
249 colors = self.colors
276 colors = self.colors
250 owrite = self.out.write
277 owrite = self.out.write
251
278
252 # line separator, so this works across platforms
279 # line separator, so this works across platforms
253 linesep = os.linesep
280 linesep = os.linesep
254
281
255 # calculate new positions
282 # calculate new positions
256 oldpos = self.pos
283 oldpos = self.pos
257 newpos = self.lines[srow] + scol
284 newpos = self.lines[srow] + scol
258 self.pos = newpos + len(toktext)
285 self.pos = newpos + len(toktext)
259
286
260 # send the original whitespace, if needed
287 # send the original whitespace, if needed
261 if newpos > oldpos:
288 if newpos > oldpos:
262 owrite(self.raw[oldpos:newpos])
289 owrite(self.raw[oldpos:newpos])
263
290
264 # skip indenting tokens
291 # skip indenting tokens
265 if toktype in [token.INDENT, token.DEDENT]:
292 if toktype in [token.INDENT, token.DEDENT]:
266 self.pos = newpos
293 self.pos = newpos
267 return
294 return
268
295
269 # map token type to a color group
296 # map token type to a color group
270 if token.LPAR <= toktype <= token.OP:
297 if token.LPAR <= toktype <= token.OP:
271 toktype = token.OP
298 toktype = token.OP
272 elif toktype == token.NAME and keyword.iskeyword(toktext):
299 elif toktype == token.NAME and keyword.iskeyword(toktext):
273 toktype = _KEYWORD
300 toktype = _KEYWORD
274 color = colors.get(toktype, colors[_TEXT])
301 color = colors.get(toktype, colors[_TEXT])
275
302
276 #print '<%s>' % toktext, # dbg
303 #print '<%s>' % toktext, # dbg
277
304
278 # Triple quoted strings must be handled carefully so that backtracking
305 # Triple quoted strings must be handled carefully so that backtracking
279 # in pagers works correctly. We need color terminators on _each_ line.
306 # in pagers works correctly. We need color terminators on _each_ line.
280 if linesep in toktext:
307 if linesep in toktext:
281 toktext = toktext.replace(linesep, '%s%s%s' %
308 toktext = toktext.replace(linesep, '%s%s%s' %
282 (colors.normal,linesep,color))
309 (colors.normal,linesep,color))
283
310
284 # send text
311 # send text
285 owrite('%s%s%s' % (color,toktext,colors.normal))
312 owrite('%s%s%s' % (color,toktext,colors.normal))
286
313
287 def main(argv=None):
314 def main(argv=None):
288 """Run as a command-line script: colorize a python file or stdin using ANSI
315 """Run as a command-line script: colorize a python file or stdin using ANSI
289 color escapes and print to stdout.
316 color escapes and print to stdout.
290
317
291 Inputs:
318 Inputs:
292
319
293 - argv(None): a list of strings like sys.argv[1:] giving the command-line
320 - argv(None): a list of strings like sys.argv[1:] giving the command-line
294 arguments. If None, use sys.argv[1:].
321 arguments. If None, use sys.argv[1:].
295 """
322 """
296
323
297 usage_msg = """%prog [options] [filename]
324 usage_msg = """%prog [options] [filename]
298
325
299 Colorize a python file or stdin using ANSI color escapes and print to stdout.
326 Colorize a python file or stdin using ANSI color escapes and print to stdout.
300 If no filename is given, or if filename is -, read standard input."""
327 If no filename is given, or if filename is -, read standard input."""
301
328
302 import optparse
329 import optparse
303 parser = optparse.OptionParser(usage=usage_msg)
330 parser = optparse.OptionParser(usage=usage_msg)
304 newopt = parser.add_option
331 newopt = parser.add_option
305 newopt('-s','--scheme',metavar='NAME',dest='scheme_name',action='store',
332 newopt('-s','--scheme',metavar='NAME',dest='scheme_name',action='store',
306 choices=['Linux','LightBG','NoColor'],default=_scheme_default,
333 choices=['Linux','LightBG','NoColor'],default=_scheme_default,
307 help="give the color scheme to use. Currently only 'Linux'\
334 help="give the color scheme to use. Currently only 'Linux'\
308 (default) and 'LightBG' and 'NoColor' are implemented (give without\
335 (default) and 'LightBG' and 'NoColor' are implemented (give without\
309 quotes)")
336 quotes)")
310
337
311 opts,args = parser.parse_args(argv)
338 opts,args = parser.parse_args(argv)
312
339
313 if len(args) > 1:
340 if len(args) > 1:
314 parser.error("you must give at most one filename.")
341 parser.error("you must give at most one filename.")
315
342
316 if len(args) == 0:
343 if len(args) == 0:
317 fname = '-' # no filename given; setup to read from stdin
344 fname = '-' # no filename given; setup to read from stdin
318 else:
345 else:
319 fname = args[0]
346 fname = args[0]
320
347
321 if fname == '-':
348 if fname == '-':
322 stream = sys.stdin
349 stream = sys.stdin
323 else:
350 else:
324 try:
351 try:
325 stream = open(fname)
352 stream = open(fname)
326 except IOError as msg:
353 except IOError as msg:
327 print(msg, file=sys.stderr)
354 print(msg, file=sys.stderr)
328 sys.exit(1)
355 sys.exit(1)
329
356
330 parser = Parser()
357 parser = Parser()
331
358
332 # we need nested try blocks because pre-2.5 python doesn't support unified
359 # we need nested try blocks because pre-2.5 python doesn't support unified
333 # try-except-finally
360 # try-except-finally
334 try:
361 try:
335 try:
362 try:
336 # write colorized version to stdout
363 # write colorized version to stdout
337 parser.format(stream.read(),scheme=opts.scheme_name)
364 parser.format(stream.read(),scheme=opts.scheme_name)
338 except IOError as msg:
365 except IOError as msg:
339 # if user reads through a pager and quits, don't print traceback
366 # if user reads through a pager and quits, don't print traceback
340 if msg.args != (32,'Broken pipe'):
367 if msg.args != (32,'Broken pipe'):
341 raise
368 raise
342 finally:
369 finally:
343 if stream is not sys.stdin:
370 if stream is not sys.stdin:
344 stream.close() # in case a non-handled exception happened above
371 stream.close() # in case a non-handled exception happened above
345
372
346 if __name__ == "__main__":
373 if __name__ == "__main__":
347 main()
374 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']
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'):
52 for scheme in ('Linux', 'NoColor','LightBG', 'Neutral'):
53
53
54 def test_unicode_colorize():
54 def test_unicode_colorize():
55 p = Parser()
55 p = Parser()
56 f1 = p.format('1/0', 'str', scheme=scheme)
56 f1 = p.format('1/0', 'str', scheme=scheme)
57 f2 = p.format(u'1/0', 'str', scheme=scheme)
57 f2 = p.format(u'1/0', 'str', scheme=scheme)
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()
64 p.format(sample, buf, scheme=scheme)
64 p.format(sample, buf, scheme=scheme)
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()
72 f1 = p.format(')', 'str', scheme=scheme)
72 f1 = p.format(')', 'str', scheme=scheme)
73 if scheme != 'NoColor':
73 if scheme != '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