interactiveshell.py 158 KB

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