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