##// END OF EJS Templates
Final work on display system....
Brian Granger -
Show More
@@ -1,118 +1,122 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(*objs, **kwargs):
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 objs : tuple of objects
33 The Python object to display.
33 The Python objects 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 include = kwargs.get('include')
44 exclude = kwargs.get('exclude')
45
43 from IPython.core.interactiveshell import InteractiveShell
46 from IPython.core.interactiveshell import InteractiveShell
44 inst = InteractiveShell.instance()
47 inst = InteractiveShell.instance()
45 format = inst.display_formatter.format
48 format = inst.display_formatter.format
46 publish = inst.display_pub.publish
49 publish = inst.display_pub.publish
47
50
51 for obj in objs:
48 format_dict = format(obj, include=include, exclude=exclude)
52 format_dict = format(obj, include=include, exclude=exclude)
49 publish('IPython.core.display.display', format_dict)
53 publish('IPython.core.display.display', format_dict)
50
54
51
55
52 def display_pretty(obj):
56 def display_pretty(*objs):
53 """Display the pretty (default) representation of an object.
57 """Display the pretty (default) representation of an object.
54
58
55 Parameters
59 Parameters
56 ----------
60 ----------
57 obj : object
61 objs : tuple of objects
58 The Python object to display.
62 The Python objects to display.
59 """
63 """
60 display(obj, include=['text/plain'])
64 display(*objs, include=['text/plain'])
61
65
62
66
63 def display_html(obj):
67 def display_html(*objs):
64 """Display the HTML representation of an object.
68 """Display the HTML representation of an object.
65
69
66 Parameters
70 Parameters
67 ----------
71 ----------
68 obj : object
72 objs : tuple of objects
69 The Python object to display.
73 The Python objects to display.
70 """
74 """
71 display(obj, include=['text/plain','text/html'])
75 display(*objs, include=['text/plain','text/html'])
72
76
73
77
74 def display_svg(obj):
78 def display_svg(*objs):
75 """Display the SVG representation of an object.
79 """Display the SVG representation of an object.
76
80
77 Parameters
81 Parameters
78 ----------
82 ----------
79 obj : object
83 objs : tuple of objects
80 The Python object to display.
84 The Python objects to display.
81 """
85 """
82 display(obj, include=['text/plain','image/svg+xml'])
86 display(*objs, include=['text/plain','image/svg+xml'])
83
87
84
88
85 def display_png(obj):
89 def display_png(*objs):
86 """Display the PNG representation of an object.
90 """Display the PNG representation of an object.
87
91
88 Parameters
92 Parameters
89 ----------
93 ----------
90 obj : object
94 objs : tuple of objects
91 The Python object to display.
95 The Python objects to display.
92 """
96 """
93 display(obj, include=['text/plain','image/png'])
97 display(*objs, include=['text/plain','image/png'])
94
98
95
99
96 def display_latex(obj):
100 def display_latex(*objs):
97 """Display the LaTeX representation of an object.
101 """Display the LaTeX representation of an object.
98
102
99 Parameters
103 Parameters
100 ----------
104 ----------
101 obj : object
105 objs : tuple of objects
102 The Python object to display.
106 The Python objects to display.
103 """
107 """
104 display(obj, include=['text/plain','text/latex'])
108 display(*objs, include=['text/plain','text/latex'])
105
109
106
110
107 def display_json(obj):
111 def display_json(*objs):
108 """Display the JSON representation of an object.
112 """Display the JSON representation of an object.
109
113
110 Parameters
114 Parameters
111 ----------
115 ----------
112 obj : object
116 objs : tuple of objects
113 The Python object to display.
117 The Python objects to display.
114 """
118 """
115 display(obj, include=['text/plain','application/json'])
119 display(*objs, include=['text/plain','application/json'])
116
120
117
121
118
122
@@ -1,322 +1,321 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 computes the format data for the object and should
198 This method only computes the format data for the object and should
199 NOT 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 format 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 return self.shell.display_formatter.format(result)
216 return format_dict
217
216
218 def write_format_data(self, format_dict):
217 def write_format_data(self, format_dict):
219 """Write the format data dict to the frontend.
218 """Write the format data dict to the frontend.
220
219
221 This default version of this method simply writes the plain text
220 This default version of this method simply writes the plain text
222 representation of the object to ``io.Term.cout``. Subclasses should
221 representation of the object to ``io.Term.cout``. Subclasses should
223 override this method to send the entire `format_dict` to the
222 override this method to send the entire `format_dict` to the
224 frontends.
223 frontends.
225
224
226 Parameters
225 Parameters
227 ----------
226 ----------
228 format_dict : dict
227 format_dict : dict
229 The format dict for the object passed to `sys.displayhook`.
228 The format dict for the object passed to `sys.displayhook`.
230 """
229 """
231 # We want to print because we want to always make sure we have a
230 # 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
231 # newline, even if all the prompt separators are ''. This is the
233 # standard IPython behavior.
232 # standard IPython behavior.
234 result_repr = format_dict['text/plain']
233 result_repr = format_dict['text/plain']
235 if '\n' in result_repr:
234 if '\n' in result_repr:
236 # So that multi-line strings line up with the left column of
235 # So that multi-line strings line up with the left column of
237 # the screen, instead of having the output prompt mess up
236 # the screen, instead of having the output prompt mess up
238 # their first line.
237 # their first line.
239 # We use the ps_out_str template instead of the expanded prompt
238 # We use the ps_out_str template instead of the expanded prompt
240 # because the expansion may add ANSI escapes that will interfere
239 # because the expansion may add ANSI escapes that will interfere
241 # with our ability to determine whether or not we should add
240 # with our ability to determine whether or not we should add
242 # a newline.
241 # a newline.
243 if self.ps_out_str and not self.ps_out_str.endswith('\n'):
242 if self.ps_out_str and not self.ps_out_str.endswith('\n'):
244 # But avoid extraneous empty lines.
243 # But avoid extraneous empty lines.
245 result_repr = '\n' + result_repr
244 result_repr = '\n' + result_repr
246
245
247 print >>IPython.utils.io.Term.cout, result_repr
246 print >>IPython.utils.io.Term.cout, result_repr
248
247
249 def update_user_ns(self, result):
248 def update_user_ns(self, result):
250 """Update user_ns with various things like _, __, _1, etc."""
249 """Update user_ns with various things like _, __, _1, etc."""
251
250
252 # Avoid recursive reference when displaying _oh/Out
251 # Avoid recursive reference when displaying _oh/Out
253 if result is not self.shell.user_ns['_oh']:
252 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:
253 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
255 warn('Output cache limit (currently '+
254 warn('Output cache limit (currently '+
256 `self.cache_size`+' entries) hit.\n'
255 `self.cache_size`+' entries) hit.\n'
257 'Flushing cache and resetting history counter...\n'
256 'Flushing cache and resetting history counter...\n'
258 'The only history variables available will be _,__,___ and _1\n'
257 'The only history variables available will be _,__,___ and _1\n'
259 'with the current result.')
258 'with the current result.')
260
259
261 self.flush()
260 self.flush()
262 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
261 # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise
263 # we cause buggy behavior for things like gettext).
262 # we cause buggy behavior for things like gettext).
264 if '_' not in __builtin__.__dict__:
263 if '_' not in __builtin__.__dict__:
265 self.___ = self.__
264 self.___ = self.__
266 self.__ = self._
265 self.__ = self._
267 self._ = result
266 self._ = result
268 self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___})
267 self.shell.user_ns.update({'_':self._,'__':self.__,'___':self.___})
269
268
270 # hackish access to top-level namespace to create _1,_2... dynamically
269 # hackish access to top-level namespace to create _1,_2... dynamically
271 to_main = {}
270 to_main = {}
272 if self.do_full_cache:
271 if self.do_full_cache:
273 new_result = '_'+`self.prompt_count`
272 new_result = '_'+`self.prompt_count`
274 to_main[new_result] = result
273 to_main[new_result] = result
275 self.shell.user_ns.update(to_main)
274 self.shell.user_ns.update(to_main)
276 self.shell.user_ns['_oh'][self.prompt_count] = result
275 self.shell.user_ns['_oh'][self.prompt_count] = result
277
276
278 def log_output(self, result):
277 def log_output(self, result):
279 """Log the output."""
278 """Log the output."""
280 if self.shell.logger.log_output:
279 if self.shell.logger.log_output:
281 self.shell.logger.log_write(repr(result), 'output')
280 self.shell.logger.log_write(repr(result), 'output')
282
281
283 def finish_displayhook(self):
282 def finish_displayhook(self):
284 """Finish up all displayhook activities."""
283 """Finish up all displayhook activities."""
285 IPython.utils.io.Term.cout.write(self.output_sep2)
284 IPython.utils.io.Term.cout.write(self.output_sep2)
286 IPython.utils.io.Term.cout.flush()
285 IPython.utils.io.Term.cout.flush()
287
286
288 def __call__(self, result=None):
287 def __call__(self, result=None):
289 """Printing with history cache management.
288 """Printing with history cache management.
290
289
291 This is invoked everytime the interpreter needs to print, and is
290 This is invoked everytime the interpreter needs to print, and is
292 activated by setting the variable sys.displayhook to it.
291 activated by setting the variable sys.displayhook to it.
293 """
292 """
294 self.check_for_underscore()
293 self.check_for_underscore()
295 if result is not None and not self.quiet():
294 if result is not None and not self.quiet():
296 self.start_displayhook()
295 self.start_displayhook()
297 self.write_output_prompt()
296 self.write_output_prompt()
298 format_dict = self.compute_format_data(result)
297 format_dict = self.compute_format_data(result)
299 self.write_format_data(format_dict)
298 self.write_format_data(format_dict)
300 self.update_user_ns(result)
299 self.update_user_ns(result)
301 self.log_output(result)
300 self.log_output(result)
302 self.finish_displayhook()
301 self.finish_displayhook()
303
302
304 def flush(self):
303 def flush(self):
305 if not self.do_full_cache:
304 if not self.do_full_cache:
306 raise ValueError,"You shouldn't have reached the cache flush "\
305 raise ValueError,"You shouldn't have reached the cache flush "\
307 "if full caching is not enabled!"
306 "if full caching is not enabled!"
308 # delete auto-generated vars from global namespace
307 # delete auto-generated vars from global namespace
309
308
310 for n in range(1,self.prompt_count + 1):
309 for n in range(1,self.prompt_count + 1):
311 key = '_'+`n`
310 key = '_'+`n`
312 try:
311 try:
313 del self.shell.user_ns[key]
312 del self.shell.user_ns[key]
314 except: pass
313 except: pass
315 self.shell.user_ns['_oh'].clear()
314 self.shell.user_ns['_oh'].clear()
316
315
317 if '_' not in __builtin__.__dict__:
316 if '_' not in __builtin__.__dict__:
318 self.shell.user_ns.update({'_':None,'__':None, '___':None})
317 self.shell.user_ns.update({'_':None,'__':None, '___':None})
319 import gc
318 import gc
320 # TODO: Is this really needed?
319 # TODO: Is this really needed?
321 gc.collect()
320 gc.collect()
322
321
@@ -1,503 +1,504 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Display formatters.
2 """Display formatters.
3
3
4
4
5 Authors:
5 Authors:
6
6
7 * Robert Kern
7 * Robert Kern
8 * Brian Granger
8 * Brian Granger
9 """
9 """
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11 # Copyright (c) 2010, IPython Development Team.
11 # Copyright (c) 2010, IPython Development Team.
12 #
12 #
13 # Distributed under the terms of the Modified BSD License.
13 # Distributed under the terms of the Modified BSD License.
14 #
14 #
15 # The full license is in the file COPYING.txt, distributed with this software.
15 # The full license is in the file COPYING.txt, distributed with this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 # Stdlib imports
22 # Stdlib imports
23 import abc
23 import abc
24 # We must use StringIO, as cStringIO doesn't handle unicode properly.
24 # We must use StringIO, as cStringIO doesn't handle unicode properly.
25 from StringIO import StringIO
25 from StringIO import StringIO
26
26
27 # Our own imports
27 # Our own imports
28 from IPython.config.configurable import Configurable
28 from IPython.config.configurable import Configurable
29 from IPython.external import pretty
29 from IPython.external import pretty
30 from IPython.utils.traitlets import Bool, Dict, Int, Str
30 from IPython.utils.traitlets import Bool, Dict, Int, Str
31
31
32
32
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
34 # The main DisplayFormatter class
34 # The main DisplayFormatter class
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
36
36
37
37
38 class DisplayFormatter(Configurable):
38 class DisplayFormatter(Configurable):
39
39
40 # When set to true only the default plain text formatter will be used.
40 # When set to true only the default plain text formatter will be used.
41 plain_text_only = Bool(False, config=True)
41 plain_text_only = Bool(False, config=True)
42
42
43 # A dict of formatter whose keys are format types (MIME types) and whose
43 # A dict of formatter whose keys are format types (MIME types) and whose
44 # values are subclasses of BaseFormatter.
44 # values are subclasses of BaseFormatter.
45 formatters = Dict(config=True)
45 formatters = Dict(config=True)
46 def _formatters_default(self):
46 def _formatters_default(self):
47 """Activate the default formatters."""
47 """Activate the default formatters."""
48 formatter_classes = [
48 formatter_classes = [
49 PlainTextFormatter,
49 PlainTextFormatter,
50 HTMLFormatter,
50 HTMLFormatter,
51 SVGFormatter,
51 SVGFormatter,
52 PNGFormatter,
52 PNGFormatter,
53 LatexFormatter,
53 LatexFormatter,
54 JSONFormatter
54 JSONFormatter
55 ]
55 ]
56 d = {}
56 d = {}
57 for cls in formatter_classes:
57 for cls in formatter_classes:
58 f = cls(config=self.config)
58 f = cls(config=self.config)
59 d[f.format_type] = f
59 d[f.format_type] = f
60 return d
60 return d
61
61
62 def format(self, obj, include=None, exclude=None):
62 def format(self, obj, include=None, exclude=None):
63 """Return a format data dict for an object.
63 """Return a format data dict for an object.
64
64
65 By default all format types will be computed.
65 By default all format types will be computed.
66
66
67 The following MIME types are currently implemented:
67 The following MIME types are currently implemented:
68
68
69 * text/plain
69 * text/plain
70 * text/html
70 * text/html
71 * text/latex
71 * text/latex
72 * application/json
72 * application/json
73 * image/png
73 * image/png
74 * immage/svg+xml
74 * immage/svg+xml
75
75
76 Parameters
76 Parameters
77 ----------
77 ----------
78 obj : object
78 obj : object
79 The Python object whose format data will be computed.
79 The Python object whose format data will be computed.
80 include : list or tuple, optional
80 include : list or tuple, optional
81 A list of format type strings (MIME types) to include in the
81 A list of format type strings (MIME types) to include in the
82 format data dict. If this is set *only* the format types included
82 format data dict. If this is set *only* the format types included
83 in this list will be computed.
83 in this list will be computed.
84 exclude : list or tuple, optional
84 exclude : list or tuple, optional
85 A list of format type string (MIME types) to exclue in the format
85 A list of format type string (MIME types) to exclue in the format
86 data dict. If this is set all format types will be computed,
86 data dict. If this is set all format types will be computed,
87 except for those included in this argument.
87 except for those included in this argument.
88
88
89 Returns
89 Returns
90 -------
90 -------
91 format_dict : dict
91 format_dict : dict
92 A dictionary of key/value pairs, one or each format that was
92 A dictionary of key/value pairs, one or each format that was
93 generated for the object. The keys are the format types, which
93 generated for the object. The keys are the format types, which
94 will usually be MIME type strings and the values and JSON'able
94 will usually be MIME type strings and the values and JSON'able
95 data structure containing the raw data for the representation in
95 data structure containing the raw data for the representation in
96 that format.
96 that format.
97 """
97 """
98 format_dict = {}
98 format_dict = {}
99
99
100 # If plain text only is active
100 # If plain text only is active
101 if self.plain_text_only:
101 if self.plain_text_only:
102 formatter = self.formatters['text/plain']
102 formatter = self.formatters['text/plain']
103 try:
103 try:
104 data = formatter(obj)
104 data = formatter(obj)
105 except:
105 except:
106 # FIXME: log the exception
106 # FIXME: log the exception
107 raise
107 raise
108 if data is not None:
108 if data is not None:
109 format_dict['text/plain'] = data
109 format_dict['text/plain'] = data
110 return format_dict
110 return format_dict
111
111
112 for format_type, formatter in self.formatters.items():
112 for format_type, formatter in self.formatters.items():
113 if include is not None:
113 if include is not None:
114 if format_type not in include:
114 if format_type not in include:
115 continue
115 continue
116 if exclude is not None:
116 if exclude is not None:
117 if format_type in exclude:
117 if format_type in exclude:
118 continue
118 continue
119 try:
119 try:
120 data = formatter(obj)
120 data = formatter(obj)
121 except:
121 except:
122 # FIXME: log the exception
122 # FIXME: log the exception
123 raise
123 raise
124 if data is not None:
124 if data is not None:
125 format_dict[format_type] = data
125 format_dict[format_type] = data
126 return format_dict
126 return format_dict
127
127
128 @property
128 @property
129 def format_types(self):
129 def format_types(self):
130 """Return the format types (MIME types) of the active formatters."""
130 """Return the format types (MIME types) of the active formatters."""
131 return self.formatters.keys()
131 return self.formatters.keys()
132
132
133
133
134 #-----------------------------------------------------------------------------
134 #-----------------------------------------------------------------------------
135 # Formatters for specific format types (text, html, svg, etc.)
135 # Formatters for specific format types (text, html, svg, etc.)
136 #-----------------------------------------------------------------------------
136 #-----------------------------------------------------------------------------
137
137
138
138
139 class FormatterABC(object):
139 class FormatterABC(object):
140 """ Abstract base class for Formatters.
140 """ Abstract base class for Formatters.
141
141
142 A formatter is a callable class that is responsible for computing the
142 A formatter is a callable class that is responsible for computing the
143 raw format data for a particular format type (MIME type). For example,
143 raw format data for a particular format type (MIME type). For example,
144 an HTML formatter would have a format type of `text/html` and would return
144 an HTML formatter would have a format type of `text/html` and would return
145 the HTML representation of the object when called.
145 the HTML representation of the object when called.
146 """
146 """
147 __metaclass__ = abc.ABCMeta
147 __metaclass__ = abc.ABCMeta
148
148
149 # The format type of the data returned, usually a MIME type.
149 # The format type of the data returned, usually a MIME type.
150 format_type = 'text/plain'
150 format_type = 'text/plain'
151
151
152 # Is the formatter enabled...
152 # Is the formatter enabled...
153 enabled = True
153 enabled = True
154
154
155 @abc.abstractmethod
155 @abc.abstractmethod
156 def __call__(self, obj):
156 def __call__(self, obj):
157 """Return a JSON'able representation of the object.
157 """Return a JSON'able representation of the object.
158
158
159 If the object cannot be formatted by this formatter, then return None
159 If the object cannot be formatted by this formatter, then return None
160 """
160 """
161 try:
161 try:
162 return repr(obj)
162 return repr(obj)
163 except TypeError:
163 except TypeError:
164 return None
164 return None
165
165
166
166
167 class BaseFormatter(Configurable):
167 class BaseFormatter(Configurable):
168 """A base formatter class that is configurable.
168 """A base formatter class that is configurable.
169
169
170 This formatter should usually be used as the base class of all formatters.
170 This formatter should usually be used as the base class of all formatters.
171 It is a traited :class:`Configurable` class and includes an extensible
171 It is a traited :class:`Configurable` class and includes an extensible
172 API for users to determine how their objects are formatted. The following
172 API for users to determine how their objects are formatted. The following
173 logic is used to find a function to format an given object.
173 logic is used to find a function to format an given object.
174
174
175 1. The object is introspected to see if it has a method with the name
175 1. The object is introspected to see if it has a method with the name
176 :attr:`print_method`. If is does, that object is passed to that method
176 :attr:`print_method`. If is does, that object is passed to that method
177 for formatting.
177 for formatting.
178 2. If no print method is found, three internal dictionaries are consulted
178 2. If no print method is found, three internal dictionaries are consulted
179 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
179 to find print method: :attr:`singleton_printers`, :attr:`type_printers`
180 and :attr:`deferred_printers`.
180 and :attr:`deferred_printers`.
181
181
182 Users should use these dictionarie to register functions that will be used
182 Users should use these dictionaries to register functions that will be
183 to compute the format data for their objects (if those objects don't have
183 used to compute the format data for their objects (if those objects don't
184 the special print methods). The easiest way of using these dictionaries
184 have the special print methods). The easiest way of using these
185 is through the :meth:`for_type` and :meth:`for_type_by_name` methods.
185 dictionaries is through the :meth:`for_type` and :meth:`for_type_by_name`
186 methods.
186
187
187 If no function/callable is found to compute the format data, ``None`` is
188 If no function/callable is found to compute the format data, ``None`` is
188 returned and this format type is not used.
189 returned and this format type is not used.
189 """
190 """
190
191
191 format_type = Str('text/plain')
192 format_type = Str('text/plain')
192
193
193 enabled = Bool(True, config=True)
194 enabled = Bool(True, config=True)
194
195
195 print_method = Str('__repr__')
196 print_method = Str('__repr__')
196
197
197 # The singleton printers.
198 # The singleton printers.
198 # Maps the IDs of the builtin singleton objects to the format functions.
199 # Maps the IDs of the builtin singleton objects to the format functions.
199 singleton_printers = Dict(config=True)
200 singleton_printers = Dict(config=True)
200 def _singleton_printers_default(self):
201 def _singleton_printers_default(self):
201 return {}
202 return {}
202
203
203 # The type-specific printers.
204 # The type-specific printers.
204 # Map type objects to the format functions.
205 # Map type objects to the format functions.
205 type_printers = Dict(config=True)
206 type_printers = Dict(config=True)
206 def _type_printers_default(self):
207 def _type_printers_default(self):
207 return {}
208 return {}
208
209
209 # The deferred-import type-specific printers.
210 # The deferred-import type-specific printers.
210 # Map (modulename, classname) pairs to the format functions.
211 # Map (modulename, classname) pairs to the format functions.
211 deferred_printers = Dict(config=True)
212 deferred_printers = Dict(config=True)
212 def _deferred_printers_default(self):
213 def _deferred_printers_default(self):
213 return {}
214 return {}
214
215
215 def __call__(self, obj):
216 def __call__(self, obj):
216 """Compute the format for an object."""
217 """Compute the format for an object."""
217 if self.enabled:
218 if self.enabled:
218 obj_id = id(obj)
219 obj_id = id(obj)
219 try:
220 try:
220 obj_class = getattr(obj, '__class__', None) or type(obj)
221 obj_class = getattr(obj, '__class__', None) or type(obj)
221 if hasattr(obj_class, self.print_method):
222 if hasattr(obj_class, self.print_method):
222 printer = getattr(obj_class, self.print_method)
223 printer = getattr(obj_class, self.print_method)
223 return printer(obj)
224 return printer(obj)
224 try:
225 try:
225 printer = self.singleton_printers[obj_id]
226 printer = self.singleton_printers[obj_id]
226 except (TypeError, KeyError):
227 except (TypeError, KeyError):
227 pass
228 pass
228 else:
229 else:
229 return printer(obj)
230 return printer(obj)
230 for cls in pretty._get_mro(obj_class):
231 for cls in pretty._get_mro(obj_class):
231 if cls in self.type_printers:
232 if cls in self.type_printers:
232 return self.type_printers[cls](obj)
233 return self.type_printers[cls](obj)
233 else:
234 else:
234 printer = self._in_deferred_types(cls)
235 printer = self._in_deferred_types(cls)
235 if printer is not None:
236 if printer is not None:
236 return printer(obj)
237 return printer(obj)
237 return None
238 return None
238 except Exception:
239 except Exception:
239 pass
240 pass
240 else:
241 else:
241 return None
242 return None
242
243
243 def for_type(self, typ, func):
244 def for_type(self, typ, func):
244 """Add a format function for a given type.
245 """Add a format function for a given type.
245
246
246 Parameteres
247 Parameters
247 -----------
248 -----------
248 typ : class
249 typ : class
249 The class of the object that will be formatted using `func`.
250 The class of the object that will be formatted using `func`.
250 func : callable
251 func : callable
251 The callable that will be called to compute the format data. The
252 The callable that will be called to compute the format data. The
252 call signature of this function is simple, it must take the
253 call signature of this function is simple, it must take the
253 object to be formatted and return the raw data for the given
254 object to be formatted and return the raw data for the given
254 format. Subclasses may use a different call signature for the
255 format. Subclasses may use a different call signature for the
255 `func` argument.
256 `func` argument.
256 """
257 """
257 oldfunc = self.type_printers.get(typ, None)
258 oldfunc = self.type_printers.get(typ, None)
258 if func is not None:
259 if func is not None:
259 # To support easy restoration of old printers, we need to ignore
260 # To support easy restoration of old printers, we need to ignore
260 # Nones.
261 # Nones.
261 self.type_printers[typ] = func
262 self.type_printers[typ] = func
262 return oldfunc
263 return oldfunc
263
264
264 def for_type_by_name(self, type_module, type_name, func):
265 def for_type_by_name(self, type_module, type_name, func):
265 """Add a format function for a type specified by the full dotted
266 """Add a format function for a type specified by the full dotted
266 module and name of the type, rather than the type of the object.
267 module and name of the type, rather than the type of the object.
267
268
268 Parameters
269 Parameters
269 ----------
270 ----------
270 type_module : str
271 type_module : str
271 The full dotted name of the module the type is defined in, like
272 The full dotted name of the module the type is defined in, like
272 ``numpy``.
273 ``numpy``.
273 type_name : str
274 type_name : str
274 The name of the type (the class name), like ``dtype``
275 The name of the type (the class name), like ``dtype``
275 func : callable
276 func : callable
276 The callable that will be called to compute the format data. The
277 The callable that will be called to compute the format data. The
277 call signature of this function is simple, it must take the
278 call signature of this function is simple, it must take the
278 object to be formatted and return the raw data for the given
279 object to be formatted and return the raw data for the given
279 format. Subclasses may use a different call signature for the
280 format. Subclasses may use a different call signature for the
280 `func` argument.
281 `func` argument.
281 """
282 """
282 key = (type_module, type_name)
283 key = (type_module, type_name)
283 oldfunc = self.deferred_printers.get(key, None)
284 oldfunc = self.deferred_printers.get(key, None)
284 if func is not None:
285 if func is not None:
285 # To support easy restoration of old printers, we need to ignore
286 # To support easy restoration of old printers, we need to ignore
286 # Nones.
287 # Nones.
287 self.deferred_printers[key] = func
288 self.deferred_printers[key] = func
288 return oldfunc
289 return oldfunc
289
290
290 def _in_deferred_types(self, cls):
291 def _in_deferred_types(self, cls):
291 """
292 """
292 Check if the given class is specified in the deferred type registry.
293 Check if the given class is specified in the deferred type registry.
293
294
294 Returns the printer from the registry if it exists, and None if the
295 Returns the printer from the registry if it exists, and None if the
295 class is not in the registry. Successful matches will be moved to the
296 class is not in the registry. Successful matches will be moved to the
296 regular type registry for future use.
297 regular type registry for future use.
297 """
298 """
298 mod = getattr(cls, '__module__', None)
299 mod = getattr(cls, '__module__', None)
299 name = getattr(cls, '__name__', None)
300 name = getattr(cls, '__name__', None)
300 key = (mod, name)
301 key = (mod, name)
301 printer = None
302 printer = None
302 if key in self.deferred_printers:
303 if key in self.deferred_printers:
303 # Move the printer over to the regular registry.
304 # Move the printer over to the regular registry.
304 printer = self.deferred_printers.pop(key)
305 printer = self.deferred_printers.pop(key)
305 self.type_printers[cls] = printer
306 self.type_printers[cls] = printer
306 return printer
307 return printer
307
308
308
309
309 class PlainTextFormatter(BaseFormatter):
310 class PlainTextFormatter(BaseFormatter):
310 """The default pretty-printer.
311 """The default pretty-printer.
311
312
312 This uses :mod:`IPython.external.pretty` to compute the format data of
313 This uses :mod:`IPython.external.pretty` to compute the format data of
313 the object. If the object cannot be pretty printed, :func:`repr` is used.
314 the object. If the object cannot be pretty printed, :func:`repr` is used.
314 See the documentation of :mod:`IPython.external.pretty` for details on
315 See the documentation of :mod:`IPython.external.pretty` for details on
315 how to write pretty printers. Here is a simple example::
316 how to write pretty printers. Here is a simple example::
316
317
317 def dtype_pprinter(obj, p, cycle):
318 def dtype_pprinter(obj, p, cycle):
318 if cycle:
319 if cycle:
319 return p.text('dtype(...)')
320 return p.text('dtype(...)')
320 if hasattr(obj, 'fields'):
321 if hasattr(obj, 'fields'):
321 if obj.fields is None:
322 if obj.fields is None:
322 p.text(repr(obj))
323 p.text(repr(obj))
323 else:
324 else:
324 p.begin_group(7, 'dtype([')
325 p.begin_group(7, 'dtype([')
325 for i, field in enumerate(obj.descr):
326 for i, field in enumerate(obj.descr):
326 if i > 0:
327 if i > 0:
327 p.text(',')
328 p.text(',')
328 p.breakable()
329 p.breakable()
329 p.pretty(field)
330 p.pretty(field)
330 p.end_group(7, '])')
331 p.end_group(7, '])')
331 """
332 """
332
333
333 # The format type of data returned.
334 # The format type of data returned.
334 format_type = Str('text/plain')
335 format_type = Str('text/plain')
335
336
336 # This subclass ignores this attribute as it always need to return
337 # This subclass ignores this attribute as it always need to return
337 # something.
338 # something.
338 enabled = Bool(True, config=False)
339 enabled = Bool(True, config=False)
339
340
340 # Look for a __pretty__ methods to use for pretty printing.
341 # Look for a __pretty__ methods to use for pretty printing.
341 print_method = Str('__pretty__')
342 print_method = Str('__pretty__')
342
343
343 # Whether to pretty-print or not.
344 # Whether to pretty-print or not.
344 pprint = Bool(True, config=True)
345 pprint = Bool(True, config=True)
345
346
346 # Whether to be verbose or not.
347 # Whether to be verbose or not.
347 verbose = Bool(False, config=True)
348 verbose = Bool(False, config=True)
348
349
349 # The maximum width.
350 # The maximum width.
350 max_width = Int(79, config=True)
351 max_width = Int(79, config=True)
351
352
352 # The newline character.
353 # The newline character.
353 newline = Str('\n', config=True)
354 newline = Str('\n', config=True)
354
355
355 # Use the default pretty printers from IPython.external.pretty.
356 # Use the default pretty printers from IPython.external.pretty.
356 def _singleton_printers_default(self):
357 def _singleton_printers_default(self):
357 return pretty._singleton_pprinters.copy()
358 return pretty._singleton_pprinters.copy()
358
359
359 def _type_printers_default(self):
360 def _type_printers_default(self):
360 return pretty._type_pprinters.copy()
361 return pretty._type_pprinters.copy()
361
362
362 def _deferred_printers_default(self):
363 def _deferred_printers_default(self):
363 return pretty._deferred_type_pprinters.copy()
364 return pretty._deferred_type_pprinters.copy()
364
365
365 #### FormatterABC interface ####
366 #### FormatterABC interface ####
366
367
367 def __call__(self, obj):
368 def __call__(self, obj):
368 """Compute the pretty representation of the object."""
369 """Compute the pretty representation of the object."""
369 if not self.pprint:
370 if not self.pprint:
370 try:
371 try:
371 return repr(obj)
372 return repr(obj)
372 except TypeError:
373 except TypeError:
373 return ''
374 return ''
374 else:
375 else:
375 # This uses use StringIO, as cStringIO doesn't handle unicode.
376 # This uses use StringIO, as cStringIO doesn't handle unicode.
376 stream = StringIO()
377 stream = StringIO()
377 printer = pretty.RepresentationPrinter(stream, self.verbose,
378 printer = pretty.RepresentationPrinter(stream, self.verbose,
378 self.max_width, self.newline,
379 self.max_width, self.newline,
379 singleton_pprinters=self.singleton_printers,
380 singleton_pprinters=self.singleton_printers,
380 type_pprinters=self.type_printers,
381 type_pprinters=self.type_printers,
381 deferred_pprinters=self.deferred_printers)
382 deferred_pprinters=self.deferred_printers)
382 printer.pretty(obj)
383 printer.pretty(obj)
383 printer.flush()
384 printer.flush()
384 return stream.getvalue()
385 return stream.getvalue()
385
386
386
387
387 class HTMLFormatter(BaseFormatter):
388 class HTMLFormatter(BaseFormatter):
388 """An HTML formatter.
389 """An HTML formatter.
389
390
390 To define the callables that compute the HTML representation of your
391 To define the callables that compute the HTML representation of your
391 objects, define a :meth:`__html__` method or use the :meth:`for_type`
392 objects, define a :meth:`__html__` method or use the :meth:`for_type`
392 or :meth:`for_type_by_name` methods to register functions that handle
393 or :meth:`for_type_by_name` methods to register functions that handle
393 this.
394 this.
394 """
395 """
395 format_type = Str('text/html')
396 format_type = Str('text/html')
396
397
397 print_method = Str('__html__')
398 print_method = Str('__html__')
398
399
399
400
400 class SVGFormatter(BaseFormatter):
401 class SVGFormatter(BaseFormatter):
401 """An SVG formatter.
402 """An SVG formatter.
402
403
403 To define the callables that compute the SVG representation of your
404 To define the callables that compute the SVG representation of your
404 objects, define a :meth:`__svg__` method or use the :meth:`for_type`
405 objects, define a :meth:`__svg__` method or use the :meth:`for_type`
405 or :meth:`for_type_by_name` methods to register functions that handle
406 or :meth:`for_type_by_name` methods to register functions that handle
406 this.
407 this.
407 """
408 """
408 format_type = Str('image/svg+xml')
409 format_type = Str('image/svg+xml')
409
410
410 print_method = Str('__svg__')
411 print_method = Str('__svg__')
411
412
412
413
413 class PNGFormatter(BaseFormatter):
414 class PNGFormatter(BaseFormatter):
414 """A PNG formatter.
415 """A PNG formatter.
415
416
416 To define the callables that compute the PNG representation of your
417 To define the callables that compute the PNG representation of your
417 objects, define a :meth:`__png__` method or use the :meth:`for_type`
418 objects, define a :meth:`__png__` method or use the :meth:`for_type`
418 or :meth:`for_type_by_name` methods to register functions that handle
419 or :meth:`for_type_by_name` methods to register functions that handle
419 this. The raw data should be the base64 encoded raw png data.
420 this. The raw data should be the base64 encoded raw png data.
420 """
421 """
421 format_type = Str('image/png')
422 format_type = Str('image/png')
422
423
423 print_method = Str('__png__')
424 print_method = Str('__png__')
424
425
425
426
426 class LatexFormatter(BaseFormatter):
427 class LatexFormatter(BaseFormatter):
427 """A LaTeX formatter.
428 """A LaTeX formatter.
428
429
429 To define the callables that compute the LaTeX representation of your
430 To define the callables that compute the LaTeX representation of your
430 objects, define a :meth:`__latex__` method or use the :meth:`for_type`
431 objects, define a :meth:`__latex__` method or use the :meth:`for_type`
431 or :meth:`for_type_by_name` methods to register functions that handle
432 or :meth:`for_type_by_name` methods to register functions that handle
432 this.
433 this.
433 """
434 """
434 format_type = Str('text/latex')
435 format_type = Str('text/latex')
435
436
436 print_method = Str('__latex__')
437 print_method = Str('__latex__')
437
438
438
439
439 class JSONFormatter(BaseFormatter):
440 class JSONFormatter(BaseFormatter):
440 """A JSON string formatter.
441 """A JSON string formatter.
441
442
442 To define the callables that compute the JSON string representation of
443 To define the callables that compute the JSON string representation of
443 your objects, define a :meth:`__json__` method or use the :meth:`for_type`
444 your objects, define a :meth:`__json__` method or use the :meth:`for_type`
444 or :meth:`for_type_by_name` methods to register functions that handle
445 or :meth:`for_type_by_name` methods to register functions that handle
445 this.
446 this.
446 """
447 """
447 format_type = Str('application/json')
448 format_type = Str('application/json')
448
449
449 print_method = Str('__json__')
450 print_method = Str('__json__')
450
451
451
452
452 FormatterABC.register(BaseFormatter)
453 FormatterABC.register(BaseFormatter)
453 FormatterABC.register(PlainTextFormatter)
454 FormatterABC.register(PlainTextFormatter)
454 FormatterABC.register(HTMLFormatter)
455 FormatterABC.register(HTMLFormatter)
455 FormatterABC.register(SVGFormatter)
456 FormatterABC.register(SVGFormatter)
456 FormatterABC.register(PNGFormatter)
457 FormatterABC.register(PNGFormatter)
457 FormatterABC.register(LatexFormatter)
458 FormatterABC.register(LatexFormatter)
458 FormatterABC.register(JSONFormatter)
459 FormatterABC.register(JSONFormatter)
459
460
460
461
461 def format_display_data(obj, include=None, exclude=None):
462 def format_display_data(obj, include=None, exclude=None):
462 """Return a format data dict for an object.
463 """Return a format data dict for an object.
463
464
464 By default all format types will be computed.
465 By default all format types will be computed.
465
466
466 The following MIME types are currently implemented:
467 The following MIME types are currently implemented:
467
468
468 * text/plain
469 * text/plain
469 * text/html
470 * text/html
470 * text/latex
471 * text/latex
471 * application/json
472 * application/json
472 * image/png
473 * image/png
473 * immage/svg+xml
474 * immage/svg+xml
474
475
475 Parameters
476 Parameters
476 ----------
477 ----------
477 obj : object
478 obj : object
478 The Python object whose format data will be computed.
479 The Python object whose format data will be computed.
479
480
480 Returns
481 Returns
481 -------
482 -------
482 format_dict : dict
483 format_dict : dict
483 A dictionary of key/value pairs, one or each format that was
484 A dictionary of key/value pairs, one or each format that was
484 generated for the object. The keys are the format types, which
485 generated for the object. The keys are the format types, which
485 will usually be MIME type strings and the values and JSON'able
486 will usually be MIME type strings and the values and JSON'able
486 data structure containing the raw data for the representation in
487 data structure containing the raw data for the representation in
487 that format.
488 that format.
488 include : list or tuple, optional
489 include : list or tuple, optional
489 A list of format type strings (MIME types) to include in the
490 A list of format type strings (MIME types) to include in the
490 format data dict. If this is set *only* the format types included
491 format data dict. If this is set *only* the format types included
491 in this list will be computed.
492 in this list will be computed.
492 exclude : list or tuple, optional
493 exclude : list or tuple, optional
493 A list of format type string (MIME types) to exclue in the format
494 A list of format type string (MIME types) to exclue in the format
494 data dict. If this is set all format types will be computed,
495 data dict. If this is set all format types will be computed,
495 except for those included in this argument.
496 except for those included in this argument.
496 """
497 """
497 from IPython.core.interactiveshell import InteractiveShell
498 from IPython.core.interactiveshell import InteractiveShell
498
499
499 InteractiveShell.instance().display_formatter.format(
500 InteractiveShell.instance().display_formatter.format(
500 obj,
501 obj,
501 include,
502 include,
502 exclude
503 exclude
503 )
504 )
@@ -1,478 +1,507 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Usage information for the main IPython applications.
2 """Usage information for the main IPython applications.
3 """
3 """
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2008-2010 The IPython Development Team
5 # Copyright (C) 2008-2010 The IPython Development Team
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 #
7 #
8 # Distributed under the terms of the BSD License. The full license is in
8 # Distributed under the terms of the BSD License. The full license is in
9 # the file COPYING, distributed as part of this software.
9 # the file COPYING, distributed as part of this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 import sys
12 import sys
13 from IPython.core import release
13 from IPython.core import release
14
14
15 cl_usage = """\
15 cl_usage = """\
16 ipython [options] [files]
16 ipython [options] [files]
17
17
18 IPython: an enhanced interactive Python shell.
18 IPython: an enhanced interactive Python shell.
19
19
20 A Python shell with automatic history (input and output), dynamic object
20 A Python shell with automatic history (input and output), dynamic object
21 introspection, easier configuration, command completion, access to the
21 introspection, easier configuration, command completion, access to the
22 system shell and more. IPython can also be embedded in running programs.
22 system shell and more. IPython can also be embedded in running programs.
23
23
24 If invoked with no options, it executes all the files listed in sequence
24 If invoked with no options, it executes all the files listed in sequence
25 and exits, use -i to enter interactive mode after running the files. Files
25 and exits, use -i to enter interactive mode after running the files. Files
26 ending in .py will be treated as normal Python, but files ending in .ipy
26 ending in .py will be treated as normal Python, but files ending in .ipy
27 can contain special IPython syntax (magic commands, shell expansions, etc.)
27 can contain special IPython syntax (magic commands, shell expansions, etc.)
28
28
29 Please note that some of the configuration options are not available at the
29 Please note that some of the configuration options are not available at the
30 command line, simply because they are not practical here. Look into your
30 command line, simply because they are not practical here. Look into your
31 ipython_config.py configuration file for details on those.
31 ipython_config.py configuration file for details on those.
32
32
33 This file typically installed in the $HOME/.ipython directory. For Windows
33 This file typically installed in the $HOME/.ipython directory. For Windows
34 users, $HOME resolves to C:\\Documents and Settings\\YourUserName in most
34 users, $HOME resolves to C:\\Documents and Settings\\YourUserName in most
35 instances.
35 instances.
36
36
37 In IPython's documentation, we will refer to this directory as IPYTHON_DIR,
37 In IPython's documentation, we will refer to this directory as IPYTHON_DIR,
38 you can change its default location by setting any path you want in this
38 you can change its default location by setting any path you want in this
39 environment variable.
39 environment variable.
40
40
41 For more information, see the manual available in HTML and PDF in your
41 For more information, see the manual available in HTML and PDF in your
42 installation, or online at http://ipython.scipy.org.
42 installation, or online at http://ipython.scipy.org.
43 """
43 """
44
44
45 interactive_usage = """
45 interactive_usage = """
46 IPython -- An enhanced Interactive Python
46 IPython -- An enhanced Interactive Python
47 =========================================
47 =========================================
48
48
49 IPython offers a combination of convenient shell features, special commands
49 IPython offers a combination of convenient shell features, special commands
50 and a history mechanism for both input (command history) and output (results
50 and a history mechanism for both input (command history) and output (results
51 caching, similar to Mathematica). It is intended to be a fully compatible
51 caching, similar to Mathematica). It is intended to be a fully compatible
52 replacement for the standard Python interpreter, while offering vastly
52 replacement for the standard Python interpreter, while offering vastly
53 improved functionality and flexibility.
53 improved functionality and flexibility.
54
54
55 At your system command line, type 'ipython -help' to see the command line
55 At your system command line, type 'ipython -help' to see the command line
56 options available. This document only describes interactive features.
56 options available. This document only describes interactive features.
57
57
58 Warning: IPython relies on the existence of a global variable called __IP which
58 Warning: IPython relies on the existence of a global variable called __IP which
59 controls the shell itself. If you redefine __IP to anything, bizarre behavior
59 controls the shell itself. If you redefine __IP to anything, bizarre behavior
60 will quickly occur.
60 will quickly occur.
61
61
62 MAIN FEATURES
62 MAIN FEATURES
63
63
64 * Access to the standard Python help. As of Python 2.1, a help system is
64 * Access to the standard Python help. As of Python 2.1, a help system is
65 available with access to object docstrings and the Python manuals. Simply
65 available with access to object docstrings and the Python manuals. Simply
66 type 'help' (no quotes) to access it.
66 type 'help' (no quotes) to access it.
67
67
68 * Magic commands: type %magic for information on the magic subsystem.
68 * Magic commands: type %magic for information on the magic subsystem.
69
69
70 * System command aliases, via the %alias command or the ipythonrc config file.
70 * System command aliases, via the %alias command or the ipythonrc config file.
71
71
72 * Dynamic object information:
72 * Dynamic object information:
73
73
74 Typing ?word or word? prints detailed information about an object. If
74 Typing ?word or word? prints detailed information about an object. If
75 certain strings in the object are too long (docstrings, code, etc.) they get
75 certain strings in the object are too long (docstrings, code, etc.) they get
76 snipped in the center for brevity.
76 snipped in the center for brevity.
77
77
78 Typing ??word or word?? gives access to the full information without
78 Typing ??word or word?? gives access to the full information without
79 snipping long strings. Long strings are sent to the screen through the less
79 snipping long strings. Long strings are sent to the screen through the less
80 pager if longer than the screen, printed otherwise.
80 pager if longer than the screen, printed otherwise.
81
81
82 The ?/?? system gives access to the full source code for any object (if
82 The ?/?? system gives access to the full source code for any object (if
83 available), shows function prototypes and other useful information.
83 available), shows function prototypes and other useful information.
84
84
85 If you just want to see an object's docstring, type '%pdoc object' (without
85 If you just want to see an object's docstring, type '%pdoc object' (without
86 quotes, and without % if you have automagic on).
86 quotes, and without % if you have automagic on).
87
87
88 Both %pdoc and ?/?? give you access to documentation even on things which are
88 Both %pdoc and ?/?? give you access to documentation even on things which are
89 not explicitely defined. Try for example typing {}.get? or after import os,
89 not explicitely defined. Try for example typing {}.get? or after import os,
90 type os.path.abspath??. The magic functions %pdef, %source and %file operate
90 type os.path.abspath??. The magic functions %pdef, %source and %file operate
91 similarly.
91 similarly.
92
92
93 * Completion in the local namespace, by typing TAB at the prompt.
93 * Completion in the local namespace, by typing TAB at the prompt.
94
94
95 At any time, hitting tab will complete any available python commands or
95 At any time, hitting tab will complete any available python commands or
96 variable names, and show you a list of the possible completions if there's
96 variable names, and show you a list of the possible completions if there's
97 no unambiguous one. It will also complete filenames in the current directory.
97 no unambiguous one. It will also complete filenames in the current directory.
98
98
99 This feature requires the readline and rlcomplete modules, so it won't work
99 This feature requires the readline and rlcomplete modules, so it won't work
100 if your Python lacks readline support (such as under Windows).
100 if your Python lacks readline support (such as under Windows).
101
101
102 * Search previous command history in two ways (also requires readline):
102 * Search previous command history in two ways (also requires readline):
103
103
104 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
104 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
105 search through only the history items that match what you've typed so
105 search through only the history items that match what you've typed so
106 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
106 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
107 normal arrow keys.
107 normal arrow keys.
108
108
109 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
109 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
110 your history for lines that match what you've typed so far, completing as
110 your history for lines that match what you've typed so far, completing as
111 much as it can.
111 much as it can.
112
112
113 * Persistent command history across sessions (readline required).
113 * Persistent command history across sessions (readline required).
114
114
115 * Logging of input with the ability to save and restore a working session.
115 * Logging of input with the ability to save and restore a working session.
116
116
117 * System escape with !. Typing !ls will run 'ls' in the current directory.
117 * System escape with !. Typing !ls will run 'ls' in the current directory.
118
118
119 * The reload command does a 'deep' reload of a module: changes made to the
119 * The reload command does a 'deep' reload of a module: changes made to the
120 module since you imported will actually be available without having to exit.
120 module since you imported will actually be available without having to exit.
121
121
122 * Verbose and colored exception traceback printouts. See the magic xmode and
122 * Verbose and colored exception traceback printouts. See the magic xmode and
123 xcolor functions for details (just type %magic).
123 xcolor functions for details (just type %magic).
124
124
125 * Input caching system:
125 * Input caching system:
126
126
127 IPython offers numbered prompts (In/Out) with input and output caching. All
127 IPython offers numbered prompts (In/Out) with input and output caching. All
128 input is saved and can be retrieved as variables (besides the usual arrow
128 input is saved and can be retrieved as variables (besides the usual arrow
129 key recall).
129 key recall).
130
130
131 The following GLOBAL variables always exist (so don't overwrite them!):
131 The following GLOBAL variables always exist (so don't overwrite them!):
132 _i: stores previous input.
132 _i: stores previous input.
133 _ii: next previous.
133 _ii: next previous.
134 _iii: next-next previous.
134 _iii: next-next previous.
135 _ih : a list of all input _ih[n] is the input from line n.
135 _ih : a list of all input _ih[n] is the input from line n.
136
136
137 Additionally, global variables named _i<n> are dynamically created (<n>
137 Additionally, global variables named _i<n> are dynamically created (<n>
138 being the prompt counter), such that _i<n> == _ih[<n>]
138 being the prompt counter), such that _i<n> == _ih[<n>]
139
139
140 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
140 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
141
141
142 You can create macros which contain multiple input lines from this history,
142 You can create macros which contain multiple input lines from this history,
143 for later re-execution, with the %macro function.
143 for later re-execution, with the %macro function.
144
144
145 The history function %hist allows you to see any part of your input history
145 The history function %hist allows you to see any part of your input history
146 by printing a range of the _i variables. Note that inputs which contain
146 by printing a range of the _i variables. Note that inputs which contain
147 magic functions (%) appear in the history with a prepended comment. This is
147 magic functions (%) appear in the history with a prepended comment. This is
148 because they aren't really valid Python code, so you can't exec them.
148 because they aren't really valid Python code, so you can't exec them.
149
149
150 * Output caching system:
150 * Output caching system:
151
151
152 For output that is returned from actions, a system similar to the input
152 For output that is returned from actions, a system similar to the input
153 cache exists but using _ instead of _i. Only actions that produce a result
153 cache exists but using _ instead of _i. Only actions that produce a result
154 (NOT assignments, for example) are cached. If you are familiar with
154 (NOT assignments, for example) are cached. If you are familiar with
155 Mathematica, IPython's _ variables behave exactly like Mathematica's %
155 Mathematica, IPython's _ variables behave exactly like Mathematica's %
156 variables.
156 variables.
157
157
158 The following GLOBAL variables always exist (so don't overwrite them!):
158 The following GLOBAL variables always exist (so don't overwrite them!):
159 _ (one underscore): previous output.
159 _ (one underscore): previous output.
160 __ (two underscores): next previous.
160 __ (two underscores): next previous.
161 ___ (three underscores): next-next previous.
161 ___ (three underscores): next-next previous.
162
162
163 Global variables named _<n> are dynamically created (<n> being the prompt
163 Global variables named _<n> are dynamically created (<n> being the prompt
164 counter), such that the result of output <n> is always available as _<n>.
164 counter), such that the result of output <n> is always available as _<n>.
165
165
166 Finally, a global dictionary named _oh exists with entries for all lines
166 Finally, a global dictionary named _oh exists with entries for all lines
167 which generated output.
167 which generated output.
168
168
169 * Directory history:
169 * Directory history:
170
170
171 Your history of visited directories is kept in the global list _dh, and the
171 Your history of visited directories is kept in the global list _dh, and the
172 magic %cd command can be used to go to any entry in that list.
172 magic %cd command can be used to go to any entry in that list.
173
173
174 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
174 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
175
175
176 1. Auto-parentheses
176 1. Auto-parentheses
177 Callable objects (i.e. functions, methods, etc) can be invoked like
177 Callable objects (i.e. functions, methods, etc) can be invoked like
178 this (notice the commas between the arguments):
178 this (notice the commas between the arguments):
179 >>> callable_ob arg1, arg2, arg3
179 >>> callable_ob arg1, arg2, arg3
180 and the input will be translated to this:
180 and the input will be translated to this:
181 --> callable_ob(arg1, arg2, arg3)
181 --> callable_ob(arg1, arg2, arg3)
182 You can force auto-parentheses by using '/' as the first character
182 You can force auto-parentheses by using '/' as the first character
183 of a line. For example:
183 of a line. For example:
184 >>> /globals # becomes 'globals()'
184 >>> /globals # becomes 'globals()'
185 Note that the '/' MUST be the first character on the line! This
185 Note that the '/' MUST be the first character on the line! This
186 won't work:
186 won't work:
187 >>> print /globals # syntax error
187 >>> print /globals # syntax error
188
188
189 In most cases the automatic algorithm should work, so you should
189 In most cases the automatic algorithm should work, so you should
190 rarely need to explicitly invoke /. One notable exception is if you
190 rarely need to explicitly invoke /. One notable exception is if you
191 are trying to call a function with a list of tuples as arguments (the
191 are trying to call a function with a list of tuples as arguments (the
192 parenthesis will confuse IPython):
192 parenthesis will confuse IPython):
193 In [1]: zip (1,2,3),(4,5,6) # won't work
193 In [1]: zip (1,2,3),(4,5,6) # won't work
194 but this will work:
194 but this will work:
195 In [2]: /zip (1,2,3),(4,5,6)
195 In [2]: /zip (1,2,3),(4,5,6)
196 ------> zip ((1,2,3),(4,5,6))
196 ------> zip ((1,2,3),(4,5,6))
197 Out[2]= [(1, 4), (2, 5), (3, 6)]
197 Out[2]= [(1, 4), (2, 5), (3, 6)]
198
198
199 IPython tells you that it has altered your command line by
199 IPython tells you that it has altered your command line by
200 displaying the new command line preceded by -->. e.g.:
200 displaying the new command line preceded by -->. e.g.:
201 In [18]: callable list
201 In [18]: callable list
202 -------> callable (list)
202 -------> callable (list)
203
203
204 2. Auto-Quoting
204 2. Auto-Quoting
205 You can force auto-quoting of a function's arguments by using ',' as
205 You can force auto-quoting of a function's arguments by using ',' as
206 the first character of a line. For example:
206 the first character of a line. For example:
207 >>> ,my_function /home/me # becomes my_function("/home/me")
207 >>> ,my_function /home/me # becomes my_function("/home/me")
208
208
209 If you use ';' instead, the whole argument is quoted as a single
209 If you use ';' instead, the whole argument is quoted as a single
210 string (while ',' splits on whitespace):
210 string (while ',' splits on whitespace):
211 >>> ,my_function a b c # becomes my_function("a","b","c")
211 >>> ,my_function a b c # becomes my_function("a","b","c")
212 >>> ;my_function a b c # becomes my_function("a b c")
212 >>> ;my_function a b c # becomes my_function("a b c")
213
213
214 Note that the ',' MUST be the first character on the line! This
214 Note that the ',' MUST be the first character on the line! This
215 won't work:
215 won't work:
216 >>> x = ,my_function /home/me # syntax error
216 >>> x = ,my_function /home/me # syntax error
217 """
217 """
218
218
219 interactive_usage_min = """\
219 interactive_usage_min = """\
220 An enhanced console for Python.
220 An enhanced console for Python.
221 Some of its features are:
221 Some of its features are:
222 - Readline support if the readline library is present.
222 - Readline support if the readline library is present.
223 - Tab completion in the local namespace.
223 - Tab completion in the local namespace.
224 - Logging of input, see command-line options.
224 - Logging of input, see command-line options.
225 - System shell escape via ! , eg !ls.
225 - System shell escape via ! , eg !ls.
226 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
226 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
227 - Keeps track of locally defined variables via %who, %whos.
227 - Keeps track of locally defined variables via %who, %whos.
228 - Show object information with a ? eg ?x or x? (use ?? for more info).
228 - Show object information with a ? eg ?x or x? (use ?? for more info).
229 """
229 """
230
230
231 quick_reference = r"""
231 quick_reference = r"""
232 IPython -- An enhanced Interactive Python - Quick Reference Card
232 IPython -- An enhanced Interactive Python - Quick Reference Card
233 ================================================================
233 ================================================================
234
234
235 obj?, obj?? : Get help, or more help for object (also works as
235 obj?, obj?? : Get help, or more help for object (also works as
236 ?obj, ??obj).
236 ?obj, ??obj).
237 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
237 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
238 %magic : Information about IPython's 'magic' % functions.
238 %magic : Information about IPython's 'magic' % functions.
239
239
240 Magic functions are prefixed by %, and typically take their arguments without
240 Magic functions are prefixed by %, and typically take their arguments without
241 parentheses, quotes or even commas for convenience.
241 parentheses, quotes or even commas for convenience.
242
242
243 Example magic function calls:
243 Example magic function calls:
244
244
245 %alias d ls -F : 'd' is now an alias for 'ls -F'
245 %alias d ls -F : 'd' is now an alias for 'ls -F'
246 alias d ls -F : Works if 'alias' not a python name
246 alias d ls -F : Works if 'alias' not a python name
247 alist = %alias : Get list of aliases to 'alist'
247 alist = %alias : Get list of aliases to 'alist'
248 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
248 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
249 %cd?? : See help AND source for magic %cd
249 %cd?? : See help AND source for magic %cd
250
250
251 System commands:
251 System commands:
252
252
253 !cp a.txt b/ : System command escape, calls os.system()
253 !cp a.txt b/ : System command escape, calls os.system()
254 cp a.txt b/ : after %rehashx, most system commands work without !
254 cp a.txt b/ : after %rehashx, most system commands work without !
255 cp ${f}.txt $bar : Variable expansion in magics and system commands
255 cp ${f}.txt $bar : Variable expansion in magics and system commands
256 files = !ls /usr : Capture sytem command output
256 files = !ls /usr : Capture sytem command output
257 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
257 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
258
258
259 History:
259 History:
260
260
261 _i, _ii, _iii : Previous, next previous, next next previous input
261 _i, _ii, _iii : Previous, next previous, next next previous input
262 _i4, _ih[2:5] : Input history line 4, lines 2-4
262 _i4, _ih[2:5] : Input history line 4, lines 2-4
263 exec _i81 : Execute input history line #81 again
263 exec _i81 : Execute input history line #81 again
264 %rep 81 : Edit input history line #81
264 %rep 81 : Edit input history line #81
265 _, __, ___ : previous, next previous, next next previous output
265 _, __, ___ : previous, next previous, next next previous output
266 _dh : Directory history
266 _dh : Directory history
267 _oh : Output history
267 _oh : Output history
268 %hist : Command history. '%hist -g foo' search history for 'foo'
268 %hist : Command history. '%hist -g foo' search history for 'foo'
269
269
270 Autocall:
270 Autocall:
271
271
272 f 1,2 : f(1,2)
272 f 1,2 : f(1,2)
273 /f 1,2 : f(1,2) (forced autoparen)
273 /f 1,2 : f(1,2) (forced autoparen)
274 ,f 1 2 : f("1","2")
274 ,f 1 2 : f("1","2")
275 ;f 1 2 : f("1 2")
275 ;f 1 2 : f("1 2")
276
276
277 Remember: TAB completion works in many contexts, not just file names
277 Remember: TAB completion works in many contexts, not just file names
278 or python names.
278 or python names.
279
279
280 The following magic functions are currently available:
280 The following magic functions are currently available:
281
281
282 """
282 """
283
283
284 gui_reference = """\
284 gui_reference = """\
285 ===============================
285 ===============================
286 The graphical IPython console
286 The graphical IPython console
287 ===============================
287 ===============================
288
288
289 This console is designed to emulate the look, feel and workflow of a terminal
289 This console is designed to emulate the look, feel and workflow of a terminal
290 environment, while adding a number of enhancements that are simply not possible
290 environment, while adding a number of enhancements that are simply not possible
291 in a real terminal, such as inline syntax highlighting, true multiline editing,
291 in a real terminal, such as inline syntax highlighting, true multiline editing,
292 inline graphics and much more.
292 inline graphics and much more.
293
293
294 This quick reference document contains the basic information you'll need to
294 This quick reference document contains the basic information you'll need to
295 know to make the most efficient use of it. For the various command line
295 know to make the most efficient use of it. For the various command line
296 options available at startup, type ``--help`` at the command line.
296 options available at startup, type ``--help`` at the command line.
297
297
298
298
299 Multiline editing
299 Multiline editing
300 =================
300 =================
301
301
302 The graphical console is capable of true multiline editing, but it also tries
302 The graphical console is capable of true multiline editing, but it also tries
303 to behave intuitively like a terminal when possible. If you are used to
303 to behave intuitively like a terminal when possible. If you are used to
304 IPyhton's old terminal behavior, you should find the transition painless, and
304 IPyhton's old terminal behavior, you should find the transition painless, and
305 once you learn a few basic keybindings it will be a much more efficient
305 once you learn a few basic keybindings it will be a much more efficient
306 environment.
306 environment.
307
307
308 For single expressions or indented blocks, the console behaves almost like the
308 For single expressions or indented blocks, the console behaves almost like the
309 terminal IPython: single expressions are immediately evaluated, and indented
309 terminal IPython: single expressions are immediately evaluated, and indented
310 blocks are evaluated once a single blank line is entered::
310 blocks are evaluated once a single blank line is entered::
311
311
312 In [1]: print "Hello IPython!" # Enter was pressed at the end of the line
312 In [1]: print "Hello IPython!" # Enter was pressed at the end of the line
313 Hello IPython!
313 Hello IPython!
314
314
315 In [2]: for i in range(10):
315 In [2]: for i in range(10):
316 ...: print i,
316 ...: print i,
317 ...:
317 ...:
318 0 1 2 3 4 5 6 7 8 9
318 0 1 2 3 4 5 6 7 8 9
319
319
320 If you want to enter more than one expression in a single input block
320 If you want to enter more than one expression in a single input block
321 (something not possible in the terminal), you can use ``Control-Enter`` at the
321 (something not possible in the terminal), you can use ``Control-Enter`` at the
322 end of your first line instead of ``Enter``. At that point the console goes
322 end of your first line instead of ``Enter``. At that point the console goes
323 into 'cell mode' and even if your inputs are not indented, it will continue
323 into 'cell mode' and even if your inputs are not indented, it will continue
324 accepting arbitrarily many lines until either you enter an extra blank line or
324 accepting arbitrarily many lines until either you enter an extra blank line or
325 you hit ``Shift-Enter`` (the key binding that forces execution). When a
325 you hit ``Shift-Enter`` (the key binding that forces execution). When a
326 multiline cell is entered, IPython analyzes it and executes its code producing
326 multiline cell is entered, IPython analyzes it and executes its code producing
327 an ``Out[n]`` prompt only for the last expression in it, while the rest of the
327 an ``Out[n]`` prompt only for the last expression in it, while the rest of the
328 cell is executed as if it was a script. An example should clarify this::
328 cell is executed as if it was a script. An example should clarify this::
329
329
330 In [3]: x=1 # Hit C-Enter here
330 In [3]: x=1 # Hit C-Enter here
331 ...: y=2 # from now on, regular Enter is sufficient
331 ...: y=2 # from now on, regular Enter is sufficient
332 ...: z=3
332 ...: z=3
333 ...: x**2 # This does *not* produce an Out[] value
333 ...: x**2 # This does *not* produce an Out[] value
334 ...: x+y+z # Only the last expression does
334 ...: x+y+z # Only the last expression does
335 ...:
335 ...:
336 Out[3]: 6
336 Out[3]: 6
337
337
338 The behavior where an extra blank line forces execution is only active if you
338 The behavior where an extra blank line forces execution is only active if you
339 are actually typing at the keyboard each line, and is meant to make it mimic
339 are actually typing at the keyboard each line, and is meant to make it mimic
340 the IPython terminal behavior. If you paste a long chunk of input (for example
340 the IPython terminal behavior. If you paste a long chunk of input (for example
341 a long script copied form an editor or web browser), it can contain arbitrarily
341 a long script copied form an editor or web browser), it can contain arbitrarily
342 many intermediate blank lines and they won't cause any problems. As always,
342 many intermediate blank lines and they won't cause any problems. As always,
343 you can then make it execute by appending a blank line *at the end* or hitting
343 you can then make it execute by appending a blank line *at the end* or hitting
344 ``Shift-Enter`` anywhere within the cell.
344 ``Shift-Enter`` anywhere within the cell.
345
345
346 With the up arrow key, you can retrieve previous blocks of input that contain
346 With the up arrow key, you can retrieve previous blocks of input that contain
347 multiple lines. You can move inside of a multiline cell like you would in any
347 multiple lines. You can move inside of a multiline cell like you would in any
348 text editor. When you want it executed, the simplest thing to do is to hit the
348 text editor. When you want it executed, the simplest thing to do is to hit the
349 force execution key, ``Shift-Enter`` (though you can also navigate to the end
349 force execution key, ``Shift-Enter`` (though you can also navigate to the end
350 and append a blank line by using ``Enter`` twice).
350 and append a blank line by using ``Enter`` twice).
351
351
352 If you've edited a multiline cell and accidentally navigate out of it with the
352 If you've edited a multiline cell and accidentally navigate out of it with the
353 up or down arrow keys, IPython will clear the cell and replace it with the
353 up or down arrow keys, IPython will clear the cell and replace it with the
354 contents of the one above or below that you navigated to. If this was an
354 contents of the one above or below that you navigated to. If this was an
355 accident and you want to retrieve the cell you were editing, use the Undo
355 accident and you want to retrieve the cell you were editing, use the Undo
356 keybinding, ``Control-z``.
356 keybinding, ``Control-z``.
357
357
358
358
359 Key bindings
359 Key bindings
360 ============
360 ============
361
361
362 The IPython console supports most of the basic Emacs line-oriented keybindings,
362 The IPython console supports most of the basic Emacs line-oriented keybindings,
363 in addition to some of its own.
363 in addition to some of its own.
364
364
365 The keybinding prefixes mean:
365 The keybinding prefixes mean:
366
366
367 - ``C``: Control
367 - ``C``: Control
368 - ``S``: Shift
368 - ``S``: Shift
369 - ``M``: Meta (typically the Alt key)
369 - ``M``: Meta (typically the Alt key)
370
370
371 The keybindings themselves are:
371 The keybindings themselves are:
372
372
373 - ``Enter``: insert new line (may cause execution, see above).
373 - ``Enter``: insert new line (may cause execution, see above).
374 - ``C-Enter``: force new line, *never* causes execution.
374 - ``C-Enter``: force new line, *never* causes execution.
375 - ``S-Enter``: *force* execution regardless of where cursor is, no newline added.
375 - ``S-Enter``: *force* execution regardless of where cursor is, no newline added.
376 - ``C-c``: copy highlighted text to clipboard (prompts are automatically stripped).
376 - ``C-c``: copy highlighted text to clipboard (prompts are automatically stripped).
377 - ``C-S-c``: copy highlighted text to clipboard (prompts are not stripped).
377 - ``C-S-c``: copy highlighted text to clipboard (prompts are not stripped).
378 - ``C-v``: paste text from clipboard.
378 - ``C-v``: paste text from clipboard.
379 - ``C-z``: undo (retrieves lost text if you move out of a cell with the arrows).
379 - ``C-z``: undo (retrieves lost text if you move out of a cell with the arrows).
380 - ``C-S-z``: redo.
380 - ``C-S-z``: redo.
381 - ``C-o``: move to 'other' area, between pager and terminal.
381 - ``C-o``: move to 'other' area, between pager and terminal.
382 - ``C-l``: clear terminal.
382 - ``C-l``: clear terminal.
383 - ``C-a``: go to beginning of line.
383 - ``C-a``: go to beginning of line.
384 - ``C-e``: go to end of line.
384 - ``C-e``: go to end of line.
385 - ``C-k``: kill from cursor to the end of the line.
385 - ``C-k``: kill from cursor to the end of the line.
386 - ``C-y``: yank (paste)
386 - ``C-y``: yank (paste)
387 - ``C-p``: previous line (like up arrow)
387 - ``C-p``: previous line (like up arrow)
388 - ``C-n``: next line (like down arrow)
388 - ``C-n``: next line (like down arrow)
389 - ``C-f``: forward (like right arrow)
389 - ``C-f``: forward (like right arrow)
390 - ``C-b``: back (like left arrow)
390 - ``C-b``: back (like left arrow)
391 - ``C-d``: delete next character.
391 - ``C-d``: delete next character.
392 - ``M-<``: move to the beginning of the input region.
392 - ``M-<``: move to the beginning of the input region.
393 - ``M->``: move to the end of the input region.
393 - ``M->``: move to the end of the input region.
394 - ``M-d``: delete next word.
394 - ``M-d``: delete next word.
395 - ``M-Backspace``: delete previous word.
395 - ``M-Backspace``: delete previous word.
396 - ``C-.``: force a kernel restart (a confirmation dialog appears).
396 - ``C-.``: force a kernel restart (a confirmation dialog appears).
397 - ``C-+``: increase font size.
397 - ``C-+``: increase font size.
398 - ``C--``: decrease font size.
398 - ``C--``: decrease font size.
399
399
400 The IPython pager
400 The IPython pager
401 =================
401 =================
402
402
403 IPython will show long blocks of text from many sources using a builtin pager.
403 IPython will show long blocks of text from many sources using a builtin pager.
404 You can control where this pager appears with the ``--paging`` command-line
404 You can control where this pager appears with the ``--paging`` command-line
405 flag:
405 flag:
406
406
407 - default: it is overlaid on top of the main terminal. You must quit the pager
407 - default: it is overlaid on top of the main terminal. You must quit the pager
408 to get back to the terminal (similar to how a pager such as ``less`` or
408 to get back to the terminal (similar to how a pager such as ``less`` or
409 ``more`` works).
409 ``more`` works).
410
410
411 - vertical: the console is made double-tall, and the pager appears on the
411 - vertical: the console is made double-tall, and the pager appears on the
412 bottom area when needed. You can view its contents while using the terminal.
412 bottom area when needed. You can view its contents while using the terminal.
413
413
414 - horizontal: the console is made double-wide, and the pager appears on the
414 - horizontal: the console is made double-wide, and the pager appears on the
415 right area when needed. You can view its contents while using the terminal.
415 right area when needed. You can view its contents while using the terminal.
416
416
417 If you use the vertical or horizontal paging modes, you can navigate between
417 If you use the vertical or horizontal paging modes, you can navigate between
418 terminal and pager as follows:
418 terminal and pager as follows:
419
419
420 - Tab key: goes from pager to terminal (but not the other way around).
420 - Tab key: goes from pager to terminal (but not the other way around).
421 - Control-o: goes from one to another always.
421 - Control-o: goes from one to another always.
422 - Mouse: click on either.
422 - Mouse: click on either.
423
423
424 In all cases, the ``q`` or ``Escape`` keys quit the pager (when used with the
424 In all cases, the ``q`` or ``Escape`` keys quit the pager (when used with the
425 focus on the pager area).
425 focus on the pager area).
426
426
427
427
428 Running subprocesses
428 Running subprocesses
429 ====================
429 ====================
430
430
431 The graphical IPython console uses the ``pexpect`` module to run subprocesses
431 The graphical IPython console uses the ``pexpect`` module to run subprocesses
432 when you type ``!command``. This has a number of advantages (true asynchronous
432 when you type ``!command``. This has a number of advantages (true asynchronous
433 output from subprocesses as well as very robust termination of rogue
433 output from subprocesses as well as very robust termination of rogue
434 subprocesses with ``Control-C``), as well as some limitations. The main
434 subprocesses with ``Control-C``), as well as some limitations. The main
435 limitation is that you can *not* interact back with the subprocess, so anything
435 limitation is that you can *not* interact back with the subprocess, so anything
436 that invokes a pager or expects you to type input into it will block and hang
436 that invokes a pager or expects you to type input into it will block and hang
437 (you can kill it with ``Control-C``).
437 (you can kill it with ``Control-C``).
438
438
439 We have provided as magics ``%less`` to page files (aliased to ``%more``),
439 We have provided as magics ``%less`` to page files (aliased to ``%more``),
440 ``%clear`` to clear the terminal, and ``%man`` on Linux/OSX. These cover the
440 ``%clear`` to clear the terminal, and ``%man`` on Linux/OSX. These cover the
441 most common commands you'd want to call in your subshell and that would cause
441 most common commands you'd want to call in your subshell and that would cause
442 problems if invoked via ``!cmd``, but you need to be aware of this limitation.
442 problems if invoked via ``!cmd``, but you need to be aware of this limitation.
443
443
444 Display
445 =======
446
447 The IPython console can now display objects in a variety of formats, including
448 HTML, PNG and SVG. This is accomplished using the display functions in
449 ``IPython.core.display``::
450
451 In [4]: from IPython.core.display import display, display_html
452
453 In [5]: from IPython.core.display import display_png, display_svg
454
455 Python objects can simply be passed to these functions and the appropriate
456 representations will be displayed in the console as long as the objects know
457 how to compute those representations. The easiest way of teaching objects how
458 to format themselves in various representations is to define special methods
459 such as: ``__html``, ``__svg__`` and ``__png__``. IPython's display formatters
460 can also be given custom formatter functions for various types::
461
462 In [6]: ip = get_ipython()
463
464 In [7]: html_formatter = ip.display_formatter.formatters['text/html']
465
466 In [8]: html_formatter.for_type(Foo, foo_to_html)
467
468 For further details, see ``IPython.core.formatters``.
444
469
445 Inline matplotlib graphics
470 Inline matplotlib graphics
446 ==========================
471 ==========================
447
472
448 The IPython console is capable of displaying matplotlib figures inline, in SVG
473 The IPython console is capable of displaying matplotlib figures inline, in SVG
449 format. If started with the ``--pylab inline`` flag, then all figures are
474 format. If started with the ``--pylab inline`` flag, then all figures are
450 rendered inline automatically. If started with ``--pylab`` or ``--pylab <your
475 rendered inline automatically. If started with ``--pylab`` or ``--pylab <your
451 backend>``, then a GUI backend will be used, but the ``pastefig()`` function is
476 backend>``, then a GUI backend will be used, but IPython's ``display()`` and
452 added to the global and ``plt`` namespaces. You can paste any figure that is
477 ``getfigs()`` functions can be used to view plots inline::
453 currently open in a window with this function; type ``pastefig?`` for
478
454 additional details."""
479 In [9]: display(*getfigs()) # display all figures inline
480
481 In[10]: display(*getfigs(1,2)) # display figures 1 and 2 inline
482 """
483
455
484
456 quick_guide = """\
485 quick_guide = """\
457 ? -> Introduction and overview of IPython's features.
486 ? -> Introduction and overview of IPython's features.
458 %quickref -> Quick reference.
487 %quickref -> Quick reference.
459 help -> Python's own help system.
488 help -> Python's own help system.
460 object? -> Details about 'object', use 'object??' for extra details.
489 object? -> Details about 'object', use 'object??' for extra details.
461 """
490 """
462
491
463 gui_note = """\
492 gui_note = """\
464 %guiref -> A brief reference about the graphical user interface.
493 %guiref -> A brief reference about the graphical user interface.
465 """
494 """
466
495
467 default_banner_parts = [
496 default_banner_parts = [
468 'Python %s\n' % (sys.version.split('\n')[0],),
497 'Python %s\n' % (sys.version.split('\n')[0],),
469 'Type "copyright", "credits" or "license" for more information.\n\n',
498 'Type "copyright", "credits" or "license" for more information.\n\n',
470 'IPython %s -- An enhanced Interactive Python.\n' % (release.version,),
499 'IPython %s -- An enhanced Interactive Python.\n' % (release.version,),
471 quick_guide
500 quick_guide
472 ]
501 ]
473
502
474 default_gui_banner_parts = default_banner_parts + [gui_note]
503 default_gui_banner_parts = default_banner_parts + [gui_note]
475
504
476 default_banner = ''.join(default_banner_parts)
505 default_banner = ''.join(default_banner_parts)
477
506
478 default_gui_banner = ''.join(default_gui_banner_parts)
507 default_gui_banner = ''.join(default_gui_banner_parts)
@@ -1,251 +1,280 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Pylab (matplotlib) support utilities.
2 """Pylab (matplotlib) support utilities.
3
3
4 Authors
4 Authors
5 -------
5 -------
6
6
7 * Fernando Perez.
7 * Fernando Perez.
8 * Brian Granger
8 * Brian Granger
9 """
9 """
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Copyright (C) 2009 The IPython Development Team
12 # Copyright (C) 2009 The IPython Development Team
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Imports
19 # Imports
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 from cStringIO import StringIO
22 from cStringIO import StringIO
23
23
24 from IPython.utils.decorators import flag_calls
24 from IPython.utils.decorators import flag_calls
25
25
26 # If user specifies a GUI, that dictates the backend, otherwise we read the
26 # If user specifies a GUI, that dictates the backend, otherwise we read the
27 # user's mpl default from the mpl rc structure
27 # user's mpl default from the mpl rc structure
28 backends = {'tk': 'TkAgg',
28 backends = {'tk': 'TkAgg',
29 'gtk': 'GTKAgg',
29 'gtk': 'GTKAgg',
30 'wx': 'WXAgg',
30 'wx': 'WXAgg',
31 'qt': 'Qt4Agg', # qt3 not supported
31 'qt': 'Qt4Agg', # qt3 not supported
32 'qt4': 'Qt4Agg',
32 'qt4': 'Qt4Agg',
33 'inline' : 'module://IPython.zmq.pylab.backend_inline'}
33 'inline' : 'module://IPython.zmq.pylab.backend_inline'}
34
34
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
36 # Matplotlib utilities
36 # Matplotlib utilities
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38
38
39
40 def getfigs(*fig_nums):
41 """Get a list of matplotlib figures by figure numbers.
42
43 If no arguments are given, all available figures are returned. If the
44 argument list contains references to invalid figures, a warning is printed
45 but the function continues pasting further figures.
46
47 Parameters
48 ----------
49 figs : tuple
50 A tuple of ints giving the figure numbers of the figures to return.
51 """
52 from matplotlib._pylab_helpers import Gcf
53 if not fig_nums:
54 fig_managers = Gcf.get_all_fig_managers()
55 return [fm.canvas.figure for fm in fig_managers]
56 else:
57 figs = []
58 for num in fig_nums:
59 f = Gcf.figs.get(num)
60 if f is None:
61 print('Warning: figure %s not available.' % num)
62 figs.append(f.canvas.figure)
63 return figs
64
65
39 def figsize(sizex, sizey):
66 def figsize(sizex, sizey):
40 """Set the default figure size to be [sizex, sizey].
67 """Set the default figure size to be [sizex, sizey].
41
68
42 This is just an easy to remember, convenience wrapper that sets::
69 This is just an easy to remember, convenience wrapper that sets::
43
70
44 matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
71 matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
45 """
72 """
46 import matplotlib
73 import matplotlib
47 matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
74 matplotlib.rcParams['figure.figsize'] = [sizex, sizey]
48
75
49
76
50 def figure_to_svg(fig):
77 def figure_to_svg(fig):
51 """Convert a figure to svg for inline display."""
78 """Convert a figure to svg for inline display."""
52 fc = fig.get_facecolor()
79 fc = fig.get_facecolor()
53 ec = fig.get_edgecolor()
80 ec = fig.get_edgecolor()
54 fig.set_facecolor('white')
81 fig.set_facecolor('white')
55 fig.set_edgecolor('white')
82 fig.set_edgecolor('white')
56 try:
83 try:
57 string_io = StringIO()
84 string_io = StringIO()
58 fig.canvas.print_figure(string_io, format='svg')
85 fig.canvas.print_figure(string_io, format='svg')
59 svg = string_io.getvalue()
86 svg = string_io.getvalue()
60 finally:
87 finally:
61 fig.set_facecolor(fc)
88 fig.set_facecolor(fc)
62 fig.set_edgecolor(ec)
89 fig.set_edgecolor(ec)
63 return svg
90 return svg
64
91
65
92
66 # We need a little factory function here to create the closure where
93 # We need a little factory function here to create the closure where
67 # safe_execfile can live.
94 # safe_execfile can live.
68 def mpl_runner(safe_execfile):
95 def mpl_runner(safe_execfile):
69 """Factory to return a matplotlib-enabled runner for %run.
96 """Factory to return a matplotlib-enabled runner for %run.
70
97
71 Parameters
98 Parameters
72 ----------
99 ----------
73 safe_execfile : function
100 safe_execfile : function
74 This must be a function with the same interface as the
101 This must be a function with the same interface as the
75 :meth:`safe_execfile` method of IPython.
102 :meth:`safe_execfile` method of IPython.
76
103
77 Returns
104 Returns
78 -------
105 -------
79 A function suitable for use as the ``runner`` argument of the %run magic
106 A function suitable for use as the ``runner`` argument of the %run magic
80 function.
107 function.
81 """
108 """
82
109
83 def mpl_execfile(fname,*where,**kw):
110 def mpl_execfile(fname,*where,**kw):
84 """matplotlib-aware wrapper around safe_execfile.
111 """matplotlib-aware wrapper around safe_execfile.
85
112
86 Its interface is identical to that of the :func:`execfile` builtin.
113 Its interface is identical to that of the :func:`execfile` builtin.
87
114
88 This is ultimately a call to execfile(), but wrapped in safeties to
115 This is ultimately a call to execfile(), but wrapped in safeties to
89 properly handle interactive rendering."""
116 properly handle interactive rendering."""
90
117
91 import matplotlib
118 import matplotlib
92 import matplotlib.pylab as pylab
119 import matplotlib.pylab as pylab
93
120
94 #print '*** Matplotlib runner ***' # dbg
121 #print '*** Matplotlib runner ***' # dbg
95 # turn off rendering until end of script
122 # turn off rendering until end of script
96 is_interactive = matplotlib.rcParams['interactive']
123 is_interactive = matplotlib.rcParams['interactive']
97 matplotlib.interactive(False)
124 matplotlib.interactive(False)
98 safe_execfile(fname,*where,**kw)
125 safe_execfile(fname,*where,**kw)
99 matplotlib.interactive(is_interactive)
126 matplotlib.interactive(is_interactive)
100 # make rendering call now, if the user tried to do it
127 # make rendering call now, if the user tried to do it
101 if pylab.draw_if_interactive.called:
128 if pylab.draw_if_interactive.called:
102 pylab.draw()
129 pylab.draw()
103 pylab.draw_if_interactive.called = False
130 pylab.draw_if_interactive.called = False
104
131
105 return mpl_execfile
132 return mpl_execfile
106
133
107
134
108 #-----------------------------------------------------------------------------
135 #-----------------------------------------------------------------------------
109 # Code for initializing matplotlib and importing pylab
136 # Code for initializing matplotlib and importing pylab
110 #-----------------------------------------------------------------------------
137 #-----------------------------------------------------------------------------
111
138
112
139
113 def find_gui_and_backend(gui=None):
140 def find_gui_and_backend(gui=None):
114 """Given a gui string return the gui and mpl backend.
141 """Given a gui string return the gui and mpl backend.
115
142
116 Parameters
143 Parameters
117 ----------
144 ----------
118 gui : str
145 gui : str
119 Can be one of ('tk','gtk','wx','qt','qt4','inline').
146 Can be one of ('tk','gtk','wx','qt','qt4','inline').
120
147
121 Returns
148 Returns
122 -------
149 -------
123 A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg',
150 A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg',
124 'WXAgg','Qt4Agg','module://IPython.zmq.pylab.backend_inline').
151 'WXAgg','Qt4Agg','module://IPython.zmq.pylab.backend_inline').
125 """
152 """
126
153
127 import matplotlib
154 import matplotlib
128
155
129 if gui:
156 if gui:
130 # select backend based on requested gui
157 # select backend based on requested gui
131 backend = backends[gui]
158 backend = backends[gui]
132 else:
159 else:
133 backend = matplotlib.rcParams['backend']
160 backend = matplotlib.rcParams['backend']
134 # In this case, we need to find what the appropriate gui selection call
161 # In this case, we need to find what the appropriate gui selection call
135 # should be for IPython, so we can activate inputhook accordingly
162 # should be for IPython, so we can activate inputhook accordingly
136 g2b = backends # maps gui names to mpl backend names
163 g2b = backends # maps gui names to mpl backend names
137 b2g = dict(zip(g2b.values(), g2b.keys())) # reverse dict
164 b2g = dict(zip(g2b.values(), g2b.keys())) # reverse dict
138 gui = b2g.get(backend, None)
165 gui = b2g.get(backend, None)
139 return gui, backend
166 return gui, backend
140
167
141
168
142 def activate_matplotlib(backend):
169 def activate_matplotlib(backend):
143 """Activate the given backend and set interactive to True."""
170 """Activate the given backend and set interactive to True."""
144
171
145 import matplotlib
172 import matplotlib
146 if backend.startswith('module://'):
173 if backend.startswith('module://'):
147 # Work around bug in matplotlib: matplotlib.use converts the
174 # Work around bug in matplotlib: matplotlib.use converts the
148 # backend_id to lowercase even if a module name is specified!
175 # backend_id to lowercase even if a module name is specified!
149 matplotlib.rcParams['backend'] = backend
176 matplotlib.rcParams['backend'] = backend
150 else:
177 else:
151 matplotlib.use(backend)
178 matplotlib.use(backend)
152 matplotlib.interactive(True)
179 matplotlib.interactive(True)
153
180
154 # This must be imported last in the matplotlib series, after
181 # This must be imported last in the matplotlib series, after
155 # backend/interactivity choices have been made
182 # backend/interactivity choices have been made
156 import matplotlib.pylab as pylab
183 import matplotlib.pylab as pylab
157
184
158 # XXX For now leave this commented out, but depending on discussions with
185 # XXX For now leave this commented out, but depending on discussions with
159 # mpl-dev, we may be able to allow interactive switching...
186 # mpl-dev, we may be able to allow interactive switching...
160 #import matplotlib.pyplot
187 #import matplotlib.pyplot
161 #matplotlib.pyplot.switch_backend(backend)
188 #matplotlib.pyplot.switch_backend(backend)
162
189
163 pylab.show._needmain = False
190 pylab.show._needmain = False
164 # We need to detect at runtime whether show() is called by the user.
191 # We need to detect at runtime whether show() is called by the user.
165 # For this, we wrap it into a decorator which adds a 'called' flag.
192 # For this, we wrap it into a decorator which adds a 'called' flag.
166 pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive)
193 pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive)
167
194
168
195
169 def import_pylab(user_ns, backend, import_all=True, shell=None):
196 def import_pylab(user_ns, backend, import_all=True, shell=None):
170 """Import the standard pylab symbols into user_ns."""
197 """Import the standard pylab symbols into user_ns."""
171
198
172 # Import numpy as np/pyplot as plt are conventions we're trying to
199 # Import numpy as np/pyplot as plt are conventions we're trying to
173 # somewhat standardize on. Making them available to users by default
200 # somewhat standardize on. Making them available to users by default
174 # will greatly help this.
201 # will greatly help this.
175 s = ("import numpy\n"
202 s = ("import numpy\n"
176 "import matplotlib\n"
203 "import matplotlib\n"
177 "from matplotlib import pylab, mlab, pyplot\n"
204 "from matplotlib import pylab, mlab, pyplot\n"
178 "np = numpy\n"
205 "np = numpy\n"
179 "plt = pyplot\n"
206 "plt = pyplot\n"
180 )
207 )
181 exec s in user_ns
208 exec s in user_ns
182
209
183 if shell is not None:
210 if shell is not None:
184 exec s in shell.user_ns_hidden
211 exec s in shell.user_ns_hidden
185 # If using our svg payload backend, register the post-execution
212 # If using our svg payload backend, register the post-execution
186 # function that will pick up the results for display. This can only be
213 # function that will pick up the results for display. This can only be
187 # done with access to the real shell object.
214 # done with access to the real shell object.
188 if backend == backends['inline']:
215 if backend == backends['inline']:
189 from IPython.zmq.pylab.backend_inline import flush_svg
216 from IPython.zmq.pylab.backend_inline import flush_svg
190 from matplotlib import pyplot
217 from matplotlib import pyplot
191 shell.register_post_execute(flush_svg)
218 shell.register_post_execute(flush_svg)
192 # The typical default figure size is too large for inline use. We
219 # The typical default figure size is too large for inline use. We
193 # might make this a user-configurable parameter later.
220 # might make this a user-configurable parameter later.
194 figsize(6.0, 4.0)
221 figsize(6.0, 4.0)
195 # Add 'figsize' to pyplot and to the user's namespace
222 # Add 'figsize' to pyplot and to the user's namespace
196 user_ns['figsize'] = pyplot.figsize = figsize
223 user_ns['figsize'] = pyplot.figsize = figsize
197 shell.user_ns_hidden['figsize'] = figsize
224 shell.user_ns_hidden['figsize'] = figsize
198
225
199 # The old pastefig function has been replaced by display
226 # The old pastefig function has been replaced by display
200 # Always add this svg formatter so display works.
227 # Always add this svg formatter so display works.
201 from IPython.zmq.pylab.backend_inline import figure_to_svg
228 from IPython.zmq.pylab.backend_inline import figure_to_svg
202 from IPython.core.display import display, display_svg
229 from IPython.core.display import display, display_svg
203 svg_formatter = shell.display_formatter.formatters['image/svg+xml']
230 svg_formatter = shell.display_formatter.formatters['image/svg+xml']
204 svg_formatter.for_type_by_name(
231 svg_formatter.for_type_by_name(
205 'matplotlib.figure','Figure',figure_to_svg
232 'matplotlib.figure','Figure',figure_to_svg
206 )
233 )
207 # Add display and display_png to the user's namespace
234 # Add display and display_png to the user's namespace
208 user_ns['display'] = display
235 user_ns['display'] = display
209 shell.user_ns_hidden['display'] = display
236 shell.user_ns_hidden['display'] = display
210 user_ns['display_svg'] = display_svg
237 user_ns['display_svg'] = display_svg
211 shell.user_ns_hidden['display_svg'] = display_svg
238 shell.user_ns_hidden['display_svg'] = display_svg
239 user_ns['getfigs'] = getfigs
240 shell.user_ns_hidden['getfigs'] = getfigs
212
241
213 if import_all:
242 if import_all:
214 s = ("from matplotlib.pylab import *\n"
243 s = ("from matplotlib.pylab import *\n"
215 "from numpy import *\n")
244 "from numpy import *\n")
216 exec s in user_ns
245 exec s in user_ns
217 if shell is not None:
246 if shell is not None:
218 exec s in shell.user_ns_hidden
247 exec s in shell.user_ns_hidden
219
248
220
249
221 def pylab_activate(user_ns, gui=None, import_all=True):
250 def pylab_activate(user_ns, gui=None, import_all=True):
222 """Activate pylab mode in the user's namespace.
251 """Activate pylab mode in the user's namespace.
223
252
224 Loads and initializes numpy, matplotlib and friends for interactive use.
253 Loads and initializes numpy, matplotlib and friends for interactive use.
225
254
226 Parameters
255 Parameters
227 ----------
256 ----------
228 user_ns : dict
257 user_ns : dict
229 Namespace where the imports will occur.
258 Namespace where the imports will occur.
230
259
231 gui : optional, string
260 gui : optional, string
232 A valid gui name following the conventions of the %gui magic.
261 A valid gui name following the conventions of the %gui magic.
233
262
234 import_all : optional, boolean
263 import_all : optional, boolean
235 If true, an 'import *' is done from numpy and pylab.
264 If true, an 'import *' is done from numpy and pylab.
236
265
237 Returns
266 Returns
238 -------
267 -------
239 The actual gui used (if not given as input, it was obtained from matplotlib
268 The actual gui used (if not given as input, it was obtained from matplotlib
240 itself, and will be needed next to configure IPython's gui integration.
269 itself, and will be needed next to configure IPython's gui integration.
241 """
270 """
242 gui, backend = find_gui_and_backend(gui)
271 gui, backend = find_gui_and_backend(gui)
243 activate_matplotlib(backend)
272 activate_matplotlib(backend)
244 import_pylab(user_ns, backend)
273 import_pylab(user_ns, backend)
245
274
246 print """
275 print """
247 Welcome to pylab, a matplotlib-based Python environment [backend: %s].
276 Welcome to pylab, a matplotlib-based Python environment [backend: %s].
248 For more information, type 'help(pylab)'.""" % backend
277 For more information, type 'help(pylab)'.""" % backend
249
278
250 return gui
279 return gui
251
280
General Comments 0
You need to be logged in to leave comments. Login now