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