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