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