interactiveshell.py 151 KB

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