displayhook.py 13 KB

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