PageRenderTime 54ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/IPython/core/displayhook.py

https://github.com/tinyclues/ipython
Python | 329 lines | 258 code | 21 blank | 50 comment | 22 complexity | d1b47e9b7c99cea8e9d1f450ba990c8e MD5 | raw file
  1. # -*- coding: utf-8 -*-
  2. """Displayhook for IPython.
  3. This defines a callable class that IPython uses for `sys.displayhook`.
  4. Authors:
  5. * Fernando Perez
  6. * Brian Granger
  7. * Robert Kern
  8. """
  9. #-----------------------------------------------------------------------------
  10. # Copyright (C) 2008-2010 The IPython Development Team
  11. # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
  12. #
  13. # Distributed under the terms of the BSD License. The full license is in
  14. # the file COPYING, distributed as part of this software.
  15. #-----------------------------------------------------------------------------
  16. #-----------------------------------------------------------------------------
  17. # Imports
  18. #-----------------------------------------------------------------------------
  19. import __builtin__
  20. from IPython.config.configurable import Configurable
  21. from IPython.core import prompts
  22. from IPython.utils import io
  23. from IPython.utils.traitlets import Instance, List
  24. from IPython.utils.warn import warn
  25. #-----------------------------------------------------------------------------
  26. # Main displayhook class
  27. #-----------------------------------------------------------------------------
  28. # TODO: The DisplayHook class should be split into two classes, one that
  29. # manages the prompts and their synchronization and another that just does the
  30. # displayhook logic and calls into the prompt manager.
  31. # TODO: Move the various attributes (cache_size, colors, input_sep,
  32. # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also
  33. # attributes of InteractiveShell. They should be on ONE object only and the
  34. # other objects should ask that one object for their values.
  35. class DisplayHook(Configurable):
  36. """The custom IPython displayhook to replace sys.displayhook.
  37. This class does many things, but the basic idea is that it is a callable
  38. that gets called anytime user code returns a value.
  39. Currently this class does more than just the displayhook logic and that
  40. extra logic should eventually be moved out of here.
  41. """
  42. shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
  43. def __init__(self, shell=None, cache_size=1000,
  44. colors='NoColor', input_sep='\n',
  45. output_sep='\n', output_sep2='',
  46. ps1 = None, ps2 = None, ps_out = None, pad_left=True,
  47. config=None):
  48. super(DisplayHook, self).__init__(shell=shell, config=config)
  49. cache_size_min = 3
  50. if cache_size <= 0:
  51. self.do_full_cache = 0
  52. cache_size = 0
  53. elif cache_size < cache_size_min:
  54. self.do_full_cache = 0
  55. cache_size = 0
  56. warn('caching was disabled (min value for cache size is %s).' %
  57. cache_size_min,level=3)
  58. else:
  59. self.do_full_cache = 1
  60. self.cache_size = cache_size
  61. self.input_sep = input_sep
  62. # we need a reference to the user-level namespace
  63. self.shell = shell
  64. # Set input prompt strings and colors
  65. if cache_size == 0:
  66. if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \
  67. or ps1.find(r'\N') > -1:
  68. ps1 = '>>> '
  69. if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \
  70. or ps2.find(r'\N') > -1:
  71. ps2 = '... '
  72. self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
  73. self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
  74. self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
  75. self.color_table = prompts.PromptColors
  76. self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str,
  77. pad_left=pad_left)
  78. self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
  79. self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str,
  80. pad_left=pad_left)
  81. self.set_colors(colors)
  82. # Store the last prompt string each time, we need it for aligning
  83. # continuation and auto-rewrite prompts
  84. self.last_prompt = ''
  85. self.output_sep = output_sep
  86. self.output_sep2 = output_sep2
  87. self._,self.__,self.___ = '','',''
  88. # these are deliberately global:
  89. to_user_ns = {'_':self._,'__':self.__,'___':self.___}
  90. self.shell.user_ns.update(to_user_ns)
  91. @property
  92. def prompt_count(self):
  93. return self.shell.execution_count
  94. def _set_prompt_str(self,p_str,cache_def,no_cache_def):
  95. if p_str is None:
  96. if self.do_full_cache:
  97. return cache_def
  98. else:
  99. return no_cache_def
  100. else:
  101. return p_str
  102. def set_colors(self, colors):
  103. """Set the active color scheme and configure colors for the three
  104. prompt subsystems."""
  105. # FIXME: This modifying of the global prompts.prompt_specials needs
  106. # to be fixed. We need to refactor all of the prompts stuff to use
  107. # proper configuration and traits notifications.
  108. if colors.lower()=='nocolor':
  109. prompts.prompt_specials = prompts.prompt_specials_nocolor
  110. else:
  111. prompts.prompt_specials = prompts.prompt_specials_color
  112. self.color_table.set_active_scheme(colors)
  113. self.prompt1.set_colors()
  114. self.prompt2.set_colors()
  115. self.prompt_out.set_colors()
  116. #-------------------------------------------------------------------------
  117. # Methods used in __call__. Override these methods to modify the behavior
  118. # of the displayhook.
  119. #-------------------------------------------------------------------------
  120. def check_for_underscore(self):
  121. """Check if the user has set the '_' variable by hand."""
  122. # If something injected a '_' variable in __builtin__, delete
  123. # ipython's automatic one so we don't clobber that. gettext() in
  124. # particular uses _, so we need to stay away from it.
  125. if '_' in __builtin__.__dict__:
  126. try:
  127. del self.shell.user_ns['_']
  128. except KeyError:
  129. pass
  130. def quiet(self):
  131. """Should we silence the display hook because of ';'?"""
  132. # do not print output if input ends in ';'
  133. try:
  134. cell = self.shell.history_manager.input_hist_parsed[self.prompt_count]
  135. if cell.rstrip().endswith(';'):
  136. return True
  137. except IndexError:
  138. # some uses of ipshellembed may fail here
  139. pass
  140. return False
  141. def start_displayhook(self):
  142. """Start the displayhook, initializing resources."""
  143. pass
  144. def write_output_prompt(self):
  145. """Write the output prompt.
  146. The default implementation simply writes the prompt to
  147. ``io.stdout``.
  148. """
  149. # Use write, not print which adds an extra space.
  150. io.stdout.write(self.output_sep)
  151. outprompt = str(self.prompt_out)
  152. if self.do_full_cache:
  153. io.stdout.write(outprompt)
  154. def compute_format_data(self, result):
  155. """Compute format data of the object to be displayed.
  156. The format data is a generalization of the :func:`repr` of an object.
  157. In the default implementation the format data is a :class:`dict` of
  158. key value pair where the keys are valid MIME types and the values
  159. are JSON'able data structure containing the raw data for that MIME
  160. type. It is up to frontends to determine pick a MIME to to use and
  161. display that data in an appropriate manner.
  162. This method only computes the format data for the object and should
  163. NOT actually print or write that to a stream.
  164. Parameters
  165. ----------
  166. result : object
  167. The Python object passed to the display hook, whose format will be
  168. computed.
  169. Returns
  170. -------
  171. format_data : dict
  172. A :class:`dict` whose keys are valid MIME types and values are
  173. JSON'able raw data for that MIME type. It is recommended that
  174. all return values of this should always include the "text/plain"
  175. MIME type representation of the object.
  176. """
  177. return self.shell.display_formatter.format(result)
  178. def write_format_data(self, format_dict):
  179. """Write the format data dict to the frontend.
  180. This default version of this method simply writes the plain text
  181. representation of the object to ``io.stdout``. Subclasses should
  182. override this method to send the entire `format_dict` to the
  183. frontends.
  184. Parameters
  185. ----------
  186. format_dict : dict
  187. The format dict for the object passed to `sys.displayhook`.
  188. """
  189. # We want to print because we want to always make sure we have a
  190. # newline, even if all the prompt separators are ''. This is the
  191. # standard IPython behavior.
  192. result_repr = format_dict['text/plain']
  193. if '\n' in result_repr:
  194. # So that multi-line strings line up with the left column of
  195. # the screen, instead of having the output prompt mess up
  196. # their first line.
  197. # We use the ps_out_str template instead of the expanded prompt
  198. # because the expansion may add ANSI escapes that will interfere
  199. # with our ability to determine whether or not we should add
  200. # a newline.
  201. if self.ps_out_str and not self.ps_out_str.endswith('\n'):
  202. # But avoid extraneous empty lines.
  203. result_repr = '\n' + result_repr
  204. print >>io.stdout, result_repr
  205. def update_user_ns(self, result):
  206. """Update user_ns with various things like _, __, _1, etc."""
  207. # Avoid recursive reference when displaying _oh/Out
  208. if result is not self.shell.user_ns['_oh']:
  209. if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
  210. warn('Output cache limit (currently '+
  211. `self.cache_size`+' entries) hit.\n'
  212. 'Flushing cache and resetting history counter...\n'
  213. 'The only history variables available will be _,__,___ and _1\n'
  214. 'with the current result.')
  215. self.flush()
  216. # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
  217. # we cause buggy behavior for things like gettext).
  218. if '_' not in __builtin__.__dict__:
  219. self.___ = self.__
  220. self.__ = self._
  221. self._ = result
  222. self.shell.user_ns.update({'_':self._,
  223. '__':self.__,
  224. '___':self.___})
  225. # hackish access to top-level namespace to create _1,_2... dynamically
  226. to_main = {}
  227. if self.do_full_cache:
  228. new_result = '_'+`self.prompt_count`
  229. to_main[new_result] = result
  230. self.shell.user_ns.update(to_main)
  231. self.shell.user_ns['_oh'][self.prompt_count] = result
  232. def log_output(self, format_dict):
  233. """Log the output."""
  234. if self.shell.logger.log_output:
  235. self.shell.logger.log_write(format_dict['text/plain'], 'output')
  236. self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
  237. format_dict['text/plain']
  238. def finish_displayhook(self):
  239. """Finish up all displayhook activities."""
  240. io.stdout.write(self.output_sep2)
  241. io.stdout.flush()
  242. def __call__(self, result=None):
  243. """Printing with history cache management.
  244. This is invoked everytime the interpreter needs to print, and is
  245. activated by setting the variable sys.displayhook to it.
  246. """
  247. self.check_for_underscore()
  248. if result is not None and not self.quiet():
  249. self.start_displayhook()
  250. self.write_output_prompt()
  251. format_dict = self.compute_format_data(result)
  252. self.write_format_data(format_dict)
  253. self.update_user_ns(result)
  254. self.log_output(format_dict)
  255. self.finish_displayhook()
  256. def flush(self):
  257. if not self.do_full_cache:
  258. raise ValueError,"You shouldn't have reached the cache flush "\
  259. "if full caching is not enabled!"
  260. # delete auto-generated vars from global namespace
  261. for n in range(1,self.prompt_count + 1):
  262. key = '_'+`n`
  263. try:
  264. del self.shell.user_ns[key]
  265. except: pass
  266. self.shell.user_ns['_oh'].clear()
  267. # Release our own references to objects:
  268. self._, self.__, self.___ = '', '', ''
  269. if '_' not in __builtin__.__dict__:
  270. self.shell.user_ns.update({'_':None,'__':None, '___':None})
  271. import gc
  272. # TODO: Is this really needed?
  273. gc.collect()