interactiveshell.py 151 KB

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