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