interactiveshell.py 129 KB

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