interactiveshell.py 129 KB

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