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