##// END OF EJS Templates
Fix display of SyntaxError in Python 3....
Thomas Kluyver -
Show More
@@ -1,2756 +1,2748 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 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import with_statement
17 from __future__ import with_statement
18 from __future__ import absolute_import
18 from __future__ import absolute_import
19
19
20 import __builtin__ as builtin_mod
20 import __builtin__ as builtin_mod
21 import __future__
21 import __future__
22 import abc
22 import abc
23 import ast
23 import ast
24 import atexit
24 import atexit
25 import codeop
25 import codeop
26 import inspect
26 import inspect
27 import os
27 import os
28 import re
28 import re
29 import sys
29 import sys
30 import tempfile
30 import tempfile
31 import types
31 import types
32
32
33 try:
33 try:
34 from contextlib import nested
34 from contextlib import nested
35 except:
35 except:
36 from IPython.utils.nested_context import nested
36 from IPython.utils.nested_context import nested
37
37
38 from IPython.config.configurable import SingletonConfigurable
38 from IPython.config.configurable import SingletonConfigurable
39 from IPython.core import debugger, oinspect
39 from IPython.core import debugger, oinspect
40 from IPython.core import history as ipcorehist
40 from IPython.core import history as ipcorehist
41 from IPython.core import page
41 from IPython.core import page
42 from IPython.core import prefilter
42 from IPython.core import prefilter
43 from IPython.core import shadowns
43 from IPython.core import shadowns
44 from IPython.core import ultratb
44 from IPython.core import ultratb
45 from IPython.core.alias import AliasManager, AliasError
45 from IPython.core.alias import AliasManager, AliasError
46 from IPython.core.autocall import ExitAutocall
46 from IPython.core.autocall import ExitAutocall
47 from IPython.core.builtin_trap import BuiltinTrap
47 from IPython.core.builtin_trap import BuiltinTrap
48 from IPython.core.compilerop import CachingCompiler
48 from IPython.core.compilerop import CachingCompiler
49 from IPython.core.display_trap import DisplayTrap
49 from IPython.core.display_trap import DisplayTrap
50 from IPython.core.displayhook import DisplayHook
50 from IPython.core.displayhook import DisplayHook
51 from IPython.core.displaypub import DisplayPublisher
51 from IPython.core.displaypub import DisplayPublisher
52 from IPython.core.error import TryNext, UsageError
52 from IPython.core.error import TryNext, UsageError
53 from IPython.core.extensions import ExtensionManager
53 from IPython.core.extensions import ExtensionManager
54 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
54 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
55 from IPython.core.formatters import DisplayFormatter
55 from IPython.core.formatters import DisplayFormatter
56 from IPython.core.history import HistoryManager
56 from IPython.core.history import HistoryManager
57 from IPython.core.inputsplitter import IPythonInputSplitter
57 from IPython.core.inputsplitter import IPythonInputSplitter
58 from IPython.core.logger import Logger
58 from IPython.core.logger import Logger
59 from IPython.core.macro import Macro
59 from IPython.core.macro import Macro
60 from IPython.core.magic import Magic
60 from IPython.core.magic import Magic
61 from IPython.core.payload import PayloadManager
61 from IPython.core.payload import PayloadManager
62 from IPython.core.plugin import PluginManager
62 from IPython.core.plugin import PluginManager
63 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
63 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
64 from IPython.core.profiledir import ProfileDir
64 from IPython.core.profiledir import ProfileDir
65 from IPython.core.pylabtools import pylab_activate
65 from IPython.core.pylabtools import pylab_activate
66 from IPython.core.prompts import PromptManager
66 from IPython.core.prompts import PromptManager
67 from IPython.utils import PyColorize
67 from IPython.utils import PyColorize
68 from IPython.utils import io
68 from IPython.utils import io
69 from IPython.utils import py3compat
69 from IPython.utils import py3compat
70 from IPython.utils.doctestreload import doctest_reload
70 from IPython.utils.doctestreload import doctest_reload
71 from IPython.utils.io import ask_yes_no, rprint
71 from IPython.utils.io import ask_yes_no, rprint
72 from IPython.utils.ipstruct import Struct
72 from IPython.utils.ipstruct import Struct
73 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
73 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
74 from IPython.utils.pickleshare import PickleShareDB
74 from IPython.utils.pickleshare import PickleShareDB
75 from IPython.utils.process import system, getoutput
75 from IPython.utils.process import system, getoutput
76 from IPython.utils.strdispatch import StrDispatch
76 from IPython.utils.strdispatch import StrDispatch
77 from IPython.utils.syspathcontext import prepended_to_syspath
77 from IPython.utils.syspathcontext import prepended_to_syspath
78 from IPython.utils.text import (num_ini_spaces, format_screen, LSString, SList,
78 from IPython.utils.text import (num_ini_spaces, format_screen, LSString, SList,
79 DollarFormatter)
79 DollarFormatter)
80 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
80 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
81 List, Unicode, Instance, Type)
81 List, Unicode, Instance, Type)
82 from IPython.utils.warn import warn, error, fatal
82 from IPython.utils.warn import warn, error, fatal
83 import IPython.core.hooks
83 import IPython.core.hooks
84
84
85 #-----------------------------------------------------------------------------
85 #-----------------------------------------------------------------------------
86 # Globals
86 # Globals
87 #-----------------------------------------------------------------------------
87 #-----------------------------------------------------------------------------
88
88
89 # compiled regexps for autoindent management
89 # compiled regexps for autoindent management
90 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
90 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
91
91
92 #-----------------------------------------------------------------------------
92 #-----------------------------------------------------------------------------
93 # Utilities
93 # Utilities
94 #-----------------------------------------------------------------------------
94 #-----------------------------------------------------------------------------
95
95
96 def softspace(file, newvalue):
96 def softspace(file, newvalue):
97 """Copied from code.py, to remove the dependency"""
97 """Copied from code.py, to remove the dependency"""
98
98
99 oldvalue = 0
99 oldvalue = 0
100 try:
100 try:
101 oldvalue = file.softspace
101 oldvalue = file.softspace
102 except AttributeError:
102 except AttributeError:
103 pass
103 pass
104 try:
104 try:
105 file.softspace = newvalue
105 file.softspace = newvalue
106 except (AttributeError, TypeError):
106 except (AttributeError, TypeError):
107 # "attribute-less object" or "read-only attributes"
107 # "attribute-less object" or "read-only attributes"
108 pass
108 pass
109 return oldvalue
109 return oldvalue
110
110
111
111
112 def no_op(*a, **kw): pass
112 def no_op(*a, **kw): pass
113
113
114 class NoOpContext(object):
114 class NoOpContext(object):
115 def __enter__(self): pass
115 def __enter__(self): pass
116 def __exit__(self, type, value, traceback): pass
116 def __exit__(self, type, value, traceback): pass
117 no_op_context = NoOpContext()
117 no_op_context = NoOpContext()
118
118
119 class SpaceInInput(Exception): pass
119 class SpaceInInput(Exception): pass
120
120
121 class Bunch: pass
121 class Bunch: pass
122
122
123
123
124 def get_default_colors():
124 def get_default_colors():
125 if sys.platform=='darwin':
125 if sys.platform=='darwin':
126 return "LightBG"
126 return "LightBG"
127 elif os.name=='nt':
127 elif os.name=='nt':
128 return 'Linux'
128 return 'Linux'
129 else:
129 else:
130 return 'Linux'
130 return 'Linux'
131
131
132
132
133 class SeparateUnicode(Unicode):
133 class SeparateUnicode(Unicode):
134 """A Unicode subclass to validate separate_in, separate_out, etc.
134 """A Unicode subclass to validate separate_in, separate_out, etc.
135
135
136 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
136 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
137 """
137 """
138
138
139 def validate(self, obj, value):
139 def validate(self, obj, value):
140 if value == '0': value = ''
140 if value == '0': value = ''
141 value = value.replace('\\n','\n')
141 value = value.replace('\\n','\n')
142 return super(SeparateUnicode, self).validate(obj, value)
142 return super(SeparateUnicode, self).validate(obj, value)
143
143
144
144
145 class ReadlineNoRecord(object):
145 class ReadlineNoRecord(object):
146 """Context manager to execute some code, then reload readline history
146 """Context manager to execute some code, then reload readline history
147 so that interactive input to the code doesn't appear when pressing up."""
147 so that interactive input to the code doesn't appear when pressing up."""
148 def __init__(self, shell):
148 def __init__(self, shell):
149 self.shell = shell
149 self.shell = shell
150 self._nested_level = 0
150 self._nested_level = 0
151
151
152 def __enter__(self):
152 def __enter__(self):
153 if self._nested_level == 0:
153 if self._nested_level == 0:
154 try:
154 try:
155 self.orig_length = self.current_length()
155 self.orig_length = self.current_length()
156 self.readline_tail = self.get_readline_tail()
156 self.readline_tail = self.get_readline_tail()
157 except (AttributeError, IndexError): # Can fail with pyreadline
157 except (AttributeError, IndexError): # Can fail with pyreadline
158 self.orig_length, self.readline_tail = 999999, []
158 self.orig_length, self.readline_tail = 999999, []
159 self._nested_level += 1
159 self._nested_level += 1
160
160
161 def __exit__(self, type, value, traceback):
161 def __exit__(self, type, value, traceback):
162 self._nested_level -= 1
162 self._nested_level -= 1
163 if self._nested_level == 0:
163 if self._nested_level == 0:
164 # Try clipping the end if it's got longer
164 # Try clipping the end if it's got longer
165 try:
165 try:
166 e = self.current_length() - self.orig_length
166 e = self.current_length() - self.orig_length
167 if e > 0:
167 if e > 0:
168 for _ in range(e):
168 for _ in range(e):
169 self.shell.readline.remove_history_item(self.orig_length)
169 self.shell.readline.remove_history_item(self.orig_length)
170
170
171 # If it still doesn't match, just reload readline history.
171 # If it still doesn't match, just reload readline history.
172 if self.current_length() != self.orig_length \
172 if self.current_length() != self.orig_length \
173 or self.get_readline_tail() != self.readline_tail:
173 or self.get_readline_tail() != self.readline_tail:
174 self.shell.refill_readline_hist()
174 self.shell.refill_readline_hist()
175 except (AttributeError, IndexError):
175 except (AttributeError, IndexError):
176 pass
176 pass
177 # Returning False will cause exceptions to propagate
177 # Returning False will cause exceptions to propagate
178 return False
178 return False
179
179
180 def current_length(self):
180 def current_length(self):
181 return self.shell.readline.get_current_history_length()
181 return self.shell.readline.get_current_history_length()
182
182
183 def get_readline_tail(self, n=10):
183 def get_readline_tail(self, n=10):
184 """Get the last n items in readline history."""
184 """Get the last n items in readline history."""
185 end = self.shell.readline.get_current_history_length() + 1
185 end = self.shell.readline.get_current_history_length() + 1
186 start = max(end-n, 1)
186 start = max(end-n, 1)
187 ghi = self.shell.readline.get_history_item
187 ghi = self.shell.readline.get_history_item
188 return [ghi(x) for x in range(start, end)]
188 return [ghi(x) for x in range(start, end)]
189
189
190 #-----------------------------------------------------------------------------
190 #-----------------------------------------------------------------------------
191 # Main IPython class
191 # Main IPython class
192 #-----------------------------------------------------------------------------
192 #-----------------------------------------------------------------------------
193
193
194 class InteractiveShell(SingletonConfigurable, Magic):
194 class InteractiveShell(SingletonConfigurable, Magic):
195 """An enhanced, interactive shell for Python."""
195 """An enhanced, interactive shell for Python."""
196
196
197 _instance = None
197 _instance = None
198
198
199 autocall = Enum((0,1,2), default_value=0, config=True, help=
199 autocall = Enum((0,1,2), default_value=0, config=True, help=
200 """
200 """
201 Make IPython automatically call any callable object even if you didn't
201 Make IPython automatically call any callable object even if you didn't
202 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
202 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
203 automatically. The value can be '0' to disable the feature, '1' for
203 automatically. The value can be '0' to disable the feature, '1' for
204 'smart' autocall, where it is not applied if there are no more
204 'smart' autocall, where it is not applied if there are no more
205 arguments on the line, and '2' for 'full' autocall, where all callable
205 arguments on the line, and '2' for 'full' autocall, where all callable
206 objects are automatically called (even if no arguments are present).
206 objects are automatically called (even if no arguments are present).
207 """
207 """
208 )
208 )
209 # TODO: remove all autoindent logic and put into frontends.
209 # TODO: remove all autoindent logic and put into frontends.
210 # We can't do this yet because even runlines uses the autoindent.
210 # We can't do this yet because even runlines uses the autoindent.
211 autoindent = CBool(True, config=True, help=
211 autoindent = CBool(True, config=True, help=
212 """
212 """
213 Autoindent IPython code entered interactively.
213 Autoindent IPython code entered interactively.
214 """
214 """
215 )
215 )
216 automagic = CBool(True, config=True, help=
216 automagic = CBool(True, config=True, help=
217 """
217 """
218 Enable magic commands to be called without the leading %.
218 Enable magic commands to be called without the leading %.
219 """
219 """
220 )
220 )
221 cache_size = Integer(1000, config=True, help=
221 cache_size = Integer(1000, config=True, help=
222 """
222 """
223 Set the size of the output cache. The default is 1000, you can
223 Set the size of the output cache. The default is 1000, you can
224 change it permanently in your config file. Setting it to 0 completely
224 change it permanently in your config file. Setting it to 0 completely
225 disables the caching system, and the minimum value accepted is 20 (if
225 disables the caching system, and the minimum value accepted is 20 (if
226 you provide a value less than 20, it is reset to 0 and a warning is
226 you provide a value less than 20, it is reset to 0 and a warning is
227 issued). This limit is defined because otherwise you'll spend more
227 issued). This limit is defined because otherwise you'll spend more
228 time re-flushing a too small cache than working
228 time re-flushing a too small cache than working
229 """
229 """
230 )
230 )
231 color_info = CBool(True, config=True, help=
231 color_info = CBool(True, config=True, help=
232 """
232 """
233 Use colors for displaying information about objects. Because this
233 Use colors for displaying information about objects. Because this
234 information is passed through a pager (like 'less'), and some pagers
234 information is passed through a pager (like 'less'), and some pagers
235 get confused with color codes, this capability can be turned off.
235 get confused with color codes, this capability can be turned off.
236 """
236 """
237 )
237 )
238 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
238 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
239 default_value=get_default_colors(), config=True,
239 default_value=get_default_colors(), config=True,
240 help="Set the color scheme (NoColor, Linux, or LightBG)."
240 help="Set the color scheme (NoColor, Linux, or LightBG)."
241 )
241 )
242 colors_force = CBool(False, help=
242 colors_force = CBool(False, help=
243 """
243 """
244 Force use of ANSI color codes, regardless of OS and readline
244 Force use of ANSI color codes, regardless of OS and readline
245 availability.
245 availability.
246 """
246 """
247 # FIXME: This is essentially a hack to allow ZMQShell to show colors
247 # FIXME: This is essentially a hack to allow ZMQShell to show colors
248 # without readline on Win32. When the ZMQ formatting system is
248 # without readline on Win32. When the ZMQ formatting system is
249 # refactored, this should be removed.
249 # refactored, this should be removed.
250 )
250 )
251 debug = CBool(False, config=True)
251 debug = CBool(False, config=True)
252 deep_reload = CBool(False, config=True, help=
252 deep_reload = CBool(False, config=True, help=
253 """
253 """
254 Enable deep (recursive) reloading by default. IPython can use the
254 Enable deep (recursive) reloading by default. IPython can use the
255 deep_reload module which reloads changes in modules recursively (it
255 deep_reload module which reloads changes in modules recursively (it
256 replaces the reload() function, so you don't need to change anything to
256 replaces the reload() function, so you don't need to change anything to
257 use it). deep_reload() forces a full reload of modules whose code may
257 use it). deep_reload() forces a full reload of modules whose code may
258 have changed, which the default reload() function does not. When
258 have changed, which the default reload() function does not. When
259 deep_reload is off, IPython will use the normal reload(), but
259 deep_reload is off, IPython will use the normal reload(), but
260 deep_reload will still be available as dreload().
260 deep_reload will still be available as dreload().
261 """
261 """
262 )
262 )
263 disable_failing_post_execute = CBool(False, config=True,
263 disable_failing_post_execute = CBool(False, config=True,
264 help="Don't call post-execute functions that have failed in the past."""
264 help="Don't call post-execute functions that have failed in the past."""
265 )
265 )
266 display_formatter = Instance(DisplayFormatter)
266 display_formatter = Instance(DisplayFormatter)
267 displayhook_class = Type(DisplayHook)
267 displayhook_class = Type(DisplayHook)
268 display_pub_class = Type(DisplayPublisher)
268 display_pub_class = Type(DisplayPublisher)
269
269
270 exit_now = CBool(False)
270 exit_now = CBool(False)
271 exiter = Instance(ExitAutocall)
271 exiter = Instance(ExitAutocall)
272 def _exiter_default(self):
272 def _exiter_default(self):
273 return ExitAutocall(self)
273 return ExitAutocall(self)
274 # Monotonically increasing execution counter
274 # Monotonically increasing execution counter
275 execution_count = Integer(1)
275 execution_count = Integer(1)
276 filename = Unicode("<ipython console>")
276 filename = Unicode("<ipython console>")
277 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
277 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
278
278
279 # Input splitter, to split entire cells of input into either individual
279 # Input splitter, to split entire cells of input into either individual
280 # interactive statements or whole blocks.
280 # interactive statements or whole blocks.
281 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
281 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
282 (), {})
282 (), {})
283 logstart = CBool(False, config=True, help=
283 logstart = CBool(False, config=True, help=
284 """
284 """
285 Start logging to the default log file.
285 Start logging to the default log file.
286 """
286 """
287 )
287 )
288 logfile = Unicode('', config=True, help=
288 logfile = Unicode('', config=True, help=
289 """
289 """
290 The name of the logfile to use.
290 The name of the logfile to use.
291 """
291 """
292 )
292 )
293 logappend = Unicode('', config=True, help=
293 logappend = Unicode('', config=True, help=
294 """
294 """
295 Start logging to the given file in append mode.
295 Start logging to the given file in append mode.
296 """
296 """
297 )
297 )
298 object_info_string_level = Enum((0,1,2), default_value=0,
298 object_info_string_level = Enum((0,1,2), default_value=0,
299 config=True)
299 config=True)
300 pdb = CBool(False, config=True, help=
300 pdb = CBool(False, config=True, help=
301 """
301 """
302 Automatically call the pdb debugger after every exception.
302 Automatically call the pdb debugger after every exception.
303 """
303 """
304 )
304 )
305 multiline_history = CBool(sys.platform != 'win32', config=True,
305 multiline_history = CBool(sys.platform != 'win32', config=True,
306 help="Save multi-line entries as one entry in readline history"
306 help="Save multi-line entries as one entry in readline history"
307 )
307 )
308
308
309 # deprecated prompt traits:
309 # deprecated prompt traits:
310
310
311 prompt_in1 = Unicode('In [\\#]: ', config=True,
311 prompt_in1 = Unicode('In [\\#]: ', config=True,
312 help="Deprecated, use PromptManager.in_template")
312 help="Deprecated, use PromptManager.in_template")
313 prompt_in2 = Unicode(' .\\D.: ', config=True,
313 prompt_in2 = Unicode(' .\\D.: ', config=True,
314 help="Deprecated, use PromptManager.in2_template")
314 help="Deprecated, use PromptManager.in2_template")
315 prompt_out = Unicode('Out[\\#]: ', config=True,
315 prompt_out = Unicode('Out[\\#]: ', config=True,
316 help="Deprecated, use PromptManager.out_template")
316 help="Deprecated, use PromptManager.out_template")
317 prompts_pad_left = CBool(True, config=True,
317 prompts_pad_left = CBool(True, config=True,
318 help="Deprecated, use PromptManager.justify")
318 help="Deprecated, use PromptManager.justify")
319
319
320 def _prompt_trait_changed(self, name, old, new):
320 def _prompt_trait_changed(self, name, old, new):
321 table = {
321 table = {
322 'prompt_in1' : 'in_template',
322 'prompt_in1' : 'in_template',
323 'prompt_in2' : 'in2_template',
323 'prompt_in2' : 'in2_template',
324 'prompt_out' : 'out_template',
324 'prompt_out' : 'out_template',
325 'prompts_pad_left' : 'justify',
325 'prompts_pad_left' : 'justify',
326 }
326 }
327 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}\n".format(
327 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}\n".format(
328 name=name, newname=table[name])
328 name=name, newname=table[name])
329 )
329 )
330 # protect against weird cases where self.config may not exist:
330 # protect against weird cases where self.config may not exist:
331 if self.config is not None:
331 if self.config is not None:
332 # propagate to corresponding PromptManager trait
332 # propagate to corresponding PromptManager trait
333 setattr(self.config.PromptManager, table[name], new)
333 setattr(self.config.PromptManager, table[name], new)
334
334
335 _prompt_in1_changed = _prompt_trait_changed
335 _prompt_in1_changed = _prompt_trait_changed
336 _prompt_in2_changed = _prompt_trait_changed
336 _prompt_in2_changed = _prompt_trait_changed
337 _prompt_out_changed = _prompt_trait_changed
337 _prompt_out_changed = _prompt_trait_changed
338 _prompt_pad_left_changed = _prompt_trait_changed
338 _prompt_pad_left_changed = _prompt_trait_changed
339
339
340 show_rewritten_input = CBool(True, config=True,
340 show_rewritten_input = CBool(True, config=True,
341 help="Show rewritten input, e.g. for autocall."
341 help="Show rewritten input, e.g. for autocall."
342 )
342 )
343
343
344 quiet = CBool(False, config=True)
344 quiet = CBool(False, config=True)
345
345
346 history_length = Integer(10000, config=True)
346 history_length = Integer(10000, config=True)
347
347
348 # The readline stuff will eventually be moved to the terminal subclass
348 # The readline stuff will eventually be moved to the terminal subclass
349 # but for now, we can't do that as readline is welded in everywhere.
349 # but for now, we can't do that as readline is welded in everywhere.
350 readline_use = CBool(True, config=True)
350 readline_use = CBool(True, config=True)
351 readline_remove_delims = Unicode('-/~', config=True)
351 readline_remove_delims = Unicode('-/~', config=True)
352 # don't use \M- bindings by default, because they
352 # don't use \M- bindings by default, because they
353 # conflict with 8-bit encodings. See gh-58,gh-88
353 # conflict with 8-bit encodings. See gh-58,gh-88
354 readline_parse_and_bind = List([
354 readline_parse_and_bind = List([
355 'tab: complete',
355 'tab: complete',
356 '"\C-l": clear-screen',
356 '"\C-l": clear-screen',
357 'set show-all-if-ambiguous on',
357 'set show-all-if-ambiguous on',
358 '"\C-o": tab-insert',
358 '"\C-o": tab-insert',
359 '"\C-r": reverse-search-history',
359 '"\C-r": reverse-search-history',
360 '"\C-s": forward-search-history',
360 '"\C-s": forward-search-history',
361 '"\C-p": history-search-backward',
361 '"\C-p": history-search-backward',
362 '"\C-n": history-search-forward',
362 '"\C-n": history-search-forward',
363 '"\e[A": history-search-backward',
363 '"\e[A": history-search-backward',
364 '"\e[B": history-search-forward',
364 '"\e[B": history-search-forward',
365 '"\C-k": kill-line',
365 '"\C-k": kill-line',
366 '"\C-u": unix-line-discard',
366 '"\C-u": unix-line-discard',
367 ], allow_none=False, config=True)
367 ], allow_none=False, config=True)
368
368
369 # TODO: this part of prompt management should be moved to the frontends.
369 # TODO: this part of prompt management should be moved to the frontends.
370 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
370 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
371 separate_in = SeparateUnicode('\n', config=True)
371 separate_in = SeparateUnicode('\n', config=True)
372 separate_out = SeparateUnicode('', config=True)
372 separate_out = SeparateUnicode('', config=True)
373 separate_out2 = SeparateUnicode('', config=True)
373 separate_out2 = SeparateUnicode('', config=True)
374 wildcards_case_sensitive = CBool(True, config=True)
374 wildcards_case_sensitive = CBool(True, config=True)
375 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
375 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
376 default_value='Context', config=True)
376 default_value='Context', config=True)
377
377
378 # Subcomponents of InteractiveShell
378 # Subcomponents of InteractiveShell
379 alias_manager = Instance('IPython.core.alias.AliasManager')
379 alias_manager = Instance('IPython.core.alias.AliasManager')
380 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
380 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
381 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
381 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
382 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
382 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
383 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
383 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
384 plugin_manager = Instance('IPython.core.plugin.PluginManager')
384 plugin_manager = Instance('IPython.core.plugin.PluginManager')
385 payload_manager = Instance('IPython.core.payload.PayloadManager')
385 payload_manager = Instance('IPython.core.payload.PayloadManager')
386 history_manager = Instance('IPython.core.history.HistoryManager')
386 history_manager = Instance('IPython.core.history.HistoryManager')
387
387
388 profile_dir = Instance('IPython.core.application.ProfileDir')
388 profile_dir = Instance('IPython.core.application.ProfileDir')
389 @property
389 @property
390 def profile(self):
390 def profile(self):
391 if self.profile_dir is not None:
391 if self.profile_dir is not None:
392 name = os.path.basename(self.profile_dir.location)
392 name = os.path.basename(self.profile_dir.location)
393 return name.replace('profile_','')
393 return name.replace('profile_','')
394
394
395
395
396 # Private interface
396 # Private interface
397 _post_execute = Instance(dict)
397 _post_execute = Instance(dict)
398
398
399 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
399 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
400 user_module=None, user_ns=None,
400 user_module=None, user_ns=None,
401 custom_exceptions=((), None)):
401 custom_exceptions=((), None)):
402
402
403 # This is where traits with a config_key argument are updated
403 # This is where traits with a config_key argument are updated
404 # from the values on config.
404 # from the values on config.
405 super(InteractiveShell, self).__init__(config=config)
405 super(InteractiveShell, self).__init__(config=config)
406 self.configurables = [self]
406 self.configurables = [self]
407
407
408 # These are relatively independent and stateless
408 # These are relatively independent and stateless
409 self.init_ipython_dir(ipython_dir)
409 self.init_ipython_dir(ipython_dir)
410 self.init_profile_dir(profile_dir)
410 self.init_profile_dir(profile_dir)
411 self.init_instance_attrs()
411 self.init_instance_attrs()
412 self.init_environment()
412 self.init_environment()
413
413
414 # Create namespaces (user_ns, user_global_ns, etc.)
414 # Create namespaces (user_ns, user_global_ns, etc.)
415 self.init_create_namespaces(user_module, user_ns)
415 self.init_create_namespaces(user_module, user_ns)
416 # This has to be done after init_create_namespaces because it uses
416 # This has to be done after init_create_namespaces because it uses
417 # something in self.user_ns, but before init_sys_modules, which
417 # something in self.user_ns, but before init_sys_modules, which
418 # is the first thing to modify sys.
418 # is the first thing to modify sys.
419 # TODO: When we override sys.stdout and sys.stderr before this class
419 # TODO: When we override sys.stdout and sys.stderr before this class
420 # is created, we are saving the overridden ones here. Not sure if this
420 # is created, we are saving the overridden ones here. Not sure if this
421 # is what we want to do.
421 # is what we want to do.
422 self.save_sys_module_state()
422 self.save_sys_module_state()
423 self.init_sys_modules()
423 self.init_sys_modules()
424
424
425 # While we're trying to have each part of the code directly access what
425 # While we're trying to have each part of the code directly access what
426 # it needs without keeping redundant references to objects, we have too
426 # it needs without keeping redundant references to objects, we have too
427 # much legacy code that expects ip.db to exist.
427 # much legacy code that expects ip.db to exist.
428 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
428 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
429
429
430 self.init_history()
430 self.init_history()
431 self.init_encoding()
431 self.init_encoding()
432 self.init_prefilter()
432 self.init_prefilter()
433
433
434 Magic.__init__(self, self)
434 Magic.__init__(self, self)
435
435
436 self.init_syntax_highlighting()
436 self.init_syntax_highlighting()
437 self.init_hooks()
437 self.init_hooks()
438 self.init_pushd_popd_magic()
438 self.init_pushd_popd_magic()
439 # self.init_traceback_handlers use to be here, but we moved it below
439 # self.init_traceback_handlers use to be here, but we moved it below
440 # because it and init_io have to come after init_readline.
440 # because it and init_io have to come after init_readline.
441 self.init_user_ns()
441 self.init_user_ns()
442 self.init_logger()
442 self.init_logger()
443 self.init_alias()
443 self.init_alias()
444 self.init_builtins()
444 self.init_builtins()
445
445
446 # pre_config_initialization
446 # pre_config_initialization
447
447
448 # The next section should contain everything that was in ipmaker.
448 # The next section should contain everything that was in ipmaker.
449 self.init_logstart()
449 self.init_logstart()
450
450
451 # The following was in post_config_initialization
451 # The following was in post_config_initialization
452 self.init_inspector()
452 self.init_inspector()
453 # init_readline() must come before init_io(), because init_io uses
453 # init_readline() must come before init_io(), because init_io uses
454 # readline related things.
454 # readline related things.
455 self.init_readline()
455 self.init_readline()
456 # We save this here in case user code replaces raw_input, but it needs
456 # We save this here in case user code replaces raw_input, but it needs
457 # to be after init_readline(), because PyPy's readline works by replacing
457 # to be after init_readline(), because PyPy's readline works by replacing
458 # raw_input.
458 # raw_input.
459 if py3compat.PY3:
459 if py3compat.PY3:
460 self.raw_input_original = input
460 self.raw_input_original = input
461 else:
461 else:
462 self.raw_input_original = raw_input
462 self.raw_input_original = raw_input
463 # init_completer must come after init_readline, because it needs to
463 # init_completer must come after init_readline, because it needs to
464 # know whether readline is present or not system-wide to configure the
464 # know whether readline is present or not system-wide to configure the
465 # completers, since the completion machinery can now operate
465 # completers, since the completion machinery can now operate
466 # independently of readline (e.g. over the network)
466 # independently of readline (e.g. over the network)
467 self.init_completer()
467 self.init_completer()
468 # TODO: init_io() needs to happen before init_traceback handlers
468 # TODO: init_io() needs to happen before init_traceback handlers
469 # because the traceback handlers hardcode the stdout/stderr streams.
469 # because the traceback handlers hardcode the stdout/stderr streams.
470 # This logic in in debugger.Pdb and should eventually be changed.
470 # This logic in in debugger.Pdb and should eventually be changed.
471 self.init_io()
471 self.init_io()
472 self.init_traceback_handlers(custom_exceptions)
472 self.init_traceback_handlers(custom_exceptions)
473 self.init_prompts()
473 self.init_prompts()
474 self.init_display_formatter()
474 self.init_display_formatter()
475 self.init_display_pub()
475 self.init_display_pub()
476 self.init_displayhook()
476 self.init_displayhook()
477 self.init_reload_doctest()
477 self.init_reload_doctest()
478 self.init_magics()
478 self.init_magics()
479 self.init_pdb()
479 self.init_pdb()
480 self.init_extension_manager()
480 self.init_extension_manager()
481 self.init_plugin_manager()
481 self.init_plugin_manager()
482 self.init_payload()
482 self.init_payload()
483 self.hooks.late_startup_hook()
483 self.hooks.late_startup_hook()
484 atexit.register(self.atexit_operations)
484 atexit.register(self.atexit_operations)
485
485
486 def get_ipython(self):
486 def get_ipython(self):
487 """Return the currently running IPython instance."""
487 """Return the currently running IPython instance."""
488 return self
488 return self
489
489
490 #-------------------------------------------------------------------------
490 #-------------------------------------------------------------------------
491 # Trait changed handlers
491 # Trait changed handlers
492 #-------------------------------------------------------------------------
492 #-------------------------------------------------------------------------
493
493
494 def _ipython_dir_changed(self, name, new):
494 def _ipython_dir_changed(self, name, new):
495 if not os.path.isdir(new):
495 if not os.path.isdir(new):
496 os.makedirs(new, mode = 0777)
496 os.makedirs(new, mode = 0777)
497
497
498 def set_autoindent(self,value=None):
498 def set_autoindent(self,value=None):
499 """Set the autoindent flag, checking for readline support.
499 """Set the autoindent flag, checking for readline support.
500
500
501 If called with no arguments, it acts as a toggle."""
501 If called with no arguments, it acts as a toggle."""
502
502
503 if value != 0 and not self.has_readline:
503 if value != 0 and not self.has_readline:
504 if os.name == 'posix':
504 if os.name == 'posix':
505 warn("The auto-indent feature requires the readline library")
505 warn("The auto-indent feature requires the readline library")
506 self.autoindent = 0
506 self.autoindent = 0
507 return
507 return
508 if value is None:
508 if value is None:
509 self.autoindent = not self.autoindent
509 self.autoindent = not self.autoindent
510 else:
510 else:
511 self.autoindent = value
511 self.autoindent = value
512
512
513 #-------------------------------------------------------------------------
513 #-------------------------------------------------------------------------
514 # init_* methods called by __init__
514 # init_* methods called by __init__
515 #-------------------------------------------------------------------------
515 #-------------------------------------------------------------------------
516
516
517 def init_ipython_dir(self, ipython_dir):
517 def init_ipython_dir(self, ipython_dir):
518 if ipython_dir is not None:
518 if ipython_dir is not None:
519 self.ipython_dir = ipython_dir
519 self.ipython_dir = ipython_dir
520 return
520 return
521
521
522 self.ipython_dir = get_ipython_dir()
522 self.ipython_dir = get_ipython_dir()
523
523
524 def init_profile_dir(self, profile_dir):
524 def init_profile_dir(self, profile_dir):
525 if profile_dir is not None:
525 if profile_dir is not None:
526 self.profile_dir = profile_dir
526 self.profile_dir = profile_dir
527 return
527 return
528 self.profile_dir =\
528 self.profile_dir =\
529 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
529 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
530
530
531 def init_instance_attrs(self):
531 def init_instance_attrs(self):
532 self.more = False
532 self.more = False
533
533
534 # command compiler
534 # command compiler
535 self.compile = CachingCompiler()
535 self.compile = CachingCompiler()
536
536
537 # Make an empty namespace, which extension writers can rely on both
537 # Make an empty namespace, which extension writers can rely on both
538 # existing and NEVER being used by ipython itself. This gives them a
538 # existing and NEVER being used by ipython itself. This gives them a
539 # convenient location for storing additional information and state
539 # convenient location for storing additional information and state
540 # their extensions may require, without fear of collisions with other
540 # their extensions may require, without fear of collisions with other
541 # ipython names that may develop later.
541 # ipython names that may develop later.
542 self.meta = Struct()
542 self.meta = Struct()
543
543
544 # Temporary files used for various purposes. Deleted at exit.
544 # Temporary files used for various purposes. Deleted at exit.
545 self.tempfiles = []
545 self.tempfiles = []
546
546
547 # Keep track of readline usage (later set by init_readline)
547 # Keep track of readline usage (later set by init_readline)
548 self.has_readline = False
548 self.has_readline = False
549
549
550 # keep track of where we started running (mainly for crash post-mortem)
550 # keep track of where we started running (mainly for crash post-mortem)
551 # This is not being used anywhere currently.
551 # This is not being used anywhere currently.
552 self.starting_dir = os.getcwdu()
552 self.starting_dir = os.getcwdu()
553
553
554 # Indentation management
554 # Indentation management
555 self.indent_current_nsp = 0
555 self.indent_current_nsp = 0
556
556
557 # Dict to track post-execution functions that have been registered
557 # Dict to track post-execution functions that have been registered
558 self._post_execute = {}
558 self._post_execute = {}
559
559
560 def init_environment(self):
560 def init_environment(self):
561 """Any changes we need to make to the user's environment."""
561 """Any changes we need to make to the user's environment."""
562 pass
562 pass
563
563
564 def init_encoding(self):
564 def init_encoding(self):
565 # Get system encoding at startup time. Certain terminals (like Emacs
565 # Get system encoding at startup time. Certain terminals (like Emacs
566 # under Win32 have it set to None, and we need to have a known valid
566 # under Win32 have it set to None, and we need to have a known valid
567 # encoding to use in the raw_input() method
567 # encoding to use in the raw_input() method
568 try:
568 try:
569 self.stdin_encoding = sys.stdin.encoding or 'ascii'
569 self.stdin_encoding = sys.stdin.encoding or 'ascii'
570 except AttributeError:
570 except AttributeError:
571 self.stdin_encoding = 'ascii'
571 self.stdin_encoding = 'ascii'
572
572
573 def init_syntax_highlighting(self):
573 def init_syntax_highlighting(self):
574 # Python source parser/formatter for syntax highlighting
574 # Python source parser/formatter for syntax highlighting
575 pyformat = PyColorize.Parser().format
575 pyformat = PyColorize.Parser().format
576 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
576 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
577
577
578 def init_pushd_popd_magic(self):
578 def init_pushd_popd_magic(self):
579 # for pushd/popd management
579 # for pushd/popd management
580 self.home_dir = get_home_dir()
580 self.home_dir = get_home_dir()
581
581
582 self.dir_stack = []
582 self.dir_stack = []
583
583
584 def init_logger(self):
584 def init_logger(self):
585 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
585 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
586 logmode='rotate')
586 logmode='rotate')
587
587
588 def init_logstart(self):
588 def init_logstart(self):
589 """Initialize logging in case it was requested at the command line.
589 """Initialize logging in case it was requested at the command line.
590 """
590 """
591 if self.logappend:
591 if self.logappend:
592 self.magic_logstart(self.logappend + ' append')
592 self.magic_logstart(self.logappend + ' append')
593 elif self.logfile:
593 elif self.logfile:
594 self.magic_logstart(self.logfile)
594 self.magic_logstart(self.logfile)
595 elif self.logstart:
595 elif self.logstart:
596 self.magic_logstart()
596 self.magic_logstart()
597
597
598 def init_builtins(self):
598 def init_builtins(self):
599 # A single, static flag that we set to True. Its presence indicates
599 # A single, static flag that we set to True. Its presence indicates
600 # that an IPython shell has been created, and we make no attempts at
600 # that an IPython shell has been created, and we make no attempts at
601 # removing on exit or representing the existence of more than one
601 # removing on exit or representing the existence of more than one
602 # IPython at a time.
602 # IPython at a time.
603 builtin_mod.__dict__['__IPYTHON__'] = True
603 builtin_mod.__dict__['__IPYTHON__'] = True
604
604
605 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
605 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
606 # manage on enter/exit, but with all our shells it's virtually
606 # manage on enter/exit, but with all our shells it's virtually
607 # impossible to get all the cases right. We're leaving the name in for
607 # impossible to get all the cases right. We're leaving the name in for
608 # those who adapted their codes to check for this flag, but will
608 # those who adapted their codes to check for this flag, but will
609 # eventually remove it after a few more releases.
609 # eventually remove it after a few more releases.
610 builtin_mod.__dict__['__IPYTHON__active'] = \
610 builtin_mod.__dict__['__IPYTHON__active'] = \
611 'Deprecated, check for __IPYTHON__'
611 'Deprecated, check for __IPYTHON__'
612
612
613 self.builtin_trap = BuiltinTrap(shell=self)
613 self.builtin_trap = BuiltinTrap(shell=self)
614
614
615 def init_inspector(self):
615 def init_inspector(self):
616 # Object inspector
616 # Object inspector
617 self.inspector = oinspect.Inspector(oinspect.InspectColors,
617 self.inspector = oinspect.Inspector(oinspect.InspectColors,
618 PyColorize.ANSICodeColors,
618 PyColorize.ANSICodeColors,
619 'NoColor',
619 'NoColor',
620 self.object_info_string_level)
620 self.object_info_string_level)
621
621
622 def init_io(self):
622 def init_io(self):
623 # This will just use sys.stdout and sys.stderr. If you want to
623 # This will just use sys.stdout and sys.stderr. If you want to
624 # override sys.stdout and sys.stderr themselves, you need to do that
624 # override sys.stdout and sys.stderr themselves, you need to do that
625 # *before* instantiating this class, because io holds onto
625 # *before* instantiating this class, because io holds onto
626 # references to the underlying streams.
626 # references to the underlying streams.
627 if sys.platform == 'win32' and self.has_readline:
627 if sys.platform == 'win32' and self.has_readline:
628 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
628 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
629 else:
629 else:
630 io.stdout = io.IOStream(sys.stdout)
630 io.stdout = io.IOStream(sys.stdout)
631 io.stderr = io.IOStream(sys.stderr)
631 io.stderr = io.IOStream(sys.stderr)
632
632
633 def init_prompts(self):
633 def init_prompts(self):
634 self.prompt_manager = PromptManager(shell=self, config=self.config)
634 self.prompt_manager = PromptManager(shell=self, config=self.config)
635 self.configurables.append(self.prompt_manager)
635 self.configurables.append(self.prompt_manager)
636
636
637 def init_display_formatter(self):
637 def init_display_formatter(self):
638 self.display_formatter = DisplayFormatter(config=self.config)
638 self.display_formatter = DisplayFormatter(config=self.config)
639 self.configurables.append(self.display_formatter)
639 self.configurables.append(self.display_formatter)
640
640
641 def init_display_pub(self):
641 def init_display_pub(self):
642 self.display_pub = self.display_pub_class(config=self.config)
642 self.display_pub = self.display_pub_class(config=self.config)
643 self.configurables.append(self.display_pub)
643 self.configurables.append(self.display_pub)
644
644
645 def init_displayhook(self):
645 def init_displayhook(self):
646 # Initialize displayhook, set in/out prompts and printing system
646 # Initialize displayhook, set in/out prompts and printing system
647 self.displayhook = self.displayhook_class(
647 self.displayhook = self.displayhook_class(
648 config=self.config,
648 config=self.config,
649 shell=self,
649 shell=self,
650 cache_size=self.cache_size,
650 cache_size=self.cache_size,
651 )
651 )
652 self.configurables.append(self.displayhook)
652 self.configurables.append(self.displayhook)
653 # This is a context manager that installs/revmoes the displayhook at
653 # This is a context manager that installs/revmoes the displayhook at
654 # the appropriate time.
654 # the appropriate time.
655 self.display_trap = DisplayTrap(hook=self.displayhook)
655 self.display_trap = DisplayTrap(hook=self.displayhook)
656
656
657 def init_reload_doctest(self):
657 def init_reload_doctest(self):
658 # Do a proper resetting of doctest, including the necessary displayhook
658 # Do a proper resetting of doctest, including the necessary displayhook
659 # monkeypatching
659 # monkeypatching
660 try:
660 try:
661 doctest_reload()
661 doctest_reload()
662 except ImportError:
662 except ImportError:
663 warn("doctest module does not exist.")
663 warn("doctest module does not exist.")
664
664
665 #-------------------------------------------------------------------------
665 #-------------------------------------------------------------------------
666 # Things related to injections into the sys module
666 # Things related to injections into the sys module
667 #-------------------------------------------------------------------------
667 #-------------------------------------------------------------------------
668
668
669 def save_sys_module_state(self):
669 def save_sys_module_state(self):
670 """Save the state of hooks in the sys module.
670 """Save the state of hooks in the sys module.
671
671
672 This has to be called after self.user_module is created.
672 This has to be called after self.user_module is created.
673 """
673 """
674 self._orig_sys_module_state = {}
674 self._orig_sys_module_state = {}
675 self._orig_sys_module_state['stdin'] = sys.stdin
675 self._orig_sys_module_state['stdin'] = sys.stdin
676 self._orig_sys_module_state['stdout'] = sys.stdout
676 self._orig_sys_module_state['stdout'] = sys.stdout
677 self._orig_sys_module_state['stderr'] = sys.stderr
677 self._orig_sys_module_state['stderr'] = sys.stderr
678 self._orig_sys_module_state['excepthook'] = sys.excepthook
678 self._orig_sys_module_state['excepthook'] = sys.excepthook
679 self._orig_sys_modules_main_name = self.user_module.__name__
679 self._orig_sys_modules_main_name = self.user_module.__name__
680
680
681 def restore_sys_module_state(self):
681 def restore_sys_module_state(self):
682 """Restore the state of the sys module."""
682 """Restore the state of the sys module."""
683 try:
683 try:
684 for k, v in self._orig_sys_module_state.iteritems():
684 for k, v in self._orig_sys_module_state.iteritems():
685 setattr(sys, k, v)
685 setattr(sys, k, v)
686 except AttributeError:
686 except AttributeError:
687 pass
687 pass
688 # Reset what what done in self.init_sys_modules
688 # Reset what what done in self.init_sys_modules
689 sys.modules[self.user_module.__name__] = self._orig_sys_modules_main_name
689 sys.modules[self.user_module.__name__] = self._orig_sys_modules_main_name
690
690
691 #-------------------------------------------------------------------------
691 #-------------------------------------------------------------------------
692 # Things related to hooks
692 # Things related to hooks
693 #-------------------------------------------------------------------------
693 #-------------------------------------------------------------------------
694
694
695 def init_hooks(self):
695 def init_hooks(self):
696 # hooks holds pointers used for user-side customizations
696 # hooks holds pointers used for user-side customizations
697 self.hooks = Struct()
697 self.hooks = Struct()
698
698
699 self.strdispatchers = {}
699 self.strdispatchers = {}
700
700
701 # Set all default hooks, defined in the IPython.hooks module.
701 # Set all default hooks, defined in the IPython.hooks module.
702 hooks = IPython.core.hooks
702 hooks = IPython.core.hooks
703 for hook_name in hooks.__all__:
703 for hook_name in hooks.__all__:
704 # default hooks have priority 100, i.e. low; user hooks should have
704 # default hooks have priority 100, i.e. low; user hooks should have
705 # 0-100 priority
705 # 0-100 priority
706 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
706 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
707
707
708 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
708 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
709 """set_hook(name,hook) -> sets an internal IPython hook.
709 """set_hook(name,hook) -> sets an internal IPython hook.
710
710
711 IPython exposes some of its internal API as user-modifiable hooks. By
711 IPython exposes some of its internal API as user-modifiable hooks. By
712 adding your function to one of these hooks, you can modify IPython's
712 adding your function to one of these hooks, you can modify IPython's
713 behavior to call at runtime your own routines."""
713 behavior to call at runtime your own routines."""
714
714
715 # At some point in the future, this should validate the hook before it
715 # At some point in the future, this should validate the hook before it
716 # accepts it. Probably at least check that the hook takes the number
716 # accepts it. Probably at least check that the hook takes the number
717 # of args it's supposed to.
717 # of args it's supposed to.
718
718
719 f = types.MethodType(hook,self)
719 f = types.MethodType(hook,self)
720
720
721 # check if the hook is for strdispatcher first
721 # check if the hook is for strdispatcher first
722 if str_key is not None:
722 if str_key is not None:
723 sdp = self.strdispatchers.get(name, StrDispatch())
723 sdp = self.strdispatchers.get(name, StrDispatch())
724 sdp.add_s(str_key, f, priority )
724 sdp.add_s(str_key, f, priority )
725 self.strdispatchers[name] = sdp
725 self.strdispatchers[name] = sdp
726 return
726 return
727 if re_key is not None:
727 if re_key is not None:
728 sdp = self.strdispatchers.get(name, StrDispatch())
728 sdp = self.strdispatchers.get(name, StrDispatch())
729 sdp.add_re(re.compile(re_key), f, priority )
729 sdp.add_re(re.compile(re_key), f, priority )
730 self.strdispatchers[name] = sdp
730 self.strdispatchers[name] = sdp
731 return
731 return
732
732
733 dp = getattr(self.hooks, name, None)
733 dp = getattr(self.hooks, name, None)
734 if name not in IPython.core.hooks.__all__:
734 if name not in IPython.core.hooks.__all__:
735 print "Warning! Hook '%s' is not one of %s" % \
735 print "Warning! Hook '%s' is not one of %s" % \
736 (name, IPython.core.hooks.__all__ )
736 (name, IPython.core.hooks.__all__ )
737 if not dp:
737 if not dp:
738 dp = IPython.core.hooks.CommandChainDispatcher()
738 dp = IPython.core.hooks.CommandChainDispatcher()
739
739
740 try:
740 try:
741 dp.add(f,priority)
741 dp.add(f,priority)
742 except AttributeError:
742 except AttributeError:
743 # it was not commandchain, plain old func - replace
743 # it was not commandchain, plain old func - replace
744 dp = f
744 dp = f
745
745
746 setattr(self.hooks,name, dp)
746 setattr(self.hooks,name, dp)
747
747
748 def register_post_execute(self, func):
748 def register_post_execute(self, func):
749 """Register a function for calling after code execution.
749 """Register a function for calling after code execution.
750 """
750 """
751 if not callable(func):
751 if not callable(func):
752 raise ValueError('argument %s must be callable' % func)
752 raise ValueError('argument %s must be callable' % func)
753 self._post_execute[func] = True
753 self._post_execute[func] = True
754
754
755 #-------------------------------------------------------------------------
755 #-------------------------------------------------------------------------
756 # Things related to the "main" module
756 # Things related to the "main" module
757 #-------------------------------------------------------------------------
757 #-------------------------------------------------------------------------
758
758
759 def new_main_mod(self,ns=None):
759 def new_main_mod(self,ns=None):
760 """Return a new 'main' module object for user code execution.
760 """Return a new 'main' module object for user code execution.
761 """
761 """
762 main_mod = self._user_main_module
762 main_mod = self._user_main_module
763 init_fakemod_dict(main_mod,ns)
763 init_fakemod_dict(main_mod,ns)
764 return main_mod
764 return main_mod
765
765
766 def cache_main_mod(self,ns,fname):
766 def cache_main_mod(self,ns,fname):
767 """Cache a main module's namespace.
767 """Cache a main module's namespace.
768
768
769 When scripts are executed via %run, we must keep a reference to the
769 When scripts are executed via %run, we must keep a reference to the
770 namespace of their __main__ module (a FakeModule instance) around so
770 namespace of their __main__ module (a FakeModule instance) around so
771 that Python doesn't clear it, rendering objects defined therein
771 that Python doesn't clear it, rendering objects defined therein
772 useless.
772 useless.
773
773
774 This method keeps said reference in a private dict, keyed by the
774 This method keeps said reference in a private dict, keyed by the
775 absolute path of the module object (which corresponds to the script
775 absolute path of the module object (which corresponds to the script
776 path). This way, for multiple executions of the same script we only
776 path). This way, for multiple executions of the same script we only
777 keep one copy of the namespace (the last one), thus preventing memory
777 keep one copy of the namespace (the last one), thus preventing memory
778 leaks from old references while allowing the objects from the last
778 leaks from old references while allowing the objects from the last
779 execution to be accessible.
779 execution to be accessible.
780
780
781 Note: we can not allow the actual FakeModule instances to be deleted,
781 Note: we can not allow the actual FakeModule instances to be deleted,
782 because of how Python tears down modules (it hard-sets all their
782 because of how Python tears down modules (it hard-sets all their
783 references to None without regard for reference counts). This method
783 references to None without regard for reference counts). This method
784 must therefore make a *copy* of the given namespace, to allow the
784 must therefore make a *copy* of the given namespace, to allow the
785 original module's __dict__ to be cleared and reused.
785 original module's __dict__ to be cleared and reused.
786
786
787
787
788 Parameters
788 Parameters
789 ----------
789 ----------
790 ns : a namespace (a dict, typically)
790 ns : a namespace (a dict, typically)
791
791
792 fname : str
792 fname : str
793 Filename associated with the namespace.
793 Filename associated with the namespace.
794
794
795 Examples
795 Examples
796 --------
796 --------
797
797
798 In [10]: import IPython
798 In [10]: import IPython
799
799
800 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
800 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
801
801
802 In [12]: IPython.__file__ in _ip._main_ns_cache
802 In [12]: IPython.__file__ in _ip._main_ns_cache
803 Out[12]: True
803 Out[12]: True
804 """
804 """
805 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
805 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
806
806
807 def clear_main_mod_cache(self):
807 def clear_main_mod_cache(self):
808 """Clear the cache of main modules.
808 """Clear the cache of main modules.
809
809
810 Mainly for use by utilities like %reset.
810 Mainly for use by utilities like %reset.
811
811
812 Examples
812 Examples
813 --------
813 --------
814
814
815 In [15]: import IPython
815 In [15]: import IPython
816
816
817 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
817 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
818
818
819 In [17]: len(_ip._main_ns_cache) > 0
819 In [17]: len(_ip._main_ns_cache) > 0
820 Out[17]: True
820 Out[17]: True
821
821
822 In [18]: _ip.clear_main_mod_cache()
822 In [18]: _ip.clear_main_mod_cache()
823
823
824 In [19]: len(_ip._main_ns_cache) == 0
824 In [19]: len(_ip._main_ns_cache) == 0
825 Out[19]: True
825 Out[19]: True
826 """
826 """
827 self._main_ns_cache.clear()
827 self._main_ns_cache.clear()
828
828
829 #-------------------------------------------------------------------------
829 #-------------------------------------------------------------------------
830 # Things related to debugging
830 # Things related to debugging
831 #-------------------------------------------------------------------------
831 #-------------------------------------------------------------------------
832
832
833 def init_pdb(self):
833 def init_pdb(self):
834 # Set calling of pdb on exceptions
834 # Set calling of pdb on exceptions
835 # self.call_pdb is a property
835 # self.call_pdb is a property
836 self.call_pdb = self.pdb
836 self.call_pdb = self.pdb
837
837
838 def _get_call_pdb(self):
838 def _get_call_pdb(self):
839 return self._call_pdb
839 return self._call_pdb
840
840
841 def _set_call_pdb(self,val):
841 def _set_call_pdb(self,val):
842
842
843 if val not in (0,1,False,True):
843 if val not in (0,1,False,True):
844 raise ValueError,'new call_pdb value must be boolean'
844 raise ValueError,'new call_pdb value must be boolean'
845
845
846 # store value in instance
846 # store value in instance
847 self._call_pdb = val
847 self._call_pdb = val
848
848
849 # notify the actual exception handlers
849 # notify the actual exception handlers
850 self.InteractiveTB.call_pdb = val
850 self.InteractiveTB.call_pdb = val
851
851
852 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
852 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
853 'Control auto-activation of pdb at exceptions')
853 'Control auto-activation of pdb at exceptions')
854
854
855 def debugger(self,force=False):
855 def debugger(self,force=False):
856 """Call the pydb/pdb debugger.
856 """Call the pydb/pdb debugger.
857
857
858 Keywords:
858 Keywords:
859
859
860 - force(False): by default, this routine checks the instance call_pdb
860 - force(False): by default, this routine checks the instance call_pdb
861 flag and does not actually invoke the debugger if the flag is false.
861 flag and does not actually invoke the debugger if the flag is false.
862 The 'force' option forces the debugger to activate even if the flag
862 The 'force' option forces the debugger to activate even if the flag
863 is false.
863 is false.
864 """
864 """
865
865
866 if not (force or self.call_pdb):
866 if not (force or self.call_pdb):
867 return
867 return
868
868
869 if not hasattr(sys,'last_traceback'):
869 if not hasattr(sys,'last_traceback'):
870 error('No traceback has been produced, nothing to debug.')
870 error('No traceback has been produced, nothing to debug.')
871 return
871 return
872
872
873 # use pydb if available
873 # use pydb if available
874 if debugger.has_pydb:
874 if debugger.has_pydb:
875 from pydb import pm
875 from pydb import pm
876 else:
876 else:
877 # fallback to our internal debugger
877 # fallback to our internal debugger
878 pm = lambda : self.InteractiveTB.debugger(force=True)
878 pm = lambda : self.InteractiveTB.debugger(force=True)
879
879
880 with self.readline_no_record:
880 with self.readline_no_record:
881 pm()
881 pm()
882
882
883 #-------------------------------------------------------------------------
883 #-------------------------------------------------------------------------
884 # Things related to IPython's various namespaces
884 # Things related to IPython's various namespaces
885 #-------------------------------------------------------------------------
885 #-------------------------------------------------------------------------
886 default_user_namespaces = True
886 default_user_namespaces = True
887
887
888 def init_create_namespaces(self, user_module=None, user_ns=None):
888 def init_create_namespaces(self, user_module=None, user_ns=None):
889 # Create the namespace where the user will operate. user_ns is
889 # Create the namespace where the user will operate. user_ns is
890 # normally the only one used, and it is passed to the exec calls as
890 # normally the only one used, and it is passed to the exec calls as
891 # the locals argument. But we do carry a user_global_ns namespace
891 # the locals argument. But we do carry a user_global_ns namespace
892 # given as the exec 'globals' argument, This is useful in embedding
892 # given as the exec 'globals' argument, This is useful in embedding
893 # situations where the ipython shell opens in a context where the
893 # situations where the ipython shell opens in a context where the
894 # distinction between locals and globals is meaningful. For
894 # distinction between locals and globals is meaningful. For
895 # non-embedded contexts, it is just the same object as the user_ns dict.
895 # non-embedded contexts, it is just the same object as the user_ns dict.
896
896
897 # FIXME. For some strange reason, __builtins__ is showing up at user
897 # FIXME. For some strange reason, __builtins__ is showing up at user
898 # level as a dict instead of a module. This is a manual fix, but I
898 # level as a dict instead of a module. This is a manual fix, but I
899 # should really track down where the problem is coming from. Alex
899 # should really track down where the problem is coming from. Alex
900 # Schmolck reported this problem first.
900 # Schmolck reported this problem first.
901
901
902 # A useful post by Alex Martelli on this topic:
902 # A useful post by Alex Martelli on this topic:
903 # Re: inconsistent value from __builtins__
903 # Re: inconsistent value from __builtins__
904 # Von: Alex Martelli <aleaxit@yahoo.com>
904 # Von: Alex Martelli <aleaxit@yahoo.com>
905 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
905 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
906 # Gruppen: comp.lang.python
906 # Gruppen: comp.lang.python
907
907
908 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
908 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
909 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
909 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
910 # > <type 'dict'>
910 # > <type 'dict'>
911 # > >>> print type(__builtins__)
911 # > >>> print type(__builtins__)
912 # > <type 'module'>
912 # > <type 'module'>
913 # > Is this difference in return value intentional?
913 # > Is this difference in return value intentional?
914
914
915 # Well, it's documented that '__builtins__' can be either a dictionary
915 # Well, it's documented that '__builtins__' can be either a dictionary
916 # or a module, and it's been that way for a long time. Whether it's
916 # or a module, and it's been that way for a long time. Whether it's
917 # intentional (or sensible), I don't know. In any case, the idea is
917 # intentional (or sensible), I don't know. In any case, the idea is
918 # that if you need to access the built-in namespace directly, you
918 # that if you need to access the built-in namespace directly, you
919 # should start with "import __builtin__" (note, no 's') which will
919 # should start with "import __builtin__" (note, no 's') which will
920 # definitely give you a module. Yeah, it's somewhat confusing:-(.
920 # definitely give you a module. Yeah, it's somewhat confusing:-(.
921
921
922 # These routines return a properly built module and dict as needed by
922 # These routines return a properly built module and dict as needed by
923 # the rest of the code, and can also be used by extension writers to
923 # the rest of the code, and can also be used by extension writers to
924 # generate properly initialized namespaces.
924 # generate properly initialized namespaces.
925 if (user_ns is not None) or (user_module is not None):
925 if (user_ns is not None) or (user_module is not None):
926 self.default_user_namespaces = False
926 self.default_user_namespaces = False
927 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
927 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
928
928
929 # A record of hidden variables we have added to the user namespace, so
929 # A record of hidden variables we have added to the user namespace, so
930 # we can list later only variables defined in actual interactive use.
930 # we can list later only variables defined in actual interactive use.
931 self.user_ns_hidden = set()
931 self.user_ns_hidden = set()
932
932
933 # Now that FakeModule produces a real module, we've run into a nasty
933 # Now that FakeModule produces a real module, we've run into a nasty
934 # problem: after script execution (via %run), the module where the user
934 # problem: after script execution (via %run), the module where the user
935 # code ran is deleted. Now that this object is a true module (needed
935 # code ran is deleted. Now that this object is a true module (needed
936 # so docetst and other tools work correctly), the Python module
936 # so docetst and other tools work correctly), the Python module
937 # teardown mechanism runs over it, and sets to None every variable
937 # teardown mechanism runs over it, and sets to None every variable
938 # present in that module. Top-level references to objects from the
938 # present in that module. Top-level references to objects from the
939 # script survive, because the user_ns is updated with them. However,
939 # script survive, because the user_ns is updated with them. However,
940 # calling functions defined in the script that use other things from
940 # calling functions defined in the script that use other things from
941 # the script will fail, because the function's closure had references
941 # the script will fail, because the function's closure had references
942 # to the original objects, which are now all None. So we must protect
942 # to the original objects, which are now all None. So we must protect
943 # these modules from deletion by keeping a cache.
943 # these modules from deletion by keeping a cache.
944 #
944 #
945 # To avoid keeping stale modules around (we only need the one from the
945 # To avoid keeping stale modules around (we only need the one from the
946 # last run), we use a dict keyed with the full path to the script, so
946 # last run), we use a dict keyed with the full path to the script, so
947 # only the last version of the module is held in the cache. Note,
947 # only the last version of the module is held in the cache. Note,
948 # however, that we must cache the module *namespace contents* (their
948 # however, that we must cache the module *namespace contents* (their
949 # __dict__). Because if we try to cache the actual modules, old ones
949 # __dict__). Because if we try to cache the actual modules, old ones
950 # (uncached) could be destroyed while still holding references (such as
950 # (uncached) could be destroyed while still holding references (such as
951 # those held by GUI objects that tend to be long-lived)>
951 # those held by GUI objects that tend to be long-lived)>
952 #
952 #
953 # The %reset command will flush this cache. See the cache_main_mod()
953 # The %reset command will flush this cache. See the cache_main_mod()
954 # and clear_main_mod_cache() methods for details on use.
954 # and clear_main_mod_cache() methods for details on use.
955
955
956 # This is the cache used for 'main' namespaces
956 # This is the cache used for 'main' namespaces
957 self._main_ns_cache = {}
957 self._main_ns_cache = {}
958 # And this is the single instance of FakeModule whose __dict__ we keep
958 # And this is the single instance of FakeModule whose __dict__ we keep
959 # copying and clearing for reuse on each %run
959 # copying and clearing for reuse on each %run
960 self._user_main_module = FakeModule()
960 self._user_main_module = FakeModule()
961
961
962 # A table holding all the namespaces IPython deals with, so that
962 # A table holding all the namespaces IPython deals with, so that
963 # introspection facilities can search easily.
963 # introspection facilities can search easily.
964 self.ns_table = {'user_global':self.user_module.__dict__,
964 self.ns_table = {'user_global':self.user_module.__dict__,
965 'user_local':self.user_ns,
965 'user_local':self.user_ns,
966 'builtin':builtin_mod.__dict__
966 'builtin':builtin_mod.__dict__
967 }
967 }
968
968
969 @property
969 @property
970 def user_global_ns(self):
970 def user_global_ns(self):
971 return self.user_module.__dict__
971 return self.user_module.__dict__
972
972
973 def prepare_user_module(self, user_module=None, user_ns=None):
973 def prepare_user_module(self, user_module=None, user_ns=None):
974 """Prepare the module and namespace in which user code will be run.
974 """Prepare the module and namespace in which user code will be run.
975
975
976 When IPython is started normally, both parameters are None: a new module
976 When IPython is started normally, both parameters are None: a new module
977 is created automatically, and its __dict__ used as the namespace.
977 is created automatically, and its __dict__ used as the namespace.
978
978
979 If only user_module is provided, its __dict__ is used as the namespace.
979 If only user_module is provided, its __dict__ is used as the namespace.
980 If only user_ns is provided, a dummy module is created, and user_ns
980 If only user_ns is provided, a dummy module is created, and user_ns
981 becomes the global namespace. If both are provided (as they may be
981 becomes the global namespace. If both are provided (as they may be
982 when embedding), user_ns is the local namespace, and user_module
982 when embedding), user_ns is the local namespace, and user_module
983 provides the global namespace.
983 provides the global namespace.
984
984
985 Parameters
985 Parameters
986 ----------
986 ----------
987 user_module : module, optional
987 user_module : module, optional
988 The current user module in which IPython is being run. If None,
988 The current user module in which IPython is being run. If None,
989 a clean module will be created.
989 a clean module will be created.
990 user_ns : dict, optional
990 user_ns : dict, optional
991 A namespace in which to run interactive commands.
991 A namespace in which to run interactive commands.
992
992
993 Returns
993 Returns
994 -------
994 -------
995 A tuple of user_module and user_ns, each properly initialised.
995 A tuple of user_module and user_ns, each properly initialised.
996 """
996 """
997 if user_module is None and user_ns is not None:
997 if user_module is None and user_ns is not None:
998 user_ns.setdefault("__name__", "__main__")
998 user_ns.setdefault("__name__", "__main__")
999 class DummyMod(object):
999 class DummyMod(object):
1000 "A dummy module used for IPython's interactive namespace."
1000 "A dummy module used for IPython's interactive namespace."
1001 pass
1001 pass
1002 user_module = DummyMod()
1002 user_module = DummyMod()
1003 user_module.__dict__ = user_ns
1003 user_module.__dict__ = user_ns
1004
1004
1005 if user_module is None:
1005 if user_module is None:
1006 user_module = types.ModuleType("__main__",
1006 user_module = types.ModuleType("__main__",
1007 doc="Automatically created module for IPython interactive environment")
1007 doc="Automatically created module for IPython interactive environment")
1008
1008
1009 # We must ensure that __builtin__ (without the final 's') is always
1009 # We must ensure that __builtin__ (without the final 's') is always
1010 # available and pointing to the __builtin__ *module*. For more details:
1010 # available and pointing to the __builtin__ *module*. For more details:
1011 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1011 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1012 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1012 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1013 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1013 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1014
1014
1015 if user_ns is None:
1015 if user_ns is None:
1016 user_ns = user_module.__dict__
1016 user_ns = user_module.__dict__
1017
1017
1018 return user_module, user_ns
1018 return user_module, user_ns
1019
1019
1020 def init_sys_modules(self):
1020 def init_sys_modules(self):
1021 # We need to insert into sys.modules something that looks like a
1021 # We need to insert into sys.modules something that looks like a
1022 # module but which accesses the IPython namespace, for shelve and
1022 # module but which accesses the IPython namespace, for shelve and
1023 # pickle to work interactively. Normally they rely on getting
1023 # pickle to work interactively. Normally they rely on getting
1024 # everything out of __main__, but for embedding purposes each IPython
1024 # everything out of __main__, but for embedding purposes each IPython
1025 # instance has its own private namespace, so we can't go shoving
1025 # instance has its own private namespace, so we can't go shoving
1026 # everything into __main__.
1026 # everything into __main__.
1027
1027
1028 # note, however, that we should only do this for non-embedded
1028 # note, however, that we should only do this for non-embedded
1029 # ipythons, which really mimic the __main__.__dict__ with their own
1029 # ipythons, which really mimic the __main__.__dict__ with their own
1030 # namespace. Embedded instances, on the other hand, should not do
1030 # namespace. Embedded instances, on the other hand, should not do
1031 # this because they need to manage the user local/global namespaces
1031 # this because they need to manage the user local/global namespaces
1032 # only, but they live within a 'normal' __main__ (meaning, they
1032 # only, but they live within a 'normal' __main__ (meaning, they
1033 # shouldn't overtake the execution environment of the script they're
1033 # shouldn't overtake the execution environment of the script they're
1034 # embedded in).
1034 # embedded in).
1035
1035
1036 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1036 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1037 main_name = self.user_module.__name__
1037 main_name = self.user_module.__name__
1038 sys.modules[main_name] = self.user_module
1038 sys.modules[main_name] = self.user_module
1039
1039
1040 def init_user_ns(self):
1040 def init_user_ns(self):
1041 """Initialize all user-visible namespaces to their minimum defaults.
1041 """Initialize all user-visible namespaces to their minimum defaults.
1042
1042
1043 Certain history lists are also initialized here, as they effectively
1043 Certain history lists are also initialized here, as they effectively
1044 act as user namespaces.
1044 act as user namespaces.
1045
1045
1046 Notes
1046 Notes
1047 -----
1047 -----
1048 All data structures here are only filled in, they are NOT reset by this
1048 All data structures here are only filled in, they are NOT reset by this
1049 method. If they were not empty before, data will simply be added to
1049 method. If they were not empty before, data will simply be added to
1050 therm.
1050 therm.
1051 """
1051 """
1052 # This function works in two parts: first we put a few things in
1052 # This function works in two parts: first we put a few things in
1053 # user_ns, and we sync that contents into user_ns_hidden so that these
1053 # user_ns, and we sync that contents into user_ns_hidden so that these
1054 # initial variables aren't shown by %who. After the sync, we add the
1054 # initial variables aren't shown by %who. After the sync, we add the
1055 # rest of what we *do* want the user to see with %who even on a new
1055 # rest of what we *do* want the user to see with %who even on a new
1056 # session (probably nothing, so theye really only see their own stuff)
1056 # session (probably nothing, so theye really only see their own stuff)
1057
1057
1058 # The user dict must *always* have a __builtin__ reference to the
1058 # The user dict must *always* have a __builtin__ reference to the
1059 # Python standard __builtin__ namespace, which must be imported.
1059 # Python standard __builtin__ namespace, which must be imported.
1060 # This is so that certain operations in prompt evaluation can be
1060 # This is so that certain operations in prompt evaluation can be
1061 # reliably executed with builtins. Note that we can NOT use
1061 # reliably executed with builtins. Note that we can NOT use
1062 # __builtins__ (note the 's'), because that can either be a dict or a
1062 # __builtins__ (note the 's'), because that can either be a dict or a
1063 # module, and can even mutate at runtime, depending on the context
1063 # module, and can even mutate at runtime, depending on the context
1064 # (Python makes no guarantees on it). In contrast, __builtin__ is
1064 # (Python makes no guarantees on it). In contrast, __builtin__ is
1065 # always a module object, though it must be explicitly imported.
1065 # always a module object, though it must be explicitly imported.
1066
1066
1067 # For more details:
1067 # For more details:
1068 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1068 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1069 ns = dict()
1069 ns = dict()
1070
1070
1071 # Put 'help' in the user namespace
1071 # Put 'help' in the user namespace
1072 try:
1072 try:
1073 from site import _Helper
1073 from site import _Helper
1074 ns['help'] = _Helper()
1074 ns['help'] = _Helper()
1075 except ImportError:
1075 except ImportError:
1076 warn('help() not available - check site.py')
1076 warn('help() not available - check site.py')
1077
1077
1078 # make global variables for user access to the histories
1078 # make global variables for user access to the histories
1079 ns['_ih'] = self.history_manager.input_hist_parsed
1079 ns['_ih'] = self.history_manager.input_hist_parsed
1080 ns['_oh'] = self.history_manager.output_hist
1080 ns['_oh'] = self.history_manager.output_hist
1081 ns['_dh'] = self.history_manager.dir_hist
1081 ns['_dh'] = self.history_manager.dir_hist
1082
1082
1083 ns['_sh'] = shadowns
1083 ns['_sh'] = shadowns
1084
1084
1085 # user aliases to input and output histories. These shouldn't show up
1085 # user aliases to input and output histories. These shouldn't show up
1086 # in %who, as they can have very large reprs.
1086 # in %who, as they can have very large reprs.
1087 ns['In'] = self.history_manager.input_hist_parsed
1087 ns['In'] = self.history_manager.input_hist_parsed
1088 ns['Out'] = self.history_manager.output_hist
1088 ns['Out'] = self.history_manager.output_hist
1089
1089
1090 # Store myself as the public api!!!
1090 # Store myself as the public api!!!
1091 ns['get_ipython'] = self.get_ipython
1091 ns['get_ipython'] = self.get_ipython
1092
1092
1093 ns['exit'] = self.exiter
1093 ns['exit'] = self.exiter
1094 ns['quit'] = self.exiter
1094 ns['quit'] = self.exiter
1095
1095
1096 # Sync what we've added so far to user_ns_hidden so these aren't seen
1096 # Sync what we've added so far to user_ns_hidden so these aren't seen
1097 # by %who
1097 # by %who
1098 self.user_ns_hidden.update(ns)
1098 self.user_ns_hidden.update(ns)
1099
1099
1100 # Anything put into ns now would show up in %who. Think twice before
1100 # Anything put into ns now would show up in %who. Think twice before
1101 # putting anything here, as we really want %who to show the user their
1101 # putting anything here, as we really want %who to show the user their
1102 # stuff, not our variables.
1102 # stuff, not our variables.
1103
1103
1104 # Finally, update the real user's namespace
1104 # Finally, update the real user's namespace
1105 self.user_ns.update(ns)
1105 self.user_ns.update(ns)
1106
1106
1107 @property
1107 @property
1108 def all_ns_refs(self):
1108 def all_ns_refs(self):
1109 """Get a list of references to all the namespace dictionaries in which
1109 """Get a list of references to all the namespace dictionaries in which
1110 IPython might store a user-created object.
1110 IPython might store a user-created object.
1111
1111
1112 Note that this does not include the displayhook, which also caches
1112 Note that this does not include the displayhook, which also caches
1113 objects from the output."""
1113 objects from the output."""
1114 return [self.user_ns, self.user_global_ns,
1114 return [self.user_ns, self.user_global_ns,
1115 self._user_main_module.__dict__] + self._main_ns_cache.values()
1115 self._user_main_module.__dict__] + self._main_ns_cache.values()
1116
1116
1117 def reset(self, new_session=True):
1117 def reset(self, new_session=True):
1118 """Clear all internal namespaces, and attempt to release references to
1118 """Clear all internal namespaces, and attempt to release references to
1119 user objects.
1119 user objects.
1120
1120
1121 If new_session is True, a new history session will be opened.
1121 If new_session is True, a new history session will be opened.
1122 """
1122 """
1123 # Clear histories
1123 # Clear histories
1124 self.history_manager.reset(new_session)
1124 self.history_manager.reset(new_session)
1125 # Reset counter used to index all histories
1125 # Reset counter used to index all histories
1126 if new_session:
1126 if new_session:
1127 self.execution_count = 1
1127 self.execution_count = 1
1128
1128
1129 # Flush cached output items
1129 # Flush cached output items
1130 if self.displayhook.do_full_cache:
1130 if self.displayhook.do_full_cache:
1131 self.displayhook.flush()
1131 self.displayhook.flush()
1132
1132
1133 # The main execution namespaces must be cleared very carefully,
1133 # The main execution namespaces must be cleared very carefully,
1134 # skipping the deletion of the builtin-related keys, because doing so
1134 # skipping the deletion of the builtin-related keys, because doing so
1135 # would cause errors in many object's __del__ methods.
1135 # would cause errors in many object's __del__ methods.
1136 if self.user_ns is not self.user_global_ns:
1136 if self.user_ns is not self.user_global_ns:
1137 self.user_ns.clear()
1137 self.user_ns.clear()
1138 ns = self.user_global_ns
1138 ns = self.user_global_ns
1139 drop_keys = set(ns.keys())
1139 drop_keys = set(ns.keys())
1140 drop_keys.discard('__builtin__')
1140 drop_keys.discard('__builtin__')
1141 drop_keys.discard('__builtins__')
1141 drop_keys.discard('__builtins__')
1142 drop_keys.discard('__name__')
1142 drop_keys.discard('__name__')
1143 for k in drop_keys:
1143 for k in drop_keys:
1144 del ns[k]
1144 del ns[k]
1145
1145
1146 self.user_ns_hidden.clear()
1146 self.user_ns_hidden.clear()
1147
1147
1148 # Restore the user namespaces to minimal usability
1148 # Restore the user namespaces to minimal usability
1149 self.init_user_ns()
1149 self.init_user_ns()
1150
1150
1151 # Restore the default and user aliases
1151 # Restore the default and user aliases
1152 self.alias_manager.clear_aliases()
1152 self.alias_manager.clear_aliases()
1153 self.alias_manager.init_aliases()
1153 self.alias_manager.init_aliases()
1154
1154
1155 # Flush the private list of module references kept for script
1155 # Flush the private list of module references kept for script
1156 # execution protection
1156 # execution protection
1157 self.clear_main_mod_cache()
1157 self.clear_main_mod_cache()
1158
1158
1159 # Clear out the namespace from the last %run
1159 # Clear out the namespace from the last %run
1160 self.new_main_mod()
1160 self.new_main_mod()
1161
1161
1162 def del_var(self, varname, by_name=False):
1162 def del_var(self, varname, by_name=False):
1163 """Delete a variable from the various namespaces, so that, as
1163 """Delete a variable from the various namespaces, so that, as
1164 far as possible, we're not keeping any hidden references to it.
1164 far as possible, we're not keeping any hidden references to it.
1165
1165
1166 Parameters
1166 Parameters
1167 ----------
1167 ----------
1168 varname : str
1168 varname : str
1169 The name of the variable to delete.
1169 The name of the variable to delete.
1170 by_name : bool
1170 by_name : bool
1171 If True, delete variables with the given name in each
1171 If True, delete variables with the given name in each
1172 namespace. If False (default), find the variable in the user
1172 namespace. If False (default), find the variable in the user
1173 namespace, and delete references to it.
1173 namespace, and delete references to it.
1174 """
1174 """
1175 if varname in ('__builtin__', '__builtins__'):
1175 if varname in ('__builtin__', '__builtins__'):
1176 raise ValueError("Refusing to delete %s" % varname)
1176 raise ValueError("Refusing to delete %s" % varname)
1177
1177
1178 ns_refs = self.all_ns_refs
1178 ns_refs = self.all_ns_refs
1179
1179
1180 if by_name: # Delete by name
1180 if by_name: # Delete by name
1181 for ns in ns_refs:
1181 for ns in ns_refs:
1182 try:
1182 try:
1183 del ns[varname]
1183 del ns[varname]
1184 except KeyError:
1184 except KeyError:
1185 pass
1185 pass
1186 else: # Delete by object
1186 else: # Delete by object
1187 try:
1187 try:
1188 obj = self.user_ns[varname]
1188 obj = self.user_ns[varname]
1189 except KeyError:
1189 except KeyError:
1190 raise NameError("name '%s' is not defined" % varname)
1190 raise NameError("name '%s' is not defined" % varname)
1191 # Also check in output history
1191 # Also check in output history
1192 ns_refs.append(self.history_manager.output_hist)
1192 ns_refs.append(self.history_manager.output_hist)
1193 for ns in ns_refs:
1193 for ns in ns_refs:
1194 to_delete = [n for n, o in ns.iteritems() if o is obj]
1194 to_delete = [n for n, o in ns.iteritems() if o is obj]
1195 for name in to_delete:
1195 for name in to_delete:
1196 del ns[name]
1196 del ns[name]
1197
1197
1198 # displayhook keeps extra references, but not in a dictionary
1198 # displayhook keeps extra references, but not in a dictionary
1199 for name in ('_', '__', '___'):
1199 for name in ('_', '__', '___'):
1200 if getattr(self.displayhook, name) is obj:
1200 if getattr(self.displayhook, name) is obj:
1201 setattr(self.displayhook, name, None)
1201 setattr(self.displayhook, name, None)
1202
1202
1203 def reset_selective(self, regex=None):
1203 def reset_selective(self, regex=None):
1204 """Clear selective variables from internal namespaces based on a
1204 """Clear selective variables from internal namespaces based on a
1205 specified regular expression.
1205 specified regular expression.
1206
1206
1207 Parameters
1207 Parameters
1208 ----------
1208 ----------
1209 regex : string or compiled pattern, optional
1209 regex : string or compiled pattern, optional
1210 A regular expression pattern that will be used in searching
1210 A regular expression pattern that will be used in searching
1211 variable names in the users namespaces.
1211 variable names in the users namespaces.
1212 """
1212 """
1213 if regex is not None:
1213 if regex is not None:
1214 try:
1214 try:
1215 m = re.compile(regex)
1215 m = re.compile(regex)
1216 except TypeError:
1216 except TypeError:
1217 raise TypeError('regex must be a string or compiled pattern')
1217 raise TypeError('regex must be a string or compiled pattern')
1218 # Search for keys in each namespace that match the given regex
1218 # Search for keys in each namespace that match the given regex
1219 # If a match is found, delete the key/value pair.
1219 # If a match is found, delete the key/value pair.
1220 for ns in self.all_ns_refs:
1220 for ns in self.all_ns_refs:
1221 for var in ns:
1221 for var in ns:
1222 if m.search(var):
1222 if m.search(var):
1223 del ns[var]
1223 del ns[var]
1224
1224
1225 def push(self, variables, interactive=True):
1225 def push(self, variables, interactive=True):
1226 """Inject a group of variables into the IPython user namespace.
1226 """Inject a group of variables into the IPython user namespace.
1227
1227
1228 Parameters
1228 Parameters
1229 ----------
1229 ----------
1230 variables : dict, str or list/tuple of str
1230 variables : dict, str or list/tuple of str
1231 The variables to inject into the user's namespace. If a dict, a
1231 The variables to inject into the user's namespace. If a dict, a
1232 simple update is done. If a str, the string is assumed to have
1232 simple update is done. If a str, the string is assumed to have
1233 variable names separated by spaces. A list/tuple of str can also
1233 variable names separated by spaces. A list/tuple of str can also
1234 be used to give the variable names. If just the variable names are
1234 be used to give the variable names. If just the variable names are
1235 give (list/tuple/str) then the variable values looked up in the
1235 give (list/tuple/str) then the variable values looked up in the
1236 callers frame.
1236 callers frame.
1237 interactive : bool
1237 interactive : bool
1238 If True (default), the variables will be listed with the ``who``
1238 If True (default), the variables will be listed with the ``who``
1239 magic.
1239 magic.
1240 """
1240 """
1241 vdict = None
1241 vdict = None
1242
1242
1243 # We need a dict of name/value pairs to do namespace updates.
1243 # We need a dict of name/value pairs to do namespace updates.
1244 if isinstance(variables, dict):
1244 if isinstance(variables, dict):
1245 vdict = variables
1245 vdict = variables
1246 elif isinstance(variables, (basestring, list, tuple)):
1246 elif isinstance(variables, (basestring, list, tuple)):
1247 if isinstance(variables, basestring):
1247 if isinstance(variables, basestring):
1248 vlist = variables.split()
1248 vlist = variables.split()
1249 else:
1249 else:
1250 vlist = variables
1250 vlist = variables
1251 vdict = {}
1251 vdict = {}
1252 cf = sys._getframe(1)
1252 cf = sys._getframe(1)
1253 for name in vlist:
1253 for name in vlist:
1254 try:
1254 try:
1255 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1255 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1256 except:
1256 except:
1257 print ('Could not get variable %s from %s' %
1257 print ('Could not get variable %s from %s' %
1258 (name,cf.f_code.co_name))
1258 (name,cf.f_code.co_name))
1259 else:
1259 else:
1260 raise ValueError('variables must be a dict/str/list/tuple')
1260 raise ValueError('variables must be a dict/str/list/tuple')
1261
1261
1262 # Propagate variables to user namespace
1262 # Propagate variables to user namespace
1263 self.user_ns.update(vdict)
1263 self.user_ns.update(vdict)
1264
1264
1265 # And configure interactive visibility
1265 # And configure interactive visibility
1266 user_ns_hidden = self.user_ns_hidden
1266 user_ns_hidden = self.user_ns_hidden
1267 if interactive:
1267 if interactive:
1268 user_ns_hidden.difference_update(vdict)
1268 user_ns_hidden.difference_update(vdict)
1269 else:
1269 else:
1270 user_ns_hidden.update(vdict)
1270 user_ns_hidden.update(vdict)
1271
1271
1272 def drop_by_id(self, variables):
1272 def drop_by_id(self, variables):
1273 """Remove a dict of variables from the user namespace, if they are the
1273 """Remove a dict of variables from the user namespace, if they are the
1274 same as the values in the dictionary.
1274 same as the values in the dictionary.
1275
1275
1276 This is intended for use by extensions: variables that they've added can
1276 This is intended for use by extensions: variables that they've added can
1277 be taken back out if they are unloaded, without removing any that the
1277 be taken back out if they are unloaded, without removing any that the
1278 user has overwritten.
1278 user has overwritten.
1279
1279
1280 Parameters
1280 Parameters
1281 ----------
1281 ----------
1282 variables : dict
1282 variables : dict
1283 A dictionary mapping object names (as strings) to the objects.
1283 A dictionary mapping object names (as strings) to the objects.
1284 """
1284 """
1285 for name, obj in variables.iteritems():
1285 for name, obj in variables.iteritems():
1286 if name in self.user_ns and self.user_ns[name] is obj:
1286 if name in self.user_ns and self.user_ns[name] is obj:
1287 del self.user_ns[name]
1287 del self.user_ns[name]
1288 self.user_ns_hidden.discard(name)
1288 self.user_ns_hidden.discard(name)
1289
1289
1290 #-------------------------------------------------------------------------
1290 #-------------------------------------------------------------------------
1291 # Things related to object introspection
1291 # Things related to object introspection
1292 #-------------------------------------------------------------------------
1292 #-------------------------------------------------------------------------
1293
1293
1294 def _ofind(self, oname, namespaces=None):
1294 def _ofind(self, oname, namespaces=None):
1295 """Find an object in the available namespaces.
1295 """Find an object in the available namespaces.
1296
1296
1297 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1297 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1298
1298
1299 Has special code to detect magic functions.
1299 Has special code to detect magic functions.
1300 """
1300 """
1301 oname = oname.strip()
1301 oname = oname.strip()
1302 #print '1- oname: <%r>' % oname # dbg
1302 #print '1- oname: <%r>' % oname # dbg
1303 if not py3compat.isidentifier(oname.lstrip(ESC_MAGIC), dotted=True):
1303 if not py3compat.isidentifier(oname.lstrip(ESC_MAGIC), dotted=True):
1304 return dict(found=False)
1304 return dict(found=False)
1305
1305
1306 alias_ns = None
1306 alias_ns = None
1307 if namespaces is None:
1307 if namespaces is None:
1308 # Namespaces to search in:
1308 # Namespaces to search in:
1309 # Put them in a list. The order is important so that we
1309 # Put them in a list. The order is important so that we
1310 # find things in the same order that Python finds them.
1310 # find things in the same order that Python finds them.
1311 namespaces = [ ('Interactive', self.user_ns),
1311 namespaces = [ ('Interactive', self.user_ns),
1312 ('Interactive (global)', self.user_global_ns),
1312 ('Interactive (global)', self.user_global_ns),
1313 ('Python builtin', builtin_mod.__dict__),
1313 ('Python builtin', builtin_mod.__dict__),
1314 ('Alias', self.alias_manager.alias_table),
1314 ('Alias', self.alias_manager.alias_table),
1315 ]
1315 ]
1316 alias_ns = self.alias_manager.alias_table
1316 alias_ns = self.alias_manager.alias_table
1317
1317
1318 # initialize results to 'null'
1318 # initialize results to 'null'
1319 found = False; obj = None; ospace = None; ds = None;
1319 found = False; obj = None; ospace = None; ds = None;
1320 ismagic = False; isalias = False; parent = None
1320 ismagic = False; isalias = False; parent = None
1321
1321
1322 # We need to special-case 'print', which as of python2.6 registers as a
1322 # We need to special-case 'print', which as of python2.6 registers as a
1323 # function but should only be treated as one if print_function was
1323 # function but should only be treated as one if print_function was
1324 # loaded with a future import. In this case, just bail.
1324 # loaded with a future import. In this case, just bail.
1325 if (oname == 'print' and not py3compat.PY3 and not \
1325 if (oname == 'print' and not py3compat.PY3 and not \
1326 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1326 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1327 return {'found':found, 'obj':obj, 'namespace':ospace,
1327 return {'found':found, 'obj':obj, 'namespace':ospace,
1328 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1328 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1329
1329
1330 # Look for the given name by splitting it in parts. If the head is
1330 # Look for the given name by splitting it in parts. If the head is
1331 # found, then we look for all the remaining parts as members, and only
1331 # found, then we look for all the remaining parts as members, and only
1332 # declare success if we can find them all.
1332 # declare success if we can find them all.
1333 oname_parts = oname.split('.')
1333 oname_parts = oname.split('.')
1334 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1334 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1335 for nsname,ns in namespaces:
1335 for nsname,ns in namespaces:
1336 try:
1336 try:
1337 obj = ns[oname_head]
1337 obj = ns[oname_head]
1338 except KeyError:
1338 except KeyError:
1339 continue
1339 continue
1340 else:
1340 else:
1341 #print 'oname_rest:', oname_rest # dbg
1341 #print 'oname_rest:', oname_rest # dbg
1342 for part in oname_rest:
1342 for part in oname_rest:
1343 try:
1343 try:
1344 parent = obj
1344 parent = obj
1345 obj = getattr(obj,part)
1345 obj = getattr(obj,part)
1346 except:
1346 except:
1347 # Blanket except b/c some badly implemented objects
1347 # Blanket except b/c some badly implemented objects
1348 # allow __getattr__ to raise exceptions other than
1348 # allow __getattr__ to raise exceptions other than
1349 # AttributeError, which then crashes IPython.
1349 # AttributeError, which then crashes IPython.
1350 break
1350 break
1351 else:
1351 else:
1352 # If we finish the for loop (no break), we got all members
1352 # If we finish the for loop (no break), we got all members
1353 found = True
1353 found = True
1354 ospace = nsname
1354 ospace = nsname
1355 if ns == alias_ns:
1355 if ns == alias_ns:
1356 isalias = True
1356 isalias = True
1357 break # namespace loop
1357 break # namespace loop
1358
1358
1359 # Try to see if it's magic
1359 # Try to see if it's magic
1360 if not found:
1360 if not found:
1361 if oname.startswith(ESC_MAGIC):
1361 if oname.startswith(ESC_MAGIC):
1362 oname = oname[1:]
1362 oname = oname[1:]
1363 obj = getattr(self,'magic_'+oname,None)
1363 obj = getattr(self,'magic_'+oname,None)
1364 if obj is not None:
1364 if obj is not None:
1365 found = True
1365 found = True
1366 ospace = 'IPython internal'
1366 ospace = 'IPython internal'
1367 ismagic = True
1367 ismagic = True
1368
1368
1369 # Last try: special-case some literals like '', [], {}, etc:
1369 # Last try: special-case some literals like '', [], {}, etc:
1370 if not found and oname_head in ["''",'""','[]','{}','()']:
1370 if not found and oname_head in ["''",'""','[]','{}','()']:
1371 obj = eval(oname_head)
1371 obj = eval(oname_head)
1372 found = True
1372 found = True
1373 ospace = 'Interactive'
1373 ospace = 'Interactive'
1374
1374
1375 return {'found':found, 'obj':obj, 'namespace':ospace,
1375 return {'found':found, 'obj':obj, 'namespace':ospace,
1376 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1376 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1377
1377
1378 def _ofind_property(self, oname, info):
1378 def _ofind_property(self, oname, info):
1379 """Second part of object finding, to look for property details."""
1379 """Second part of object finding, to look for property details."""
1380 if info.found:
1380 if info.found:
1381 # Get the docstring of the class property if it exists.
1381 # Get the docstring of the class property if it exists.
1382 path = oname.split('.')
1382 path = oname.split('.')
1383 root = '.'.join(path[:-1])
1383 root = '.'.join(path[:-1])
1384 if info.parent is not None:
1384 if info.parent is not None:
1385 try:
1385 try:
1386 target = getattr(info.parent, '__class__')
1386 target = getattr(info.parent, '__class__')
1387 # The object belongs to a class instance.
1387 # The object belongs to a class instance.
1388 try:
1388 try:
1389 target = getattr(target, path[-1])
1389 target = getattr(target, path[-1])
1390 # The class defines the object.
1390 # The class defines the object.
1391 if isinstance(target, property):
1391 if isinstance(target, property):
1392 oname = root + '.__class__.' + path[-1]
1392 oname = root + '.__class__.' + path[-1]
1393 info = Struct(self._ofind(oname))
1393 info = Struct(self._ofind(oname))
1394 except AttributeError: pass
1394 except AttributeError: pass
1395 except AttributeError: pass
1395 except AttributeError: pass
1396
1396
1397 # We return either the new info or the unmodified input if the object
1397 # We return either the new info or the unmodified input if the object
1398 # hadn't been found
1398 # hadn't been found
1399 return info
1399 return info
1400
1400
1401 def _object_find(self, oname, namespaces=None):
1401 def _object_find(self, oname, namespaces=None):
1402 """Find an object and return a struct with info about it."""
1402 """Find an object and return a struct with info about it."""
1403 inf = Struct(self._ofind(oname, namespaces))
1403 inf = Struct(self._ofind(oname, namespaces))
1404 return Struct(self._ofind_property(oname, inf))
1404 return Struct(self._ofind_property(oname, inf))
1405
1405
1406 def _inspect(self, meth, oname, namespaces=None, **kw):
1406 def _inspect(self, meth, oname, namespaces=None, **kw):
1407 """Generic interface to the inspector system.
1407 """Generic interface to the inspector system.
1408
1408
1409 This function is meant to be called by pdef, pdoc & friends."""
1409 This function is meant to be called by pdef, pdoc & friends."""
1410 info = self._object_find(oname)
1410 info = self._object_find(oname)
1411 if info.found:
1411 if info.found:
1412 pmethod = getattr(self.inspector, meth)
1412 pmethod = getattr(self.inspector, meth)
1413 formatter = format_screen if info.ismagic else None
1413 formatter = format_screen if info.ismagic else None
1414 if meth == 'pdoc':
1414 if meth == 'pdoc':
1415 pmethod(info.obj, oname, formatter)
1415 pmethod(info.obj, oname, formatter)
1416 elif meth == 'pinfo':
1416 elif meth == 'pinfo':
1417 pmethod(info.obj, oname, formatter, info, **kw)
1417 pmethod(info.obj, oname, formatter, info, **kw)
1418 else:
1418 else:
1419 pmethod(info.obj, oname)
1419 pmethod(info.obj, oname)
1420 else:
1420 else:
1421 print 'Object `%s` not found.' % oname
1421 print 'Object `%s` not found.' % oname
1422 return 'not found' # so callers can take other action
1422 return 'not found' # so callers can take other action
1423
1423
1424 def object_inspect(self, oname):
1424 def object_inspect(self, oname):
1425 with self.builtin_trap:
1425 with self.builtin_trap:
1426 info = self._object_find(oname)
1426 info = self._object_find(oname)
1427 if info.found:
1427 if info.found:
1428 return self.inspector.info(info.obj, oname, info=info)
1428 return self.inspector.info(info.obj, oname, info=info)
1429 else:
1429 else:
1430 return oinspect.object_info(name=oname, found=False)
1430 return oinspect.object_info(name=oname, found=False)
1431
1431
1432 #-------------------------------------------------------------------------
1432 #-------------------------------------------------------------------------
1433 # Things related to history management
1433 # Things related to history management
1434 #-------------------------------------------------------------------------
1434 #-------------------------------------------------------------------------
1435
1435
1436 def init_history(self):
1436 def init_history(self):
1437 """Sets up the command history, and starts regular autosaves."""
1437 """Sets up the command history, and starts regular autosaves."""
1438 self.history_manager = HistoryManager(shell=self, config=self.config)
1438 self.history_manager = HistoryManager(shell=self, config=self.config)
1439 self.configurables.append(self.history_manager)
1439 self.configurables.append(self.history_manager)
1440
1440
1441 #-------------------------------------------------------------------------
1441 #-------------------------------------------------------------------------
1442 # Things related to exception handling and tracebacks (not debugging)
1442 # Things related to exception handling and tracebacks (not debugging)
1443 #-------------------------------------------------------------------------
1443 #-------------------------------------------------------------------------
1444
1444
1445 def init_traceback_handlers(self, custom_exceptions):
1445 def init_traceback_handlers(self, custom_exceptions):
1446 # Syntax error handler.
1446 # Syntax error handler.
1447 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1447 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1448
1448
1449 # The interactive one is initialized with an offset, meaning we always
1449 # The interactive one is initialized with an offset, meaning we always
1450 # want to remove the topmost item in the traceback, which is our own
1450 # want to remove the topmost item in the traceback, which is our own
1451 # internal code. Valid modes: ['Plain','Context','Verbose']
1451 # internal code. Valid modes: ['Plain','Context','Verbose']
1452 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1452 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1453 color_scheme='NoColor',
1453 color_scheme='NoColor',
1454 tb_offset = 1,
1454 tb_offset = 1,
1455 check_cache=self.compile.check_cache)
1455 check_cache=self.compile.check_cache)
1456
1456
1457 # The instance will store a pointer to the system-wide exception hook,
1457 # The instance will store a pointer to the system-wide exception hook,
1458 # so that runtime code (such as magics) can access it. This is because
1458 # so that runtime code (such as magics) can access it. This is because
1459 # during the read-eval loop, it may get temporarily overwritten.
1459 # during the read-eval loop, it may get temporarily overwritten.
1460 self.sys_excepthook = sys.excepthook
1460 self.sys_excepthook = sys.excepthook
1461
1461
1462 # and add any custom exception handlers the user may have specified
1462 # and add any custom exception handlers the user may have specified
1463 self.set_custom_exc(*custom_exceptions)
1463 self.set_custom_exc(*custom_exceptions)
1464
1464
1465 # Set the exception mode
1465 # Set the exception mode
1466 self.InteractiveTB.set_mode(mode=self.xmode)
1466 self.InteractiveTB.set_mode(mode=self.xmode)
1467
1467
1468 def set_custom_exc(self, exc_tuple, handler):
1468 def set_custom_exc(self, exc_tuple, handler):
1469 """set_custom_exc(exc_tuple,handler)
1469 """set_custom_exc(exc_tuple,handler)
1470
1470
1471 Set a custom exception handler, which will be called if any of the
1471 Set a custom exception handler, which will be called if any of the
1472 exceptions in exc_tuple occur in the mainloop (specifically, in the
1472 exceptions in exc_tuple occur in the mainloop (specifically, in the
1473 run_code() method).
1473 run_code() method).
1474
1474
1475 Parameters
1475 Parameters
1476 ----------
1476 ----------
1477
1477
1478 exc_tuple : tuple of exception classes
1478 exc_tuple : tuple of exception classes
1479 A *tuple* of exception classes, for which to call the defined
1479 A *tuple* of exception classes, for which to call the defined
1480 handler. It is very important that you use a tuple, and NOT A
1480 handler. It is very important that you use a tuple, and NOT A
1481 LIST here, because of the way Python's except statement works. If
1481 LIST here, because of the way Python's except statement works. If
1482 you only want to trap a single exception, use a singleton tuple::
1482 you only want to trap a single exception, use a singleton tuple::
1483
1483
1484 exc_tuple == (MyCustomException,)
1484 exc_tuple == (MyCustomException,)
1485
1485
1486 handler : callable
1486 handler : callable
1487 handler must have the following signature::
1487 handler must have the following signature::
1488
1488
1489 def my_handler(self, etype, value, tb, tb_offset=None):
1489 def my_handler(self, etype, value, tb, tb_offset=None):
1490 ...
1490 ...
1491 return structured_traceback
1491 return structured_traceback
1492
1492
1493 Your handler must return a structured traceback (a list of strings),
1493 Your handler must return a structured traceback (a list of strings),
1494 or None.
1494 or None.
1495
1495
1496 This will be made into an instance method (via types.MethodType)
1496 This will be made into an instance method (via types.MethodType)
1497 of IPython itself, and it will be called if any of the exceptions
1497 of IPython itself, and it will be called if any of the exceptions
1498 listed in the exc_tuple are caught. If the handler is None, an
1498 listed in the exc_tuple are caught. If the handler is None, an
1499 internal basic one is used, which just prints basic info.
1499 internal basic one is used, which just prints basic info.
1500
1500
1501 To protect IPython from crashes, if your handler ever raises an
1501 To protect IPython from crashes, if your handler ever raises an
1502 exception or returns an invalid result, it will be immediately
1502 exception or returns an invalid result, it will be immediately
1503 disabled.
1503 disabled.
1504
1504
1505 WARNING: by putting in your own exception handler into IPython's main
1505 WARNING: by putting in your own exception handler into IPython's main
1506 execution loop, you run a very good chance of nasty crashes. This
1506 execution loop, you run a very good chance of nasty crashes. This
1507 facility should only be used if you really know what you are doing."""
1507 facility should only be used if you really know what you are doing."""
1508
1508
1509 assert type(exc_tuple)==type(()) , \
1509 assert type(exc_tuple)==type(()) , \
1510 "The custom exceptions must be given AS A TUPLE."
1510 "The custom exceptions must be given AS A TUPLE."
1511
1511
1512 def dummy_handler(self,etype,value,tb,tb_offset=None):
1512 def dummy_handler(self,etype,value,tb,tb_offset=None):
1513 print '*** Simple custom exception handler ***'
1513 print '*** Simple custom exception handler ***'
1514 print 'Exception type :',etype
1514 print 'Exception type :',etype
1515 print 'Exception value:',value
1515 print 'Exception value:',value
1516 print 'Traceback :',tb
1516 print 'Traceback :',tb
1517 #print 'Source code :','\n'.join(self.buffer)
1517 #print 'Source code :','\n'.join(self.buffer)
1518
1518
1519 def validate_stb(stb):
1519 def validate_stb(stb):
1520 """validate structured traceback return type
1520 """validate structured traceback return type
1521
1521
1522 return type of CustomTB *should* be a list of strings, but allow
1522 return type of CustomTB *should* be a list of strings, but allow
1523 single strings or None, which are harmless.
1523 single strings or None, which are harmless.
1524
1524
1525 This function will *always* return a list of strings,
1525 This function will *always* return a list of strings,
1526 and will raise a TypeError if stb is inappropriate.
1526 and will raise a TypeError if stb is inappropriate.
1527 """
1527 """
1528 msg = "CustomTB must return list of strings, not %r" % stb
1528 msg = "CustomTB must return list of strings, not %r" % stb
1529 if stb is None:
1529 if stb is None:
1530 return []
1530 return []
1531 elif isinstance(stb, basestring):
1531 elif isinstance(stb, basestring):
1532 return [stb]
1532 return [stb]
1533 elif not isinstance(stb, list):
1533 elif not isinstance(stb, list):
1534 raise TypeError(msg)
1534 raise TypeError(msg)
1535 # it's a list
1535 # it's a list
1536 for line in stb:
1536 for line in stb:
1537 # check every element
1537 # check every element
1538 if not isinstance(line, basestring):
1538 if not isinstance(line, basestring):
1539 raise TypeError(msg)
1539 raise TypeError(msg)
1540 return stb
1540 return stb
1541
1541
1542 if handler is None:
1542 if handler is None:
1543 wrapped = dummy_handler
1543 wrapped = dummy_handler
1544 else:
1544 else:
1545 def wrapped(self,etype,value,tb,tb_offset=None):
1545 def wrapped(self,etype,value,tb,tb_offset=None):
1546 """wrap CustomTB handler, to protect IPython from user code
1546 """wrap CustomTB handler, to protect IPython from user code
1547
1547
1548 This makes it harder (but not impossible) for custom exception
1548 This makes it harder (but not impossible) for custom exception
1549 handlers to crash IPython.
1549 handlers to crash IPython.
1550 """
1550 """
1551 try:
1551 try:
1552 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1552 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1553 return validate_stb(stb)
1553 return validate_stb(stb)
1554 except:
1554 except:
1555 # clear custom handler immediately
1555 # clear custom handler immediately
1556 self.set_custom_exc((), None)
1556 self.set_custom_exc((), None)
1557 print >> io.stderr, "Custom TB Handler failed, unregistering"
1557 print >> io.stderr, "Custom TB Handler failed, unregistering"
1558 # show the exception in handler first
1558 # show the exception in handler first
1559 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1559 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1560 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1560 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1561 print >> io.stdout, "The original exception:"
1561 print >> io.stdout, "The original exception:"
1562 stb = self.InteractiveTB.structured_traceback(
1562 stb = self.InteractiveTB.structured_traceback(
1563 (etype,value,tb), tb_offset=tb_offset
1563 (etype,value,tb), tb_offset=tb_offset
1564 )
1564 )
1565 return stb
1565 return stb
1566
1566
1567 self.CustomTB = types.MethodType(wrapped,self)
1567 self.CustomTB = types.MethodType(wrapped,self)
1568 self.custom_exceptions = exc_tuple
1568 self.custom_exceptions = exc_tuple
1569
1569
1570 def excepthook(self, etype, value, tb):
1570 def excepthook(self, etype, value, tb):
1571 """One more defense for GUI apps that call sys.excepthook.
1571 """One more defense for GUI apps that call sys.excepthook.
1572
1572
1573 GUI frameworks like wxPython trap exceptions and call
1573 GUI frameworks like wxPython trap exceptions and call
1574 sys.excepthook themselves. I guess this is a feature that
1574 sys.excepthook themselves. I guess this is a feature that
1575 enables them to keep running after exceptions that would
1575 enables them to keep running after exceptions that would
1576 otherwise kill their mainloop. This is a bother for IPython
1576 otherwise kill their mainloop. This is a bother for IPython
1577 which excepts to catch all of the program exceptions with a try:
1577 which excepts to catch all of the program exceptions with a try:
1578 except: statement.
1578 except: statement.
1579
1579
1580 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1580 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1581 any app directly invokes sys.excepthook, it will look to the user like
1581 any app directly invokes sys.excepthook, it will look to the user like
1582 IPython crashed. In order to work around this, we can disable the
1582 IPython crashed. In order to work around this, we can disable the
1583 CrashHandler and replace it with this excepthook instead, which prints a
1583 CrashHandler and replace it with this excepthook instead, which prints a
1584 regular traceback using our InteractiveTB. In this fashion, apps which
1584 regular traceback using our InteractiveTB. In this fashion, apps which
1585 call sys.excepthook will generate a regular-looking exception from
1585 call sys.excepthook will generate a regular-looking exception from
1586 IPython, and the CrashHandler will only be triggered by real IPython
1586 IPython, and the CrashHandler will only be triggered by real IPython
1587 crashes.
1587 crashes.
1588
1588
1589 This hook should be used sparingly, only in places which are not likely
1589 This hook should be used sparingly, only in places which are not likely
1590 to be true IPython errors.
1590 to be true IPython errors.
1591 """
1591 """
1592 self.showtraceback((etype,value,tb),tb_offset=0)
1592 self.showtraceback((etype,value,tb),tb_offset=0)
1593
1593
1594 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1594 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1595 exception_only=False):
1595 exception_only=False):
1596 """Display the exception that just occurred.
1596 """Display the exception that just occurred.
1597
1597
1598 If nothing is known about the exception, this is the method which
1598 If nothing is known about the exception, this is the method which
1599 should be used throughout the code for presenting user tracebacks,
1599 should be used throughout the code for presenting user tracebacks,
1600 rather than directly invoking the InteractiveTB object.
1600 rather than directly invoking the InteractiveTB object.
1601
1601
1602 A specific showsyntaxerror() also exists, but this method can take
1602 A specific showsyntaxerror() also exists, but this method can take
1603 care of calling it if needed, so unless you are explicitly catching a
1603 care of calling it if needed, so unless you are explicitly catching a
1604 SyntaxError exception, don't try to analyze the stack manually and
1604 SyntaxError exception, don't try to analyze the stack manually and
1605 simply call this method."""
1605 simply call this method."""
1606
1606
1607 try:
1607 try:
1608 if exc_tuple is None:
1608 if exc_tuple is None:
1609 etype, value, tb = sys.exc_info()
1609 etype, value, tb = sys.exc_info()
1610 else:
1610 else:
1611 etype, value, tb = exc_tuple
1611 etype, value, tb = exc_tuple
1612
1612
1613 if etype is None:
1613 if etype is None:
1614 if hasattr(sys, 'last_type'):
1614 if hasattr(sys, 'last_type'):
1615 etype, value, tb = sys.last_type, sys.last_value, \
1615 etype, value, tb = sys.last_type, sys.last_value, \
1616 sys.last_traceback
1616 sys.last_traceback
1617 else:
1617 else:
1618 self.write_err('No traceback available to show.\n')
1618 self.write_err('No traceback available to show.\n')
1619 return
1619 return
1620
1620
1621 if etype is SyntaxError:
1621 if etype is SyntaxError:
1622 # Though this won't be called by syntax errors in the input
1622 # Though this won't be called by syntax errors in the input
1623 # line, there may be SyntaxError cases with imported code.
1623 # line, there may be SyntaxError cases with imported code.
1624 self.showsyntaxerror(filename)
1624 self.showsyntaxerror(filename)
1625 elif etype is UsageError:
1625 elif etype is UsageError:
1626 self.write_err("UsageError: %s" % value)
1626 self.write_err("UsageError: %s" % value)
1627 else:
1627 else:
1628 # WARNING: these variables are somewhat deprecated and not
1628 # WARNING: these variables are somewhat deprecated and not
1629 # necessarily safe to use in a threaded environment, but tools
1629 # necessarily safe to use in a threaded environment, but tools
1630 # like pdb depend on their existence, so let's set them. If we
1630 # like pdb depend on their existence, so let's set them. If we
1631 # find problems in the field, we'll need to revisit their use.
1631 # find problems in the field, we'll need to revisit their use.
1632 sys.last_type = etype
1632 sys.last_type = etype
1633 sys.last_value = value
1633 sys.last_value = value
1634 sys.last_traceback = tb
1634 sys.last_traceback = tb
1635 if etype in self.custom_exceptions:
1635 if etype in self.custom_exceptions:
1636 stb = self.CustomTB(etype, value, tb, tb_offset)
1636 stb = self.CustomTB(etype, value, tb, tb_offset)
1637 else:
1637 else:
1638 if exception_only:
1638 if exception_only:
1639 stb = ['An exception has occurred, use %tb to see '
1639 stb = ['An exception has occurred, use %tb to see '
1640 'the full traceback.\n']
1640 'the full traceback.\n']
1641 stb.extend(self.InteractiveTB.get_exception_only(etype,
1641 stb.extend(self.InteractiveTB.get_exception_only(etype,
1642 value))
1642 value))
1643 else:
1643 else:
1644 stb = self.InteractiveTB.structured_traceback(etype,
1644 stb = self.InteractiveTB.structured_traceback(etype,
1645 value, tb, tb_offset=tb_offset)
1645 value, tb, tb_offset=tb_offset)
1646
1646
1647 self._showtraceback(etype, value, stb)
1647 self._showtraceback(etype, value, stb)
1648 if self.call_pdb:
1648 if self.call_pdb:
1649 # drop into debugger
1649 # drop into debugger
1650 self.debugger(force=True)
1650 self.debugger(force=True)
1651 return
1651 return
1652
1652
1653 # Actually show the traceback
1653 # Actually show the traceback
1654 self._showtraceback(etype, value, stb)
1654 self._showtraceback(etype, value, stb)
1655
1655
1656 except KeyboardInterrupt:
1656 except KeyboardInterrupt:
1657 self.write_err("\nKeyboardInterrupt\n")
1657 self.write_err("\nKeyboardInterrupt\n")
1658
1658
1659 def _showtraceback(self, etype, evalue, stb):
1659 def _showtraceback(self, etype, evalue, stb):
1660 """Actually show a traceback.
1660 """Actually show a traceback.
1661
1661
1662 Subclasses may override this method to put the traceback on a different
1662 Subclasses may override this method to put the traceback on a different
1663 place, like a side channel.
1663 place, like a side channel.
1664 """
1664 """
1665 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1665 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1666
1666
1667 def showsyntaxerror(self, filename=None):
1667 def showsyntaxerror(self, filename=None):
1668 """Display the syntax error that just occurred.
1668 """Display the syntax error that just occurred.
1669
1669
1670 This doesn't display a stack trace because there isn't one.
1670 This doesn't display a stack trace because there isn't one.
1671
1671
1672 If a filename is given, it is stuffed in the exception instead
1672 If a filename is given, it is stuffed in the exception instead
1673 of what was there before (because Python's parser always uses
1673 of what was there before (because Python's parser always uses
1674 "<string>" when reading from a string).
1674 "<string>" when reading from a string).
1675 """
1675 """
1676 etype, value, last_traceback = sys.exc_info()
1676 etype, value, last_traceback = sys.exc_info()
1677
1677
1678 # See note about these variables in showtraceback() above
1678 # See note about these variables in showtraceback() above
1679 sys.last_type = etype
1679 sys.last_type = etype
1680 sys.last_value = value
1680 sys.last_value = value
1681 sys.last_traceback = last_traceback
1681 sys.last_traceback = last_traceback
1682
1682
1683 if filename and etype is SyntaxError:
1683 if filename and etype is SyntaxError:
1684 # Work hard to stuff the correct filename in the exception
1685 try:
1684 try:
1686 msg, (dummy_filename, lineno, offset, line) = value
1685 value.filename = filename
1687 except:
1686 except:
1688 # Not the format we expect; leave it alone
1687 # Not the format we expect; leave it alone
1689 pass
1688 pass
1690 else:
1689
1691 # Stuff in the right filename
1692 try:
1693 # Assume SyntaxError is a class exception
1694 value = SyntaxError(msg, (filename, lineno, offset, line))
1695 except:
1696 # If that failed, assume SyntaxError is a string
1697 value = msg, (filename, lineno, offset, line)
1698 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1690 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1699 self._showtraceback(etype, value, stb)
1691 self._showtraceback(etype, value, stb)
1700
1692
1701 # This is overridden in TerminalInteractiveShell to show a message about
1693 # This is overridden in TerminalInteractiveShell to show a message about
1702 # the %paste magic.
1694 # the %paste magic.
1703 def showindentationerror(self):
1695 def showindentationerror(self):
1704 """Called by run_cell when there's an IndentationError in code entered
1696 """Called by run_cell when there's an IndentationError in code entered
1705 at the prompt.
1697 at the prompt.
1706
1698
1707 This is overridden in TerminalInteractiveShell to show a message about
1699 This is overridden in TerminalInteractiveShell to show a message about
1708 the %paste magic."""
1700 the %paste magic."""
1709 self.showsyntaxerror()
1701 self.showsyntaxerror()
1710
1702
1711 #-------------------------------------------------------------------------
1703 #-------------------------------------------------------------------------
1712 # Things related to readline
1704 # Things related to readline
1713 #-------------------------------------------------------------------------
1705 #-------------------------------------------------------------------------
1714
1706
1715 def init_readline(self):
1707 def init_readline(self):
1716 """Command history completion/saving/reloading."""
1708 """Command history completion/saving/reloading."""
1717
1709
1718 if self.readline_use:
1710 if self.readline_use:
1719 import IPython.utils.rlineimpl as readline
1711 import IPython.utils.rlineimpl as readline
1720
1712
1721 self.rl_next_input = None
1713 self.rl_next_input = None
1722 self.rl_do_indent = False
1714 self.rl_do_indent = False
1723
1715
1724 if not self.readline_use or not readline.have_readline:
1716 if not self.readline_use or not readline.have_readline:
1725 self.has_readline = False
1717 self.has_readline = False
1726 self.readline = None
1718 self.readline = None
1727 # Set a number of methods that depend on readline to be no-op
1719 # Set a number of methods that depend on readline to be no-op
1728 self.readline_no_record = no_op_context
1720 self.readline_no_record = no_op_context
1729 self.set_readline_completer = no_op
1721 self.set_readline_completer = no_op
1730 self.set_custom_completer = no_op
1722 self.set_custom_completer = no_op
1731 self.set_completer_frame = no_op
1723 self.set_completer_frame = no_op
1732 if self.readline_use:
1724 if self.readline_use:
1733 warn('Readline services not available or not loaded.')
1725 warn('Readline services not available or not loaded.')
1734 else:
1726 else:
1735 self.has_readline = True
1727 self.has_readline = True
1736 self.readline = readline
1728 self.readline = readline
1737 sys.modules['readline'] = readline
1729 sys.modules['readline'] = readline
1738
1730
1739 # Platform-specific configuration
1731 # Platform-specific configuration
1740 if os.name == 'nt':
1732 if os.name == 'nt':
1741 # FIXME - check with Frederick to see if we can harmonize
1733 # FIXME - check with Frederick to see if we can harmonize
1742 # naming conventions with pyreadline to avoid this
1734 # naming conventions with pyreadline to avoid this
1743 # platform-dependent check
1735 # platform-dependent check
1744 self.readline_startup_hook = readline.set_pre_input_hook
1736 self.readline_startup_hook = readline.set_pre_input_hook
1745 else:
1737 else:
1746 self.readline_startup_hook = readline.set_startup_hook
1738 self.readline_startup_hook = readline.set_startup_hook
1747
1739
1748 # Load user's initrc file (readline config)
1740 # Load user's initrc file (readline config)
1749 # Or if libedit is used, load editrc.
1741 # Or if libedit is used, load editrc.
1750 inputrc_name = os.environ.get('INPUTRC')
1742 inputrc_name = os.environ.get('INPUTRC')
1751 if inputrc_name is None:
1743 if inputrc_name is None:
1752 inputrc_name = '.inputrc'
1744 inputrc_name = '.inputrc'
1753 if readline.uses_libedit:
1745 if readline.uses_libedit:
1754 inputrc_name = '.editrc'
1746 inputrc_name = '.editrc'
1755 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1747 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1756 if os.path.isfile(inputrc_name):
1748 if os.path.isfile(inputrc_name):
1757 try:
1749 try:
1758 readline.read_init_file(inputrc_name)
1750 readline.read_init_file(inputrc_name)
1759 except:
1751 except:
1760 warn('Problems reading readline initialization file <%s>'
1752 warn('Problems reading readline initialization file <%s>'
1761 % inputrc_name)
1753 % inputrc_name)
1762
1754
1763 # Configure readline according to user's prefs
1755 # Configure readline according to user's prefs
1764 # This is only done if GNU readline is being used. If libedit
1756 # This is only done if GNU readline is being used. If libedit
1765 # is being used (as on Leopard) the readline config is
1757 # is being used (as on Leopard) the readline config is
1766 # not run as the syntax for libedit is different.
1758 # not run as the syntax for libedit is different.
1767 if not readline.uses_libedit:
1759 if not readline.uses_libedit:
1768 for rlcommand in self.readline_parse_and_bind:
1760 for rlcommand in self.readline_parse_and_bind:
1769 #print "loading rl:",rlcommand # dbg
1761 #print "loading rl:",rlcommand # dbg
1770 readline.parse_and_bind(rlcommand)
1762 readline.parse_and_bind(rlcommand)
1771
1763
1772 # Remove some chars from the delimiters list. If we encounter
1764 # Remove some chars from the delimiters list. If we encounter
1773 # unicode chars, discard them.
1765 # unicode chars, discard them.
1774 delims = readline.get_completer_delims()
1766 delims = readline.get_completer_delims()
1775 if not py3compat.PY3:
1767 if not py3compat.PY3:
1776 delims = delims.encode("ascii", "ignore")
1768 delims = delims.encode("ascii", "ignore")
1777 for d in self.readline_remove_delims:
1769 for d in self.readline_remove_delims:
1778 delims = delims.replace(d, "")
1770 delims = delims.replace(d, "")
1779 delims = delims.replace(ESC_MAGIC, '')
1771 delims = delims.replace(ESC_MAGIC, '')
1780 readline.set_completer_delims(delims)
1772 readline.set_completer_delims(delims)
1781 # otherwise we end up with a monster history after a while:
1773 # otherwise we end up with a monster history after a while:
1782 readline.set_history_length(self.history_length)
1774 readline.set_history_length(self.history_length)
1783
1775
1784 self.refill_readline_hist()
1776 self.refill_readline_hist()
1785 self.readline_no_record = ReadlineNoRecord(self)
1777 self.readline_no_record = ReadlineNoRecord(self)
1786
1778
1787 # Configure auto-indent for all platforms
1779 # Configure auto-indent for all platforms
1788 self.set_autoindent(self.autoindent)
1780 self.set_autoindent(self.autoindent)
1789
1781
1790 def refill_readline_hist(self):
1782 def refill_readline_hist(self):
1791 # Load the last 1000 lines from history
1783 # Load the last 1000 lines from history
1792 self.readline.clear_history()
1784 self.readline.clear_history()
1793 stdin_encoding = sys.stdin.encoding or "utf-8"
1785 stdin_encoding = sys.stdin.encoding or "utf-8"
1794 last_cell = u""
1786 last_cell = u""
1795 for _, _, cell in self.history_manager.get_tail(1000,
1787 for _, _, cell in self.history_manager.get_tail(1000,
1796 include_latest=True):
1788 include_latest=True):
1797 # Ignore blank lines and consecutive duplicates
1789 # Ignore blank lines and consecutive duplicates
1798 cell = cell.rstrip()
1790 cell = cell.rstrip()
1799 if cell and (cell != last_cell):
1791 if cell and (cell != last_cell):
1800 if self.multiline_history:
1792 if self.multiline_history:
1801 self.readline.add_history(py3compat.unicode_to_str(cell,
1793 self.readline.add_history(py3compat.unicode_to_str(cell,
1802 stdin_encoding))
1794 stdin_encoding))
1803 else:
1795 else:
1804 for line in cell.splitlines():
1796 for line in cell.splitlines():
1805 self.readline.add_history(py3compat.unicode_to_str(line,
1797 self.readline.add_history(py3compat.unicode_to_str(line,
1806 stdin_encoding))
1798 stdin_encoding))
1807 last_cell = cell
1799 last_cell = cell
1808
1800
1809 def set_next_input(self, s):
1801 def set_next_input(self, s):
1810 """ Sets the 'default' input string for the next command line.
1802 """ Sets the 'default' input string for the next command line.
1811
1803
1812 Requires readline.
1804 Requires readline.
1813
1805
1814 Example:
1806 Example:
1815
1807
1816 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1808 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1817 [D:\ipython]|2> Hello Word_ # cursor is here
1809 [D:\ipython]|2> Hello Word_ # cursor is here
1818 """
1810 """
1819 self.rl_next_input = py3compat.cast_bytes_py2(s)
1811 self.rl_next_input = py3compat.cast_bytes_py2(s)
1820
1812
1821 # Maybe move this to the terminal subclass?
1813 # Maybe move this to the terminal subclass?
1822 def pre_readline(self):
1814 def pre_readline(self):
1823 """readline hook to be used at the start of each line.
1815 """readline hook to be used at the start of each line.
1824
1816
1825 Currently it handles auto-indent only."""
1817 Currently it handles auto-indent only."""
1826
1818
1827 if self.rl_do_indent:
1819 if self.rl_do_indent:
1828 self.readline.insert_text(self._indent_current_str())
1820 self.readline.insert_text(self._indent_current_str())
1829 if self.rl_next_input is not None:
1821 if self.rl_next_input is not None:
1830 self.readline.insert_text(self.rl_next_input)
1822 self.readline.insert_text(self.rl_next_input)
1831 self.rl_next_input = None
1823 self.rl_next_input = None
1832
1824
1833 def _indent_current_str(self):
1825 def _indent_current_str(self):
1834 """return the current level of indentation as a string"""
1826 """return the current level of indentation as a string"""
1835 return self.input_splitter.indent_spaces * ' '
1827 return self.input_splitter.indent_spaces * ' '
1836
1828
1837 #-------------------------------------------------------------------------
1829 #-------------------------------------------------------------------------
1838 # Things related to text completion
1830 # Things related to text completion
1839 #-------------------------------------------------------------------------
1831 #-------------------------------------------------------------------------
1840
1832
1841 def init_completer(self):
1833 def init_completer(self):
1842 """Initialize the completion machinery.
1834 """Initialize the completion machinery.
1843
1835
1844 This creates completion machinery that can be used by client code,
1836 This creates completion machinery that can be used by client code,
1845 either interactively in-process (typically triggered by the readline
1837 either interactively in-process (typically triggered by the readline
1846 library), programatically (such as in test suites) or out-of-prcess
1838 library), programatically (such as in test suites) or out-of-prcess
1847 (typically over the network by remote frontends).
1839 (typically over the network by remote frontends).
1848 """
1840 """
1849 from IPython.core.completer import IPCompleter
1841 from IPython.core.completer import IPCompleter
1850 from IPython.core.completerlib import (module_completer,
1842 from IPython.core.completerlib import (module_completer,
1851 magic_run_completer, cd_completer)
1843 magic_run_completer, cd_completer)
1852
1844
1853 self.Completer = IPCompleter(shell=self,
1845 self.Completer = IPCompleter(shell=self,
1854 namespace=self.user_ns,
1846 namespace=self.user_ns,
1855 global_namespace=self.user_global_ns,
1847 global_namespace=self.user_global_ns,
1856 alias_table=self.alias_manager.alias_table,
1848 alias_table=self.alias_manager.alias_table,
1857 use_readline=self.has_readline,
1849 use_readline=self.has_readline,
1858 config=self.config,
1850 config=self.config,
1859 )
1851 )
1860 self.configurables.append(self.Completer)
1852 self.configurables.append(self.Completer)
1861
1853
1862 # Add custom completers to the basic ones built into IPCompleter
1854 # Add custom completers to the basic ones built into IPCompleter
1863 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1855 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1864 self.strdispatchers['complete_command'] = sdisp
1856 self.strdispatchers['complete_command'] = sdisp
1865 self.Completer.custom_completers = sdisp
1857 self.Completer.custom_completers = sdisp
1866
1858
1867 self.set_hook('complete_command', module_completer, str_key = 'import')
1859 self.set_hook('complete_command', module_completer, str_key = 'import')
1868 self.set_hook('complete_command', module_completer, str_key = 'from')
1860 self.set_hook('complete_command', module_completer, str_key = 'from')
1869 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1861 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1870 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1862 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1871
1863
1872 # Only configure readline if we truly are using readline. IPython can
1864 # Only configure readline if we truly are using readline. IPython can
1873 # do tab-completion over the network, in GUIs, etc, where readline
1865 # do tab-completion over the network, in GUIs, etc, where readline
1874 # itself may be absent
1866 # itself may be absent
1875 if self.has_readline:
1867 if self.has_readline:
1876 self.set_readline_completer()
1868 self.set_readline_completer()
1877
1869
1878 def complete(self, text, line=None, cursor_pos=None):
1870 def complete(self, text, line=None, cursor_pos=None):
1879 """Return the completed text and a list of completions.
1871 """Return the completed text and a list of completions.
1880
1872
1881 Parameters
1873 Parameters
1882 ----------
1874 ----------
1883
1875
1884 text : string
1876 text : string
1885 A string of text to be completed on. It can be given as empty and
1877 A string of text to be completed on. It can be given as empty and
1886 instead a line/position pair are given. In this case, the
1878 instead a line/position pair are given. In this case, the
1887 completer itself will split the line like readline does.
1879 completer itself will split the line like readline does.
1888
1880
1889 line : string, optional
1881 line : string, optional
1890 The complete line that text is part of.
1882 The complete line that text is part of.
1891
1883
1892 cursor_pos : int, optional
1884 cursor_pos : int, optional
1893 The position of the cursor on the input line.
1885 The position of the cursor on the input line.
1894
1886
1895 Returns
1887 Returns
1896 -------
1888 -------
1897 text : string
1889 text : string
1898 The actual text that was completed.
1890 The actual text that was completed.
1899
1891
1900 matches : list
1892 matches : list
1901 A sorted list with all possible completions.
1893 A sorted list with all possible completions.
1902
1894
1903 The optional arguments allow the completion to take more context into
1895 The optional arguments allow the completion to take more context into
1904 account, and are part of the low-level completion API.
1896 account, and are part of the low-level completion API.
1905
1897
1906 This is a wrapper around the completion mechanism, similar to what
1898 This is a wrapper around the completion mechanism, similar to what
1907 readline does at the command line when the TAB key is hit. By
1899 readline does at the command line when the TAB key is hit. By
1908 exposing it as a method, it can be used by other non-readline
1900 exposing it as a method, it can be used by other non-readline
1909 environments (such as GUIs) for text completion.
1901 environments (such as GUIs) for text completion.
1910
1902
1911 Simple usage example:
1903 Simple usage example:
1912
1904
1913 In [1]: x = 'hello'
1905 In [1]: x = 'hello'
1914
1906
1915 In [2]: _ip.complete('x.l')
1907 In [2]: _ip.complete('x.l')
1916 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1908 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1917 """
1909 """
1918
1910
1919 # Inject names into __builtin__ so we can complete on the added names.
1911 # Inject names into __builtin__ so we can complete on the added names.
1920 with self.builtin_trap:
1912 with self.builtin_trap:
1921 return self.Completer.complete(text, line, cursor_pos)
1913 return self.Completer.complete(text, line, cursor_pos)
1922
1914
1923 def set_custom_completer(self, completer, pos=0):
1915 def set_custom_completer(self, completer, pos=0):
1924 """Adds a new custom completer function.
1916 """Adds a new custom completer function.
1925
1917
1926 The position argument (defaults to 0) is the index in the completers
1918 The position argument (defaults to 0) is the index in the completers
1927 list where you want the completer to be inserted."""
1919 list where you want the completer to be inserted."""
1928
1920
1929 newcomp = types.MethodType(completer,self.Completer)
1921 newcomp = types.MethodType(completer,self.Completer)
1930 self.Completer.matchers.insert(pos,newcomp)
1922 self.Completer.matchers.insert(pos,newcomp)
1931
1923
1932 def set_readline_completer(self):
1924 def set_readline_completer(self):
1933 """Reset readline's completer to be our own."""
1925 """Reset readline's completer to be our own."""
1934 self.readline.set_completer(self.Completer.rlcomplete)
1926 self.readline.set_completer(self.Completer.rlcomplete)
1935
1927
1936 def set_completer_frame(self, frame=None):
1928 def set_completer_frame(self, frame=None):
1937 """Set the frame of the completer."""
1929 """Set the frame of the completer."""
1938 if frame:
1930 if frame:
1939 self.Completer.namespace = frame.f_locals
1931 self.Completer.namespace = frame.f_locals
1940 self.Completer.global_namespace = frame.f_globals
1932 self.Completer.global_namespace = frame.f_globals
1941 else:
1933 else:
1942 self.Completer.namespace = self.user_ns
1934 self.Completer.namespace = self.user_ns
1943 self.Completer.global_namespace = self.user_global_ns
1935 self.Completer.global_namespace = self.user_global_ns
1944
1936
1945 #-------------------------------------------------------------------------
1937 #-------------------------------------------------------------------------
1946 # Things related to magics
1938 # Things related to magics
1947 #-------------------------------------------------------------------------
1939 #-------------------------------------------------------------------------
1948
1940
1949 def init_magics(self):
1941 def init_magics(self):
1950 # FIXME: Move the color initialization to the DisplayHook, which
1942 # FIXME: Move the color initialization to the DisplayHook, which
1951 # should be split into a prompt manager and displayhook. We probably
1943 # should be split into a prompt manager and displayhook. We probably
1952 # even need a centralize colors management object.
1944 # even need a centralize colors management object.
1953 self.magic_colors(self.colors)
1945 self.magic_colors(self.colors)
1954 # History was moved to a separate module
1946 # History was moved to a separate module
1955 from IPython.core import history
1947 from IPython.core import history
1956 history.init_ipython(self)
1948 history.init_ipython(self)
1957
1949
1958 def magic(self, arg_s, next_input=None):
1950 def magic(self, arg_s, next_input=None):
1959 """Call a magic function by name.
1951 """Call a magic function by name.
1960
1952
1961 Input: a string containing the name of the magic function to call and
1953 Input: a string containing the name of the magic function to call and
1962 any additional arguments to be passed to the magic.
1954 any additional arguments to be passed to the magic.
1963
1955
1964 magic('name -opt foo bar') is equivalent to typing at the ipython
1956 magic('name -opt foo bar') is equivalent to typing at the ipython
1965 prompt:
1957 prompt:
1966
1958
1967 In[1]: %name -opt foo bar
1959 In[1]: %name -opt foo bar
1968
1960
1969 To call a magic without arguments, simply use magic('name').
1961 To call a magic without arguments, simply use magic('name').
1970
1962
1971 This provides a proper Python function to call IPython's magics in any
1963 This provides a proper Python function to call IPython's magics in any
1972 valid Python code you can type at the interpreter, including loops and
1964 valid Python code you can type at the interpreter, including loops and
1973 compound statements.
1965 compound statements.
1974 """
1966 """
1975 # Allow setting the next input - this is used if the user does `a=abs?`.
1967 # Allow setting the next input - this is used if the user does `a=abs?`.
1976 # We do this first so that magic functions can override it.
1968 # We do this first so that magic functions can override it.
1977 if next_input:
1969 if next_input:
1978 self.set_next_input(next_input)
1970 self.set_next_input(next_input)
1979
1971
1980 args = arg_s.split(' ',1)
1972 args = arg_s.split(' ',1)
1981 magic_name = args[0]
1973 magic_name = args[0]
1982 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1974 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1983
1975
1984 try:
1976 try:
1985 magic_args = args[1]
1977 magic_args = args[1]
1986 except IndexError:
1978 except IndexError:
1987 magic_args = ''
1979 magic_args = ''
1988 fn = getattr(self,'magic_'+magic_name,None)
1980 fn = getattr(self,'magic_'+magic_name,None)
1989 if fn is None:
1981 if fn is None:
1990 error("Magic function `%s` not found." % magic_name)
1982 error("Magic function `%s` not found." % magic_name)
1991 else:
1983 else:
1992 magic_args = self.var_expand(magic_args,1)
1984 magic_args = self.var_expand(magic_args,1)
1993 # Grab local namespace if we need it:
1985 # Grab local namespace if we need it:
1994 if getattr(fn, "needs_local_scope", False):
1986 if getattr(fn, "needs_local_scope", False):
1995 self._magic_locals = sys._getframe(1).f_locals
1987 self._magic_locals = sys._getframe(1).f_locals
1996 with self.builtin_trap:
1988 with self.builtin_trap:
1997 result = fn(magic_args)
1989 result = fn(magic_args)
1998 # Ensure we're not keeping object references around:
1990 # Ensure we're not keeping object references around:
1999 self._magic_locals = {}
1991 self._magic_locals = {}
2000 return result
1992 return result
2001
1993
2002 def define_magic(self, magicname, func):
1994 def define_magic(self, magicname, func):
2003 """Expose own function as magic function for ipython
1995 """Expose own function as magic function for ipython
2004
1996
2005 Example::
1997 Example::
2006
1998
2007 def foo_impl(self,parameter_s=''):
1999 def foo_impl(self,parameter_s=''):
2008 'My very own magic!. (Use docstrings, IPython reads them).'
2000 'My very own magic!. (Use docstrings, IPython reads them).'
2009 print 'Magic function. Passed parameter is between < >:'
2001 print 'Magic function. Passed parameter is between < >:'
2010 print '<%s>' % parameter_s
2002 print '<%s>' % parameter_s
2011 print 'The self object is:', self
2003 print 'The self object is:', self
2012
2004
2013 ip.define_magic('foo',foo_impl)
2005 ip.define_magic('foo',foo_impl)
2014 """
2006 """
2015 im = types.MethodType(func,self)
2007 im = types.MethodType(func,self)
2016 old = getattr(self, "magic_" + magicname, None)
2008 old = getattr(self, "magic_" + magicname, None)
2017 setattr(self, "magic_" + magicname, im)
2009 setattr(self, "magic_" + magicname, im)
2018 return old
2010 return old
2019
2011
2020 #-------------------------------------------------------------------------
2012 #-------------------------------------------------------------------------
2021 # Things related to macros
2013 # Things related to macros
2022 #-------------------------------------------------------------------------
2014 #-------------------------------------------------------------------------
2023
2015
2024 def define_macro(self, name, themacro):
2016 def define_macro(self, name, themacro):
2025 """Define a new macro
2017 """Define a new macro
2026
2018
2027 Parameters
2019 Parameters
2028 ----------
2020 ----------
2029 name : str
2021 name : str
2030 The name of the macro.
2022 The name of the macro.
2031 themacro : str or Macro
2023 themacro : str or Macro
2032 The action to do upon invoking the macro. If a string, a new
2024 The action to do upon invoking the macro. If a string, a new
2033 Macro object is created by passing the string to it.
2025 Macro object is created by passing the string to it.
2034 """
2026 """
2035
2027
2036 from IPython.core import macro
2028 from IPython.core import macro
2037
2029
2038 if isinstance(themacro, basestring):
2030 if isinstance(themacro, basestring):
2039 themacro = macro.Macro(themacro)
2031 themacro = macro.Macro(themacro)
2040 if not isinstance(themacro, macro.Macro):
2032 if not isinstance(themacro, macro.Macro):
2041 raise ValueError('A macro must be a string or a Macro instance.')
2033 raise ValueError('A macro must be a string or a Macro instance.')
2042 self.user_ns[name] = themacro
2034 self.user_ns[name] = themacro
2043
2035
2044 #-------------------------------------------------------------------------
2036 #-------------------------------------------------------------------------
2045 # Things related to the running of system commands
2037 # Things related to the running of system commands
2046 #-------------------------------------------------------------------------
2038 #-------------------------------------------------------------------------
2047
2039
2048 def system_piped(self, cmd):
2040 def system_piped(self, cmd):
2049 """Call the given cmd in a subprocess, piping stdout/err
2041 """Call the given cmd in a subprocess, piping stdout/err
2050
2042
2051 Parameters
2043 Parameters
2052 ----------
2044 ----------
2053 cmd : str
2045 cmd : str
2054 Command to execute (can not end in '&', as background processes are
2046 Command to execute (can not end in '&', as background processes are
2055 not supported. Should not be a command that expects input
2047 not supported. Should not be a command that expects input
2056 other than simple text.
2048 other than simple text.
2057 """
2049 """
2058 if cmd.rstrip().endswith('&'):
2050 if cmd.rstrip().endswith('&'):
2059 # this is *far* from a rigorous test
2051 # this is *far* from a rigorous test
2060 # We do not support backgrounding processes because we either use
2052 # We do not support backgrounding processes because we either use
2061 # pexpect or pipes to read from. Users can always just call
2053 # pexpect or pipes to read from. Users can always just call
2062 # os.system() or use ip.system=ip.system_raw
2054 # os.system() or use ip.system=ip.system_raw
2063 # if they really want a background process.
2055 # if they really want a background process.
2064 raise OSError("Background processes not supported.")
2056 raise OSError("Background processes not supported.")
2065
2057
2066 # we explicitly do NOT return the subprocess status code, because
2058 # we explicitly do NOT return the subprocess status code, because
2067 # a non-None value would trigger :func:`sys.displayhook` calls.
2059 # a non-None value would trigger :func:`sys.displayhook` calls.
2068 # Instead, we store the exit_code in user_ns.
2060 # Instead, we store the exit_code in user_ns.
2069 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=2))
2061 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=2))
2070
2062
2071 def system_raw(self, cmd):
2063 def system_raw(self, cmd):
2072 """Call the given cmd in a subprocess using os.system
2064 """Call the given cmd in a subprocess using os.system
2073
2065
2074 Parameters
2066 Parameters
2075 ----------
2067 ----------
2076 cmd : str
2068 cmd : str
2077 Command to execute.
2069 Command to execute.
2078 """
2070 """
2079 cmd = self.var_expand(cmd, depth=2)
2071 cmd = self.var_expand(cmd, depth=2)
2080 # protect os.system from UNC paths on Windows, which it can't handle:
2072 # protect os.system from UNC paths on Windows, which it can't handle:
2081 if sys.platform == 'win32':
2073 if sys.platform == 'win32':
2082 from IPython.utils._process_win32 import AvoidUNCPath
2074 from IPython.utils._process_win32 import AvoidUNCPath
2083 with AvoidUNCPath() as path:
2075 with AvoidUNCPath() as path:
2084 if path is not None:
2076 if path is not None:
2085 cmd = '"pushd %s &&"%s' % (path, cmd)
2077 cmd = '"pushd %s &&"%s' % (path, cmd)
2086 cmd = py3compat.unicode_to_str(cmd)
2078 cmd = py3compat.unicode_to_str(cmd)
2087 ec = os.system(cmd)
2079 ec = os.system(cmd)
2088 else:
2080 else:
2089 cmd = py3compat.unicode_to_str(cmd)
2081 cmd = py3compat.unicode_to_str(cmd)
2090 ec = os.system(cmd)
2082 ec = os.system(cmd)
2091
2083
2092 # We explicitly do NOT return the subprocess status code, because
2084 # We explicitly do NOT return the subprocess status code, because
2093 # a non-None value would trigger :func:`sys.displayhook` calls.
2085 # a non-None value would trigger :func:`sys.displayhook` calls.
2094 # Instead, we store the exit_code in user_ns.
2086 # Instead, we store the exit_code in user_ns.
2095 self.user_ns['_exit_code'] = ec
2087 self.user_ns['_exit_code'] = ec
2096
2088
2097 # use piped system by default, because it is better behaved
2089 # use piped system by default, because it is better behaved
2098 system = system_piped
2090 system = system_piped
2099
2091
2100 def getoutput(self, cmd, split=True):
2092 def getoutput(self, cmd, split=True):
2101 """Get output (possibly including stderr) from a subprocess.
2093 """Get output (possibly including stderr) from a subprocess.
2102
2094
2103 Parameters
2095 Parameters
2104 ----------
2096 ----------
2105 cmd : str
2097 cmd : str
2106 Command to execute (can not end in '&', as background processes are
2098 Command to execute (can not end in '&', as background processes are
2107 not supported.
2099 not supported.
2108 split : bool, optional
2100 split : bool, optional
2109
2101
2110 If True, split the output into an IPython SList. Otherwise, an
2102 If True, split the output into an IPython SList. Otherwise, an
2111 IPython LSString is returned. These are objects similar to normal
2103 IPython LSString is returned. These are objects similar to normal
2112 lists and strings, with a few convenience attributes for easier
2104 lists and strings, with a few convenience attributes for easier
2113 manipulation of line-based output. You can use '?' on them for
2105 manipulation of line-based output. You can use '?' on them for
2114 details.
2106 details.
2115 """
2107 """
2116 if cmd.rstrip().endswith('&'):
2108 if cmd.rstrip().endswith('&'):
2117 # this is *far* from a rigorous test
2109 # this is *far* from a rigorous test
2118 raise OSError("Background processes not supported.")
2110 raise OSError("Background processes not supported.")
2119 out = getoutput(self.var_expand(cmd, depth=2))
2111 out = getoutput(self.var_expand(cmd, depth=2))
2120 if split:
2112 if split:
2121 out = SList(out.splitlines())
2113 out = SList(out.splitlines())
2122 else:
2114 else:
2123 out = LSString(out)
2115 out = LSString(out)
2124 return out
2116 return out
2125
2117
2126 #-------------------------------------------------------------------------
2118 #-------------------------------------------------------------------------
2127 # Things related to aliases
2119 # Things related to aliases
2128 #-------------------------------------------------------------------------
2120 #-------------------------------------------------------------------------
2129
2121
2130 def init_alias(self):
2122 def init_alias(self):
2131 self.alias_manager = AliasManager(shell=self, config=self.config)
2123 self.alias_manager = AliasManager(shell=self, config=self.config)
2132 self.configurables.append(self.alias_manager)
2124 self.configurables.append(self.alias_manager)
2133 self.ns_table['alias'] = self.alias_manager.alias_table,
2125 self.ns_table['alias'] = self.alias_manager.alias_table,
2134
2126
2135 #-------------------------------------------------------------------------
2127 #-------------------------------------------------------------------------
2136 # Things related to extensions and plugins
2128 # Things related to extensions and plugins
2137 #-------------------------------------------------------------------------
2129 #-------------------------------------------------------------------------
2138
2130
2139 def init_extension_manager(self):
2131 def init_extension_manager(self):
2140 self.extension_manager = ExtensionManager(shell=self, config=self.config)
2132 self.extension_manager = ExtensionManager(shell=self, config=self.config)
2141 self.configurables.append(self.extension_manager)
2133 self.configurables.append(self.extension_manager)
2142
2134
2143 def init_plugin_manager(self):
2135 def init_plugin_manager(self):
2144 self.plugin_manager = PluginManager(config=self.config)
2136 self.plugin_manager = PluginManager(config=self.config)
2145 self.configurables.append(self.plugin_manager)
2137 self.configurables.append(self.plugin_manager)
2146
2138
2147
2139
2148 #-------------------------------------------------------------------------
2140 #-------------------------------------------------------------------------
2149 # Things related to payloads
2141 # Things related to payloads
2150 #-------------------------------------------------------------------------
2142 #-------------------------------------------------------------------------
2151
2143
2152 def init_payload(self):
2144 def init_payload(self):
2153 self.payload_manager = PayloadManager(config=self.config)
2145 self.payload_manager = PayloadManager(config=self.config)
2154 self.configurables.append(self.payload_manager)
2146 self.configurables.append(self.payload_manager)
2155
2147
2156 #-------------------------------------------------------------------------
2148 #-------------------------------------------------------------------------
2157 # Things related to the prefilter
2149 # Things related to the prefilter
2158 #-------------------------------------------------------------------------
2150 #-------------------------------------------------------------------------
2159
2151
2160 def init_prefilter(self):
2152 def init_prefilter(self):
2161 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2153 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
2162 self.configurables.append(self.prefilter_manager)
2154 self.configurables.append(self.prefilter_manager)
2163 # Ultimately this will be refactored in the new interpreter code, but
2155 # Ultimately this will be refactored in the new interpreter code, but
2164 # for now, we should expose the main prefilter method (there's legacy
2156 # for now, we should expose the main prefilter method (there's legacy
2165 # code out there that may rely on this).
2157 # code out there that may rely on this).
2166 self.prefilter = self.prefilter_manager.prefilter_lines
2158 self.prefilter = self.prefilter_manager.prefilter_lines
2167
2159
2168 def auto_rewrite_input(self, cmd):
2160 def auto_rewrite_input(self, cmd):
2169 """Print to the screen the rewritten form of the user's command.
2161 """Print to the screen the rewritten form of the user's command.
2170
2162
2171 This shows visual feedback by rewriting input lines that cause
2163 This shows visual feedback by rewriting input lines that cause
2172 automatic calling to kick in, like::
2164 automatic calling to kick in, like::
2173
2165
2174 /f x
2166 /f x
2175
2167
2176 into::
2168 into::
2177
2169
2178 ------> f(x)
2170 ------> f(x)
2179
2171
2180 after the user's input prompt. This helps the user understand that the
2172 after the user's input prompt. This helps the user understand that the
2181 input line was transformed automatically by IPython.
2173 input line was transformed automatically by IPython.
2182 """
2174 """
2183 if not self.show_rewritten_input:
2175 if not self.show_rewritten_input:
2184 return
2176 return
2185
2177
2186 rw = self.prompt_manager.render('rewrite') + cmd
2178 rw = self.prompt_manager.render('rewrite') + cmd
2187
2179
2188 try:
2180 try:
2189 # plain ascii works better w/ pyreadline, on some machines, so
2181 # plain ascii works better w/ pyreadline, on some machines, so
2190 # we use it and only print uncolored rewrite if we have unicode
2182 # we use it and only print uncolored rewrite if we have unicode
2191 rw = str(rw)
2183 rw = str(rw)
2192 print >> io.stdout, rw
2184 print >> io.stdout, rw
2193 except UnicodeEncodeError:
2185 except UnicodeEncodeError:
2194 print "------> " + cmd
2186 print "------> " + cmd
2195
2187
2196 #-------------------------------------------------------------------------
2188 #-------------------------------------------------------------------------
2197 # Things related to extracting values/expressions from kernel and user_ns
2189 # Things related to extracting values/expressions from kernel and user_ns
2198 #-------------------------------------------------------------------------
2190 #-------------------------------------------------------------------------
2199
2191
2200 def _simple_error(self):
2192 def _simple_error(self):
2201 etype, value = sys.exc_info()[:2]
2193 etype, value = sys.exc_info()[:2]
2202 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2194 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
2203
2195
2204 def user_variables(self, names):
2196 def user_variables(self, names):
2205 """Get a list of variable names from the user's namespace.
2197 """Get a list of variable names from the user's namespace.
2206
2198
2207 Parameters
2199 Parameters
2208 ----------
2200 ----------
2209 names : list of strings
2201 names : list of strings
2210 A list of names of variables to be read from the user namespace.
2202 A list of names of variables to be read from the user namespace.
2211
2203
2212 Returns
2204 Returns
2213 -------
2205 -------
2214 A dict, keyed by the input names and with the repr() of each value.
2206 A dict, keyed by the input names and with the repr() of each value.
2215 """
2207 """
2216 out = {}
2208 out = {}
2217 user_ns = self.user_ns
2209 user_ns = self.user_ns
2218 for varname in names:
2210 for varname in names:
2219 try:
2211 try:
2220 value = repr(user_ns[varname])
2212 value = repr(user_ns[varname])
2221 except:
2213 except:
2222 value = self._simple_error()
2214 value = self._simple_error()
2223 out[varname] = value
2215 out[varname] = value
2224 return out
2216 return out
2225
2217
2226 def user_expressions(self, expressions):
2218 def user_expressions(self, expressions):
2227 """Evaluate a dict of expressions in the user's namespace.
2219 """Evaluate a dict of expressions in the user's namespace.
2228
2220
2229 Parameters
2221 Parameters
2230 ----------
2222 ----------
2231 expressions : dict
2223 expressions : dict
2232 A dict with string keys and string values. The expression values
2224 A dict with string keys and string values. The expression values
2233 should be valid Python expressions, each of which will be evaluated
2225 should be valid Python expressions, each of which will be evaluated
2234 in the user namespace.
2226 in the user namespace.
2235
2227
2236 Returns
2228 Returns
2237 -------
2229 -------
2238 A dict, keyed like the input expressions dict, with the repr() of each
2230 A dict, keyed like the input expressions dict, with the repr() of each
2239 value.
2231 value.
2240 """
2232 """
2241 out = {}
2233 out = {}
2242 user_ns = self.user_ns
2234 user_ns = self.user_ns
2243 global_ns = self.user_global_ns
2235 global_ns = self.user_global_ns
2244 for key, expr in expressions.iteritems():
2236 for key, expr in expressions.iteritems():
2245 try:
2237 try:
2246 value = repr(eval(expr, global_ns, user_ns))
2238 value = repr(eval(expr, global_ns, user_ns))
2247 except:
2239 except:
2248 value = self._simple_error()
2240 value = self._simple_error()
2249 out[key] = value
2241 out[key] = value
2250 return out
2242 return out
2251
2243
2252 #-------------------------------------------------------------------------
2244 #-------------------------------------------------------------------------
2253 # Things related to the running of code
2245 # Things related to the running of code
2254 #-------------------------------------------------------------------------
2246 #-------------------------------------------------------------------------
2255
2247
2256 def ex(self, cmd):
2248 def ex(self, cmd):
2257 """Execute a normal python statement in user namespace."""
2249 """Execute a normal python statement in user namespace."""
2258 with self.builtin_trap:
2250 with self.builtin_trap:
2259 exec cmd in self.user_global_ns, self.user_ns
2251 exec cmd in self.user_global_ns, self.user_ns
2260
2252
2261 def ev(self, expr):
2253 def ev(self, expr):
2262 """Evaluate python expression expr in user namespace.
2254 """Evaluate python expression expr in user namespace.
2263
2255
2264 Returns the result of evaluation
2256 Returns the result of evaluation
2265 """
2257 """
2266 with self.builtin_trap:
2258 with self.builtin_trap:
2267 return eval(expr, self.user_global_ns, self.user_ns)
2259 return eval(expr, self.user_global_ns, self.user_ns)
2268
2260
2269 def safe_execfile(self, fname, *where, **kw):
2261 def safe_execfile(self, fname, *where, **kw):
2270 """A safe version of the builtin execfile().
2262 """A safe version of the builtin execfile().
2271
2263
2272 This version will never throw an exception, but instead print
2264 This version will never throw an exception, but instead print
2273 helpful error messages to the screen. This only works on pure
2265 helpful error messages to the screen. This only works on pure
2274 Python files with the .py extension.
2266 Python files with the .py extension.
2275
2267
2276 Parameters
2268 Parameters
2277 ----------
2269 ----------
2278 fname : string
2270 fname : string
2279 The name of the file to be executed.
2271 The name of the file to be executed.
2280 where : tuple
2272 where : tuple
2281 One or two namespaces, passed to execfile() as (globals,locals).
2273 One or two namespaces, passed to execfile() as (globals,locals).
2282 If only one is given, it is passed as both.
2274 If only one is given, it is passed as both.
2283 exit_ignore : bool (False)
2275 exit_ignore : bool (False)
2284 If True, then silence SystemExit for non-zero status (it is always
2276 If True, then silence SystemExit for non-zero status (it is always
2285 silenced for zero status, as it is so common).
2277 silenced for zero status, as it is so common).
2286 raise_exceptions : bool (False)
2278 raise_exceptions : bool (False)
2287 If True raise exceptions everywhere. Meant for testing.
2279 If True raise exceptions everywhere. Meant for testing.
2288
2280
2289 """
2281 """
2290 kw.setdefault('exit_ignore', False)
2282 kw.setdefault('exit_ignore', False)
2291 kw.setdefault('raise_exceptions', False)
2283 kw.setdefault('raise_exceptions', False)
2292
2284
2293 fname = os.path.abspath(os.path.expanduser(fname))
2285 fname = os.path.abspath(os.path.expanduser(fname))
2294
2286
2295 # Make sure we can open the file
2287 # Make sure we can open the file
2296 try:
2288 try:
2297 with open(fname) as thefile:
2289 with open(fname) as thefile:
2298 pass
2290 pass
2299 except:
2291 except:
2300 warn('Could not open file <%s> for safe execution.' % fname)
2292 warn('Could not open file <%s> for safe execution.' % fname)
2301 return
2293 return
2302
2294
2303 # Find things also in current directory. This is needed to mimic the
2295 # Find things also in current directory. This is needed to mimic the
2304 # behavior of running a script from the system command line, where
2296 # behavior of running a script from the system command line, where
2305 # Python inserts the script's directory into sys.path
2297 # Python inserts the script's directory into sys.path
2306 dname = os.path.dirname(fname)
2298 dname = os.path.dirname(fname)
2307
2299
2308 with prepended_to_syspath(dname):
2300 with prepended_to_syspath(dname):
2309 try:
2301 try:
2310 py3compat.execfile(fname,*where)
2302 py3compat.execfile(fname,*where)
2311 except SystemExit, status:
2303 except SystemExit, status:
2312 # If the call was made with 0 or None exit status (sys.exit(0)
2304 # If the call was made with 0 or None exit status (sys.exit(0)
2313 # or sys.exit() ), don't bother showing a traceback, as both of
2305 # or sys.exit() ), don't bother showing a traceback, as both of
2314 # these are considered normal by the OS:
2306 # these are considered normal by the OS:
2315 # > python -c'import sys;sys.exit(0)'; echo $?
2307 # > python -c'import sys;sys.exit(0)'; echo $?
2316 # 0
2308 # 0
2317 # > python -c'import sys;sys.exit()'; echo $?
2309 # > python -c'import sys;sys.exit()'; echo $?
2318 # 0
2310 # 0
2319 # For other exit status, we show the exception unless
2311 # For other exit status, we show the exception unless
2320 # explicitly silenced, but only in short form.
2312 # explicitly silenced, but only in short form.
2321 if kw['raise_exceptions']:
2313 if kw['raise_exceptions']:
2322 raise
2314 raise
2323 if status.code not in (0, None) and not kw['exit_ignore']:
2315 if status.code not in (0, None) and not kw['exit_ignore']:
2324 self.showtraceback(exception_only=True)
2316 self.showtraceback(exception_only=True)
2325 except:
2317 except:
2326 if kw['raise_exceptions']:
2318 if kw['raise_exceptions']:
2327 raise
2319 raise
2328 self.showtraceback()
2320 self.showtraceback()
2329
2321
2330 def safe_execfile_ipy(self, fname):
2322 def safe_execfile_ipy(self, fname):
2331 """Like safe_execfile, but for .ipy files with IPython syntax.
2323 """Like safe_execfile, but for .ipy files with IPython syntax.
2332
2324
2333 Parameters
2325 Parameters
2334 ----------
2326 ----------
2335 fname : str
2327 fname : str
2336 The name of the file to execute. The filename must have a
2328 The name of the file to execute. The filename must have a
2337 .ipy extension.
2329 .ipy extension.
2338 """
2330 """
2339 fname = os.path.abspath(os.path.expanduser(fname))
2331 fname = os.path.abspath(os.path.expanduser(fname))
2340
2332
2341 # Make sure we can open the file
2333 # Make sure we can open the file
2342 try:
2334 try:
2343 with open(fname) as thefile:
2335 with open(fname) as thefile:
2344 pass
2336 pass
2345 except:
2337 except:
2346 warn('Could not open file <%s> for safe execution.' % fname)
2338 warn('Could not open file <%s> for safe execution.' % fname)
2347 return
2339 return
2348
2340
2349 # Find things also in current directory. This is needed to mimic the
2341 # Find things also in current directory. This is needed to mimic the
2350 # behavior of running a script from the system command line, where
2342 # behavior of running a script from the system command line, where
2351 # Python inserts the script's directory into sys.path
2343 # Python inserts the script's directory into sys.path
2352 dname = os.path.dirname(fname)
2344 dname = os.path.dirname(fname)
2353
2345
2354 with prepended_to_syspath(dname):
2346 with prepended_to_syspath(dname):
2355 try:
2347 try:
2356 with open(fname) as thefile:
2348 with open(fname) as thefile:
2357 # self.run_cell currently captures all exceptions
2349 # self.run_cell currently captures all exceptions
2358 # raised in user code. It would be nice if there were
2350 # raised in user code. It would be nice if there were
2359 # versions of runlines, execfile that did raise, so
2351 # versions of runlines, execfile that did raise, so
2360 # we could catch the errors.
2352 # we could catch the errors.
2361 self.run_cell(thefile.read(), store_history=False)
2353 self.run_cell(thefile.read(), store_history=False)
2362 except:
2354 except:
2363 self.showtraceback()
2355 self.showtraceback()
2364 warn('Unknown failure executing file: <%s>' % fname)
2356 warn('Unknown failure executing file: <%s>' % fname)
2365
2357
2366 def run_cell(self, raw_cell, store_history=False):
2358 def run_cell(self, raw_cell, store_history=False):
2367 """Run a complete IPython cell.
2359 """Run a complete IPython cell.
2368
2360
2369 Parameters
2361 Parameters
2370 ----------
2362 ----------
2371 raw_cell : str
2363 raw_cell : str
2372 The code (including IPython code such as %magic functions) to run.
2364 The code (including IPython code such as %magic functions) to run.
2373 store_history : bool
2365 store_history : bool
2374 If True, the raw and translated cell will be stored in IPython's
2366 If True, the raw and translated cell will be stored in IPython's
2375 history. For user code calling back into IPython's machinery, this
2367 history. For user code calling back into IPython's machinery, this
2376 should be set to False.
2368 should be set to False.
2377 """
2369 """
2378 if (not raw_cell) or raw_cell.isspace():
2370 if (not raw_cell) or raw_cell.isspace():
2379 return
2371 return
2380
2372
2381 for line in raw_cell.splitlines():
2373 for line in raw_cell.splitlines():
2382 self.input_splitter.push(line)
2374 self.input_splitter.push(line)
2383 cell = self.input_splitter.source_reset()
2375 cell = self.input_splitter.source_reset()
2384
2376
2385 with self.builtin_trap:
2377 with self.builtin_trap:
2386 prefilter_failed = False
2378 prefilter_failed = False
2387 if len(cell.splitlines()) == 1:
2379 if len(cell.splitlines()) == 1:
2388 try:
2380 try:
2389 # use prefilter_lines to handle trailing newlines
2381 # use prefilter_lines to handle trailing newlines
2390 # restore trailing newline for ast.parse
2382 # restore trailing newline for ast.parse
2391 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2383 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2392 except AliasError as e:
2384 except AliasError as e:
2393 error(e)
2385 error(e)
2394 prefilter_failed = True
2386 prefilter_failed = True
2395 except Exception:
2387 except Exception:
2396 # don't allow prefilter errors to crash IPython
2388 # don't allow prefilter errors to crash IPython
2397 self.showtraceback()
2389 self.showtraceback()
2398 prefilter_failed = True
2390 prefilter_failed = True
2399
2391
2400 # Store raw and processed history
2392 # Store raw and processed history
2401 if store_history:
2393 if store_history:
2402 self.history_manager.store_inputs(self.execution_count,
2394 self.history_manager.store_inputs(self.execution_count,
2403 cell, raw_cell)
2395 cell, raw_cell)
2404
2396
2405 self.logger.log(cell, raw_cell)
2397 self.logger.log(cell, raw_cell)
2406
2398
2407 if not prefilter_failed:
2399 if not prefilter_failed:
2408 # don't run if prefilter failed
2400 # don't run if prefilter failed
2409 cell_name = self.compile.cache(cell, self.execution_count)
2401 cell_name = self.compile.cache(cell, self.execution_count)
2410
2402
2411 with self.display_trap:
2403 with self.display_trap:
2412 try:
2404 try:
2413 code_ast = self.compile.ast_parse(cell, filename=cell_name)
2405 code_ast = self.compile.ast_parse(cell, filename=cell_name)
2414 except IndentationError:
2406 except IndentationError:
2415 self.showindentationerror()
2407 self.showindentationerror()
2416 if store_history:
2408 if store_history:
2417 self.execution_count += 1
2409 self.execution_count += 1
2418 return None
2410 return None
2419 except (OverflowError, SyntaxError, ValueError, TypeError,
2411 except (OverflowError, SyntaxError, ValueError, TypeError,
2420 MemoryError):
2412 MemoryError):
2421 self.showsyntaxerror()
2413 self.showsyntaxerror()
2422 if store_history:
2414 if store_history:
2423 self.execution_count += 1
2415 self.execution_count += 1
2424 return None
2416 return None
2425
2417
2426 self.run_ast_nodes(code_ast.body, cell_name,
2418 self.run_ast_nodes(code_ast.body, cell_name,
2427 interactivity="last_expr")
2419 interactivity="last_expr")
2428
2420
2429 # Execute any registered post-execution functions.
2421 # Execute any registered post-execution functions.
2430 for func, status in self._post_execute.iteritems():
2422 for func, status in self._post_execute.iteritems():
2431 if self.disable_failing_post_execute and not status:
2423 if self.disable_failing_post_execute and not status:
2432 continue
2424 continue
2433 try:
2425 try:
2434 func()
2426 func()
2435 except KeyboardInterrupt:
2427 except KeyboardInterrupt:
2436 print >> io.stderr, "\nKeyboardInterrupt"
2428 print >> io.stderr, "\nKeyboardInterrupt"
2437 except Exception:
2429 except Exception:
2438 # register as failing:
2430 # register as failing:
2439 self._post_execute[func] = False
2431 self._post_execute[func] = False
2440 self.showtraceback()
2432 self.showtraceback()
2441 print >> io.stderr, '\n'.join([
2433 print >> io.stderr, '\n'.join([
2442 "post-execution function %r produced an error." % func,
2434 "post-execution function %r produced an error." % func,
2443 "If this problem persists, you can disable failing post-exec functions with:",
2435 "If this problem persists, you can disable failing post-exec functions with:",
2444 "",
2436 "",
2445 " get_ipython().disable_failing_post_execute = True"
2437 " get_ipython().disable_failing_post_execute = True"
2446 ])
2438 ])
2447
2439
2448 if store_history:
2440 if store_history:
2449 # Write output to the database. Does nothing unless
2441 # Write output to the database. Does nothing unless
2450 # history output logging is enabled.
2442 # history output logging is enabled.
2451 self.history_manager.store_output(self.execution_count)
2443 self.history_manager.store_output(self.execution_count)
2452 # Each cell is a *single* input, regardless of how many lines it has
2444 # Each cell is a *single* input, regardless of how many lines it has
2453 self.execution_count += 1
2445 self.execution_count += 1
2454
2446
2455 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2447 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2456 """Run a sequence of AST nodes. The execution mode depends on the
2448 """Run a sequence of AST nodes. The execution mode depends on the
2457 interactivity parameter.
2449 interactivity parameter.
2458
2450
2459 Parameters
2451 Parameters
2460 ----------
2452 ----------
2461 nodelist : list
2453 nodelist : list
2462 A sequence of AST nodes to run.
2454 A sequence of AST nodes to run.
2463 cell_name : str
2455 cell_name : str
2464 Will be passed to the compiler as the filename of the cell. Typically
2456 Will be passed to the compiler as the filename of the cell. Typically
2465 the value returned by ip.compile.cache(cell).
2457 the value returned by ip.compile.cache(cell).
2466 interactivity : str
2458 interactivity : str
2467 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2459 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2468 run interactively (displaying output from expressions). 'last_expr'
2460 run interactively (displaying output from expressions). 'last_expr'
2469 will run the last node interactively only if it is an expression (i.e.
2461 will run the last node interactively only if it is an expression (i.e.
2470 expressions in loops or other blocks are not displayed. Other values
2462 expressions in loops or other blocks are not displayed. Other values
2471 for this parameter will raise a ValueError.
2463 for this parameter will raise a ValueError.
2472 """
2464 """
2473 if not nodelist:
2465 if not nodelist:
2474 return
2466 return
2475
2467
2476 if interactivity == 'last_expr':
2468 if interactivity == 'last_expr':
2477 if isinstance(nodelist[-1], ast.Expr):
2469 if isinstance(nodelist[-1], ast.Expr):
2478 interactivity = "last"
2470 interactivity = "last"
2479 else:
2471 else:
2480 interactivity = "none"
2472 interactivity = "none"
2481
2473
2482 if interactivity == 'none':
2474 if interactivity == 'none':
2483 to_run_exec, to_run_interactive = nodelist, []
2475 to_run_exec, to_run_interactive = nodelist, []
2484 elif interactivity == 'last':
2476 elif interactivity == 'last':
2485 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2477 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2486 elif interactivity == 'all':
2478 elif interactivity == 'all':
2487 to_run_exec, to_run_interactive = [], nodelist
2479 to_run_exec, to_run_interactive = [], nodelist
2488 else:
2480 else:
2489 raise ValueError("Interactivity was %r" % interactivity)
2481 raise ValueError("Interactivity was %r" % interactivity)
2490
2482
2491 exec_count = self.execution_count
2483 exec_count = self.execution_count
2492
2484
2493 try:
2485 try:
2494 for i, node in enumerate(to_run_exec):
2486 for i, node in enumerate(to_run_exec):
2495 mod = ast.Module([node])
2487 mod = ast.Module([node])
2496 code = self.compile(mod, cell_name, "exec")
2488 code = self.compile(mod, cell_name, "exec")
2497 if self.run_code(code):
2489 if self.run_code(code):
2498 return True
2490 return True
2499
2491
2500 for i, node in enumerate(to_run_interactive):
2492 for i, node in enumerate(to_run_interactive):
2501 mod = ast.Interactive([node])
2493 mod = ast.Interactive([node])
2502 code = self.compile(mod, cell_name, "single")
2494 code = self.compile(mod, cell_name, "single")
2503 if self.run_code(code):
2495 if self.run_code(code):
2504 return True
2496 return True
2505 except:
2497 except:
2506 # It's possible to have exceptions raised here, typically by
2498 # It's possible to have exceptions raised here, typically by
2507 # compilation of odd code (such as a naked 'return' outside a
2499 # compilation of odd code (such as a naked 'return' outside a
2508 # function) that did parse but isn't valid. Typically the exception
2500 # function) that did parse but isn't valid. Typically the exception
2509 # is a SyntaxError, but it's safest just to catch anything and show
2501 # is a SyntaxError, but it's safest just to catch anything and show
2510 # the user a traceback.
2502 # the user a traceback.
2511
2503
2512 # We do only one try/except outside the loop to minimize the impact
2504 # We do only one try/except outside the loop to minimize the impact
2513 # on runtime, and also because if any node in the node list is
2505 # on runtime, and also because if any node in the node list is
2514 # broken, we should stop execution completely.
2506 # broken, we should stop execution completely.
2515 self.showtraceback()
2507 self.showtraceback()
2516
2508
2517 return False
2509 return False
2518
2510
2519 def run_code(self, code_obj):
2511 def run_code(self, code_obj):
2520 """Execute a code object.
2512 """Execute a code object.
2521
2513
2522 When an exception occurs, self.showtraceback() is called to display a
2514 When an exception occurs, self.showtraceback() is called to display a
2523 traceback.
2515 traceback.
2524
2516
2525 Parameters
2517 Parameters
2526 ----------
2518 ----------
2527 code_obj : code object
2519 code_obj : code object
2528 A compiled code object, to be executed
2520 A compiled code object, to be executed
2529 post_execute : bool [default: True]
2521 post_execute : bool [default: True]
2530 whether to call post_execute hooks after this particular execution.
2522 whether to call post_execute hooks after this particular execution.
2531
2523
2532 Returns
2524 Returns
2533 -------
2525 -------
2534 False : successful execution.
2526 False : successful execution.
2535 True : an error occurred.
2527 True : an error occurred.
2536 """
2528 """
2537
2529
2538 # Set our own excepthook in case the user code tries to call it
2530 # Set our own excepthook in case the user code tries to call it
2539 # directly, so that the IPython crash handler doesn't get triggered
2531 # directly, so that the IPython crash handler doesn't get triggered
2540 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2532 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2541
2533
2542 # we save the original sys.excepthook in the instance, in case config
2534 # we save the original sys.excepthook in the instance, in case config
2543 # code (such as magics) needs access to it.
2535 # code (such as magics) needs access to it.
2544 self.sys_excepthook = old_excepthook
2536 self.sys_excepthook = old_excepthook
2545 outflag = 1 # happens in more places, so it's easier as default
2537 outflag = 1 # happens in more places, so it's easier as default
2546 try:
2538 try:
2547 try:
2539 try:
2548 self.hooks.pre_run_code_hook()
2540 self.hooks.pre_run_code_hook()
2549 #rprint('Running code', repr(code_obj)) # dbg
2541 #rprint('Running code', repr(code_obj)) # dbg
2550 exec code_obj in self.user_global_ns, self.user_ns
2542 exec code_obj in self.user_global_ns, self.user_ns
2551 finally:
2543 finally:
2552 # Reset our crash handler in place
2544 # Reset our crash handler in place
2553 sys.excepthook = old_excepthook
2545 sys.excepthook = old_excepthook
2554 except SystemExit:
2546 except SystemExit:
2555 self.showtraceback(exception_only=True)
2547 self.showtraceback(exception_only=True)
2556 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2548 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2557 except self.custom_exceptions:
2549 except self.custom_exceptions:
2558 etype,value,tb = sys.exc_info()
2550 etype,value,tb = sys.exc_info()
2559 self.CustomTB(etype,value,tb)
2551 self.CustomTB(etype,value,tb)
2560 except:
2552 except:
2561 self.showtraceback()
2553 self.showtraceback()
2562 else:
2554 else:
2563 outflag = 0
2555 outflag = 0
2564 if softspace(sys.stdout, 0):
2556 if softspace(sys.stdout, 0):
2565 print
2557 print
2566
2558
2567 return outflag
2559 return outflag
2568
2560
2569 # For backwards compatibility
2561 # For backwards compatibility
2570 runcode = run_code
2562 runcode = run_code
2571
2563
2572 #-------------------------------------------------------------------------
2564 #-------------------------------------------------------------------------
2573 # Things related to GUI support and pylab
2565 # Things related to GUI support and pylab
2574 #-------------------------------------------------------------------------
2566 #-------------------------------------------------------------------------
2575
2567
2576 def enable_gui(self, gui=None):
2568 def enable_gui(self, gui=None):
2577 raise NotImplementedError('Implement enable_gui in a subclass')
2569 raise NotImplementedError('Implement enable_gui in a subclass')
2578
2570
2579 def enable_pylab(self, gui=None, import_all=True):
2571 def enable_pylab(self, gui=None, import_all=True):
2580 """Activate pylab support at runtime.
2572 """Activate pylab support at runtime.
2581
2573
2582 This turns on support for matplotlib, preloads into the interactive
2574 This turns on support for matplotlib, preloads into the interactive
2583 namespace all of numpy and pylab, and configures IPython to correctly
2575 namespace all of numpy and pylab, and configures IPython to correctly
2584 interact with the GUI event loop. The GUI backend to be used can be
2576 interact with the GUI event loop. The GUI backend to be used can be
2585 optionally selected with the optional :param:`gui` argument.
2577 optionally selected with the optional :param:`gui` argument.
2586
2578
2587 Parameters
2579 Parameters
2588 ----------
2580 ----------
2589 gui : optional, string
2581 gui : optional, string
2590
2582
2591 If given, dictates the choice of matplotlib GUI backend to use
2583 If given, dictates the choice of matplotlib GUI backend to use
2592 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2584 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2593 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2585 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2594 matplotlib (as dictated by the matplotlib build-time options plus the
2586 matplotlib (as dictated by the matplotlib build-time options plus the
2595 user's matplotlibrc configuration file). Note that not all backends
2587 user's matplotlibrc configuration file). Note that not all backends
2596 make sense in all contexts, for example a terminal ipython can't
2588 make sense in all contexts, for example a terminal ipython can't
2597 display figures inline.
2589 display figures inline.
2598 """
2590 """
2599
2591
2600 # We want to prevent the loading of pylab to pollute the user's
2592 # We want to prevent the loading of pylab to pollute the user's
2601 # namespace as shown by the %who* magics, so we execute the activation
2593 # namespace as shown by the %who* magics, so we execute the activation
2602 # code in an empty namespace, and we update *both* user_ns and
2594 # code in an empty namespace, and we update *both* user_ns and
2603 # user_ns_hidden with this information.
2595 # user_ns_hidden with this information.
2604 ns = {}
2596 ns = {}
2605 try:
2597 try:
2606 gui = pylab_activate(ns, gui, import_all, self)
2598 gui = pylab_activate(ns, gui, import_all, self)
2607 except KeyError:
2599 except KeyError:
2608 error("Backend %r not supported" % gui)
2600 error("Backend %r not supported" % gui)
2609 return
2601 return
2610 self.user_ns.update(ns)
2602 self.user_ns.update(ns)
2611 self.user_ns_hidden.update(ns)
2603 self.user_ns_hidden.update(ns)
2612 # Now we must activate the gui pylab wants to use, and fix %run to take
2604 # Now we must activate the gui pylab wants to use, and fix %run to take
2613 # plot updates into account
2605 # plot updates into account
2614 self.enable_gui(gui)
2606 self.enable_gui(gui)
2615 self.magic_run = self._pylab_magic_run
2607 self.magic_run = self._pylab_magic_run
2616
2608
2617 #-------------------------------------------------------------------------
2609 #-------------------------------------------------------------------------
2618 # Utilities
2610 # Utilities
2619 #-------------------------------------------------------------------------
2611 #-------------------------------------------------------------------------
2620
2612
2621 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2613 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2622 """Expand python variables in a string.
2614 """Expand python variables in a string.
2623
2615
2624 The depth argument indicates how many frames above the caller should
2616 The depth argument indicates how many frames above the caller should
2625 be walked to look for the local namespace where to expand variables.
2617 be walked to look for the local namespace where to expand variables.
2626
2618
2627 The global namespace for expansion is always the user's interactive
2619 The global namespace for expansion is always the user's interactive
2628 namespace.
2620 namespace.
2629 """
2621 """
2630 ns = self.user_ns.copy()
2622 ns = self.user_ns.copy()
2631 ns.update(sys._getframe(depth+1).f_locals)
2623 ns.update(sys._getframe(depth+1).f_locals)
2632 ns.pop('self', None)
2624 ns.pop('self', None)
2633 return formatter.format(cmd, **ns)
2625 return formatter.format(cmd, **ns)
2634
2626
2635 def mktempfile(self, data=None, prefix='ipython_edit_'):
2627 def mktempfile(self, data=None, prefix='ipython_edit_'):
2636 """Make a new tempfile and return its filename.
2628 """Make a new tempfile and return its filename.
2637
2629
2638 This makes a call to tempfile.mktemp, but it registers the created
2630 This makes a call to tempfile.mktemp, but it registers the created
2639 filename internally so ipython cleans it up at exit time.
2631 filename internally so ipython cleans it up at exit time.
2640
2632
2641 Optional inputs:
2633 Optional inputs:
2642
2634
2643 - data(None): if data is given, it gets written out to the temp file
2635 - data(None): if data is given, it gets written out to the temp file
2644 immediately, and the file is closed again."""
2636 immediately, and the file is closed again."""
2645
2637
2646 filename = tempfile.mktemp('.py', prefix)
2638 filename = tempfile.mktemp('.py', prefix)
2647 self.tempfiles.append(filename)
2639 self.tempfiles.append(filename)
2648
2640
2649 if data:
2641 if data:
2650 tmp_file = open(filename,'w')
2642 tmp_file = open(filename,'w')
2651 tmp_file.write(data)
2643 tmp_file.write(data)
2652 tmp_file.close()
2644 tmp_file.close()
2653 return filename
2645 return filename
2654
2646
2655 # TODO: This should be removed when Term is refactored.
2647 # TODO: This should be removed when Term is refactored.
2656 def write(self,data):
2648 def write(self,data):
2657 """Write a string to the default output"""
2649 """Write a string to the default output"""
2658 io.stdout.write(data)
2650 io.stdout.write(data)
2659
2651
2660 # TODO: This should be removed when Term is refactored.
2652 # TODO: This should be removed when Term is refactored.
2661 def write_err(self,data):
2653 def write_err(self,data):
2662 """Write a string to the default error output"""
2654 """Write a string to the default error output"""
2663 io.stderr.write(data)
2655 io.stderr.write(data)
2664
2656
2665 def ask_yes_no(self, prompt, default=None):
2657 def ask_yes_no(self, prompt, default=None):
2666 if self.quiet:
2658 if self.quiet:
2667 return True
2659 return True
2668 return ask_yes_no(prompt,default)
2660 return ask_yes_no(prompt,default)
2669
2661
2670 def show_usage(self):
2662 def show_usage(self):
2671 """Show a usage message"""
2663 """Show a usage message"""
2672 page.page(IPython.core.usage.interactive_usage)
2664 page.page(IPython.core.usage.interactive_usage)
2673
2665
2674 def find_user_code(self, target, raw=True):
2666 def find_user_code(self, target, raw=True):
2675 """Get a code string from history, file, or a string or macro.
2667 """Get a code string from history, file, or a string or macro.
2676
2668
2677 This is mainly used by magic functions.
2669 This is mainly used by magic functions.
2678
2670
2679 Parameters
2671 Parameters
2680 ----------
2672 ----------
2681 target : str
2673 target : str
2682 A string specifying code to retrieve. This will be tried respectively
2674 A string specifying code to retrieve. This will be tried respectively
2683 as: ranges of input history (see %history for syntax), a filename, or
2675 as: ranges of input history (see %history for syntax), a filename, or
2684 an expression evaluating to a string or Macro in the user namespace.
2676 an expression evaluating to a string or Macro in the user namespace.
2685 raw : bool
2677 raw : bool
2686 If true (default), retrieve raw history. Has no effect on the other
2678 If true (default), retrieve raw history. Has no effect on the other
2687 retrieval mechanisms.
2679 retrieval mechanisms.
2688
2680
2689 Returns
2681 Returns
2690 -------
2682 -------
2691 A string of code.
2683 A string of code.
2692
2684
2693 ValueError is raised if nothing is found, and TypeError if it evaluates
2685 ValueError is raised if nothing is found, and TypeError if it evaluates
2694 to an object of another type. In each case, .args[0] is a printable
2686 to an object of another type. In each case, .args[0] is a printable
2695 message.
2687 message.
2696 """
2688 """
2697 code = self.extract_input_lines(target, raw=raw) # Grab history
2689 code = self.extract_input_lines(target, raw=raw) # Grab history
2698 if code:
2690 if code:
2699 return code
2691 return code
2700 if os.path.isfile(target): # Read file
2692 if os.path.isfile(target): # Read file
2701 return open(target, "r").read()
2693 return open(target, "r").read()
2702
2694
2703 try: # User namespace
2695 try: # User namespace
2704 codeobj = eval(target, self.user_ns)
2696 codeobj = eval(target, self.user_ns)
2705 except Exception:
2697 except Exception:
2706 raise ValueError(("'%s' was not found in history, as a file, nor in"
2698 raise ValueError(("'%s' was not found in history, as a file, nor in"
2707 " the user namespace.") % target)
2699 " the user namespace.") % target)
2708 if isinstance(codeobj, basestring):
2700 if isinstance(codeobj, basestring):
2709 return codeobj
2701 return codeobj
2710 elif isinstance(codeobj, Macro):
2702 elif isinstance(codeobj, Macro):
2711 return codeobj.value
2703 return codeobj.value
2712
2704
2713 raise TypeError("%s is neither a string nor a macro." % target,
2705 raise TypeError("%s is neither a string nor a macro." % target,
2714 codeobj)
2706 codeobj)
2715
2707
2716 #-------------------------------------------------------------------------
2708 #-------------------------------------------------------------------------
2717 # Things related to IPython exiting
2709 # Things related to IPython exiting
2718 #-------------------------------------------------------------------------
2710 #-------------------------------------------------------------------------
2719 def atexit_operations(self):
2711 def atexit_operations(self):
2720 """This will be executed at the time of exit.
2712 """This will be executed at the time of exit.
2721
2713
2722 Cleanup operations and saving of persistent data that is done
2714 Cleanup operations and saving of persistent data that is done
2723 unconditionally by IPython should be performed here.
2715 unconditionally by IPython should be performed here.
2724
2716
2725 For things that may depend on startup flags or platform specifics (such
2717 For things that may depend on startup flags or platform specifics (such
2726 as having readline or not), register a separate atexit function in the
2718 as having readline or not), register a separate atexit function in the
2727 code that has the appropriate information, rather than trying to
2719 code that has the appropriate information, rather than trying to
2728 clutter
2720 clutter
2729 """
2721 """
2730 # Close the history session (this stores the end time and line count)
2722 # Close the history session (this stores the end time and line count)
2731 # this must be *before* the tempfile cleanup, in case of temporary
2723 # this must be *before* the tempfile cleanup, in case of temporary
2732 # history db
2724 # history db
2733 self.history_manager.end_session()
2725 self.history_manager.end_session()
2734
2726
2735 # Cleanup all tempfiles left around
2727 # Cleanup all tempfiles left around
2736 for tfile in self.tempfiles:
2728 for tfile in self.tempfiles:
2737 try:
2729 try:
2738 os.unlink(tfile)
2730 os.unlink(tfile)
2739 except OSError:
2731 except OSError:
2740 pass
2732 pass
2741
2733
2742 # Clear all user namespaces to release all references cleanly.
2734 # Clear all user namespaces to release all references cleanly.
2743 self.reset(new_session=False)
2735 self.reset(new_session=False)
2744
2736
2745 # Run user hooks
2737 # Run user hooks
2746 self.hooks.shutdown_hook()
2738 self.hooks.shutdown_hook()
2747
2739
2748 def cleanup(self):
2740 def cleanup(self):
2749 self.restore_sys_module_state()
2741 self.restore_sys_module_state()
2750
2742
2751
2743
2752 class InteractiveShellABC(object):
2744 class InteractiveShellABC(object):
2753 """An abstract base class for InteractiveShell."""
2745 """An abstract base class for InteractiveShell."""
2754 __metaclass__ = abc.ABCMeta
2746 __metaclass__ = abc.ABCMeta
2755
2747
2756 InteractiveShellABC.register(InteractiveShell)
2748 InteractiveShellABC.register(InteractiveShell)
@@ -1,1249 +1,1245 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 ultratb.py -- Spice up your tracebacks!
3 ultratb.py -- Spice up your tracebacks!
4
4
5 * ColorTB
5 * ColorTB
6 I've always found it a bit hard to visually parse tracebacks in Python. The
6 I've always found it a bit hard to visually parse tracebacks in Python. The
7 ColorTB class is a solution to that problem. It colors the different parts of a
7 ColorTB class is a solution to that problem. It colors the different parts of a
8 traceback in a manner similar to what you would expect from a syntax-highlighting
8 traceback in a manner similar to what you would expect from a syntax-highlighting
9 text editor.
9 text editor.
10
10
11 Installation instructions for ColorTB:
11 Installation instructions for ColorTB:
12 import sys,ultratb
12 import sys,ultratb
13 sys.excepthook = ultratb.ColorTB()
13 sys.excepthook = ultratb.ColorTB()
14
14
15 * VerboseTB
15 * VerboseTB
16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
17 of useful info when a traceback occurs. Ping originally had it spit out HTML
17 of useful info when a traceback occurs. Ping originally had it spit out HTML
18 and intended it for CGI programmers, but why should they have all the fun? I
18 and intended it for CGI programmers, but why should they have all the fun? I
19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
20 but kind of neat, and maybe useful for long-running programs that you believe
20 but kind of neat, and maybe useful for long-running programs that you believe
21 are bug-free. If a crash *does* occur in that type of program you want details.
21 are bug-free. If a crash *does* occur in that type of program you want details.
22 Give it a shot--you'll love it or you'll hate it.
22 Give it a shot--you'll love it or you'll hate it.
23
23
24 Note:
24 Note:
25
25
26 The Verbose mode prints the variables currently visible where the exception
26 The Verbose mode prints the variables currently visible where the exception
27 happened (shortening their strings if too long). This can potentially be
27 happened (shortening their strings if too long). This can potentially be
28 very slow, if you happen to have a huge data structure whose string
28 very slow, if you happen to have a huge data structure whose string
29 representation is complex to compute. Your computer may appear to freeze for
29 representation is complex to compute. Your computer may appear to freeze for
30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
31 with Ctrl-C (maybe hitting it more than once).
31 with Ctrl-C (maybe hitting it more than once).
32
32
33 If you encounter this kind of situation often, you may want to use the
33 If you encounter this kind of situation often, you may want to use the
34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
35 variables (but otherwise includes the information and context given by
35 variables (but otherwise includes the information and context given by
36 Verbose).
36 Verbose).
37
37
38
38
39 Installation instructions for ColorTB:
39 Installation instructions for ColorTB:
40 import sys,ultratb
40 import sys,ultratb
41 sys.excepthook = ultratb.VerboseTB()
41 sys.excepthook = ultratb.VerboseTB()
42
42
43 Note: Much of the code in this module was lifted verbatim from the standard
43 Note: Much of the code in this module was lifted verbatim from the standard
44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
45
45
46 * Color schemes
46 * Color schemes
47 The colors are defined in the class TBTools through the use of the
47 The colors are defined in the class TBTools through the use of the
48 ColorSchemeTable class. Currently the following exist:
48 ColorSchemeTable class. Currently the following exist:
49
49
50 - NoColor: allows all of this module to be used in any terminal (the color
50 - NoColor: allows all of this module to be used in any terminal (the color
51 escapes are just dummy blank strings).
51 escapes are just dummy blank strings).
52
52
53 - Linux: is meant to look good in a terminal like the Linux console (black
53 - Linux: is meant to look good in a terminal like the Linux console (black
54 or very dark background).
54 or very dark background).
55
55
56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
57 in light background terminals.
57 in light background terminals.
58
58
59 You can implement other color schemes easily, the syntax is fairly
59 You can implement other color schemes easily, the syntax is fairly
60 self-explanatory. Please send back new schemes you develop to the author for
60 self-explanatory. Please send back new schemes you develop to the author for
61 possible inclusion in future releases.
61 possible inclusion in future releases.
62 """
62 """
63
63
64 #*****************************************************************************
64 #*****************************************************************************
65 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
65 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
66 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
66 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
67 #
67 #
68 # Distributed under the terms of the BSD License. The full license is in
68 # Distributed under the terms of the BSD License. The full license is in
69 # the file COPYING, distributed as part of this software.
69 # the file COPYING, distributed as part of this software.
70 #*****************************************************************************
70 #*****************************************************************************
71
71
72 from __future__ import with_statement
72 from __future__ import with_statement
73
73
74 import inspect
74 import inspect
75 import keyword
75 import keyword
76 import linecache
76 import linecache
77 import os
77 import os
78 import pydoc
78 import pydoc
79 import re
79 import re
80 import sys
80 import sys
81 import time
81 import time
82 import tokenize
82 import tokenize
83 import traceback
83 import traceback
84 import types
84 import types
85
85
86 try: # Python 2
86 try: # Python 2
87 generate_tokens = tokenize.generate_tokens
87 generate_tokens = tokenize.generate_tokens
88 except AttributeError: # Python 3
88 except AttributeError: # Python 3
89 generate_tokens = tokenize.tokenize
89 generate_tokens = tokenize.tokenize
90
90
91 # For purposes of monkeypatching inspect to fix a bug in it.
91 # For purposes of monkeypatching inspect to fix a bug in it.
92 from inspect import getsourcefile, getfile, getmodule,\
92 from inspect import getsourcefile, getfile, getmodule,\
93 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
93 ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode
94
94
95 # IPython's own modules
95 # IPython's own modules
96 # Modified pdb which doesn't damage IPython's readline handling
96 # Modified pdb which doesn't damage IPython's readline handling
97 from IPython.core import debugger, ipapi
97 from IPython.core import debugger, ipapi
98 from IPython.core.display_trap import DisplayTrap
98 from IPython.core.display_trap import DisplayTrap
99 from IPython.core.excolors import exception_colors
99 from IPython.core.excolors import exception_colors
100 from IPython.utils import PyColorize
100 from IPython.utils import PyColorize
101 from IPython.utils import io
101 from IPython.utils import io
102 from IPython.utils import py3compat
102 from IPython.utils import py3compat
103 from IPython.utils.data import uniq_stable
103 from IPython.utils.data import uniq_stable
104 from IPython.utils.warn import info, error
104 from IPython.utils.warn import info, error
105
105
106 # Globals
106 # Globals
107 # amount of space to put line numbers before verbose tracebacks
107 # amount of space to put line numbers before verbose tracebacks
108 INDENT_SIZE = 8
108 INDENT_SIZE = 8
109
109
110 # Default color scheme. This is used, for example, by the traceback
110 # Default color scheme. This is used, for example, by the traceback
111 # formatter. When running in an actual IPython instance, the user's rc.colors
111 # formatter. When running in an actual IPython instance, the user's rc.colors
112 # value is used, but havinga module global makes this functionality available
112 # value is used, but havinga module global makes this functionality available
113 # to users of ultratb who are NOT running inside ipython.
113 # to users of ultratb who are NOT running inside ipython.
114 DEFAULT_SCHEME = 'NoColor'
114 DEFAULT_SCHEME = 'NoColor'
115
115
116 #---------------------------------------------------------------------------
116 #---------------------------------------------------------------------------
117 # Code begins
117 # Code begins
118
118
119 # Utility functions
119 # Utility functions
120 def inspect_error():
120 def inspect_error():
121 """Print a message about internal inspect errors.
121 """Print a message about internal inspect errors.
122
122
123 These are unfortunately quite common."""
123 These are unfortunately quite common."""
124
124
125 error('Internal Python error in the inspect module.\n'
125 error('Internal Python error in the inspect module.\n'
126 'Below is the traceback from this internal error.\n')
126 'Below is the traceback from this internal error.\n')
127
127
128
128
129 def findsource(object):
129 def findsource(object):
130 """Return the entire source file and starting line number for an object.
130 """Return the entire source file and starting line number for an object.
131
131
132 The argument may be a module, class, method, function, traceback, frame,
132 The argument may be a module, class, method, function, traceback, frame,
133 or code object. The source code is returned as a list of all the lines
133 or code object. The source code is returned as a list of all the lines
134 in the file and the line number indexes a line in that list. An IOError
134 in the file and the line number indexes a line in that list. An IOError
135 is raised if the source code cannot be retrieved.
135 is raised if the source code cannot be retrieved.
136
136
137 FIXED version with which we monkeypatch the stdlib to work around a bug."""
137 FIXED version with which we monkeypatch the stdlib to work around a bug."""
138
138
139 file = getsourcefile(object) or getfile(object)
139 file = getsourcefile(object) or getfile(object)
140 # If the object is a frame, then trying to get the globals dict from its
140 # If the object is a frame, then trying to get the globals dict from its
141 # module won't work. Instead, the frame object itself has the globals
141 # module won't work. Instead, the frame object itself has the globals
142 # dictionary.
142 # dictionary.
143 globals_dict = None
143 globals_dict = None
144 if inspect.isframe(object):
144 if inspect.isframe(object):
145 # XXX: can this ever be false?
145 # XXX: can this ever be false?
146 globals_dict = object.f_globals
146 globals_dict = object.f_globals
147 else:
147 else:
148 module = getmodule(object, file)
148 module = getmodule(object, file)
149 if module:
149 if module:
150 globals_dict = module.__dict__
150 globals_dict = module.__dict__
151 lines = linecache.getlines(file, globals_dict)
151 lines = linecache.getlines(file, globals_dict)
152 if not lines:
152 if not lines:
153 raise IOError('could not get source code')
153 raise IOError('could not get source code')
154
154
155 if ismodule(object):
155 if ismodule(object):
156 return lines, 0
156 return lines, 0
157
157
158 if isclass(object):
158 if isclass(object):
159 name = object.__name__
159 name = object.__name__
160 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
160 pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
161 # make some effort to find the best matching class definition:
161 # make some effort to find the best matching class definition:
162 # use the one with the least indentation, which is the one
162 # use the one with the least indentation, which is the one
163 # that's most probably not inside a function definition.
163 # that's most probably not inside a function definition.
164 candidates = []
164 candidates = []
165 for i in range(len(lines)):
165 for i in range(len(lines)):
166 match = pat.match(lines[i])
166 match = pat.match(lines[i])
167 if match:
167 if match:
168 # if it's at toplevel, it's already the best one
168 # if it's at toplevel, it's already the best one
169 if lines[i][0] == 'c':
169 if lines[i][0] == 'c':
170 return lines, i
170 return lines, i
171 # else add whitespace to candidate list
171 # else add whitespace to candidate list
172 candidates.append((match.group(1), i))
172 candidates.append((match.group(1), i))
173 if candidates:
173 if candidates:
174 # this will sort by whitespace, and by line number,
174 # this will sort by whitespace, and by line number,
175 # less whitespace first
175 # less whitespace first
176 candidates.sort()
176 candidates.sort()
177 return lines, candidates[0][1]
177 return lines, candidates[0][1]
178 else:
178 else:
179 raise IOError('could not find class definition')
179 raise IOError('could not find class definition')
180
180
181 if ismethod(object):
181 if ismethod(object):
182 object = object.im_func
182 object = object.im_func
183 if isfunction(object):
183 if isfunction(object):
184 object = object.func_code
184 object = object.func_code
185 if istraceback(object):
185 if istraceback(object):
186 object = object.tb_frame
186 object = object.tb_frame
187 if isframe(object):
187 if isframe(object):
188 object = object.f_code
188 object = object.f_code
189 if iscode(object):
189 if iscode(object):
190 if not hasattr(object, 'co_firstlineno'):
190 if not hasattr(object, 'co_firstlineno'):
191 raise IOError('could not find function definition')
191 raise IOError('could not find function definition')
192 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
192 pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
193 pmatch = pat.match
193 pmatch = pat.match
194 # fperez - fix: sometimes, co_firstlineno can give a number larger than
194 # fperez - fix: sometimes, co_firstlineno can give a number larger than
195 # the length of lines, which causes an error. Safeguard against that.
195 # the length of lines, which causes an error. Safeguard against that.
196 lnum = min(object.co_firstlineno,len(lines))-1
196 lnum = min(object.co_firstlineno,len(lines))-1
197 while lnum > 0:
197 while lnum > 0:
198 if pmatch(lines[lnum]): break
198 if pmatch(lines[lnum]): break
199 lnum -= 1
199 lnum -= 1
200
200
201 return lines, lnum
201 return lines, lnum
202 raise IOError('could not find code object')
202 raise IOError('could not find code object')
203
203
204 # Monkeypatch inspect to apply our bugfix. This code only works with py25
204 # Monkeypatch inspect to apply our bugfix. This code only works with py25
205 if sys.version_info[:2] >= (2,5):
205 if sys.version_info[:2] >= (2,5):
206 inspect.findsource = findsource
206 inspect.findsource = findsource
207
207
208 def fix_frame_records_filenames(records):
208 def fix_frame_records_filenames(records):
209 """Try to fix the filenames in each record from inspect.getinnerframes().
209 """Try to fix the filenames in each record from inspect.getinnerframes().
210
210
211 Particularly, modules loaded from within zip files have useless filenames
211 Particularly, modules loaded from within zip files have useless filenames
212 attached to their code object, and inspect.getinnerframes() just uses it.
212 attached to their code object, and inspect.getinnerframes() just uses it.
213 """
213 """
214 fixed_records = []
214 fixed_records = []
215 for frame, filename, line_no, func_name, lines, index in records:
215 for frame, filename, line_no, func_name, lines, index in records:
216 # Look inside the frame's globals dictionary for __file__, which should
216 # Look inside the frame's globals dictionary for __file__, which should
217 # be better.
217 # be better.
218 better_fn = frame.f_globals.get('__file__', None)
218 better_fn = frame.f_globals.get('__file__', None)
219 if isinstance(better_fn, str):
219 if isinstance(better_fn, str):
220 # Check the type just in case someone did something weird with
220 # Check the type just in case someone did something weird with
221 # __file__. It might also be None if the error occurred during
221 # __file__. It might also be None if the error occurred during
222 # import.
222 # import.
223 filename = better_fn
223 filename = better_fn
224 fixed_records.append((frame, filename, line_no, func_name, lines, index))
224 fixed_records.append((frame, filename, line_no, func_name, lines, index))
225 return fixed_records
225 return fixed_records
226
226
227
227
228 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
228 def _fixed_getinnerframes(etb, context=1,tb_offset=0):
229 import linecache
229 import linecache
230 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
230 LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5
231
231
232 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
232 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
233
233
234 # If the error is at the console, don't build any context, since it would
234 # If the error is at the console, don't build any context, since it would
235 # otherwise produce 5 blank lines printed out (there is no file at the
235 # otherwise produce 5 blank lines printed out (there is no file at the
236 # console)
236 # console)
237 rec_check = records[tb_offset:]
237 rec_check = records[tb_offset:]
238 try:
238 try:
239 rname = rec_check[0][1]
239 rname = rec_check[0][1]
240 if rname == '<ipython console>' or rname.endswith('<string>'):
240 if rname == '<ipython console>' or rname.endswith('<string>'):
241 return rec_check
241 return rec_check
242 except IndexError:
242 except IndexError:
243 pass
243 pass
244
244
245 aux = traceback.extract_tb(etb)
245 aux = traceback.extract_tb(etb)
246 assert len(records) == len(aux)
246 assert len(records) == len(aux)
247 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
247 for i, (file, lnum, _, _) in zip(range(len(records)), aux):
248 maybeStart = lnum-1 - context//2
248 maybeStart = lnum-1 - context//2
249 start = max(maybeStart, 0)
249 start = max(maybeStart, 0)
250 end = start + context
250 end = start + context
251 lines = linecache.getlines(file)[start:end]
251 lines = linecache.getlines(file)[start:end]
252 buf = list(records[i])
252 buf = list(records[i])
253 buf[LNUM_POS] = lnum
253 buf[LNUM_POS] = lnum
254 buf[INDEX_POS] = lnum - 1 - start
254 buf[INDEX_POS] = lnum - 1 - start
255 buf[LINES_POS] = lines
255 buf[LINES_POS] = lines
256 records[i] = tuple(buf)
256 records[i] = tuple(buf)
257 return records[tb_offset:]
257 return records[tb_offset:]
258
258
259 # Helper function -- largely belongs to VerboseTB, but we need the same
259 # Helper function -- largely belongs to VerboseTB, but we need the same
260 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
260 # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they
261 # can be recognized properly by ipython.el's py-traceback-line-re
261 # can be recognized properly by ipython.el's py-traceback-line-re
262 # (SyntaxErrors have to be treated specially because they have no traceback)
262 # (SyntaxErrors have to be treated specially because they have no traceback)
263
263
264 _parser = PyColorize.Parser()
264 _parser = PyColorize.Parser()
265
265
266 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None):
266 def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None):
267 numbers_width = INDENT_SIZE - 1
267 numbers_width = INDENT_SIZE - 1
268 res = []
268 res = []
269 i = lnum - index
269 i = lnum - index
270
270
271 # This lets us get fully syntax-highlighted tracebacks.
271 # This lets us get fully syntax-highlighted tracebacks.
272 if scheme is None:
272 if scheme is None:
273 ipinst = ipapi.get()
273 ipinst = ipapi.get()
274 if ipinst is not None:
274 if ipinst is not None:
275 scheme = ipinst.colors
275 scheme = ipinst.colors
276 else:
276 else:
277 scheme = DEFAULT_SCHEME
277 scheme = DEFAULT_SCHEME
278
278
279 _line_format = _parser.format2
279 _line_format = _parser.format2
280
280
281 for line in lines:
281 for line in lines:
282 # FIXME: we need to ensure the source is a pure string at this point,
282 # FIXME: we need to ensure the source is a pure string at this point,
283 # else the coloring code makes a royal mess. This is in need of a
283 # else the coloring code makes a royal mess. This is in need of a
284 # serious refactoring, so that all of the ultratb and PyColorize code
284 # serious refactoring, so that all of the ultratb and PyColorize code
285 # is unicode-safe. So for now this is rather an ugly hack, but
285 # is unicode-safe. So for now this is rather an ugly hack, but
286 # necessary to at least have readable tracebacks. Improvements welcome!
286 # necessary to at least have readable tracebacks. Improvements welcome!
287 line = py3compat.cast_bytes_py2(line, 'utf-8')
287 line = py3compat.cast_bytes_py2(line, 'utf-8')
288
288
289 new_line, err = _line_format(line, 'str', scheme)
289 new_line, err = _line_format(line, 'str', scheme)
290 if not err: line = new_line
290 if not err: line = new_line
291
291
292 if i == lnum:
292 if i == lnum:
293 # This is the line with the error
293 # This is the line with the error
294 pad = numbers_width - len(str(i))
294 pad = numbers_width - len(str(i))
295 if pad >= 3:
295 if pad >= 3:
296 marker = '-'*(pad-3) + '-> '
296 marker = '-'*(pad-3) + '-> '
297 elif pad == 2:
297 elif pad == 2:
298 marker = '> '
298 marker = '> '
299 elif pad == 1:
299 elif pad == 1:
300 marker = '>'
300 marker = '>'
301 else:
301 else:
302 marker = ''
302 marker = ''
303 num = marker + str(i)
303 num = marker + str(i)
304 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
304 line = '%s%s%s %s%s' %(Colors.linenoEm, num,
305 Colors.line, line, Colors.Normal)
305 Colors.line, line, Colors.Normal)
306 else:
306 else:
307 num = '%*s' % (numbers_width,i)
307 num = '%*s' % (numbers_width,i)
308 line = '%s%s%s %s' %(Colors.lineno, num,
308 line = '%s%s%s %s' %(Colors.lineno, num,
309 Colors.Normal, line)
309 Colors.Normal, line)
310
310
311 res.append(line)
311 res.append(line)
312 if lvals and i == lnum:
312 if lvals and i == lnum:
313 res.append(lvals + '\n')
313 res.append(lvals + '\n')
314 i = i + 1
314 i = i + 1
315 return res
315 return res
316
316
317
317
318 #---------------------------------------------------------------------------
318 #---------------------------------------------------------------------------
319 # Module classes
319 # Module classes
320 class TBTools(object):
320 class TBTools(object):
321 """Basic tools used by all traceback printer classes."""
321 """Basic tools used by all traceback printer classes."""
322
322
323 # Number of frames to skip when reporting tracebacks
323 # Number of frames to skip when reporting tracebacks
324 tb_offset = 0
324 tb_offset = 0
325
325
326 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None):
326 def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None):
327 # Whether to call the interactive pdb debugger after printing
327 # Whether to call the interactive pdb debugger after printing
328 # tracebacks or not
328 # tracebacks or not
329 self.call_pdb = call_pdb
329 self.call_pdb = call_pdb
330
330
331 # Output stream to write to. Note that we store the original value in
331 # Output stream to write to. Note that we store the original value in
332 # a private attribute and then make the public ostream a property, so
332 # a private attribute and then make the public ostream a property, so
333 # that we can delay accessing io.stdout until runtime. The way
333 # that we can delay accessing io.stdout until runtime. The way
334 # things are written now, the io.stdout object is dynamically managed
334 # things are written now, the io.stdout object is dynamically managed
335 # so a reference to it should NEVER be stored statically. This
335 # so a reference to it should NEVER be stored statically. This
336 # property approach confines this detail to a single location, and all
336 # property approach confines this detail to a single location, and all
337 # subclasses can simply access self.ostream for writing.
337 # subclasses can simply access self.ostream for writing.
338 self._ostream = ostream
338 self._ostream = ostream
339
339
340 # Create color table
340 # Create color table
341 self.color_scheme_table = exception_colors()
341 self.color_scheme_table = exception_colors()
342
342
343 self.set_colors(color_scheme)
343 self.set_colors(color_scheme)
344 self.old_scheme = color_scheme # save initial value for toggles
344 self.old_scheme = color_scheme # save initial value for toggles
345
345
346 if call_pdb:
346 if call_pdb:
347 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
347 self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name)
348 else:
348 else:
349 self.pdb = None
349 self.pdb = None
350
350
351 def _get_ostream(self):
351 def _get_ostream(self):
352 """Output stream that exceptions are written to.
352 """Output stream that exceptions are written to.
353
353
354 Valid values are:
354 Valid values are:
355
355
356 - None: the default, which means that IPython will dynamically resolve
356 - None: the default, which means that IPython will dynamically resolve
357 to io.stdout. This ensures compatibility with most tools, including
357 to io.stdout. This ensures compatibility with most tools, including
358 Windows (where plain stdout doesn't recognize ANSI escapes).
358 Windows (where plain stdout doesn't recognize ANSI escapes).
359
359
360 - Any object with 'write' and 'flush' attributes.
360 - Any object with 'write' and 'flush' attributes.
361 """
361 """
362 return io.stdout if self._ostream is None else self._ostream
362 return io.stdout if self._ostream is None else self._ostream
363
363
364 def _set_ostream(self, val):
364 def _set_ostream(self, val):
365 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
365 assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
366 self._ostream = val
366 self._ostream = val
367
367
368 ostream = property(_get_ostream, _set_ostream)
368 ostream = property(_get_ostream, _set_ostream)
369
369
370 def set_colors(self,*args,**kw):
370 def set_colors(self,*args,**kw):
371 """Shorthand access to the color table scheme selector method."""
371 """Shorthand access to the color table scheme selector method."""
372
372
373 # Set own color table
373 # Set own color table
374 self.color_scheme_table.set_active_scheme(*args,**kw)
374 self.color_scheme_table.set_active_scheme(*args,**kw)
375 # for convenience, set Colors to the active scheme
375 # for convenience, set Colors to the active scheme
376 self.Colors = self.color_scheme_table.active_colors
376 self.Colors = self.color_scheme_table.active_colors
377 # Also set colors of debugger
377 # Also set colors of debugger
378 if hasattr(self,'pdb') and self.pdb is not None:
378 if hasattr(self,'pdb') and self.pdb is not None:
379 self.pdb.set_colors(*args,**kw)
379 self.pdb.set_colors(*args,**kw)
380
380
381 def color_toggle(self):
381 def color_toggle(self):
382 """Toggle between the currently active color scheme and NoColor."""
382 """Toggle between the currently active color scheme and NoColor."""
383
383
384 if self.color_scheme_table.active_scheme_name == 'NoColor':
384 if self.color_scheme_table.active_scheme_name == 'NoColor':
385 self.color_scheme_table.set_active_scheme(self.old_scheme)
385 self.color_scheme_table.set_active_scheme(self.old_scheme)
386 self.Colors = self.color_scheme_table.active_colors
386 self.Colors = self.color_scheme_table.active_colors
387 else:
387 else:
388 self.old_scheme = self.color_scheme_table.active_scheme_name
388 self.old_scheme = self.color_scheme_table.active_scheme_name
389 self.color_scheme_table.set_active_scheme('NoColor')
389 self.color_scheme_table.set_active_scheme('NoColor')
390 self.Colors = self.color_scheme_table.active_colors
390 self.Colors = self.color_scheme_table.active_colors
391
391
392 def stb2text(self, stb):
392 def stb2text(self, stb):
393 """Convert a structured traceback (a list) to a string."""
393 """Convert a structured traceback (a list) to a string."""
394 return '\n'.join(stb)
394 return '\n'.join(stb)
395
395
396 def text(self, etype, value, tb, tb_offset=None, context=5):
396 def text(self, etype, value, tb, tb_offset=None, context=5):
397 """Return formatted traceback.
397 """Return formatted traceback.
398
398
399 Subclasses may override this if they add extra arguments.
399 Subclasses may override this if they add extra arguments.
400 """
400 """
401 tb_list = self.structured_traceback(etype, value, tb,
401 tb_list = self.structured_traceback(etype, value, tb,
402 tb_offset, context)
402 tb_offset, context)
403 return self.stb2text(tb_list)
403 return self.stb2text(tb_list)
404
404
405 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
405 def structured_traceback(self, etype, evalue, tb, tb_offset=None,
406 context=5, mode=None):
406 context=5, mode=None):
407 """Return a list of traceback frames.
407 """Return a list of traceback frames.
408
408
409 Must be implemented by each class.
409 Must be implemented by each class.
410 """
410 """
411 raise NotImplementedError()
411 raise NotImplementedError()
412
412
413
413
414 #---------------------------------------------------------------------------
414 #---------------------------------------------------------------------------
415 class ListTB(TBTools):
415 class ListTB(TBTools):
416 """Print traceback information from a traceback list, with optional color.
416 """Print traceback information from a traceback list, with optional color.
417
417
418 Calling: requires 3 arguments:
418 Calling: requires 3 arguments:
419 (etype, evalue, elist)
419 (etype, evalue, elist)
420 as would be obtained by:
420 as would be obtained by:
421 etype, evalue, tb = sys.exc_info()
421 etype, evalue, tb = sys.exc_info()
422 if tb:
422 if tb:
423 elist = traceback.extract_tb(tb)
423 elist = traceback.extract_tb(tb)
424 else:
424 else:
425 elist = None
425 elist = None
426
426
427 It can thus be used by programs which need to process the traceback before
427 It can thus be used by programs which need to process the traceback before
428 printing (such as console replacements based on the code module from the
428 printing (such as console replacements based on the code module from the
429 standard library).
429 standard library).
430
430
431 Because they are meant to be called without a full traceback (only a
431 Because they are meant to be called without a full traceback (only a
432 list), instances of this class can't call the interactive pdb debugger."""
432 list), instances of this class can't call the interactive pdb debugger."""
433
433
434 def __init__(self,color_scheme = 'NoColor', call_pdb=False, ostream=None):
434 def __init__(self,color_scheme = 'NoColor', call_pdb=False, ostream=None):
435 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
435 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
436 ostream=ostream)
436 ostream=ostream)
437
437
438 def __call__(self, etype, value, elist):
438 def __call__(self, etype, value, elist):
439 self.ostream.flush()
439 self.ostream.flush()
440 self.ostream.write(self.text(etype, value, elist))
440 self.ostream.write(self.text(etype, value, elist))
441 self.ostream.write('\n')
441 self.ostream.write('\n')
442
442
443 def structured_traceback(self, etype, value, elist, tb_offset=None,
443 def structured_traceback(self, etype, value, elist, tb_offset=None,
444 context=5):
444 context=5):
445 """Return a color formatted string with the traceback info.
445 """Return a color formatted string with the traceback info.
446
446
447 Parameters
447 Parameters
448 ----------
448 ----------
449 etype : exception type
449 etype : exception type
450 Type of the exception raised.
450 Type of the exception raised.
451
451
452 value : object
452 value : object
453 Data stored in the exception
453 Data stored in the exception
454
454
455 elist : list
455 elist : list
456 List of frames, see class docstring for details.
456 List of frames, see class docstring for details.
457
457
458 tb_offset : int, optional
458 tb_offset : int, optional
459 Number of frames in the traceback to skip. If not given, the
459 Number of frames in the traceback to skip. If not given, the
460 instance value is used (set in constructor).
460 instance value is used (set in constructor).
461
461
462 context : int, optional
462 context : int, optional
463 Number of lines of context information to print.
463 Number of lines of context information to print.
464
464
465 Returns
465 Returns
466 -------
466 -------
467 String with formatted exception.
467 String with formatted exception.
468 """
468 """
469 tb_offset = self.tb_offset if tb_offset is None else tb_offset
469 tb_offset = self.tb_offset if tb_offset is None else tb_offset
470 Colors = self.Colors
470 Colors = self.Colors
471 out_list = []
471 out_list = []
472 if elist:
472 if elist:
473
473
474 if tb_offset and len(elist) > tb_offset:
474 if tb_offset and len(elist) > tb_offset:
475 elist = elist[tb_offset:]
475 elist = elist[tb_offset:]
476
476
477 out_list.append('Traceback %s(most recent call last)%s:' %
477 out_list.append('Traceback %s(most recent call last)%s:' %
478 (Colors.normalEm, Colors.Normal) + '\n')
478 (Colors.normalEm, Colors.Normal) + '\n')
479 out_list.extend(self._format_list(elist))
479 out_list.extend(self._format_list(elist))
480 # The exception info should be a single entry in the list.
480 # The exception info should be a single entry in the list.
481 lines = ''.join(self._format_exception_only(etype, value))
481 lines = ''.join(self._format_exception_only(etype, value))
482 out_list.append(lines)
482 out_list.append(lines)
483
483
484 # Note: this code originally read:
484 # Note: this code originally read:
485
485
486 ## for line in lines[:-1]:
486 ## for line in lines[:-1]:
487 ## out_list.append(" "+line)
487 ## out_list.append(" "+line)
488 ## out_list.append(lines[-1])
488 ## out_list.append(lines[-1])
489
489
490 # This means it was indenting everything but the last line by a little
490 # This means it was indenting everything but the last line by a little
491 # bit. I've disabled this for now, but if we see ugliness somewhre we
491 # bit. I've disabled this for now, but if we see ugliness somewhre we
492 # can restore it.
492 # can restore it.
493
493
494 return out_list
494 return out_list
495
495
496 def _format_list(self, extracted_list):
496 def _format_list(self, extracted_list):
497 """Format a list of traceback entry tuples for printing.
497 """Format a list of traceback entry tuples for printing.
498
498
499 Given a list of tuples as returned by extract_tb() or
499 Given a list of tuples as returned by extract_tb() or
500 extract_stack(), return a list of strings ready for printing.
500 extract_stack(), return a list of strings ready for printing.
501 Each string in the resulting list corresponds to the item with the
501 Each string in the resulting list corresponds to the item with the
502 same index in the argument list. Each string ends in a newline;
502 same index in the argument list. Each string ends in a newline;
503 the strings may contain internal newlines as well, for those items
503 the strings may contain internal newlines as well, for those items
504 whose source text line is not None.
504 whose source text line is not None.
505
505
506 Lifted almost verbatim from traceback.py
506 Lifted almost verbatim from traceback.py
507 """
507 """
508
508
509 Colors = self.Colors
509 Colors = self.Colors
510 list = []
510 list = []
511 for filename, lineno, name, line in extracted_list[:-1]:
511 for filename, lineno, name, line in extracted_list[:-1]:
512 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
512 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
513 (Colors.filename, filename, Colors.Normal,
513 (Colors.filename, filename, Colors.Normal,
514 Colors.lineno, lineno, Colors.Normal,
514 Colors.lineno, lineno, Colors.Normal,
515 Colors.name, name, Colors.Normal)
515 Colors.name, name, Colors.Normal)
516 if line:
516 if line:
517 item = item + ' %s\n' % line.strip()
517 item = item + ' %s\n' % line.strip()
518 list.append(item)
518 list.append(item)
519 # Emphasize the last entry
519 # Emphasize the last entry
520 filename, lineno, name, line = extracted_list[-1]
520 filename, lineno, name, line = extracted_list[-1]
521 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
521 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
522 (Colors.normalEm,
522 (Colors.normalEm,
523 Colors.filenameEm, filename, Colors.normalEm,
523 Colors.filenameEm, filename, Colors.normalEm,
524 Colors.linenoEm, lineno, Colors.normalEm,
524 Colors.linenoEm, lineno, Colors.normalEm,
525 Colors.nameEm, name, Colors.normalEm,
525 Colors.nameEm, name, Colors.normalEm,
526 Colors.Normal)
526 Colors.Normal)
527 if line:
527 if line:
528 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
528 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
529 Colors.Normal)
529 Colors.Normal)
530 list.append(item)
530 list.append(item)
531 #from pprint import pformat; print 'LISTTB', pformat(list) # dbg
531 #from pprint import pformat; print 'LISTTB', pformat(list) # dbg
532 return list
532 return list
533
533
534 def _format_exception_only(self, etype, value):
534 def _format_exception_only(self, etype, value):
535 """Format the exception part of a traceback.
535 """Format the exception part of a traceback.
536
536
537 The arguments are the exception type and value such as given by
537 The arguments are the exception type and value such as given by
538 sys.exc_info()[:2]. The return value is a list of strings, each ending
538 sys.exc_info()[:2]. The return value is a list of strings, each ending
539 in a newline. Normally, the list contains a single string; however,
539 in a newline. Normally, the list contains a single string; however,
540 for SyntaxError exceptions, it contains several lines that (when
540 for SyntaxError exceptions, it contains several lines that (when
541 printed) display detailed information about where the syntax error
541 printed) display detailed information about where the syntax error
542 occurred. The message indicating which exception occurred is the
542 occurred. The message indicating which exception occurred is the
543 always last string in the list.
543 always last string in the list.
544
544
545 Also lifted nearly verbatim from traceback.py
545 Also lifted nearly verbatim from traceback.py
546 """
546 """
547
547
548 have_filedata = False
548 have_filedata = False
549 Colors = self.Colors
549 Colors = self.Colors
550 list = []
550 list = []
551 try:
551 stype = Colors.excName + etype.__name__ + Colors.Normal
552 stype = Colors.excName + etype.__name__ + Colors.Normal
553 except AttributeError:
554 stype = etype # String exceptions don't get special coloring
555 if value is None:
552 if value is None:
553 # Not sure if this can still happen in Python 2.6 and above
556 list.append( str(stype) + '\n')
554 list.append( str(stype) + '\n')
557 else:
555 else:
558 if etype is SyntaxError:
556 if etype is SyntaxError:
559 try:
557 have_filedata = True
560 msg, (filename, lineno, offset, line) = value
558 #print 'filename is',filename # dbg
561 except:
559 if not value.filename: value.filename = "<string>"
562 have_filedata = False
560 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
563 else:
561 (Colors.normalEm,
564 have_filedata = True
562 Colors.filenameEm, value.filename, Colors.normalEm,
565 #print 'filename is',filename # dbg
563 Colors.linenoEm, value.lineno, Colors.Normal ))
566 if not filename: filename = "<string>"
564 if value.text is not None:
567 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
565 i = 0
568 (Colors.normalEm,
566 while i < len(value.text) and value.text[i].isspace():
569 Colors.filenameEm, filename, Colors.normalEm,
567 i = i+1
570 Colors.linenoEm, lineno, Colors.Normal ))
568 list.append('%s %s%s\n' % (Colors.line,
571 if line is not None:
569 value.text.strip(),
572 i = 0
570 Colors.Normal))
573 while i < len(line) and line[i].isspace():
571 if value.offset is not None:
574 i = i+1
572 s = ' '
575 list.append('%s %s%s\n' % (Colors.line,
573 for c in value.text[i:value.offset-1]:
576 line.strip(),
574 if c.isspace():
577 Colors.Normal))
575 s = s + c
578 if offset is not None:
576 else:
579 s = ' '
577 s = s + ' '
580 for c in line[i:offset-1]:
578 list.append('%s%s^%s\n' % (Colors.caret, s,
581 if c.isspace():
579 Colors.Normal) )
582 s = s + c
580
583 else:
581 try:
584 s = s + ' '
582 s = value.msg
585 list.append('%s%s^%s\n' % (Colors.caret, s,
583 except Exception:
586 Colors.Normal) )
584 s = self._some_str(value)
587 value = msg
588 s = self._some_str(value)
589 if s:
585 if s:
590 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
586 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
591 Colors.Normal, s))
587 Colors.Normal, s))
592 else:
588 else:
593 list.append('%s\n' % str(stype))
589 list.append('%s\n' % str(stype))
594
590
595 # sync with user hooks
591 # sync with user hooks
596 if have_filedata:
592 if have_filedata:
597 ipinst = ipapi.get()
593 ipinst = ipapi.get()
598 if ipinst is not None:
594 if ipinst is not None:
599 ipinst.hooks.synchronize_with_editor(filename, lineno, 0)
595 ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0)
600
596
601 return list
597 return list
602
598
603 def get_exception_only(self, etype, value):
599 def get_exception_only(self, etype, value):
604 """Only print the exception type and message, without a traceback.
600 """Only print the exception type and message, without a traceback.
605
601
606 Parameters
602 Parameters
607 ----------
603 ----------
608 etype : exception type
604 etype : exception type
609 value : exception value
605 value : exception value
610 """
606 """
611 return ListTB.structured_traceback(self, etype, value, [])
607 return ListTB.structured_traceback(self, etype, value, [])
612
608
613
609
614 def show_exception_only(self, etype, evalue):
610 def show_exception_only(self, etype, evalue):
615 """Only print the exception type and message, without a traceback.
611 """Only print the exception type and message, without a traceback.
616
612
617 Parameters
613 Parameters
618 ----------
614 ----------
619 etype : exception type
615 etype : exception type
620 value : exception value
616 value : exception value
621 """
617 """
622 # This method needs to use __call__ from *this* class, not the one from
618 # This method needs to use __call__ from *this* class, not the one from
623 # a subclass whose signature or behavior may be different
619 # a subclass whose signature or behavior may be different
624 ostream = self.ostream
620 ostream = self.ostream
625 ostream.flush()
621 ostream.flush()
626 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
622 ostream.write('\n'.join(self.get_exception_only(etype, evalue)))
627 ostream.flush()
623 ostream.flush()
628
624
629 def _some_str(self, value):
625 def _some_str(self, value):
630 # Lifted from traceback.py
626 # Lifted from traceback.py
631 try:
627 try:
632 return str(value)
628 return str(value)
633 except:
629 except:
634 return '<unprintable %s object>' % type(value).__name__
630 return '<unprintable %s object>' % type(value).__name__
635
631
636 #----------------------------------------------------------------------------
632 #----------------------------------------------------------------------------
637 class VerboseTB(TBTools):
633 class VerboseTB(TBTools):
638 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
634 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
639 of HTML. Requires inspect and pydoc. Crazy, man.
635 of HTML. Requires inspect and pydoc. Crazy, man.
640
636
641 Modified version which optionally strips the topmost entries from the
637 Modified version which optionally strips the topmost entries from the
642 traceback, to be used with alternate interpreters (because their own code
638 traceback, to be used with alternate interpreters (because their own code
643 would appear in the traceback)."""
639 would appear in the traceback)."""
644
640
645 def __init__(self,color_scheme = 'Linux', call_pdb=False, ostream=None,
641 def __init__(self,color_scheme = 'Linux', call_pdb=False, ostream=None,
646 tb_offset=0, long_header=False, include_vars=True,
642 tb_offset=0, long_header=False, include_vars=True,
647 check_cache=None):
643 check_cache=None):
648 """Specify traceback offset, headers and color scheme.
644 """Specify traceback offset, headers and color scheme.
649
645
650 Define how many frames to drop from the tracebacks. Calling it with
646 Define how many frames to drop from the tracebacks. Calling it with
651 tb_offset=1 allows use of this handler in interpreters which will have
647 tb_offset=1 allows use of this handler in interpreters which will have
652 their own code at the top of the traceback (VerboseTB will first
648 their own code at the top of the traceback (VerboseTB will first
653 remove that frame before printing the traceback info)."""
649 remove that frame before printing the traceback info)."""
654 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
650 TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
655 ostream=ostream)
651 ostream=ostream)
656 self.tb_offset = tb_offset
652 self.tb_offset = tb_offset
657 self.long_header = long_header
653 self.long_header = long_header
658 self.include_vars = include_vars
654 self.include_vars = include_vars
659 # By default we use linecache.checkcache, but the user can provide a
655 # By default we use linecache.checkcache, but the user can provide a
660 # different check_cache implementation. This is used by the IPython
656 # different check_cache implementation. This is used by the IPython
661 # kernel to provide tracebacks for interactive code that is cached,
657 # kernel to provide tracebacks for interactive code that is cached,
662 # by a compiler instance that flushes the linecache but preserves its
658 # by a compiler instance that flushes the linecache but preserves its
663 # own code cache.
659 # own code cache.
664 if check_cache is None:
660 if check_cache is None:
665 check_cache = linecache.checkcache
661 check_cache = linecache.checkcache
666 self.check_cache = check_cache
662 self.check_cache = check_cache
667
663
668 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
664 def structured_traceback(self, etype, evalue, etb, tb_offset=None,
669 context=5):
665 context=5):
670 """Return a nice text document describing the traceback."""
666 """Return a nice text document describing the traceback."""
671
667
672 tb_offset = self.tb_offset if tb_offset is None else tb_offset
668 tb_offset = self.tb_offset if tb_offset is None else tb_offset
673
669
674 # some locals
670 # some locals
675 try:
671 try:
676 etype = etype.__name__
672 etype = etype.__name__
677 except AttributeError:
673 except AttributeError:
678 pass
674 pass
679 Colors = self.Colors # just a shorthand + quicker name lookup
675 Colors = self.Colors # just a shorthand + quicker name lookup
680 ColorsNormal = Colors.Normal # used a lot
676 ColorsNormal = Colors.Normal # used a lot
681 col_scheme = self.color_scheme_table.active_scheme_name
677 col_scheme = self.color_scheme_table.active_scheme_name
682 indent = ' '*INDENT_SIZE
678 indent = ' '*INDENT_SIZE
683 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
679 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
684 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
680 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
685 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
681 exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal)
686
682
687 # some internal-use functions
683 # some internal-use functions
688 def text_repr(value):
684 def text_repr(value):
689 """Hopefully pretty robust repr equivalent."""
685 """Hopefully pretty robust repr equivalent."""
690 # this is pretty horrible but should always return *something*
686 # this is pretty horrible but should always return *something*
691 try:
687 try:
692 return pydoc.text.repr(value)
688 return pydoc.text.repr(value)
693 except KeyboardInterrupt:
689 except KeyboardInterrupt:
694 raise
690 raise
695 except:
691 except:
696 try:
692 try:
697 return repr(value)
693 return repr(value)
698 except KeyboardInterrupt:
694 except KeyboardInterrupt:
699 raise
695 raise
700 except:
696 except:
701 try:
697 try:
702 # all still in an except block so we catch
698 # all still in an except block so we catch
703 # getattr raising
699 # getattr raising
704 name = getattr(value, '__name__', None)
700 name = getattr(value, '__name__', None)
705 if name:
701 if name:
706 # ick, recursion
702 # ick, recursion
707 return text_repr(name)
703 return text_repr(name)
708 klass = getattr(value, '__class__', None)
704 klass = getattr(value, '__class__', None)
709 if klass:
705 if klass:
710 return '%s instance' % text_repr(klass)
706 return '%s instance' % text_repr(klass)
711 except KeyboardInterrupt:
707 except KeyboardInterrupt:
712 raise
708 raise
713 except:
709 except:
714 return 'UNRECOVERABLE REPR FAILURE'
710 return 'UNRECOVERABLE REPR FAILURE'
715 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
711 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
716 def nullrepr(value, repr=text_repr): return ''
712 def nullrepr(value, repr=text_repr): return ''
717
713
718 # meat of the code begins
714 # meat of the code begins
719 try:
715 try:
720 etype = etype.__name__
716 etype = etype.__name__
721 except AttributeError:
717 except AttributeError:
722 pass
718 pass
723
719
724 if self.long_header:
720 if self.long_header:
725 # Header with the exception type, python version, and date
721 # Header with the exception type, python version, and date
726 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
722 pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
727 date = time.ctime(time.time())
723 date = time.ctime(time.time())
728
724
729 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
725 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
730 exc, ' '*(75-len(str(etype))-len(pyver)),
726 exc, ' '*(75-len(str(etype))-len(pyver)),
731 pyver, date.rjust(75) )
727 pyver, date.rjust(75) )
732 head += "\nA problem occured executing Python code. Here is the sequence of function"\
728 head += "\nA problem occured executing Python code. Here is the sequence of function"\
733 "\ncalls leading up to the error, with the most recent (innermost) call last."
729 "\ncalls leading up to the error, with the most recent (innermost) call last."
734 else:
730 else:
735 # Simplified header
731 # Simplified header
736 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
732 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
737 'Traceback (most recent call last)'.\
733 'Traceback (most recent call last)'.\
738 rjust(75 - len(str(etype)) ) )
734 rjust(75 - len(str(etype)) ) )
739 frames = []
735 frames = []
740 # Flush cache before calling inspect. This helps alleviate some of the
736 # Flush cache before calling inspect. This helps alleviate some of the
741 # problems with python 2.3's inspect.py.
737 # problems with python 2.3's inspect.py.
742 ##self.check_cache()
738 ##self.check_cache()
743 # Drop topmost frames if requested
739 # Drop topmost frames if requested
744 try:
740 try:
745 # Try the default getinnerframes and Alex's: Alex's fixes some
741 # Try the default getinnerframes and Alex's: Alex's fixes some
746 # problems, but it generates empty tracebacks for console errors
742 # problems, but it generates empty tracebacks for console errors
747 # (5 blanks lines) where none should be returned.
743 # (5 blanks lines) where none should be returned.
748 #records = inspect.getinnerframes(etb, context)[tb_offset:]
744 #records = inspect.getinnerframes(etb, context)[tb_offset:]
749 #print 'python records:', records # dbg
745 #print 'python records:', records # dbg
750 records = _fixed_getinnerframes(etb, context, tb_offset)
746 records = _fixed_getinnerframes(etb, context, tb_offset)
751 #print 'alex records:', records # dbg
747 #print 'alex records:', records # dbg
752 except:
748 except:
753
749
754 # FIXME: I've been getting many crash reports from python 2.3
750 # FIXME: I've been getting many crash reports from python 2.3
755 # users, traceable to inspect.py. If I can find a small test-case
751 # users, traceable to inspect.py. If I can find a small test-case
756 # to reproduce this, I should either write a better workaround or
752 # to reproduce this, I should either write a better workaround or
757 # file a bug report against inspect (if that's the real problem).
753 # file a bug report against inspect (if that's the real problem).
758 # So far, I haven't been able to find an isolated example to
754 # So far, I haven't been able to find an isolated example to
759 # reproduce the problem.
755 # reproduce the problem.
760 inspect_error()
756 inspect_error()
761 traceback.print_exc(file=self.ostream)
757 traceback.print_exc(file=self.ostream)
762 info('\nUnfortunately, your original traceback can not be constructed.\n')
758 info('\nUnfortunately, your original traceback can not be constructed.\n')
763 return ''
759 return ''
764
760
765 # build some color string templates outside these nested loops
761 # build some color string templates outside these nested loops
766 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
762 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
767 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
763 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
768 ColorsNormal)
764 ColorsNormal)
769 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
765 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
770 (Colors.vName, Colors.valEm, ColorsNormal)
766 (Colors.vName, Colors.valEm, ColorsNormal)
771 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
767 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
772 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
768 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
773 Colors.vName, ColorsNormal)
769 Colors.vName, ColorsNormal)
774 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
770 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
775 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
771 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
776 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
772 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
777 ColorsNormal)
773 ColorsNormal)
778
774
779 # now, loop over all records printing context and info
775 # now, loop over all records printing context and info
780 abspath = os.path.abspath
776 abspath = os.path.abspath
781 for frame, file, lnum, func, lines, index in records:
777 for frame, file, lnum, func, lines, index in records:
782 #print '*** record:',file,lnum,func,lines,index # dbg
778 #print '*** record:',file,lnum,func,lines,index # dbg
783 try:
779 try:
784 file = file and abspath(file) or '?'
780 file = file and abspath(file) or '?'
785 except OSError:
781 except OSError:
786 # if file is '<console>' or something not in the filesystem,
782 # if file is '<console>' or something not in the filesystem,
787 # the abspath call will throw an OSError. Just ignore it and
783 # the abspath call will throw an OSError. Just ignore it and
788 # keep the original file string.
784 # keep the original file string.
789 pass
785 pass
790 link = tpl_link % file
786 link = tpl_link % file
791 try:
787 try:
792 args, varargs, varkw, locals = inspect.getargvalues(frame)
788 args, varargs, varkw, locals = inspect.getargvalues(frame)
793 except:
789 except:
794 # This can happen due to a bug in python2.3. We should be
790 # This can happen due to a bug in python2.3. We should be
795 # able to remove this try/except when 2.4 becomes a
791 # able to remove this try/except when 2.4 becomes a
796 # requirement. Bug details at http://python.org/sf/1005466
792 # requirement. Bug details at http://python.org/sf/1005466
797 inspect_error()
793 inspect_error()
798 traceback.print_exc(file=self.ostream)
794 traceback.print_exc(file=self.ostream)
799 info("\nIPython's exception reporting continues...\n")
795 info("\nIPython's exception reporting continues...\n")
800
796
801 if func == '?':
797 if func == '?':
802 call = ''
798 call = ''
803 else:
799 else:
804 # Decide whether to include variable details or not
800 # Decide whether to include variable details or not
805 var_repr = self.include_vars and eqrepr or nullrepr
801 var_repr = self.include_vars and eqrepr or nullrepr
806 try:
802 try:
807 call = tpl_call % (func,inspect.formatargvalues(args,
803 call = tpl_call % (func,inspect.formatargvalues(args,
808 varargs, varkw,
804 varargs, varkw,
809 locals,formatvalue=var_repr))
805 locals,formatvalue=var_repr))
810 except KeyError:
806 except KeyError:
811 # This happens in situations like errors inside generator
807 # This happens in situations like errors inside generator
812 # expressions, where local variables are listed in the
808 # expressions, where local variables are listed in the
813 # line, but can't be extracted from the frame. I'm not
809 # line, but can't be extracted from the frame. I'm not
814 # 100% sure this isn't actually a bug in inspect itself,
810 # 100% sure this isn't actually a bug in inspect itself,
815 # but since there's no info for us to compute with, the
811 # but since there's no info for us to compute with, the
816 # best we can do is report the failure and move on. Here
812 # best we can do is report the failure and move on. Here
817 # we must *not* call any traceback construction again,
813 # we must *not* call any traceback construction again,
818 # because that would mess up use of %debug later on. So we
814 # because that would mess up use of %debug later on. So we
819 # simply report the failure and move on. The only
815 # simply report the failure and move on. The only
820 # limitation will be that this frame won't have locals
816 # limitation will be that this frame won't have locals
821 # listed in the call signature. Quite subtle problem...
817 # listed in the call signature. Quite subtle problem...
822 # I can't think of a good way to validate this in a unit
818 # I can't think of a good way to validate this in a unit
823 # test, but running a script consisting of:
819 # test, but running a script consisting of:
824 # dict( (k,v.strip()) for (k,v) in range(10) )
820 # dict( (k,v.strip()) for (k,v) in range(10) )
825 # will illustrate the error, if this exception catch is
821 # will illustrate the error, if this exception catch is
826 # disabled.
822 # disabled.
827 call = tpl_call_fail % func
823 call = tpl_call_fail % func
828
824
829 # Initialize a list of names on the current line, which the
825 # Initialize a list of names on the current line, which the
830 # tokenizer below will populate.
826 # tokenizer below will populate.
831 names = []
827 names = []
832
828
833 def tokeneater(token_type, token, start, end, line):
829 def tokeneater(token_type, token, start, end, line):
834 """Stateful tokeneater which builds dotted names.
830 """Stateful tokeneater which builds dotted names.
835
831
836 The list of names it appends to (from the enclosing scope) can
832 The list of names it appends to (from the enclosing scope) can
837 contain repeated composite names. This is unavoidable, since
833 contain repeated composite names. This is unavoidable, since
838 there is no way to disambguate partial dotted structures until
834 there is no way to disambguate partial dotted structures until
839 the full list is known. The caller is responsible for pruning
835 the full list is known. The caller is responsible for pruning
840 the final list of duplicates before using it."""
836 the final list of duplicates before using it."""
841
837
842 # build composite names
838 # build composite names
843 if token == '.':
839 if token == '.':
844 try:
840 try:
845 names[-1] += '.'
841 names[-1] += '.'
846 # store state so the next token is added for x.y.z names
842 # store state so the next token is added for x.y.z names
847 tokeneater.name_cont = True
843 tokeneater.name_cont = True
848 return
844 return
849 except IndexError:
845 except IndexError:
850 pass
846 pass
851 if token_type == tokenize.NAME and token not in keyword.kwlist:
847 if token_type == tokenize.NAME and token not in keyword.kwlist:
852 if tokeneater.name_cont:
848 if tokeneater.name_cont:
853 # Dotted names
849 # Dotted names
854 names[-1] += token
850 names[-1] += token
855 tokeneater.name_cont = False
851 tokeneater.name_cont = False
856 else:
852 else:
857 # Regular new names. We append everything, the caller
853 # Regular new names. We append everything, the caller
858 # will be responsible for pruning the list later. It's
854 # will be responsible for pruning the list later. It's
859 # very tricky to try to prune as we go, b/c composite
855 # very tricky to try to prune as we go, b/c composite
860 # names can fool us. The pruning at the end is easy
856 # names can fool us. The pruning at the end is easy
861 # to do (or the caller can print a list with repeated
857 # to do (or the caller can print a list with repeated
862 # names if so desired.
858 # names if so desired.
863 names.append(token)
859 names.append(token)
864 elif token_type == tokenize.NEWLINE:
860 elif token_type == tokenize.NEWLINE:
865 raise IndexError
861 raise IndexError
866 # we need to store a bit of state in the tokenizer to build
862 # we need to store a bit of state in the tokenizer to build
867 # dotted names
863 # dotted names
868 tokeneater.name_cont = False
864 tokeneater.name_cont = False
869
865
870 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
866 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
871 line = getline(file, lnum[0])
867 line = getline(file, lnum[0])
872 lnum[0] += 1
868 lnum[0] += 1
873 return line
869 return line
874
870
875 # Build the list of names on this line of code where the exception
871 # Build the list of names on this line of code where the exception
876 # occurred.
872 # occurred.
877 try:
873 try:
878 # This builds the names list in-place by capturing it from the
874 # This builds the names list in-place by capturing it from the
879 # enclosing scope.
875 # enclosing scope.
880 for token in generate_tokens(linereader):
876 for token in generate_tokens(linereader):
881 tokeneater(*token)
877 tokeneater(*token)
882 except (IndexError, UnicodeDecodeError):
878 except (IndexError, UnicodeDecodeError):
883 # signals exit of tokenizer
879 # signals exit of tokenizer
884 pass
880 pass
885 except tokenize.TokenError,msg:
881 except tokenize.TokenError,msg:
886 _m = ("An unexpected error occurred while tokenizing input\n"
882 _m = ("An unexpected error occurred while tokenizing input\n"
887 "The following traceback may be corrupted or invalid\n"
883 "The following traceback may be corrupted or invalid\n"
888 "The error message is: %s\n" % msg)
884 "The error message is: %s\n" % msg)
889 error(_m)
885 error(_m)
890
886
891 # prune names list of duplicates, but keep the right order
887 # prune names list of duplicates, but keep the right order
892 unique_names = uniq_stable(names)
888 unique_names = uniq_stable(names)
893
889
894 # Start loop over vars
890 # Start loop over vars
895 lvals = []
891 lvals = []
896 if self.include_vars:
892 if self.include_vars:
897 for name_full in unique_names:
893 for name_full in unique_names:
898 name_base = name_full.split('.',1)[0]
894 name_base = name_full.split('.',1)[0]
899 if name_base in frame.f_code.co_varnames:
895 if name_base in frame.f_code.co_varnames:
900 if locals.has_key(name_base):
896 if locals.has_key(name_base):
901 try:
897 try:
902 value = repr(eval(name_full,locals))
898 value = repr(eval(name_full,locals))
903 except:
899 except:
904 value = undefined
900 value = undefined
905 else:
901 else:
906 value = undefined
902 value = undefined
907 name = tpl_local_var % name_full
903 name = tpl_local_var % name_full
908 else:
904 else:
909 if frame.f_globals.has_key(name_base):
905 if frame.f_globals.has_key(name_base):
910 try:
906 try:
911 value = repr(eval(name_full,frame.f_globals))
907 value = repr(eval(name_full,frame.f_globals))
912 except:
908 except:
913 value = undefined
909 value = undefined
914 else:
910 else:
915 value = undefined
911 value = undefined
916 name = tpl_global_var % name_full
912 name = tpl_global_var % name_full
917 lvals.append(tpl_name_val % (name,value))
913 lvals.append(tpl_name_val % (name,value))
918 if lvals:
914 if lvals:
919 lvals = '%s%s' % (indent,em_normal.join(lvals))
915 lvals = '%s%s' % (indent,em_normal.join(lvals))
920 else:
916 else:
921 lvals = ''
917 lvals = ''
922
918
923 level = '%s %s\n' % (link,call)
919 level = '%s %s\n' % (link,call)
924
920
925 if index is None:
921 if index is None:
926 frames.append(level)
922 frames.append(level)
927 else:
923 else:
928 frames.append('%s%s' % (level,''.join(
924 frames.append('%s%s' % (level,''.join(
929 _format_traceback_lines(lnum,index,lines,Colors,lvals,
925 _format_traceback_lines(lnum,index,lines,Colors,lvals,
930 col_scheme))))
926 col_scheme))))
931
927
932 # Get (safely) a string form of the exception info
928 # Get (safely) a string form of the exception info
933 try:
929 try:
934 etype_str,evalue_str = map(str,(etype,evalue))
930 etype_str,evalue_str = map(str,(etype,evalue))
935 except:
931 except:
936 # User exception is improperly defined.
932 # User exception is improperly defined.
937 etype,evalue = str,sys.exc_info()[:2]
933 etype,evalue = str,sys.exc_info()[:2]
938 etype_str,evalue_str = map(str,(etype,evalue))
934 etype_str,evalue_str = map(str,(etype,evalue))
939 # ... and format it
935 # ... and format it
940 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
936 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
941 ColorsNormal, evalue_str)]
937 ColorsNormal, evalue_str)]
942 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
938 if (not py3compat.PY3) and type(evalue) is types.InstanceType:
943 try:
939 try:
944 names = [w for w in dir(evalue) if isinstance(w, basestring)]
940 names = [w for w in dir(evalue) if isinstance(w, basestring)]
945 except:
941 except:
946 # Every now and then, an object with funny inernals blows up
942 # Every now and then, an object with funny inernals blows up
947 # when dir() is called on it. We do the best we can to report
943 # when dir() is called on it. We do the best we can to report
948 # the problem and continue
944 # the problem and continue
949 _m = '%sException reporting error (object with broken dir())%s:'
945 _m = '%sException reporting error (object with broken dir())%s:'
950 exception.append(_m % (Colors.excName,ColorsNormal))
946 exception.append(_m % (Colors.excName,ColorsNormal))
951 etype_str,evalue_str = map(str,sys.exc_info()[:2])
947 etype_str,evalue_str = map(str,sys.exc_info()[:2])
952 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
948 exception.append('%s%s%s: %s' % (Colors.excName,etype_str,
953 ColorsNormal, evalue_str))
949 ColorsNormal, evalue_str))
954 names = []
950 names = []
955 for name in names:
951 for name in names:
956 value = text_repr(getattr(evalue, name))
952 value = text_repr(getattr(evalue, name))
957 exception.append('\n%s%s = %s' % (indent, name, value))
953 exception.append('\n%s%s = %s' % (indent, name, value))
958
954
959 # vds: >>
955 # vds: >>
960 if records:
956 if records:
961 filepath, lnum = records[-1][1:3]
957 filepath, lnum = records[-1][1:3]
962 #print "file:", str(file), "linenb", str(lnum) # dbg
958 #print "file:", str(file), "linenb", str(lnum) # dbg
963 filepath = os.path.abspath(filepath)
959 filepath = os.path.abspath(filepath)
964 ipinst = ipapi.get()
960 ipinst = ipapi.get()
965 if ipinst is not None:
961 if ipinst is not None:
966 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
962 ipinst.hooks.synchronize_with_editor(filepath, lnum, 0)
967 # vds: <<
963 # vds: <<
968
964
969 # return all our info assembled as a single string
965 # return all our info assembled as a single string
970 # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
966 # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
971 return [head] + frames + [''.join(exception[0])]
967 return [head] + frames + [''.join(exception[0])]
972
968
973 def debugger(self,force=False):
969 def debugger(self,force=False):
974 """Call up the pdb debugger if desired, always clean up the tb
970 """Call up the pdb debugger if desired, always clean up the tb
975 reference.
971 reference.
976
972
977 Keywords:
973 Keywords:
978
974
979 - force(False): by default, this routine checks the instance call_pdb
975 - force(False): by default, this routine checks the instance call_pdb
980 flag and does not actually invoke the debugger if the flag is false.
976 flag and does not actually invoke the debugger if the flag is false.
981 The 'force' option forces the debugger to activate even if the flag
977 The 'force' option forces the debugger to activate even if the flag
982 is false.
978 is false.
983
979
984 If the call_pdb flag is set, the pdb interactive debugger is
980 If the call_pdb flag is set, the pdb interactive debugger is
985 invoked. In all cases, the self.tb reference to the current traceback
981 invoked. In all cases, the self.tb reference to the current traceback
986 is deleted to prevent lingering references which hamper memory
982 is deleted to prevent lingering references which hamper memory
987 management.
983 management.
988
984
989 Note that each call to pdb() does an 'import readline', so if your app
985 Note that each call to pdb() does an 'import readline', so if your app
990 requires a special setup for the readline completers, you'll have to
986 requires a special setup for the readline completers, you'll have to
991 fix that by hand after invoking the exception handler."""
987 fix that by hand after invoking the exception handler."""
992
988
993 if force or self.call_pdb:
989 if force or self.call_pdb:
994 if self.pdb is None:
990 if self.pdb is None:
995 self.pdb = debugger.Pdb(
991 self.pdb = debugger.Pdb(
996 self.color_scheme_table.active_scheme_name)
992 self.color_scheme_table.active_scheme_name)
997 # the system displayhook may have changed, restore the original
993 # the system displayhook may have changed, restore the original
998 # for pdb
994 # for pdb
999 display_trap = DisplayTrap(hook=sys.__displayhook__)
995 display_trap = DisplayTrap(hook=sys.__displayhook__)
1000 with display_trap:
996 with display_trap:
1001 self.pdb.reset()
997 self.pdb.reset()
1002 # Find the right frame so we don't pop up inside ipython itself
998 # Find the right frame so we don't pop up inside ipython itself
1003 if hasattr(self,'tb') and self.tb is not None:
999 if hasattr(self,'tb') and self.tb is not None:
1004 etb = self.tb
1000 etb = self.tb
1005 else:
1001 else:
1006 etb = self.tb = sys.last_traceback
1002 etb = self.tb = sys.last_traceback
1007 while self.tb is not None and self.tb.tb_next is not None:
1003 while self.tb is not None and self.tb.tb_next is not None:
1008 self.tb = self.tb.tb_next
1004 self.tb = self.tb.tb_next
1009 if etb and etb.tb_next:
1005 if etb and etb.tb_next:
1010 etb = etb.tb_next
1006 etb = etb.tb_next
1011 self.pdb.botframe = etb.tb_frame
1007 self.pdb.botframe = etb.tb_frame
1012 self.pdb.interaction(self.tb.tb_frame, self.tb)
1008 self.pdb.interaction(self.tb.tb_frame, self.tb)
1013
1009
1014 if hasattr(self,'tb'):
1010 if hasattr(self,'tb'):
1015 del self.tb
1011 del self.tb
1016
1012
1017 def handler(self, info=None):
1013 def handler(self, info=None):
1018 (etype, evalue, etb) = info or sys.exc_info()
1014 (etype, evalue, etb) = info or sys.exc_info()
1019 self.tb = etb
1015 self.tb = etb
1020 ostream = self.ostream
1016 ostream = self.ostream
1021 ostream.flush()
1017 ostream.flush()
1022 ostream.write(self.text(etype, evalue, etb))
1018 ostream.write(self.text(etype, evalue, etb))
1023 ostream.write('\n')
1019 ostream.write('\n')
1024 ostream.flush()
1020 ostream.flush()
1025
1021
1026 # Changed so an instance can just be called as VerboseTB_inst() and print
1022 # Changed so an instance can just be called as VerboseTB_inst() and print
1027 # out the right info on its own.
1023 # out the right info on its own.
1028 def __call__(self, etype=None, evalue=None, etb=None):
1024 def __call__(self, etype=None, evalue=None, etb=None):
1029 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1025 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
1030 if etb is None:
1026 if etb is None:
1031 self.handler()
1027 self.handler()
1032 else:
1028 else:
1033 self.handler((etype, evalue, etb))
1029 self.handler((etype, evalue, etb))
1034 try:
1030 try:
1035 self.debugger()
1031 self.debugger()
1036 except KeyboardInterrupt:
1032 except KeyboardInterrupt:
1037 print "\nKeyboardInterrupt"
1033 print "\nKeyboardInterrupt"
1038
1034
1039 #----------------------------------------------------------------------------
1035 #----------------------------------------------------------------------------
1040 class FormattedTB(VerboseTB, ListTB):
1036 class FormattedTB(VerboseTB, ListTB):
1041 """Subclass ListTB but allow calling with a traceback.
1037 """Subclass ListTB but allow calling with a traceback.
1042
1038
1043 It can thus be used as a sys.excepthook for Python > 2.1.
1039 It can thus be used as a sys.excepthook for Python > 2.1.
1044
1040
1045 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1041 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
1046
1042
1047 Allows a tb_offset to be specified. This is useful for situations where
1043 Allows a tb_offset to be specified. This is useful for situations where
1048 one needs to remove a number of topmost frames from the traceback (such as
1044 one needs to remove a number of topmost frames from the traceback (such as
1049 occurs with python programs that themselves execute other python code,
1045 occurs with python programs that themselves execute other python code,
1050 like Python shells). """
1046 like Python shells). """
1051
1047
1052 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1048 def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
1053 ostream=None,
1049 ostream=None,
1054 tb_offset=0, long_header=False, include_vars=False,
1050 tb_offset=0, long_header=False, include_vars=False,
1055 check_cache=None):
1051 check_cache=None):
1056
1052
1057 # NEVER change the order of this list. Put new modes at the end:
1053 # NEVER change the order of this list. Put new modes at the end:
1058 self.valid_modes = ['Plain','Context','Verbose']
1054 self.valid_modes = ['Plain','Context','Verbose']
1059 self.verbose_modes = self.valid_modes[1:3]
1055 self.verbose_modes = self.valid_modes[1:3]
1060
1056
1061 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1057 VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
1062 ostream=ostream, tb_offset=tb_offset,
1058 ostream=ostream, tb_offset=tb_offset,
1063 long_header=long_header, include_vars=include_vars,
1059 long_header=long_header, include_vars=include_vars,
1064 check_cache=check_cache)
1060 check_cache=check_cache)
1065
1061
1066 # Different types of tracebacks are joined with different separators to
1062 # Different types of tracebacks are joined with different separators to
1067 # form a single string. They are taken from this dict
1063 # form a single string. They are taken from this dict
1068 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1064 self._join_chars = dict(Plain='', Context='\n', Verbose='\n')
1069 # set_mode also sets the tb_join_char attribute
1065 # set_mode also sets the tb_join_char attribute
1070 self.set_mode(mode)
1066 self.set_mode(mode)
1071
1067
1072 def _extract_tb(self,tb):
1068 def _extract_tb(self,tb):
1073 if tb:
1069 if tb:
1074 return traceback.extract_tb(tb)
1070 return traceback.extract_tb(tb)
1075 else:
1071 else:
1076 return None
1072 return None
1077
1073
1078 def structured_traceback(self, etype, value, tb, tb_offset=None, context=5):
1074 def structured_traceback(self, etype, value, tb, tb_offset=None, context=5):
1079 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1075 tb_offset = self.tb_offset if tb_offset is None else tb_offset
1080 mode = self.mode
1076 mode = self.mode
1081 if mode in self.verbose_modes:
1077 if mode in self.verbose_modes:
1082 # Verbose modes need a full traceback
1078 # Verbose modes need a full traceback
1083 return VerboseTB.structured_traceback(
1079 return VerboseTB.structured_traceback(
1084 self, etype, value, tb, tb_offset, context
1080 self, etype, value, tb, tb_offset, context
1085 )
1081 )
1086 else:
1082 else:
1087 # We must check the source cache because otherwise we can print
1083 # We must check the source cache because otherwise we can print
1088 # out-of-date source code.
1084 # out-of-date source code.
1089 self.check_cache()
1085 self.check_cache()
1090 # Now we can extract and format the exception
1086 # Now we can extract and format the exception
1091 elist = self._extract_tb(tb)
1087 elist = self._extract_tb(tb)
1092 return ListTB.structured_traceback(
1088 return ListTB.structured_traceback(
1093 self, etype, value, elist, tb_offset, context
1089 self, etype, value, elist, tb_offset, context
1094 )
1090 )
1095
1091
1096 def stb2text(self, stb):
1092 def stb2text(self, stb):
1097 """Convert a structured traceback (a list) to a string."""
1093 """Convert a structured traceback (a list) to a string."""
1098 return self.tb_join_char.join(stb)
1094 return self.tb_join_char.join(stb)
1099
1095
1100
1096
1101 def set_mode(self,mode=None):
1097 def set_mode(self,mode=None):
1102 """Switch to the desired mode.
1098 """Switch to the desired mode.
1103
1099
1104 If mode is not specified, cycles through the available modes."""
1100 If mode is not specified, cycles through the available modes."""
1105
1101
1106 if not mode:
1102 if not mode:
1107 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
1103 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
1108 len(self.valid_modes)
1104 len(self.valid_modes)
1109 self.mode = self.valid_modes[new_idx]
1105 self.mode = self.valid_modes[new_idx]
1110 elif mode not in self.valid_modes:
1106 elif mode not in self.valid_modes:
1111 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
1107 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
1112 'Valid modes: '+str(self.valid_modes)
1108 'Valid modes: '+str(self.valid_modes)
1113 else:
1109 else:
1114 self.mode = mode
1110 self.mode = mode
1115 # include variable details only in 'Verbose' mode
1111 # include variable details only in 'Verbose' mode
1116 self.include_vars = (self.mode == self.valid_modes[2])
1112 self.include_vars = (self.mode == self.valid_modes[2])
1117 # Set the join character for generating text tracebacks
1113 # Set the join character for generating text tracebacks
1118 self.tb_join_char = self._join_chars[self.mode]
1114 self.tb_join_char = self._join_chars[self.mode]
1119
1115
1120 # some convenient shorcuts
1116 # some convenient shorcuts
1121 def plain(self):
1117 def plain(self):
1122 self.set_mode(self.valid_modes[0])
1118 self.set_mode(self.valid_modes[0])
1123
1119
1124 def context(self):
1120 def context(self):
1125 self.set_mode(self.valid_modes[1])
1121 self.set_mode(self.valid_modes[1])
1126
1122
1127 def verbose(self):
1123 def verbose(self):
1128 self.set_mode(self.valid_modes[2])
1124 self.set_mode(self.valid_modes[2])
1129
1125
1130 #----------------------------------------------------------------------------
1126 #----------------------------------------------------------------------------
1131 class AutoFormattedTB(FormattedTB):
1127 class AutoFormattedTB(FormattedTB):
1132 """A traceback printer which can be called on the fly.
1128 """A traceback printer which can be called on the fly.
1133
1129
1134 It will find out about exceptions by itself.
1130 It will find out about exceptions by itself.
1135
1131
1136 A brief example:
1132 A brief example:
1137
1133
1138 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1134 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
1139 try:
1135 try:
1140 ...
1136 ...
1141 except:
1137 except:
1142 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1138 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
1143 """
1139 """
1144
1140
1145 def __call__(self,etype=None,evalue=None,etb=None,
1141 def __call__(self,etype=None,evalue=None,etb=None,
1146 out=None,tb_offset=None):
1142 out=None,tb_offset=None):
1147 """Print out a formatted exception traceback.
1143 """Print out a formatted exception traceback.
1148
1144
1149 Optional arguments:
1145 Optional arguments:
1150 - out: an open file-like object to direct output to.
1146 - out: an open file-like object to direct output to.
1151
1147
1152 - tb_offset: the number of frames to skip over in the stack, on a
1148 - tb_offset: the number of frames to skip over in the stack, on a
1153 per-call basis (this overrides temporarily the instance's tb_offset
1149 per-call basis (this overrides temporarily the instance's tb_offset
1154 given at initialization time. """
1150 given at initialization time. """
1155
1151
1156
1152
1157 if out is None:
1153 if out is None:
1158 out = self.ostream
1154 out = self.ostream
1159 out.flush()
1155 out.flush()
1160 out.write(self.text(etype, evalue, etb, tb_offset))
1156 out.write(self.text(etype, evalue, etb, tb_offset))
1161 out.write('\n')
1157 out.write('\n')
1162 out.flush()
1158 out.flush()
1163 # FIXME: we should remove the auto pdb behavior from here and leave
1159 # FIXME: we should remove the auto pdb behavior from here and leave
1164 # that to the clients.
1160 # that to the clients.
1165 try:
1161 try:
1166 self.debugger()
1162 self.debugger()
1167 except KeyboardInterrupt:
1163 except KeyboardInterrupt:
1168 print "\nKeyboardInterrupt"
1164 print "\nKeyboardInterrupt"
1169
1165
1170 def structured_traceback(self, etype=None, value=None, tb=None,
1166 def structured_traceback(self, etype=None, value=None, tb=None,
1171 tb_offset=None, context=5):
1167 tb_offset=None, context=5):
1172 if etype is None:
1168 if etype is None:
1173 etype,value,tb = sys.exc_info()
1169 etype,value,tb = sys.exc_info()
1174 self.tb = tb
1170 self.tb = tb
1175 return FormattedTB.structured_traceback(
1171 return FormattedTB.structured_traceback(
1176 self, etype, value, tb, tb_offset, context)
1172 self, etype, value, tb, tb_offset, context)
1177
1173
1178 #---------------------------------------------------------------------------
1174 #---------------------------------------------------------------------------
1179
1175
1180 # A simple class to preserve Nathan's original functionality.
1176 # A simple class to preserve Nathan's original functionality.
1181 class ColorTB(FormattedTB):
1177 class ColorTB(FormattedTB):
1182 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1178 """Shorthand to initialize a FormattedTB in Linux colors mode."""
1183 def __init__(self,color_scheme='Linux',call_pdb=0):
1179 def __init__(self,color_scheme='Linux',call_pdb=0):
1184 FormattedTB.__init__(self,color_scheme=color_scheme,
1180 FormattedTB.__init__(self,color_scheme=color_scheme,
1185 call_pdb=call_pdb)
1181 call_pdb=call_pdb)
1186
1182
1187
1183
1188 class SyntaxTB(ListTB):
1184 class SyntaxTB(ListTB):
1189 """Extension which holds some state: the last exception value"""
1185 """Extension which holds some state: the last exception value"""
1190
1186
1191 def __init__(self,color_scheme = 'NoColor'):
1187 def __init__(self,color_scheme = 'NoColor'):
1192 ListTB.__init__(self,color_scheme)
1188 ListTB.__init__(self,color_scheme)
1193 self.last_syntax_error = None
1189 self.last_syntax_error = None
1194
1190
1195 def __call__(self, etype, value, elist):
1191 def __call__(self, etype, value, elist):
1196 self.last_syntax_error = value
1192 self.last_syntax_error = value
1197 ListTB.__call__(self,etype,value,elist)
1193 ListTB.__call__(self,etype,value,elist)
1198
1194
1199 def clear_err_state(self):
1195 def clear_err_state(self):
1200 """Return the current error state and clear it"""
1196 """Return the current error state and clear it"""
1201 e = self.last_syntax_error
1197 e = self.last_syntax_error
1202 self.last_syntax_error = None
1198 self.last_syntax_error = None
1203 return e
1199 return e
1204
1200
1205 def stb2text(self, stb):
1201 def stb2text(self, stb):
1206 """Convert a structured traceback (a list) to a string."""
1202 """Convert a structured traceback (a list) to a string."""
1207 return ''.join(stb)
1203 return ''.join(stb)
1208
1204
1209
1205
1210 #----------------------------------------------------------------------------
1206 #----------------------------------------------------------------------------
1211 # module testing (minimal)
1207 # module testing (minimal)
1212 if __name__ == "__main__":
1208 if __name__ == "__main__":
1213 def spam(c, (d, e)):
1209 def spam(c, (d, e)):
1214 x = c + d
1210 x = c + d
1215 y = c * d
1211 y = c * d
1216 foo(x, y)
1212 foo(x, y)
1217
1213
1218 def foo(a, b, bar=1):
1214 def foo(a, b, bar=1):
1219 eggs(a, b + bar)
1215 eggs(a, b + bar)
1220
1216
1221 def eggs(f, g, z=globals()):
1217 def eggs(f, g, z=globals()):
1222 h = f + g
1218 h = f + g
1223 i = f - g
1219 i = f - g
1224 return h / i
1220 return h / i
1225
1221
1226 print ''
1222 print ''
1227 print '*** Before ***'
1223 print '*** Before ***'
1228 try:
1224 try:
1229 print spam(1, (2, 3))
1225 print spam(1, (2, 3))
1230 except:
1226 except:
1231 traceback.print_exc()
1227 traceback.print_exc()
1232 print ''
1228 print ''
1233
1229
1234 handler = ColorTB()
1230 handler = ColorTB()
1235 print '*** ColorTB ***'
1231 print '*** ColorTB ***'
1236 try:
1232 try:
1237 print spam(1, (2, 3))
1233 print spam(1, (2, 3))
1238 except:
1234 except:
1239 apply(handler, sys.exc_info() )
1235 apply(handler, sys.exc_info() )
1240 print ''
1236 print ''
1241
1237
1242 handler = VerboseTB()
1238 handler = VerboseTB()
1243 print '*** VerboseTB ***'
1239 print '*** VerboseTB ***'
1244 try:
1240 try:
1245 print spam(1, (2, 3))
1241 print spam(1, (2, 3))
1246 except:
1242 except:
1247 apply(handler, sys.exc_info() )
1243 apply(handler, sys.exc_info() )
1248 print ''
1244 print ''
1249
1245
@@ -1,182 +1,179 b''
1 """Test suite for the irunner module.
1 """Test suite for the irunner module.
2
2
3 Not the most elegant or fine-grained, but it does cover at least the bulk
3 Not the most elegant or fine-grained, but it does cover at least the bulk
4 functionality."""
4 functionality."""
5
5
6 # Global to make tests extra verbose and help debugging
6 # Global to make tests extra verbose and help debugging
7 VERBOSE = True
7 VERBOSE = True
8
8
9 # stdlib imports
9 # stdlib imports
10 import StringIO
10 import StringIO
11 import sys
11 import sys
12 import unittest
12 import unittest
13
13
14 # IPython imports
14 # IPython imports
15 from IPython.lib import irunner
15 from IPython.lib import irunner
16 from IPython.testing.decorators import known_failure_py3
17 from IPython.utils.py3compat import doctest_refactor_print
16 from IPython.utils.py3compat import doctest_refactor_print
18
17
19 # Testing code begins
18 # Testing code begins
20 class RunnerTestCase(unittest.TestCase):
19 class RunnerTestCase(unittest.TestCase):
21
20
22 def setUp(self):
21 def setUp(self):
23 self.out = StringIO.StringIO()
22 self.out = StringIO.StringIO()
24 #self.out = sys.stdout
23 #self.out = sys.stdout
25
24
26 def _test_runner(self,runner,source,output):
25 def _test_runner(self,runner,source,output):
27 """Test that a given runner's input/output match."""
26 """Test that a given runner's input/output match."""
28
27
29 runner.run_source(source)
28 runner.run_source(source)
30 out = self.out.getvalue()
29 out = self.out.getvalue()
31 #out = ''
30 #out = ''
32 # this output contains nasty \r\n lineends, and the initial ipython
31 # this output contains nasty \r\n lineends, and the initial ipython
33 # banner. clean it up for comparison, removing lines of whitespace
32 # banner. clean it up for comparison, removing lines of whitespace
34 output_l = [l for l in output.splitlines() if l and not l.isspace()]
33 output_l = [l for l in output.splitlines() if l and not l.isspace()]
35 out_l = [l for l in out.splitlines() if l and not l.isspace()]
34 out_l = [l for l in out.splitlines() if l and not l.isspace()]
36 mismatch = 0
35 mismatch = 0
37 if len(output_l) != len(out_l):
36 if len(output_l) != len(out_l):
38 message = ("Mismatch in number of lines\n\n"
37 message = ("Mismatch in number of lines\n\n"
39 "Expected:\n"
38 "Expected:\n"
40 "~~~~~~~~~\n"
39 "~~~~~~~~~\n"
41 "%s\n\n"
40 "%s\n\n"
42 "Got:\n"
41 "Got:\n"
43 "~~~~~~~~~\n"
42 "~~~~~~~~~\n"
44 "%s"
43 "%s"
45 ) % ("\n".join(output_l), "\n".join(out_l))
44 ) % ("\n".join(output_l), "\n".join(out_l))
46 self.fail(message)
45 self.fail(message)
47 for n in range(len(output_l)):
46 for n in range(len(output_l)):
48 # Do a line-by-line comparison
47 # Do a line-by-line comparison
49 ol1 = output_l[n].strip()
48 ol1 = output_l[n].strip()
50 ol2 = out_l[n].strip()
49 ol2 = out_l[n].strip()
51 if ol1 != ol2:
50 if ol1 != ol2:
52 mismatch += 1
51 mismatch += 1
53 if VERBOSE:
52 if VERBOSE:
54 print '<<< line %s does not match:' % n
53 print '<<< line %s does not match:' % n
55 print repr(ol1)
54 print repr(ol1)
56 print repr(ol2)
55 print repr(ol2)
57 print '>>>'
56 print '>>>'
58 self.assert_(mismatch==0,'Number of mismatched lines: %s' %
57 self.assert_(mismatch==0,'Number of mismatched lines: %s' %
59 mismatch)
58 mismatch)
60
59
61 # The SyntaxError appears differently in Python 3, for some reason.
62 @known_failure_py3
63 def testIPython(self):
60 def testIPython(self):
64 """Test the IPython runner."""
61 """Test the IPython runner."""
65 source = doctest_refactor_print("""
62 source = doctest_refactor_print("""
66 print 'hello, this is python'
63 print 'hello, this is python'
67 # some more code
64 # some more code
68 x=1;y=2
65 x=1;y=2
69 x+y**2
66 x+y**2
70
67
71 # An example of autocall functionality
68 # An example of autocall functionality
72 from math import *
69 from math import *
73 autocall 1
70 autocall 1
74 cos pi
71 cos pi
75 autocall 0
72 autocall 0
76 cos pi
73 cos pi
77 cos(pi)
74 cos(pi)
78
75
79 for i in range(5):
76 for i in range(5):
80 print i
77 print i
81
78
82 print "that's all folks!"
79 print "that's all folks!"
83
80
84 exit
81 exit
85 """)
82 """)
86 output = doctest_refactor_print("""\
83 output = doctest_refactor_print("""\
87 In [1]: print 'hello, this is python'
84 In [1]: print 'hello, this is python'
88 hello, this is python
85 hello, this is python
89
86
90
87
91 # some more code
88 # some more code
92 In [2]: x=1;y=2
89 In [2]: x=1;y=2
93
90
94 In [3]: x+y**2
91 In [3]: x+y**2
95 Out[3]: 5
92 Out[3]: 5
96
93
97
94
98 # An example of autocall functionality
95 # An example of autocall functionality
99 In [4]: from math import *
96 In [4]: from math import *
100
97
101 In [5]: autocall 1
98 In [5]: autocall 1
102 Automatic calling is: Smart
99 Automatic calling is: Smart
103
100
104 In [6]: cos pi
101 In [6]: cos pi
105 ------> cos(pi)
102 ------> cos(pi)
106 Out[6]: -1.0
103 Out[6]: -1.0
107
104
108 In [7]: autocall 0
105 In [7]: autocall 0
109 Automatic calling is: OFF
106 Automatic calling is: OFF
110
107
111 In [8]: cos pi
108 In [8]: cos pi
112 File "<ipython-input-8-6bd7313dd9a9>", line 1
109 File "<ipython-input-8-6bd7313dd9a9>", line 1
113 cos pi
110 cos pi
114 ^
111 ^
115 SyntaxError: invalid syntax
112 SyntaxError: invalid syntax
116
113
117
114
118 In [9]: cos(pi)
115 In [9]: cos(pi)
119 Out[9]: -1.0
116 Out[9]: -1.0
120
117
121
118
122 In [10]: for i in range(5):
119 In [10]: for i in range(5):
123 ....: print i
120 ....: print i
124 ....:
121 ....:
125 0
122 0
126 1
123 1
127 2
124 2
128 3
125 3
129 4
126 4
130
127
131 In [11]: print "that's all folks!"
128 In [11]: print "that's all folks!"
132 that's all folks!
129 that's all folks!
133
130
134
131
135 In [12]: exit
132 In [12]: exit
136 """)
133 """)
137 runner = irunner.IPythonRunner(out=self.out)
134 runner = irunner.IPythonRunner(out=self.out)
138 self._test_runner(runner,source,output)
135 self._test_runner(runner,source,output)
139
136
140 def testPython(self):
137 def testPython(self):
141 """Test the Python runner."""
138 """Test the Python runner."""
142 runner = irunner.PythonRunner(out=self.out)
139 runner = irunner.PythonRunner(out=self.out)
143 source = doctest_refactor_print("""
140 source = doctest_refactor_print("""
144 print 'hello, this is python'
141 print 'hello, this is python'
145
142
146 # some more code
143 # some more code
147 x=1;y=2
144 x=1;y=2
148 x+y**2
145 x+y**2
149
146
150 from math import *
147 from math import *
151 cos(pi)
148 cos(pi)
152
149
153 for i in range(5):
150 for i in range(5):
154 print i
151 print i
155
152
156 print "that's all folks!"
153 print "that's all folks!"
157 """)
154 """)
158 output = doctest_refactor_print("""\
155 output = doctest_refactor_print("""\
159 >>> print 'hello, this is python'
156 >>> print 'hello, this is python'
160 hello, this is python
157 hello, this is python
161
158
162 # some more code
159 # some more code
163 >>> x=1;y=2
160 >>> x=1;y=2
164 >>> x+y**2
161 >>> x+y**2
165 5
162 5
166
163
167 >>> from math import *
164 >>> from math import *
168 >>> cos(pi)
165 >>> cos(pi)
169 -1.0
166 -1.0
170
167
171 >>> for i in range(5):
168 >>> for i in range(5):
172 ... print i
169 ... print i
173 ...
170 ...
174 0
171 0
175 1
172 1
176 2
173 2
177 3
174 3
178 4
175 4
179 >>> print "that's all folks!"
176 >>> print "that's all folks!"
180 that's all folks!
177 that's all folks!
181 """)
178 """)
182 self._test_runner(runner,source,output)
179 self._test_runner(runner,source,output)
General Comments 0
You need to be logged in to leave comments. Login now