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