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