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