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