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