displayhook.py 13 KB

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