displayhook.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. # -*- coding: utf-8 -*-
  2. """Displayhook for IPython.
  3. This defines a callable class that IPython uses for `sys.displayhook`.
  4. """
  5. # Copyright (c) IPython Development Team.
  6. # Distributed under the terms of the Modified BSD License.
  7. from __future__ import print_function
  8. import sys
  9. import io as _io
  10. import tokenize
  11. from traitlets.config.configurable import Configurable
  12. from IPython.utils.py3compat import builtin_mod, cast_unicode_py2
  13. from traitlets import Instance, Float
  14. from warnings import warn
  15. # TODO: Move the various attributes (cache_size, [others now moved]). Some
  16. # of these are also attributes of InteractiveShell. They should be on ONE object
  17. # only and the other objects should ask that one object for their values.
  18. class DisplayHook(Configurable):
  19. """The custom IPython displayhook to replace sys.displayhook.
  20. This class does many things, but the basic idea is that it is a callable
  21. that gets called anytime user code returns a value.
  22. """
  23. shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
  24. allow_none=True)
  25. exec_result = Instance('IPython.core.interactiveshell.ExecutionResult',
  26. allow_none=True)
  27. cull_fraction = Float(0.2)
  28. def __init__(self, shell=None, cache_size=1000, **kwargs):
  29. super(DisplayHook, self).__init__(shell=shell, **kwargs)
  30. cache_size_min = 3
  31. if cache_size <= 0:
  32. self.do_full_cache = 0
  33. cache_size = 0
  34. elif cache_size < cache_size_min:
  35. self.do_full_cache = 0
  36. cache_size = 0
  37. warn('caching was disabled (min value for cache size is %s).' %
  38. cache_size_min,stacklevel=3)
  39. else:
  40. self.do_full_cache = 1
  41. self.cache_size = cache_size
  42. # we need a reference to the user-level namespace
  43. self.shell = shell
  44. self._,self.__,self.___ = '','',''
  45. # these are deliberately global:
  46. to_user_ns = {'_':self._,'__':self.__,'___':self.___}
  47. self.shell.user_ns.update(to_user_ns)
  48. @property
  49. def prompt_count(self):
  50. return self.shell.execution_count
  51. #-------------------------------------------------------------------------
  52. # Methods used in __call__. Override these methods to modify the behavior
  53. # of the displayhook.
  54. #-------------------------------------------------------------------------
  55. def check_for_underscore(self):
  56. """Check if the user has set the '_' variable by hand."""
  57. # If something injected a '_' variable in __builtin__, delete
  58. # ipython's automatic one so we don't clobber that. gettext() in
  59. # particular uses _, so we need to stay away from it.
  60. if '_' in builtin_mod.__dict__:
  61. try:
  62. del self.shell.user_ns['_']
  63. except KeyError:
  64. pass
  65. def quiet(self):
  66. """Should we silence the display hook because of ';'?"""
  67. # do not print output if input ends in ';'
  68. try:
  69. cell = cast_unicode_py2(self.shell.history_manager.input_hist_parsed[-1])
  70. except IndexError:
  71. # some uses of ipshellembed may fail here
  72. return False
  73. sio = _io.StringIO(cell)
  74. tokens = list(tokenize.generate_tokens(sio.readline))
  75. for token in reversed(tokens):
  76. if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT):
  77. continue
  78. if (token[0] == tokenize.OP) and (token[1] == ';'):
  79. return True
  80. else:
  81. return False
  82. def start_displayhook(self):
  83. """Start the displayhook, initializing resources."""
  84. pass
  85. def write_output_prompt(self):
  86. """Write the output prompt.
  87. The default implementation simply writes the prompt to
  88. ``sys.stdout``.
  89. """
  90. # Use write, not print which adds an extra space.
  91. sys.stdout.write(self.shell.separate_out)
  92. outprompt = 'Out[{}]: '.format(self.shell.execution_count)
  93. if self.do_full_cache:
  94. sys.stdout.write(outprompt)
  95. def compute_format_data(self, result):
  96. """Compute format data of the object to be displayed.
  97. The format data is a generalization of the :func:`repr` of an object.
  98. In the default implementation the format data is a :class:`dict` of
  99. key value pair where the keys are valid MIME types and the values
  100. are JSON'able data structure containing the raw data for that MIME
  101. type. It is up to frontends to determine pick a MIME to to use and
  102. display that data in an appropriate manner.
  103. This method only computes the format data for the object and should
  104. NOT actually print or write that to a stream.
  105. Parameters
  106. ----------
  107. result : object
  108. The Python object passed to the display hook, whose format will be
  109. computed.
  110. Returns
  111. -------
  112. (format_dict, md_dict) : dict
  113. format_dict is a :class:`dict` whose keys are valid MIME types and values are
  114. JSON'able raw data for that MIME type. It is recommended that
  115. all return values of this should always include the "text/plain"
  116. MIME type representation of the object.
  117. md_dict is a :class:`dict` with the same MIME type keys
  118. of metadata associated with each output.
  119. """
  120. return self.shell.display_formatter.format(result)
  121. # This can be set to True by the write_output_prompt method in a subclass
  122. prompt_end_newline = False
  123. def write_format_data(self, format_dict, md_dict=None):
  124. """Write the format data dict to the frontend.
  125. This default version of this method simply writes the plain text
  126. representation of the object to ``sys.stdout``. Subclasses should
  127. override this method to send the entire `format_dict` to the
  128. frontends.
  129. Parameters
  130. ----------
  131. format_dict : dict
  132. The format dict for the object passed to `sys.displayhook`.
  133. md_dict : dict (optional)
  134. The metadata dict to be associated with the display data.
  135. """
  136. if 'text/plain' not in format_dict:
  137. # nothing to do
  138. return
  139. # We want to print because we want to always make sure we have a
  140. # newline, even if all the prompt separators are ''. This is the
  141. # standard IPython behavior.
  142. result_repr = format_dict['text/plain']
  143. if '\n' in result_repr:
  144. # So that multi-line strings line up with the left column of
  145. # the screen, instead of having the output prompt mess up
  146. # their first line.
  147. # We use the prompt template instead of the expanded prompt
  148. # because the expansion may add ANSI escapes that will interfere
  149. # with our ability to determine whether or not we should add
  150. # a newline.
  151. if not self.prompt_end_newline:
  152. # But avoid extraneous empty lines.
  153. result_repr = '\n' + result_repr
  154. print(result_repr)
  155. def update_user_ns(self, result):
  156. """Update user_ns with various things like _, __, _1, etc."""
  157. # Avoid recursive reference when displaying _oh/Out
  158. if result is not self.shell.user_ns['_oh']:
  159. if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
  160. self.cull_cache()
  161. # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
  162. # we cause buggy behavior for things like gettext).
  163. if '_' not in builtin_mod.__dict__:
  164. self.___ = self.__
  165. self.__ = self._
  166. self._ = result
  167. self.shell.push({'_':self._,
  168. '__':self.__,
  169. '___':self.___}, interactive=False)
  170. # hackish access to top-level namespace to create _1,_2... dynamically
  171. to_main = {}
  172. if self.do_full_cache:
  173. new_result = '_'+repr(self.prompt_count)
  174. to_main[new_result] = result
  175. self.shell.push(to_main, interactive=False)
  176. self.shell.user_ns['_oh'][self.prompt_count] = result
  177. def fill_exec_result(self, result):
  178. if self.exec_result is not None:
  179. self.exec_result.result = result
  180. def log_output(self, format_dict):
  181. """Log the output."""
  182. if 'text/plain' not in format_dict:
  183. # nothing to do
  184. return
  185. if self.shell.logger.log_output:
  186. self.shell.logger.log_write(format_dict['text/plain'], 'output')
  187. self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
  188. format_dict['text/plain']
  189. def finish_displayhook(self):
  190. """Finish up all displayhook activities."""
  191. sys.stdout.write(self.shell.separate_out2)
  192. sys.stdout.flush()
  193. def __call__(self, result=None):
  194. """Printing with history cache management.
  195. This is invoked everytime the interpreter needs to print, and is
  196. activated by setting the variable sys.displayhook to it.
  197. """
  198. self.check_for_underscore()
  199. if result is not None and not self.quiet():
  200. self.start_displayhook()
  201. self.write_output_prompt()
  202. format_dict, md_dict = self.compute_format_data(result)
  203. self.update_user_ns(result)
  204. self.fill_exec_result(result)
  205. if format_dict:
  206. self.write_format_data(format_dict, md_dict)
  207. self.log_output(format_dict)
  208. self.finish_displayhook()
  209. def cull_cache(self):
  210. """Output cache is full, cull the oldest entries"""
  211. oh = self.shell.user_ns.get('_oh', {})
  212. sz = len(oh)
  213. cull_count = max(int(sz * self.cull_fraction), 2)
  214. warn('Output cache limit (currently {sz} entries) hit.\n'
  215. 'Flushing oldest {cull_count} entries.'.format(sz=sz, cull_count=cull_count))
  216. for i, n in enumerate(sorted(oh)):
  217. if i >= cull_count:
  218. break
  219. self.shell.user_ns.pop('_%i' % n, None)
  220. oh.pop(n, None)
  221. def flush(self):
  222. if not self.do_full_cache:
  223. raise ValueError("You shouldn't have reached the cache flush "
  224. "if full caching is not enabled!")
  225. # delete auto-generated vars from global namespace
  226. for n in range(1,self.prompt_count + 1):
  227. key = '_'+repr(n)
  228. try:
  229. del self.shell.user_ns[key]
  230. except: pass
  231. # In some embedded circumstances, the user_ns doesn't have the
  232. # '_oh' key set up.
  233. oh = self.shell.user_ns.get('_oh', None)
  234. if oh is not None:
  235. oh.clear()
  236. # Release our own references to objects:
  237. self._, self.__, self.___ = '', '', ''
  238. if '_' not in builtin_mod.__dict__:
  239. self.shell.user_ns.update({'_':None,'__':None, '___':None})
  240. import gc
  241. # TODO: Is this really needed?
  242. # IronPython blocks here forever
  243. if sys.platform != "cli":
  244. gc.collect()
  245. class CapturingDisplayHook(object):
  246. def __init__(self, shell, outputs=None):
  247. self.shell = shell
  248. if outputs is None:
  249. outputs = []
  250. self.outputs = outputs
  251. def __call__(self, result=None):
  252. if result is None:
  253. return
  254. format_dict, md_dict = self.shell.display_formatter.format(result)
  255. self.outputs.append({ 'data': format_dict, 'metadata': md_dict })