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