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