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