interactiveshell.py 150 KB

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