##// END OF EJS Templates
Rename 'paste' function to 'pastefig'.
Fernando Perez -
Show More
@@ -1,477 +1,477 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Usage information for the main IPython applications.
2 """Usage information for the main IPython applications.
3 """
3 """
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2008-2010 The IPython Development Team
5 # Copyright (C) 2008-2010 The IPython Development Team
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 #
7 #
8 # Distributed under the terms of the BSD License. The full license is in
8 # Distributed under the terms of the BSD License. The full license is in
9 # the file COPYING, distributed as part of this software.
9 # the file COPYING, distributed as part of this software.
10 #-----------------------------------------------------------------------------
10 #-----------------------------------------------------------------------------
11
11
12 import sys
12 import sys
13 from IPython.core import release
13 from IPython.core import release
14
14
15 cl_usage = """\
15 cl_usage = """\
16 ipython [options] [files]
16 ipython [options] [files]
17
17
18 IPython: an enhanced interactive Python shell.
18 IPython: an enhanced interactive Python shell.
19
19
20 A Python shell with automatic history (input and output), dynamic object
20 A Python shell with automatic history (input and output), dynamic object
21 introspection, easier configuration, command completion, access to the
21 introspection, easier configuration, command completion, access to the
22 system shell and more. IPython can also be embedded in running programs.
22 system shell and more. IPython can also be embedded in running programs.
23
23
24 If invoked with no options, it executes all the files listed in sequence
24 If invoked with no options, it executes all the files listed in sequence
25 and exits, use -i to enter interactive mode after running the files. Files
25 and exits, use -i to enter interactive mode after running the files. Files
26 ending in .py will be treated as normal Python, but files ending in .ipy
26 ending in .py will be treated as normal Python, but files ending in .ipy
27 can contain special IPython syntax (magic commands, shell expansions, etc.)
27 can contain special IPython syntax (magic commands, shell expansions, etc.)
28
28
29 Please note that some of the configuration options are not available at the
29 Please note that some of the configuration options are not available at the
30 command line, simply because they are not practical here. Look into your
30 command line, simply because they are not practical here. Look into your
31 ipython_config.py configuration file for details on those.
31 ipython_config.py configuration file for details on those.
32
32
33 This file typically installed in the $HOME/.ipython directory. For Windows
33 This file typically installed in the $HOME/.ipython directory. For Windows
34 users, $HOME resolves to C:\\Documents and Settings\\YourUserName in most
34 users, $HOME resolves to C:\\Documents and Settings\\YourUserName in most
35 instances.
35 instances.
36
36
37 In IPython's documentation, we will refer to this directory as IPYTHON_DIR,
37 In IPython's documentation, we will refer to this directory as IPYTHON_DIR,
38 you can change its default location by setting any path you want in this
38 you can change its default location by setting any path you want in this
39 environment variable.
39 environment variable.
40
40
41 For more information, see the manual available in HTML and PDF in your
41 For more information, see the manual available in HTML and PDF in your
42 installation, or online at http://ipython.scipy.org.
42 installation, or online at http://ipython.scipy.org.
43 """
43 """
44
44
45 interactive_usage = """
45 interactive_usage = """
46 IPython -- An enhanced Interactive Python
46 IPython -- An enhanced Interactive Python
47 =========================================
47 =========================================
48
48
49 IPython offers a combination of convenient shell features, special commands
49 IPython offers a combination of convenient shell features, special commands
50 and a history mechanism for both input (command history) and output (results
50 and a history mechanism for both input (command history) and output (results
51 caching, similar to Mathematica). It is intended to be a fully compatible
51 caching, similar to Mathematica). It is intended to be a fully compatible
52 replacement for the standard Python interpreter, while offering vastly
52 replacement for the standard Python interpreter, while offering vastly
53 improved functionality and flexibility.
53 improved functionality and flexibility.
54
54
55 At your system command line, type 'ipython -help' to see the command line
55 At your system command line, type 'ipython -help' to see the command line
56 options available. This document only describes interactive features.
56 options available. This document only describes interactive features.
57
57
58 Warning: IPython relies on the existence of a global variable called __IP which
58 Warning: IPython relies on the existence of a global variable called __IP which
59 controls the shell itself. If you redefine __IP to anything, bizarre behavior
59 controls the shell itself. If you redefine __IP to anything, bizarre behavior
60 will quickly occur.
60 will quickly occur.
61
61
62 MAIN FEATURES
62 MAIN FEATURES
63
63
64 * Access to the standard Python help. As of Python 2.1, a help system is
64 * Access to the standard Python help. As of Python 2.1, a help system is
65 available with access to object docstrings and the Python manuals. Simply
65 available with access to object docstrings and the Python manuals. Simply
66 type 'help' (no quotes) to access it.
66 type 'help' (no quotes) to access it.
67
67
68 * Magic commands: type %magic for information on the magic subsystem.
68 * Magic commands: type %magic for information on the magic subsystem.
69
69
70 * System command aliases, via the %alias command or the ipythonrc config file.
70 * System command aliases, via the %alias command or the ipythonrc config file.
71
71
72 * Dynamic object information:
72 * Dynamic object information:
73
73
74 Typing ?word or word? prints detailed information about an object. If
74 Typing ?word or word? prints detailed information about an object. If
75 certain strings in the object are too long (docstrings, code, etc.) they get
75 certain strings in the object are too long (docstrings, code, etc.) they get
76 snipped in the center for brevity.
76 snipped in the center for brevity.
77
77
78 Typing ??word or word?? gives access to the full information without
78 Typing ??word or word?? gives access to the full information without
79 snipping long strings. Long strings are sent to the screen through the less
79 snipping long strings. Long strings are sent to the screen through the less
80 pager if longer than the screen, printed otherwise.
80 pager if longer than the screen, printed otherwise.
81
81
82 The ?/?? system gives access to the full source code for any object (if
82 The ?/?? system gives access to the full source code for any object (if
83 available), shows function prototypes and other useful information.
83 available), shows function prototypes and other useful information.
84
84
85 If you just want to see an object's docstring, type '%pdoc object' (without
85 If you just want to see an object's docstring, type '%pdoc object' (without
86 quotes, and without % if you have automagic on).
86 quotes, and without % if you have automagic on).
87
87
88 Both %pdoc and ?/?? give you access to documentation even on things which are
88 Both %pdoc and ?/?? give you access to documentation even on things which are
89 not explicitely defined. Try for example typing {}.get? or after import os,
89 not explicitely defined. Try for example typing {}.get? or after import os,
90 type os.path.abspath??. The magic functions %pdef, %source and %file operate
90 type os.path.abspath??. The magic functions %pdef, %source and %file operate
91 similarly.
91 similarly.
92
92
93 * Completion in the local namespace, by typing TAB at the prompt.
93 * Completion in the local namespace, by typing TAB at the prompt.
94
94
95 At any time, hitting tab will complete any available python commands or
95 At any time, hitting tab will complete any available python commands or
96 variable names, and show you a list of the possible completions if there's
96 variable names, and show you a list of the possible completions if there's
97 no unambiguous one. It will also complete filenames in the current directory.
97 no unambiguous one. It will also complete filenames in the current directory.
98
98
99 This feature requires the readline and rlcomplete modules, so it won't work
99 This feature requires the readline and rlcomplete modules, so it won't work
100 if your Python lacks readline support (such as under Windows).
100 if your Python lacks readline support (such as under Windows).
101
101
102 * Search previous command history in two ways (also requires readline):
102 * Search previous command history in two ways (also requires readline):
103
103
104 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
104 - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to
105 search through only the history items that match what you've typed so
105 search through only the history items that match what you've typed so
106 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
106 far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like
107 normal arrow keys.
107 normal arrow keys.
108
108
109 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
109 - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches
110 your history for lines that match what you've typed so far, completing as
110 your history for lines that match what you've typed so far, completing as
111 much as it can.
111 much as it can.
112
112
113 * Persistent command history across sessions (readline required).
113 * Persistent command history across sessions (readline required).
114
114
115 * Logging of input with the ability to save and restore a working session.
115 * Logging of input with the ability to save and restore a working session.
116
116
117 * System escape with !. Typing !ls will run 'ls' in the current directory.
117 * System escape with !. Typing !ls will run 'ls' in the current directory.
118
118
119 * The reload command does a 'deep' reload of a module: changes made to the
119 * The reload command does a 'deep' reload of a module: changes made to the
120 module since you imported will actually be available without having to exit.
120 module since you imported will actually be available without having to exit.
121
121
122 * Verbose and colored exception traceback printouts. See the magic xmode and
122 * Verbose and colored exception traceback printouts. See the magic xmode and
123 xcolor functions for details (just type %magic).
123 xcolor functions for details (just type %magic).
124
124
125 * Input caching system:
125 * Input caching system:
126
126
127 IPython offers numbered prompts (In/Out) with input and output caching. All
127 IPython offers numbered prompts (In/Out) with input and output caching. All
128 input is saved and can be retrieved as variables (besides the usual arrow
128 input is saved and can be retrieved as variables (besides the usual arrow
129 key recall).
129 key recall).
130
130
131 The following GLOBAL variables always exist (so don't overwrite them!):
131 The following GLOBAL variables always exist (so don't overwrite them!):
132 _i: stores previous input.
132 _i: stores previous input.
133 _ii: next previous.
133 _ii: next previous.
134 _iii: next-next previous.
134 _iii: next-next previous.
135 _ih : a list of all input _ih[n] is the input from line n.
135 _ih : a list of all input _ih[n] is the input from line n.
136
136
137 Additionally, global variables named _i<n> are dynamically created (<n>
137 Additionally, global variables named _i<n> are dynamically created (<n>
138 being the prompt counter), such that _i<n> == _ih[<n>]
138 being the prompt counter), such that _i<n> == _ih[<n>]
139
139
140 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
140 For example, what you typed at prompt 14 is available as _i14 and _ih[14].
141
141
142 You can create macros which contain multiple input lines from this history,
142 You can create macros which contain multiple input lines from this history,
143 for later re-execution, with the %macro function.
143 for later re-execution, with the %macro function.
144
144
145 The history function %hist allows you to see any part of your input history
145 The history function %hist allows you to see any part of your input history
146 by printing a range of the _i variables. Note that inputs which contain
146 by printing a range of the _i variables. Note that inputs which contain
147 magic functions (%) appear in the history with a prepended comment. This is
147 magic functions (%) appear in the history with a prepended comment. This is
148 because they aren't really valid Python code, so you can't exec them.
148 because they aren't really valid Python code, so you can't exec them.
149
149
150 * Output caching system:
150 * Output caching system:
151
151
152 For output that is returned from actions, a system similar to the input
152 For output that is returned from actions, a system similar to the input
153 cache exists but using _ instead of _i. Only actions that produce a result
153 cache exists but using _ instead of _i. Only actions that produce a result
154 (NOT assignments, for example) are cached. If you are familiar with
154 (NOT assignments, for example) are cached. If you are familiar with
155 Mathematica, IPython's _ variables behave exactly like Mathematica's %
155 Mathematica, IPython's _ variables behave exactly like Mathematica's %
156 variables.
156 variables.
157
157
158 The following GLOBAL variables always exist (so don't overwrite them!):
158 The following GLOBAL variables always exist (so don't overwrite them!):
159 _ (one underscore): previous output.
159 _ (one underscore): previous output.
160 __ (two underscores): next previous.
160 __ (two underscores): next previous.
161 ___ (three underscores): next-next previous.
161 ___ (three underscores): next-next previous.
162
162
163 Global variables named _<n> are dynamically created (<n> being the prompt
163 Global variables named _<n> are dynamically created (<n> being the prompt
164 counter), such that the result of output <n> is always available as _<n>.
164 counter), such that the result of output <n> is always available as _<n>.
165
165
166 Finally, a global dictionary named _oh exists with entries for all lines
166 Finally, a global dictionary named _oh exists with entries for all lines
167 which generated output.
167 which generated output.
168
168
169 * Directory history:
169 * Directory history:
170
170
171 Your history of visited directories is kept in the global list _dh, and the
171 Your history of visited directories is kept in the global list _dh, and the
172 magic %cd command can be used to go to any entry in that list.
172 magic %cd command can be used to go to any entry in that list.
173
173
174 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
174 * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython)
175
175
176 1. Auto-parentheses
176 1. Auto-parentheses
177 Callable objects (i.e. functions, methods, etc) can be invoked like
177 Callable objects (i.e. functions, methods, etc) can be invoked like
178 this (notice the commas between the arguments):
178 this (notice the commas between the arguments):
179 >>> callable_ob arg1, arg2, arg3
179 >>> callable_ob arg1, arg2, arg3
180 and the input will be translated to this:
180 and the input will be translated to this:
181 --> callable_ob(arg1, arg2, arg3)
181 --> callable_ob(arg1, arg2, arg3)
182 You can force auto-parentheses by using '/' as the first character
182 You can force auto-parentheses by using '/' as the first character
183 of a line. For example:
183 of a line. For example:
184 >>> /globals # becomes 'globals()'
184 >>> /globals # becomes 'globals()'
185 Note that the '/' MUST be the first character on the line! This
185 Note that the '/' MUST be the first character on the line! This
186 won't work:
186 won't work:
187 >>> print /globals # syntax error
187 >>> print /globals # syntax error
188
188
189 In most cases the automatic algorithm should work, so you should
189 In most cases the automatic algorithm should work, so you should
190 rarely need to explicitly invoke /. One notable exception is if you
190 rarely need to explicitly invoke /. One notable exception is if you
191 are trying to call a function with a list of tuples as arguments (the
191 are trying to call a function with a list of tuples as arguments (the
192 parenthesis will confuse IPython):
192 parenthesis will confuse IPython):
193 In [1]: zip (1,2,3),(4,5,6) # won't work
193 In [1]: zip (1,2,3),(4,5,6) # won't work
194 but this will work:
194 but this will work:
195 In [2]: /zip (1,2,3),(4,5,6)
195 In [2]: /zip (1,2,3),(4,5,6)
196 ------> zip ((1,2,3),(4,5,6))
196 ------> zip ((1,2,3),(4,5,6))
197 Out[2]= [(1, 4), (2, 5), (3, 6)]
197 Out[2]= [(1, 4), (2, 5), (3, 6)]
198
198
199 IPython tells you that it has altered your command line by
199 IPython tells you that it has altered your command line by
200 displaying the new command line preceded by -->. e.g.:
200 displaying the new command line preceded by -->. e.g.:
201 In [18]: callable list
201 In [18]: callable list
202 -------> callable (list)
202 -------> callable (list)
203
203
204 2. Auto-Quoting
204 2. Auto-Quoting
205 You can force auto-quoting of a function's arguments by using ',' as
205 You can force auto-quoting of a function's arguments by using ',' as
206 the first character of a line. For example:
206 the first character of a line. For example:
207 >>> ,my_function /home/me # becomes my_function("/home/me")
207 >>> ,my_function /home/me # becomes my_function("/home/me")
208
208
209 If you use ';' instead, the whole argument is quoted as a single
209 If you use ';' instead, the whole argument is quoted as a single
210 string (while ',' splits on whitespace):
210 string (while ',' splits on whitespace):
211 >>> ,my_function a b c # becomes my_function("a","b","c")
211 >>> ,my_function a b c # becomes my_function("a","b","c")
212 >>> ;my_function a b c # becomes my_function("a b c")
212 >>> ;my_function a b c # becomes my_function("a b c")
213
213
214 Note that the ',' MUST be the first character on the line! This
214 Note that the ',' MUST be the first character on the line! This
215 won't work:
215 won't work:
216 >>> x = ,my_function /home/me # syntax error
216 >>> x = ,my_function /home/me # syntax error
217 """
217 """
218
218
219 interactive_usage_min = """\
219 interactive_usage_min = """\
220 An enhanced console for Python.
220 An enhanced console for Python.
221 Some of its features are:
221 Some of its features are:
222 - Readline support if the readline library is present.
222 - Readline support if the readline library is present.
223 - Tab completion in the local namespace.
223 - Tab completion in the local namespace.
224 - Logging of input, see command-line options.
224 - Logging of input, see command-line options.
225 - System shell escape via ! , eg !ls.
225 - System shell escape via ! , eg !ls.
226 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
226 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
227 - Keeps track of locally defined variables via %who, %whos.
227 - Keeps track of locally defined variables via %who, %whos.
228 - Show object information with a ? eg ?x or x? (use ?? for more info).
228 - Show object information with a ? eg ?x or x? (use ?? for more info).
229 """
229 """
230
230
231 quick_reference = r"""
231 quick_reference = r"""
232 IPython -- An enhanced Interactive Python - Quick Reference Card
232 IPython -- An enhanced Interactive Python - Quick Reference Card
233 ================================================================
233 ================================================================
234
234
235 obj?, obj?? : Get help, or more help for object (also works as
235 obj?, obj?? : Get help, or more help for object (also works as
236 ?obj, ??obj).
236 ?obj, ??obj).
237 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
237 ?foo.*abc* : List names in 'foo' containing 'abc' in them.
238 %magic : Information about IPython's 'magic' % functions.
238 %magic : Information about IPython's 'magic' % functions.
239
239
240 Magic functions are prefixed by %, and typically take their arguments without
240 Magic functions are prefixed by %, and typically take their arguments without
241 parentheses, quotes or even commas for convenience.
241 parentheses, quotes or even commas for convenience.
242
242
243 Example magic function calls:
243 Example magic function calls:
244
244
245 %alias d ls -F : 'd' is now an alias for 'ls -F'
245 %alias d ls -F : 'd' is now an alias for 'ls -F'
246 alias d ls -F : Works if 'alias' not a python name
246 alias d ls -F : Works if 'alias' not a python name
247 alist = %alias : Get list of aliases to 'alist'
247 alist = %alias : Get list of aliases to 'alist'
248 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
248 cd /usr/share : Obvious. cd -<tab> to choose from visited dirs.
249 %cd?? : See help AND source for magic %cd
249 %cd?? : See help AND source for magic %cd
250
250
251 System commands:
251 System commands:
252
252
253 !cp a.txt b/ : System command escape, calls os.system()
253 !cp a.txt b/ : System command escape, calls os.system()
254 cp a.txt b/ : after %rehashx, most system commands work without !
254 cp a.txt b/ : after %rehashx, most system commands work without !
255 cp ${f}.txt $bar : Variable expansion in magics and system commands
255 cp ${f}.txt $bar : Variable expansion in magics and system commands
256 files = !ls /usr : Capture sytem command output
256 files = !ls /usr : Capture sytem command output
257 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
257 files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc'
258
258
259 History:
259 History:
260
260
261 _i, _ii, _iii : Previous, next previous, next next previous input
261 _i, _ii, _iii : Previous, next previous, next next previous input
262 _i4, _ih[2:5] : Input history line 4, lines 2-4
262 _i4, _ih[2:5] : Input history line 4, lines 2-4
263 exec _i81 : Execute input history line #81 again
263 exec _i81 : Execute input history line #81 again
264 %rep 81 : Edit input history line #81
264 %rep 81 : Edit input history line #81
265 _, __, ___ : previous, next previous, next next previous output
265 _, __, ___ : previous, next previous, next next previous output
266 _dh : Directory history
266 _dh : Directory history
267 _oh : Output history
267 _oh : Output history
268 %hist : Command history. '%hist -g foo' search history for 'foo'
268 %hist : Command history. '%hist -g foo' search history for 'foo'
269
269
270 Autocall:
270 Autocall:
271
271
272 f 1,2 : f(1,2)
272 f 1,2 : f(1,2)
273 /f 1,2 : f(1,2) (forced autoparen)
273 /f 1,2 : f(1,2) (forced autoparen)
274 ,f 1 2 : f("1","2")
274 ,f 1 2 : f("1","2")
275 ;f 1 2 : f("1 2")
275 ;f 1 2 : f("1 2")
276
276
277 Remember: TAB completion works in many contexts, not just file names
277 Remember: TAB completion works in many contexts, not just file names
278 or python names.
278 or python names.
279
279
280 The following magic functions are currently available:
280 The following magic functions are currently available:
281
281
282 """
282 """
283
283
284 gui_reference = """\
284 gui_reference = """\
285 ===============================
285 ===============================
286 The graphical IPython console
286 The graphical IPython console
287 ===============================
287 ===============================
288
288
289 This console is designed to emulate the look, feel and workflow of a terminal
289 This console is designed to emulate the look, feel and workflow of a terminal
290 environment, while adding a number of enhancements that are simply not possible
290 environment, while adding a number of enhancements that are simply not possible
291 in a real terminal, such as inline syntax highlighting, true multiline editing,
291 in a real terminal, such as inline syntax highlighting, true multiline editing,
292 inline graphics and much more.
292 inline graphics and much more.
293
293
294 This quick reference document contains the basic information you'll need to
294 This quick reference document contains the basic information you'll need to
295 know to make the most efficient use of it. For the various command line
295 know to make the most efficient use of it. For the various command line
296 options available at startup, type ``--help`` at the command line.
296 options available at startup, type ``--help`` at the command line.
297
297
298
298
299 Multiline editing
299 Multiline editing
300 =================
300 =================
301
301
302 The graphical console is capable of true multiline editing, but it also tries
302 The graphical console is capable of true multiline editing, but it also tries
303 to behave intuitively like a terminal when possible. If you are used to
303 to behave intuitively like a terminal when possible. If you are used to
304 IPyhton's old terminal behavior, you should find the transition painless, and
304 IPyhton's old terminal behavior, you should find the transition painless, and
305 once you learn a few basic keybindings it will be a much more efficient
305 once you learn a few basic keybindings it will be a much more efficient
306 environment.
306 environment.
307
307
308 For single expressions or indented blocks, the console behaves almost like the
308 For single expressions or indented blocks, the console behaves almost like the
309 terminal IPython: single expressions are immediately evaluated, and indented
309 terminal IPython: single expressions are immediately evaluated, and indented
310 blocks are evaluated once a single blank line is entered::
310 blocks are evaluated once a single blank line is entered::
311
311
312 In [1]: print "Hello IPython!" # Enter was pressed at the end of the line
312 In [1]: print "Hello IPython!" # Enter was pressed at the end of the line
313 Hello IPython!
313 Hello IPython!
314
314
315 In [2]: for i in range(10):
315 In [2]: for i in range(10):
316 ...: print i,
316 ...: print i,
317 ...:
317 ...:
318 0 1 2 3 4 5 6 7 8 9
318 0 1 2 3 4 5 6 7 8 9
319
319
320 If you want to enter more than one expression in a single input block
320 If you want to enter more than one expression in a single input block
321 (something not possible in the terminal), you can use ``Control-Enter`` at the
321 (something not possible in the terminal), you can use ``Control-Enter`` at the
322 end of your first line instead of ``Enter``. At that point the console goes
322 end of your first line instead of ``Enter``. At that point the console goes
323 into 'cell mode' and even if your inputs are not indented, it will continue
323 into 'cell mode' and even if your inputs are not indented, it will continue
324 accepting arbitrarily many lines until either you enter an extra blank line or
324 accepting arbitrarily many lines until either you enter an extra blank line or
325 you hit ``Shift-Enter`` (the key binding that forces execution). When a
325 you hit ``Shift-Enter`` (the key binding that forces execution). When a
326 multiline cell is entered, IPython analyzes it and executes its code producing
326 multiline cell is entered, IPython analyzes it and executes its code producing
327 an ``Out[n]`` prompt only for the last expression in it, while the rest of the
327 an ``Out[n]`` prompt only for the last expression in it, while the rest of the
328 cell is executed as if it was a script. An example should clarify this::
328 cell is executed as if it was a script. An example should clarify this::
329
329
330 In [3]: x=1 # Hit C-Enter here
330 In [3]: x=1 # Hit C-Enter here
331 ...: y=2 # from now on, regular Enter is sufficient
331 ...: y=2 # from now on, regular Enter is sufficient
332 ...: z=3
332 ...: z=3
333 ...: x**2 # This does *not* produce an Out[] value
333 ...: x**2 # This does *not* produce an Out[] value
334 ...: x+y+z # Only the last expression does
334 ...: x+y+z # Only the last expression does
335 ...:
335 ...:
336 Out[3]: 6
336 Out[3]: 6
337
337
338 The behavior where an extra blank line forces execution is only active if you
338 The behavior where an extra blank line forces execution is only active if you
339 are actually typing at the keyboard each line, and is meant to make it mimic
339 are actually typing at the keyboard each line, and is meant to make it mimic
340 the IPython terminal behavior. If you paste a long chunk of input (for example
340 the IPython terminal behavior. If you paste a long chunk of input (for example
341 a long script copied form an editor or web browser), it can contain arbitrarily
341 a long script copied form an editor or web browser), it can contain arbitrarily
342 many intermediate blank lines and they won't cause any problems. As always,
342 many intermediate blank lines and they won't cause any problems. As always,
343 you can then make it execute by appending a blank line *at the end* or hitting
343 you can then make it execute by appending a blank line *at the end* or hitting
344 ``Shift-Enter`` anywhere within the cell.
344 ``Shift-Enter`` anywhere within the cell.
345
345
346 With the up arrow key, you can retrieve previous blocks of input that contain
346 With the up arrow key, you can retrieve previous blocks of input that contain
347 multiple lines. You can move inside of a multiline cell like you would in any
347 multiple lines. You can move inside of a multiline cell like you would in any
348 text editor. When you want it executed, the simplest thing to do is to hit the
348 text editor. When you want it executed, the simplest thing to do is to hit the
349 force execution key, ``Shift-Enter`` (though you can also navigate to the end
349 force execution key, ``Shift-Enter`` (though you can also navigate to the end
350 and append a blank line by using ``Enter`` twice).
350 and append a blank line by using ``Enter`` twice).
351
351
352 If you've edited a multiline cell and accidentally navigate out of it with the
352 If you've edited a multiline cell and accidentally navigate out of it with the
353 up or down arrow keys, IPython will clear the cell and replace it with the
353 up or down arrow keys, IPython will clear the cell and replace it with the
354 contents of the one above or below that you navigated to. If this was an
354 contents of the one above or below that you navigated to. If this was an
355 accident and you want to retrieve the cell you were editing, use the Undo
355 accident and you want to retrieve the cell you were editing, use the Undo
356 keybinding, ``Control-z``.
356 keybinding, ``Control-z``.
357
357
358
358
359 Key bindings
359 Key bindings
360 ============
360 ============
361
361
362 The IPython console supports most of the basic Emacs line-oriented keybindings,
362 The IPython console supports most of the basic Emacs line-oriented keybindings,
363 in addition to some of its own.
363 in addition to some of its own.
364
364
365 The keybinding prefixes mean:
365 The keybinding prefixes mean:
366
366
367 - ``C``: Control
367 - ``C``: Control
368 - ``S``: Shift
368 - ``S``: Shift
369 - ``M``: Meta (typically the Alt key)
369 - ``M``: Meta (typically the Alt key)
370
370
371 The keybindings themselves are:
371 The keybindings themselves are:
372
372
373 - ``Enter``: insert new line (may cause execution, see above).
373 - ``Enter``: insert new line (may cause execution, see above).
374 - ``C-Enter``: force new line, *never* causes execution.
374 - ``C-Enter``: force new line, *never* causes execution.
375 - ``S-Enter``: *force* execution regardless of where cursor is, no newline added.
375 - ``S-Enter``: *force* execution regardless of where cursor is, no newline added.
376 - ``C-c``: copy highlighted text to clipboard (prompts are automatically stripped).
376 - ``C-c``: copy highlighted text to clipboard (prompts are automatically stripped).
377 - ``C-S-c``: copy highlighted text to clipboard (prompts are not stripped).
377 - ``C-S-c``: copy highlighted text to clipboard (prompts are not stripped).
378 - ``C-v``: paste text from clipboard.
378 - ``C-v``: paste text from clipboard.
379 - ``C-z``: undo (retrieves lost text if you move out of a cell with the arrows).
379 - ``C-z``: undo (retrieves lost text if you move out of a cell with the arrows).
380 - ``C-S-z``: redo.
380 - ``C-S-z``: redo.
381 - ``C-o``: move to 'other' area, between pager and terminal.
381 - ``C-o``: move to 'other' area, between pager and terminal.
382 - ``C-l``: clear terminal.
382 - ``C-l``: clear terminal.
383 - ``C-a``: go to beginning of line.
383 - ``C-a``: go to beginning of line.
384 - ``C-e``: go to end of line.
384 - ``C-e``: go to end of line.
385 - ``C-k``: kill from cursor to the end of the line.
385 - ``C-k``: kill from cursor to the end of the line.
386 - ``C-y``: yank (paste)
386 - ``C-y``: yank (paste)
387 - ``C-p``: previous line (like up arrow)
387 - ``C-p``: previous line (like up arrow)
388 - ``C-n``: next line (like down arrow)
388 - ``C-n``: next line (like down arrow)
389 - ``C-f``: forward (like right arrow)
389 - ``C-f``: forward (like right arrow)
390 - ``C-b``: back (like left arrow)
390 - ``C-b``: back (like left arrow)
391 - ``C-d``: delete next character.
391 - ``C-d``: delete next character.
392 - ``M-<``: move to the beginning of the input region.
392 - ``M-<``: move to the beginning of the input region.
393 - ``M->``: move to the end of the input region.
393 - ``M->``: move to the end of the input region.
394 - ``M-d``: delete next word.
394 - ``M-d``: delete next word.
395 - ``M-Backspace``: delete previous word.
395 - ``M-Backspace``: delete previous word.
396 - ``C-.``: force a kernel restart (a confirmation dialog appears).
396 - ``C-.``: force a kernel restart (a confirmation dialog appears).
397
397
398
398
399 The IPython pager
399 The IPython pager
400 =================
400 =================
401
401
402 IPython will show long blocks of text from many sources using a builtin pager.
402 IPython will show long blocks of text from many sources using a builtin pager.
403 You can control where this pager appears with the ``--paging`` command-line
403 You can control where this pager appears with the ``--paging`` command-line
404 flag:
404 flag:
405
405
406 - default: it is overlaid on top of the main terminal. You must quit the pager
406 - default: it is overlaid on top of the main terminal. You must quit the pager
407 to get back to the terminal (similar to how a pager such as ``less`` or
407 to get back to the terminal (similar to how a pager such as ``less`` or
408 ``more`` works).
408 ``more`` works).
409
409
410 - vertical: the console is made double-tall, and the pager appears on the
410 - vertical: the console is made double-tall, and the pager appears on the
411 bottom area when needed. You can view its contents while using the terminal.
411 bottom area when needed. You can view its contents while using the terminal.
412
412
413 - horizontal: the console is made double-wide, and the pager appears on the
413 - horizontal: the console is made double-wide, and the pager appears on the
414 right area when needed. You can view its contents while using the terminal.
414 right area when needed. You can view its contents while using the terminal.
415
415
416 If you use the vertical or horizontal paging modes, you can navigate between
416 If you use the vertical or horizontal paging modes, you can navigate between
417 terminal and pager as follows:
417 terminal and pager as follows:
418
418
419 - Tab key: goes from pager to terminal (but not the other way around).
419 - Tab key: goes from pager to terminal (but not the other way around).
420 - Control-o: goes from one to another always.
420 - Control-o: goes from one to another always.
421 - Mouse: click on either.
421 - Mouse: click on either.
422
422
423 In all cases, the ``q`` or ``Escape`` keys quit the pager (when used with the
423 In all cases, the ``q`` or ``Escape`` keys quit the pager (when used with the
424 focus on the pager area).
424 focus on the pager area).
425
425
426
426
427 Running subprocesses
427 Running subprocesses
428 ====================
428 ====================
429
429
430 The graphical IPython console uses the ``pexpect`` module to run subprocesses
430 The graphical IPython console uses the ``pexpect`` module to run subprocesses
431 when you type ``!command``. This has a number of advantages (true asynchronous
431 when you type ``!command``. This has a number of advantages (true asynchronous
432 output from subprocesses as well as very robust termination of rogue
432 output from subprocesses as well as very robust termination of rogue
433 subprocesses with ``Control-C``), as well as some limitations. The main
433 subprocesses with ``Control-C``), as well as some limitations. The main
434 limitation is that you can *not* interact back with the subprocess, so anything
434 limitation is that you can *not* interact back with the subprocess, so anything
435 that invokes a pager or expects you to type input into it will block and hang
435 that invokes a pager or expects you to type input into it will block and hang
436 (you can kill it with ``Control-C``).
436 (you can kill it with ``Control-C``).
437
437
438 We have provided as magics ``%less`` to page files (aliased to ``%more``),
438 We have provided as magics ``%less`` to page files (aliased to ``%more``),
439 ``%clear`` to clear the terminal, and ``%man`` on Linux/OSX. These cover the
439 ``%clear`` to clear the terminal, and ``%man`` on Linux/OSX. These cover the
440 most common commands you'd want to call in your subshell and that would cause
440 most common commands you'd want to call in your subshell and that would cause
441 problems if invoked via ``!cmd``, but you need to be aware of this limitation.
441 problems if invoked via ``!cmd``, but you need to be aware of this limitation.
442
442
443
443
444 Inline matplotlib graphics
444 Inline matplotlib graphics
445 ==========================
445 ==========================
446
446
447 The IPython console is capable of displaying matplotlib figures inline, in SVG
447 The IPython console is capable of displaying matplotlib figures inline, in SVG
448 format. If started with the ``--pylab inline`` flag, then all figures are
448 format. If started with the ``--pylab inline`` flag, then all figures are
449 rendered inline automatically. If started with ``--pylab`` or ``--pylab
449 rendered inline automatically. If started with ``--pylab`` or ``--pylab <your
450 <your backend>``, then a GUI backend will be used, but the ``paste()`` function
450 backend>``, then a GUI backend will be used, but the ``pastefig()`` function is
451 is added to the global and ``plt`` namespaces. You can paste any figure that
451 added to the global and ``plt`` namespaces. You can paste any figure that is
452 is currently open in a window with this function; type ``paste?`` for
452 currently open in a window with this function; type ``pastefig?`` for
453 additional details."""
453 additional details."""
454
454
455 quick_guide = """\
455 quick_guide = """\
456 ? -> Introduction and overview of IPython's features.
456 ? -> Introduction and overview of IPython's features.
457 %quickref -> Quick reference.
457 %quickref -> Quick reference.
458 help -> Python's own help system.
458 help -> Python's own help system.
459 object? -> Details about 'object', use 'object??' for extra details.
459 object? -> Details about 'object', use 'object??' for extra details.
460 """
460 """
461
461
462 gui_note = """\
462 gui_note = """\
463 %guiref -> A brief reference about the graphical user interface.
463 %guiref -> A brief reference about the graphical user interface.
464 """
464 """
465
465
466 default_banner_parts = [
466 default_banner_parts = [
467 'Python %s\n' % (sys.version.split('\n')[0],),
467 'Python %s\n' % (sys.version.split('\n')[0],),
468 'Type "copyright", "credits" or "license" for more information.\n\n',
468 'Type "copyright", "credits" or "license" for more information.\n\n',
469 'IPython %s -- An enhanced Interactive Python.\n' % (release.version,),
469 'IPython %s -- An enhanced Interactive Python.\n' % (release.version,),
470 quick_guide
470 quick_guide
471 ]
471 ]
472
472
473 default_gui_banner_parts = default_banner_parts + [gui_note]
473 default_gui_banner_parts = default_banner_parts + [gui_note]
474
474
475 default_banner = ''.join(default_banner_parts)
475 default_banner = ''.join(default_banner_parts)
476
476
477 default_gui_banner = ''.join(default_gui_banner_parts)
477 default_gui_banner = ''.join(default_gui_banner_parts)
@@ -1,196 +1,196 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 IPython.utils.decorators import flag_calls
22 from IPython.utils.decorators import flag_calls
23
23
24 # If user specifies a GUI, that dictates the backend, otherwise we read the
24 # If user specifies a GUI, that dictates the backend, otherwise we read the
25 # user's mpl default from the mpl rc structure
25 # user's mpl default from the mpl rc structure
26 backends = {'tk': 'TkAgg',
26 backends = {'tk': 'TkAgg',
27 'gtk': 'GTKAgg',
27 'gtk': 'GTKAgg',
28 'wx': 'WXAgg',
28 'wx': 'WXAgg',
29 'qt': 'Qt4Agg', # qt3 not supported
29 'qt': 'Qt4Agg', # qt3 not supported
30 'qt4': 'Qt4Agg',
30 'qt4': 'Qt4Agg',
31 'inline' : 'module://IPython.zmq.pylab.backend_inline'}
31 'inline' : 'module://IPython.zmq.pylab.backend_inline'}
32
32
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
34 # Main classes and functions
34 # Main classes and functions
35 #-----------------------------------------------------------------------------
35 #-----------------------------------------------------------------------------
36
36
37
37
38 def find_gui_and_backend(gui=None):
38 def find_gui_and_backend(gui=None):
39 """Given a gui string return the gui and mpl backend.
39 """Given a gui string return the gui and mpl backend.
40
40
41 Parameters
41 Parameters
42 ----------
42 ----------
43 gui : str
43 gui : str
44 Can be one of ('tk','gtk','wx','qt','qt4','inline').
44 Can be one of ('tk','gtk','wx','qt','qt4','inline').
45
45
46 Returns
46 Returns
47 -------
47 -------
48 A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg',
48 A tuple of (gui, backend) where backend is one of ('TkAgg','GTKAgg',
49 'WXAgg','Qt4Agg','module://IPython.zmq.pylab.backend_inline').
49 'WXAgg','Qt4Agg','module://IPython.zmq.pylab.backend_inline').
50 """
50 """
51
51
52 import matplotlib
52 import matplotlib
53
53
54 if gui:
54 if gui:
55 # select backend based on requested gui
55 # select backend based on requested gui
56 backend = backends[gui]
56 backend = backends[gui]
57 else:
57 else:
58 backend = matplotlib.rcParams['backend']
58 backend = matplotlib.rcParams['backend']
59 # In this case, we need to find what the appropriate gui selection call
59 # In this case, we need to find what the appropriate gui selection call
60 # should be for IPython, so we can activate inputhook accordingly
60 # should be for IPython, so we can activate inputhook accordingly
61 g2b = backends # maps gui names to mpl backend names
61 g2b = backends # maps gui names to mpl backend names
62 b2g = dict(zip(g2b.values(), g2b.keys())) # reverse dict
62 b2g = dict(zip(g2b.values(), g2b.keys())) # reverse dict
63 gui = b2g.get(backend, None)
63 gui = b2g.get(backend, None)
64 return gui, backend
64 return gui, backend
65
65
66
66
67 def activate_matplotlib(backend):
67 def activate_matplotlib(backend):
68 """Activate the given backend and set interactive to True."""
68 """Activate the given backend and set interactive to True."""
69
69
70 import matplotlib
70 import matplotlib
71 if backend.startswith('module://'):
71 if backend.startswith('module://'):
72 # Work around bug in matplotlib: matplotlib.use converts the
72 # Work around bug in matplotlib: matplotlib.use converts the
73 # backend_id to lowercase even if a module name is specified!
73 # backend_id to lowercase even if a module name is specified!
74 matplotlib.rcParams['backend'] = backend
74 matplotlib.rcParams['backend'] = backend
75 else:
75 else:
76 matplotlib.use(backend)
76 matplotlib.use(backend)
77 matplotlib.interactive(True)
77 matplotlib.interactive(True)
78
78
79 # This must be imported last in the matplotlib series, after
79 # This must be imported last in the matplotlib series, after
80 # backend/interactivity choices have been made
80 # backend/interactivity choices have been made
81 import matplotlib.pylab as pylab
81 import matplotlib.pylab as pylab
82
82
83 # XXX For now leave this commented out, but depending on discussions with
83 # XXX For now leave this commented out, but depending on discussions with
84 # mpl-dev, we may be able to allow interactive switching...
84 # mpl-dev, we may be able to allow interactive switching...
85 #import matplotlib.pyplot
85 #import matplotlib.pyplot
86 #matplotlib.pyplot.switch_backend(backend)
86 #matplotlib.pyplot.switch_backend(backend)
87
87
88 pylab.show._needmain = False
88 pylab.show._needmain = False
89 # We need to detect at runtime whether show() is called by the user.
89 # We need to detect at runtime whether show() is called by the user.
90 # For this, we wrap it into a decorator which adds a 'called' flag.
90 # For this, we wrap it into a decorator which adds a 'called' flag.
91 pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive)
91 pylab.draw_if_interactive = flag_calls(pylab.draw_if_interactive)
92
92
93
93
94 def import_pylab(user_ns, backend, import_all=True, shell=None):
94 def import_pylab(user_ns, backend, import_all=True, shell=None):
95 """Import the standard pylab symbols into user_ns."""
95 """Import the standard pylab symbols into user_ns."""
96
96
97 # Import numpy as np/pyplot as plt are conventions we're trying to
97 # Import numpy as np/pyplot as plt are conventions we're trying to
98 # somewhat standardize on. Making them available to users by default
98 # somewhat standardize on. Making them available to users by default
99 # will greatly help this.
99 # will greatly help this.
100 exec ("import numpy\n"
100 exec ("import numpy\n"
101 "import matplotlib\n"
101 "import matplotlib\n"
102 "from matplotlib import pylab, mlab, pyplot\n"
102 "from matplotlib import pylab, mlab, pyplot\n"
103 "np = numpy\n"
103 "np = numpy\n"
104 "plt = pyplot\n"
104 "plt = pyplot\n"
105 ) in user_ns
105 ) in user_ns
106
106
107 if shell is not None:
107 if shell is not None:
108 # If using our svg payload backend, register the post-execution
108 # If using our svg payload backend, register the post-execution
109 # function that will pick up the results for display. This can only be
109 # function that will pick up the results for display. This can only be
110 # done with access to the real shell object.
110 # done with access to the real shell object.
111 if backend == backends['inline']:
111 if backend == backends['inline']:
112 from IPython.zmq.pylab.backend_inline import flush_svg
112 from IPython.zmq.pylab.backend_inline import flush_svg
113 shell.register_post_execute(flush_svg)
113 shell.register_post_execute(flush_svg)
114 else:
114 else:
115 from IPython.zmq.pylab.backend_inline import paste
115 from IPython.zmq.pylab.backend_inline import pastefig
116 from matplotlib import pyplot
116 from matplotlib import pyplot
117 # Add 'paste' to pyplot and to the user's namespace
117 # Add 'paste' to pyplot and to the user's namespace
118 user_ns['paste'] = pyplot.paste = paste
118 user_ns['pastefig'] = pyplot.pastefig = pastefig
119
119
120 if import_all:
120 if import_all:
121 exec("from matplotlib.pylab import *\n"
121 exec("from matplotlib.pylab import *\n"
122 "from numpy import *\n") in user_ns
122 "from numpy import *\n") in user_ns
123
123
124
124
125 def pylab_activate(user_ns, gui=None, import_all=True):
125 def pylab_activate(user_ns, gui=None, import_all=True):
126 """Activate pylab mode in the user's namespace.
126 """Activate pylab mode in the user's namespace.
127
127
128 Loads and initializes numpy, matplotlib and friends for interactive use.
128 Loads and initializes numpy, matplotlib and friends for interactive use.
129
129
130 Parameters
130 Parameters
131 ----------
131 ----------
132 user_ns : dict
132 user_ns : dict
133 Namespace where the imports will occur.
133 Namespace where the imports will occur.
134
134
135 gui : optional, string
135 gui : optional, string
136 A valid gui name following the conventions of the %gui magic.
136 A valid gui name following the conventions of the %gui magic.
137
137
138 import_all : optional, boolean
138 import_all : optional, boolean
139 If true, an 'import *' is done from numpy and pylab.
139 If true, an 'import *' is done from numpy and pylab.
140
140
141 Returns
141 Returns
142 -------
142 -------
143 The actual gui used (if not given as input, it was obtained from matplotlib
143 The actual gui used (if not given as input, it was obtained from matplotlib
144 itself, and will be needed next to configure IPython's gui integration.
144 itself, and will be needed next to configure IPython's gui integration.
145 """
145 """
146 gui, backend = find_gui_and_backend(gui)
146 gui, backend = find_gui_and_backend(gui)
147 activate_matplotlib(backend)
147 activate_matplotlib(backend)
148 import_pylab(user_ns, backend)
148 import_pylab(user_ns, backend)
149
149
150 print """
150 print """
151 Welcome to pylab, a matplotlib-based Python environment [backend: %s].
151 Welcome to pylab, a matplotlib-based Python environment [backend: %s].
152 For more information, type 'help(pylab)'.""" % backend
152 For more information, type 'help(pylab)'.""" % backend
153
153
154 return gui
154 return gui
155
155
156 # We need a little factory function here to create the closure where
156 # We need a little factory function here to create the closure where
157 # safe_execfile can live.
157 # safe_execfile can live.
158 def mpl_runner(safe_execfile):
158 def mpl_runner(safe_execfile):
159 """Factory to return a matplotlib-enabled runner for %run.
159 """Factory to return a matplotlib-enabled runner for %run.
160
160
161 Parameters
161 Parameters
162 ----------
162 ----------
163 safe_execfile : function
163 safe_execfile : function
164 This must be a function with the same interface as the
164 This must be a function with the same interface as the
165 :meth:`safe_execfile` method of IPython.
165 :meth:`safe_execfile` method of IPython.
166
166
167 Returns
167 Returns
168 -------
168 -------
169 A function suitable for use as the ``runner`` argument of the %run magic
169 A function suitable for use as the ``runner`` argument of the %run magic
170 function.
170 function.
171 """
171 """
172
172
173 def mpl_execfile(fname,*where,**kw):
173 def mpl_execfile(fname,*where,**kw):
174 """matplotlib-aware wrapper around safe_execfile.
174 """matplotlib-aware wrapper around safe_execfile.
175
175
176 Its interface is identical to that of the :func:`execfile` builtin.
176 Its interface is identical to that of the :func:`execfile` builtin.
177
177
178 This is ultimately a call to execfile(), but wrapped in safeties to
178 This is ultimately a call to execfile(), but wrapped in safeties to
179 properly handle interactive rendering."""
179 properly handle interactive rendering."""
180
180
181 import matplotlib
181 import matplotlib
182 import matplotlib.pylab as pylab
182 import matplotlib.pylab as pylab
183
183
184 #print '*** Matplotlib runner ***' # dbg
184 #print '*** Matplotlib runner ***' # dbg
185 # turn off rendering until end of script
185 # turn off rendering until end of script
186 is_interactive = matplotlib.rcParams['interactive']
186 is_interactive = matplotlib.rcParams['interactive']
187 matplotlib.interactive(False)
187 matplotlib.interactive(False)
188 safe_execfile(fname,*where,**kw)
188 safe_execfile(fname,*where,**kw)
189 matplotlib.interactive(is_interactive)
189 matplotlib.interactive(is_interactive)
190 # make rendering call now, if the user tried to do it
190 # make rendering call now, if the user tried to do it
191 if pylab.draw_if_interactive.called:
191 if pylab.draw_if_interactive.called:
192 pylab.draw()
192 pylab.draw()
193 pylab.draw_if_interactive.called = False
193 pylab.draw_if_interactive.called = False
194
194
195 return mpl_execfile
195 return mpl_execfile
196
196
@@ -1,112 +1,112 b''
1 """Produce SVG versions of active plots for display by the rich Qt frontend.
1 """Produce SVG versions of active plots for display by the rich Qt frontend.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Imports
4 # Imports
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 from __future__ import print_function
6 from __future__ import print_function
7
7
8 # Standard library imports
8 # Standard library imports
9 from cStringIO import StringIO
9 from cStringIO import StringIO
10
10
11 # System library imports.
11 # System library imports.
12 import matplotlib
12 import matplotlib
13 from matplotlib.backends.backend_svg import new_figure_manager
13 from matplotlib.backends.backend_svg import new_figure_manager
14 from matplotlib._pylab_helpers import Gcf
14 from matplotlib._pylab_helpers import Gcf
15
15
16 # Local imports.
16 # Local imports.
17 from backend_payload import add_plot_payload
17 from backend_payload import add_plot_payload
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Functions
20 # Functions
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 def show(close=True):
23 def show(close=True):
24 """Show all figures as SVG payloads sent to the IPython clients.
24 """Show all figures as SVG payloads sent to the IPython clients.
25
25
26 Parameters
26 Parameters
27 ----------
27 ----------
28 close : bool, optional
28 close : bool, optional
29 If true, a ``plt.close('all')`` call is automatically issued after
29 If true, a ``plt.close('all')`` call is automatically issued after
30 sending all the SVG figures.
30 sending all the SVG figures.
31 """
31 """
32 for figure_manager in Gcf.get_all_fig_managers():
32 for figure_manager in Gcf.get_all_fig_managers():
33 send_svg_canvas(figure_manager.canvas)
33 send_svg_canvas(figure_manager.canvas)
34 if close:
34 if close:
35 matplotlib.pyplot.close('all')
35 matplotlib.pyplot.close('all')
36
36
37 # This flag will be reset by draw_if_interactive when called
37 # This flag will be reset by draw_if_interactive when called
38 show._draw_called = False
38 show._draw_called = False
39
39
40
40
41 def paste(*figs):
41 def pastefig(*figs):
42 """Paste figures into the console workspace.
42 """Paste one or more figures into the console workspace.
43
43
44 If no arguments are given, all available figures are pasted. If the
44 If no arguments are given, all available figures are pasted. 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 that can contain any mixture of integers and figure objects.
51 A tuple that can contain any mixture of integers and figure objects.
52 """
52 """
53 if not figs:
53 if not figs:
54 show(close=False)
54 show(close=False)
55 else:
55 else:
56 fig_managers = Gcf.get_all_fig_managers()
56 fig_managers = Gcf.get_all_fig_managers()
57 fig_index = dict( [(fm.canvas.figure, fm.canvas) for fm in fig_managers]
57 fig_index = dict( [(fm.canvas.figure, fm.canvas) for fm in fig_managers]
58 + [ (fm.canvas.figure.number, fm.canvas) for fm in fig_managers] )
58 + [ (fm.canvas.figure.number, fm.canvas) for fm in fig_managers] )
59
59
60 for fig in figs:
60 for fig in figs:
61 canvas = fig_index.get(fig)
61 canvas = fig_index.get(fig)
62 if canvas is None:
62 if canvas is None:
63 print('Warning: figure %s not available.' % fig)
63 print('Warning: figure %s not available.' % fig)
64 else:
64 else:
65 send_svg_canvas(canvas)
65 send_svg_canvas(canvas)
66
66
67
67
68 def send_svg_canvas(canvas):
68 def send_svg_canvas(canvas):
69 """Draw the current canvas and send it as an SVG payload.
69 """Draw the current canvas and send it as an SVG payload.
70 """
70 """
71 # Make the background transparent.
71 # Make the background transparent.
72 # figure_manager.canvas.figure.patch.set_alpha(0.0)
72 # figure_manager.canvas.figure.patch.set_alpha(0.0)
73
73
74 # Set the background to white instead so it looks good on black. We store
74 # Set the background to white instead so it looks good on black. We store
75 # the current values to restore them at the end.
75 # the current values to restore them at the end.
76 fc = canvas.figure.get_facecolor()
76 fc = canvas.figure.get_facecolor()
77 ec = canvas.figure.get_edgecolor()
77 ec = canvas.figure.get_edgecolor()
78 canvas.figure.set_facecolor('white')
78 canvas.figure.set_facecolor('white')
79 canvas.figure.set_edgecolor('white')
79 canvas.figure.set_edgecolor('white')
80 try:
80 try:
81 add_plot_payload('svg', svg_from_canvas(canvas))
81 add_plot_payload('svg', svg_from_canvas(canvas))
82 finally:
82 finally:
83 canvas.figure.set_facecolor(fc)
83 canvas.figure.set_facecolor(fc)
84 canvas.figure.set_edgecolor(ec)
84 canvas.figure.set_edgecolor(ec)
85
85
86
86
87 def svg_from_canvas(canvas):
87 def svg_from_canvas(canvas):
88 """ Return a string containing the SVG representation of a FigureCanvasSvg.
88 """ Return a string containing the SVG representation of a FigureCanvasSvg.
89 """
89 """
90 string_io = StringIO()
90 string_io = StringIO()
91 canvas.print_svg(string_io)
91 canvas.print_svg(string_io)
92 return string_io.getvalue()
92 return string_io.getvalue()
93
93
94
94
95 def draw_if_interactive():
95 def draw_if_interactive():
96 """
96 """
97 Is called after every pylab drawing command
97 Is called after every pylab drawing command
98 """
98 """
99 # We simply flag we were called and otherwise do nothing. At the end of
99 # We simply flag we were called and otherwise do nothing. At the end of
100 # the code execution, a separate call to show_close() will act upon this.
100 # the code execution, a separate call to show_close() will act upon this.
101 show._draw_called = True
101 show._draw_called = True
102
102
103
103
104 def flush_svg():
104 def flush_svg():
105 """Call show, close all open figures, sending all SVG images.
105 """Call show, close all open figures, sending all SVG images.
106
106
107 This is meant to be called automatically and will call show() if, during
107 This is meant to be called automatically and will call show() if, during
108 prior code execution, there had been any calls to draw_if_interactive.
108 prior code execution, there had been any calls to draw_if_interactive.
109 """
109 """
110 if show._draw_called:
110 if show._draw_called:
111 show(close=True)
111 show(close=True)
112 show._draw_called = False
112 show._draw_called = False
General Comments 0
You need to be logged in to leave comments. Login now