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