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