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