##// END OF EJS Templates
Add mention of %rep to interactive use tutorial section of the docs....
Fernando Perez -
Show More
@@ -1,325 +1,336 b''
1 .. _tutorial:
1 .. _tutorial:
2
2
3 ======================
3 ======================
4 Quick IPython tutorial
4 Quick IPython tutorial
5 ======================
5 ======================
6
6
7 .. warning::
7 .. warning::
8
8
9 As of the 0.11 version of IPython, some of the features and APIs
9 As of the 0.11 version of IPython, some of the features and APIs
10 described in this section have been deprecated or are broken. Our plan
10 described in this section have been deprecated or are broken. Our plan
11 is to continue to support these features, but they need to be updated
11 is to continue to support these features, but they need to be updated
12 to take advantage of recent API changes. Furthermore, this section
12 to take advantage of recent API changes. Furthermore, this section
13 of the documentation need to be updated to reflect all of these changes.
13 of the documentation need to be updated to reflect all of these changes.
14
14
15 IPython can be used as an improved replacement for the Python prompt,
15 IPython can be used as an improved replacement for the Python prompt,
16 and for that you don't really need to read any more of this manual. But
16 and for that you don't really need to read any more of this manual. But
17 in this section we'll try to summarize a few tips on how to make the
17 in this section we'll try to summarize a few tips on how to make the
18 most effective use of it for everyday Python development, highlighting
18 most effective use of it for everyday Python development, highlighting
19 things you might miss in the rest of the manual (which is getting long).
19 things you might miss in the rest of the manual (which is getting long).
20 We'll give references to parts in the manual which provide more detail
20 We'll give references to parts in the manual which provide more detail
21 when appropriate.
21 when appropriate.
22
22
23 The following article by Jeremy Jones provides an introductory tutorial
23 The following article by Jeremy Jones provides an introductory tutorial
24 about IPython: http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html
24 about IPython: http://www.onlamp.com/pub/a/python/2005/01/27/ipython.html
25
25
26 Highlights
26 Highlights
27 ==========
27 ==========
28
28
29 Tab completion
29 Tab completion
30 --------------
30 --------------
31
31
32 TAB-completion, especially for attributes, is a convenient way to explore the
32 TAB-completion, especially for attributes, is a convenient way to explore the
33 structure of any object you're dealing with. Simply type object_name.<TAB> and
33 structure of any object you're dealing with. Simply type object_name.<TAB> and
34 a list of the object's attributes will be printed (see :ref:`the readline
34 a list of the object's attributes will be printed (see :ref:`the readline
35 section <readline>` for more). Tab completion also works on file and directory
35 section <readline>` for more). Tab completion also works on file and directory
36 names, which combined with IPython's alias system allows you to do from within
36 names, which combined with IPython's alias system allows you to do from within
37 IPython many of the things you normally would need the system shell for.
37 IPython many of the things you normally would need the system shell for.
38
38
39 Explore your objects
39 Explore your objects
40 --------------------
40 --------------------
41
41
42 Typing object_name? will print all sorts of details about any object,
42 Typing object_name? will print all sorts of details about any object,
43 including docstrings, function definition lines (for call arguments) and
43 including docstrings, function definition lines (for call arguments) and
44 constructor details for classes. The magic commands %pdoc, %pdef, %psource
44 constructor details for classes. The magic commands %pdoc, %pdef, %psource
45 and %pfile will respectively print the docstring, function definition line,
45 and %pfile will respectively print the docstring, function definition line,
46 full source code and the complete file for any object (when they can be
46 full source code and the complete file for any object (when they can be
47 found). If automagic is on (it is by default), you don't need to type the '%'
47 found). If automagic is on (it is by default), you don't need to type the '%'
48 explicitly. See :ref:`this section <dynamic_object_info>` for more.
48 explicitly. See :ref:`this section <dynamic_object_info>` for more.
49
49
50 The `%run` magic command
50 The `%run` magic command
51 ------------------------
51 ------------------------
52
52
53 The %run magic command allows you to run any python script and load all of its
53 The %run magic command allows you to run any python script and load all of its
54 data directly into the interactive namespace. Since the file is re-read from
54 data directly into the interactive namespace. Since the file is re-read from
55 disk each time, changes you make to it are reflected immediately (in contrast
55 disk each time, changes you make to it are reflected immediately (in contrast
56 to the behavior of import). I rarely use import for code I am testing, relying
56 to the behavior of import). I rarely use import for code I am testing, relying
57 on %run instead. See :ref:`this section <magic>` for more on this and other
57 on %run instead. See :ref:`this section <magic>` for more on this and other
58 magic commands, or type the name of any magic command and ? to get details on
58 magic commands, or type the name of any magic command and ? to get details on
59 it. See also :ref:`this section <dreload>` for a recursive reload command. %run
59 it. See also :ref:`this section <dreload>` for a recursive reload command. %run
60 also has special flags for timing the execution of your scripts (-t) and for
60 also has special flags for timing the execution of your scripts (-t) and for
61 executing them under the control of either Python's pdb debugger (-d) or
61 executing them under the control of either Python's pdb debugger (-d) or
62 profiler (-p). With all of these, %run can be used as the main tool for
62 profiler (-p). With all of these, %run can be used as the main tool for
63 efficient interactive development of code which you write in your editor of
63 efficient interactive development of code which you write in your editor of
64 choice.
64 choice.
65
65
66 Debug a Python script
66 Debug a Python script
67 ---------------------
67 ---------------------
68
68
69 Use the Python debugger, pdb. The %pdb command allows you to toggle on and off
69 Use the Python debugger, pdb. The %pdb command allows you to toggle on and off
70 the automatic invocation of an IPython-enhanced pdb debugger (with coloring,
70 the automatic invocation of an IPython-enhanced pdb debugger (with coloring,
71 tab completion and more) at any uncaught exception. The advantage of this is
71 tab completion and more) at any uncaught exception. The advantage of this is
72 that pdb starts inside the function where the exception occurred, with all data
72 that pdb starts inside the function where the exception occurred, with all data
73 still available. You can print variables, see code, execute statements and even
73 still available. You can print variables, see code, execute statements and even
74 walk up and down the call stack to track down the true source of the problem
74 walk up and down the call stack to track down the true source of the problem
75 (which often is many layers in the stack above where the exception gets
75 (which often is many layers in the stack above where the exception gets
76 triggered). Running programs with %run and pdb active can be an efficient to
76 triggered). Running programs with %run and pdb active can be an efficient to
77 develop and debug code, in many cases eliminating the need for print statements
77 develop and debug code, in many cases eliminating the need for print statements
78 or external debugging tools. I often simply put a 1/0 in a place where I want
78 or external debugging tools. I often simply put a 1/0 in a place where I want
79 to take a look so that pdb gets called, quickly view whatever variables I need
79 to take a look so that pdb gets called, quickly view whatever variables I need
80 to or test various pieces of code and then remove the 1/0. Note also that '%run
80 to or test various pieces of code and then remove the 1/0. Note also that '%run
81 -d' activates pdb and automatically sets initial breakpoints for you to step
81 -d' activates pdb and automatically sets initial breakpoints for you to step
82 through your code, watch variables, etc. The :ref:`output caching section
82 through your code, watch variables, etc. The :ref:`output caching section
83 <output_caching>` has more details.
83 <output_caching>` has more details.
84
84
85 Use the output cache
85 Use the output cache
86 --------------------
86 --------------------
87
87
88 All output results are automatically stored in a global dictionary named Out
88 All output results are automatically stored in a global dictionary named Out
89 and variables named _1, _2, etc. alias them. For example, the result of input
89 and variables named _1, _2, etc. alias them. For example, the result of input
90 line 4 is available either as Out[4] or as _4. Additionally, three variables
90 line 4 is available either as Out[4] or as _4. Additionally, three variables
91 named _, __ and ___ are always kept updated with the for the last three
91 named _, __ and ___ are always kept updated with the for the last three
92 results. This allows you to recall any previous result and further use it for
92 results. This allows you to recall any previous result and further use it for
93 new calculations. See :ref:`the output caching section <output_caching>` for
93 new calculations. See :ref:`the output caching section <output_caching>` for
94 more.
94 more.
95
95
96 Suppress output
96 Suppress output
97 ---------------
97 ---------------
98
98
99 Put a ';' at the end of a line to suppress the printing of output. This is
99 Put a ';' at the end of a line to suppress the printing of output. This is
100 useful when doing calculations which generate long output you are not
100 useful when doing calculations which generate long output you are not
101 interested in seeing. The _* variables and the Out[] list do get updated with
101 interested in seeing. The _* variables and the Out[] list do get updated with
102 the contents of the output, even if it is not printed. You can thus still
102 the contents of the output, even if it is not printed. You can thus still
103 access the generated results this way for further processing.
103 access the generated results this way for further processing.
104
104
105 Input cache
105 Input cache
106 -----------
106 -----------
107
107
108 A similar system exists for caching input. All input is stored in a global
108 A similar system exists for caching input. All input is stored in a global
109 list called In , so you can re-execute lines 22 through 28 plus line 34 by
109 list called In , so you can re-execute lines 22 through 28 plus line 34 by
110 typing 'exec In[22:29]+In[34]' (using Python slicing notation). If you need
110 typing 'exec In[22:29]+In[34]' (using Python slicing notation). If you need
111 to execute the same set of lines often, you can assign them to a macro with
111 to execute the same set of lines often, you can assign them to a macro with
112 the %macro function. See :ref:`here <input_caching>` for more.
112 the %macro function. See :ref:`here <input_caching>` for more.
113
113
114 Use your input history
114 Use your input history
115 ----------------------
115 ----------------------
116
116
117 The %hist command can show you all previous input, without line numbers if
117 The %hist command can show you all previous input, without line numbers if
118 desired (option -n) so you can directly copy and paste code either back in
118 desired (option -n) so you can directly copy and paste code either back in
119 IPython or in a text editor. You can also save all your history by turning on
119 IPython or in a text editor. You can also save all your history by turning on
120 logging via %logstart; these logs can later be either reloaded as IPython
120 logging via %logstart; these logs can later be either reloaded as IPython
121 sessions or used as code for your programs.
121 sessions or used as code for your programs.
122
122
123 In particular, note taht the %rep magic function can repeat a command or get a
124 command to the input line for further editing::
125
126 $ l = ["hei", "vaan"]
127 $ "".join(l)
128 ==> heivaan
129 $ %rep
130 $ heivaan_ <== cursor blinking
131
132 For more details, type ``%rep?`` as usual.
133
123 Define your own system aliases
134 Define your own system aliases
124 ------------------------------
135 ------------------------------
125
136
126 Even though IPython gives you access to your system shell via the ! prefix,
137 Even though IPython gives you access to your system shell via the ! prefix,
127 it is convenient to have aliases to the system commands you use most often.
138 it is convenient to have aliases to the system commands you use most often.
128 This allows you to work seamlessly from inside IPython with the same commands
139 This allows you to work seamlessly from inside IPython with the same commands
129 you are used to in your system shell. IPython comes with some pre-defined
140 you are used to in your system shell. IPython comes with some pre-defined
130 aliases and a complete system for changing directories, both via a stack (see
141 aliases and a complete system for changing directories, both via a stack (see
131 %pushd, %popd and %dhist) and via direct %cd. The latter keeps a history of
142 %pushd, %popd and %dhist) and via direct %cd. The latter keeps a history of
132 visited directories and allows you to go to any previously visited one.
143 visited directories and allows you to go to any previously visited one.
133
144
134 Call system shell commands
145 Call system shell commands
135 --------------------------
146 --------------------------
136
147
137 Use Python to manipulate the results of system commands. The '!!' special
148 Use Python to manipulate the results of system commands. The '!!' special
138 syntax, and the %sc and %sx magic commands allow you to capture system output
149 syntax, and the %sc and %sx magic commands allow you to capture system output
139 into Python variables.
150 into Python variables.
140
151
141 Use Python variables when calling the shell
152 Use Python variables when calling the shell
142 -------------------------------------------
153 -------------------------------------------
143
154
144 Expand python variables when calling the shell (either via '!' and '!!' or via
155 Expand python variables when calling the shell (either via '!' and '!!' or via
145 aliases) by prepending a $ in front of them. You can also expand complete
156 aliases) by prepending a $ in front of them. You can also expand complete
146 python expressions. See :ref:`our shell section <system_shell_access>` for
157 python expressions. See :ref:`our shell section <system_shell_access>` for
147 more details.
158 more details.
148
159
149 Use profiles
160 Use profiles
150 ------------
161 ------------
151
162
152 Use profiles to maintain different configurations (modules to load, function
163 Use profiles to maintain different configurations (modules to load, function
153 definitions, option settings) for particular tasks. You can then have
164 definitions, option settings) for particular tasks. You can then have
154 customized versions of IPython for specific purposes. :ref:`This section
165 customized versions of IPython for specific purposes. :ref:`This section
155 <profiles>` has more details.
166 <profiles>` has more details.
156
167
157
168
158 Embed IPython in your programs
169 Embed IPython in your programs
159 ------------------------------
170 ------------------------------
160
171
161 A few lines of code are enough to load a complete IPython inside your own
172 A few lines of code are enough to load a complete IPython inside your own
162 programs, giving you the ability to work with your data interactively after
173 programs, giving you the ability to work with your data interactively after
163 automatic processing has been completed. See :ref:`here <embedding>` for more.
174 automatic processing has been completed. See :ref:`here <embedding>` for more.
164
175
165 Use the Python profiler
176 Use the Python profiler
166 -----------------------
177 -----------------------
167
178
168 When dealing with performance issues, the %run command with a -p option
179 When dealing with performance issues, the %run command with a -p option
169 allows you to run complete programs under the control of the Python profiler.
180 allows you to run complete programs under the control of the Python profiler.
170 The %prun command does a similar job for single Python expressions (like
181 The %prun command does a similar job for single Python expressions (like
171 function calls).
182 function calls).
172
183
173 Use IPython to present interactive demos
184 Use IPython to present interactive demos
174 ----------------------------------------
185 ----------------------------------------
175
186
176 Use the IPython.demo.Demo class to load any Python script as an interactive
187 Use the IPython.demo.Demo class to load any Python script as an interactive
177 demo. With a minimal amount of simple markup, you can control the execution of
188 demo. With a minimal amount of simple markup, you can control the execution of
178 the script, stopping as needed. See :ref:`here <interactive_demos>` for more.
189 the script, stopping as needed. See :ref:`here <interactive_demos>` for more.
179
190
180 Run doctests
191 Run doctests
181 ------------
192 ------------
182
193
183 Run your doctests from within IPython for development and debugging. The
194 Run your doctests from within IPython for development and debugging. The
184 special %doctest_mode command toggles a mode where the prompt, output and
195 special %doctest_mode command toggles a mode where the prompt, output and
185 exceptions display matches as closely as possible that of the default Python
196 exceptions display matches as closely as possible that of the default Python
186 interpreter. In addition, this mode allows you to directly paste in code that
197 interpreter. In addition, this mode allows you to directly paste in code that
187 contains leading '>>>' prompts, even if they have extra leading whitespace
198 contains leading '>>>' prompts, even if they have extra leading whitespace
188 (as is common in doctest files). This combined with the '%history -tn' call
199 (as is common in doctest files). This combined with the '%history -tn' call
189 to see your translated history (with these extra prompts removed and no line
200 to see your translated history (with these extra prompts removed and no line
190 numbers) allows for an easy doctest workflow, where you can go from doctest
201 numbers) allows for an easy doctest workflow, where you can go from doctest
191 to interactive execution to pasting into valid Python code as needed.
202 to interactive execution to pasting into valid Python code as needed.
192
203
193 Source code handling tips
204 Source code handling tips
194 =========================
205 =========================
195
206
196 IPython is a line-oriented program, without full control of the
207 IPython is a line-oriented program, without full control of the
197 terminal. Therefore, it doesn't support true multiline editing. However,
208 terminal. Therefore, it doesn't support true multiline editing. However,
198 it has a number of useful tools to help you in dealing effectively with
209 it has a number of useful tools to help you in dealing effectively with
199 more complex editing.
210 more complex editing.
200
211
201 The %edit command gives a reasonable approximation of multiline editing,
212 The %edit command gives a reasonable approximation of multiline editing,
202 by invoking your favorite editor on the spot. IPython will execute the
213 by invoking your favorite editor on the spot. IPython will execute the
203 code you type in there as if it were typed interactively. Type %edit?
214 code you type in there as if it were typed interactively. Type %edit?
204 for the full details on the edit command.
215 for the full details on the edit command.
205
216
206 If you have typed various commands during a session, which you'd like to
217 If you have typed various commands during a session, which you'd like to
207 reuse, IPython provides you with a number of tools. Start by using %hist
218 reuse, IPython provides you with a number of tools. Start by using %hist
208 to see your input history, so you can see the line numbers of all input.
219 to see your input history, so you can see the line numbers of all input.
209 Let us say that you'd like to reuse lines 10 through 20, plus lines 24
220 Let us say that you'd like to reuse lines 10 through 20, plus lines 24
210 and 28. All the commands below can operate on these with the syntax::
221 and 28. All the commands below can operate on these with the syntax::
211
222
212 %command 10-20 24 28
223 %command 10-20 24 28
213
224
214 where the command given can be:
225 where the command given can be:
215
226
216 * %macro <macroname>: this stores the lines into a variable which,
227 * %macro <macroname>: this stores the lines into a variable which,
217 when called at the prompt, re-executes the input. Macros can be
228 when called at the prompt, re-executes the input. Macros can be
218 edited later using '%edit macroname', and they can be stored
229 edited later using '%edit macroname', and they can be stored
219 persistently across sessions with '%store macroname' (the storage
230 persistently across sessions with '%store macroname' (the storage
220 system is per-profile). The combination of quick macros,
231 system is per-profile). The combination of quick macros,
221 persistent storage and editing, allows you to easily refine
232 persistent storage and editing, allows you to easily refine
222 quick-and-dirty interactive input into permanent utilities, always
233 quick-and-dirty interactive input into permanent utilities, always
223 available both in IPython and as files for general reuse.
234 available both in IPython and as files for general reuse.
224 * %edit: this will open a text editor with those lines pre-loaded
235 * %edit: this will open a text editor with those lines pre-loaded
225 for further modification. It will then execute the resulting
236 for further modification. It will then execute the resulting
226 file's contents as if you had typed it at the prompt.
237 file's contents as if you had typed it at the prompt.
227 * %save <filename>: this saves the lines directly to a named file on
238 * %save <filename>: this saves the lines directly to a named file on
228 disk.
239 disk.
229
240
230 While %macro saves input lines into memory for interactive re-execution,
241 While %macro saves input lines into memory for interactive re-execution,
231 sometimes you'd like to save your input directly to a file. The %save
242 sometimes you'd like to save your input directly to a file. The %save
232 magic does this: its input sytnax is the same as %macro, but it saves
243 magic does this: its input sytnax is the same as %macro, but it saves
233 your input directly to a Python file. Note that the %logstart command
244 your input directly to a Python file. Note that the %logstart command
234 also saves input, but it logs all input to disk (though you can
245 also saves input, but it logs all input to disk (though you can
235 temporarily suspend it and reactivate it with %logoff/%logon); %save
246 temporarily suspend it and reactivate it with %logoff/%logon); %save
236 allows you to select which lines of input you need to save.
247 allows you to select which lines of input you need to save.
237
248
238
249
239 Lightweight 'version control'
250 Lightweight 'version control'
240 =============================
251 =============================
241
252
242 When you call %edit with no arguments, IPython opens an empty editor
253 When you call %edit with no arguments, IPython opens an empty editor
243 with a temporary file, and it returns the contents of your editing
254 with a temporary file, and it returns the contents of your editing
244 session as a string variable. Thanks to IPython's output caching
255 session as a string variable. Thanks to IPython's output caching
245 mechanism, this is automatically stored::
256 mechanism, this is automatically stored::
246
257
247 In [1]: %edit
258 In [1]: %edit
248
259
249 IPython will make a temporary file named: /tmp/ipython_edit_yR-HCN.py
260 IPython will make a temporary file named: /tmp/ipython_edit_yR-HCN.py
250
261
251 Editing... done. Executing edited code...
262 Editing... done. Executing edited code...
252
263
253 hello - this is a temporary file
264 hello - this is a temporary file
254
265
255 Out[1]: "print 'hello - this is a temporary file'\n"
266 Out[1]: "print 'hello - this is a temporary file'\n"
256
267
257 Now, if you call '%edit -p', IPython tries to open an editor with the
268 Now, if you call '%edit -p', IPython tries to open an editor with the
258 same data as the last time you used %edit. So if you haven't used %edit
269 same data as the last time you used %edit. So if you haven't used %edit
259 in the meantime, this same contents will reopen; however, it will be
270 in the meantime, this same contents will reopen; however, it will be
260 done in a new file. This means that if you make changes and you later
271 done in a new file. This means that if you make changes and you later
261 want to find an old version, you can always retrieve it by using its
272 want to find an old version, you can always retrieve it by using its
262 output number, via '%edit _NN', where NN is the number of the output
273 output number, via '%edit _NN', where NN is the number of the output
263 prompt.
274 prompt.
264
275
265 Continuing with the example above, this should illustrate this idea::
276 Continuing with the example above, this should illustrate this idea::
266
277
267 In [2]: edit -p
278 In [2]: edit -p
268
279
269 IPython will make a temporary file named: /tmp/ipython_edit_nA09Qk.py
280 IPython will make a temporary file named: /tmp/ipython_edit_nA09Qk.py
270
281
271 Editing... done. Executing edited code...
282 Editing... done. Executing edited code...
272
283
273 hello - now I made some changes
284 hello - now I made some changes
274
285
275 Out[2]: "print 'hello - now I made some changes'\n"
286 Out[2]: "print 'hello - now I made some changes'\n"
276
287
277 In [3]: edit _1
288 In [3]: edit _1
278
289
279 IPython will make a temporary file named: /tmp/ipython_edit_gy6-zD.py
290 IPython will make a temporary file named: /tmp/ipython_edit_gy6-zD.py
280
291
281 Editing... done. Executing edited code...
292 Editing... done. Executing edited code...
282
293
283 hello - this is a temporary file
294 hello - this is a temporary file
284
295
285 IPython version control at work :)
296 IPython version control at work :)
286
297
287 Out[3]: "print 'hello - this is a temporary file'\nprint 'IPython version control at work :)'\n"
298 Out[3]: "print 'hello - this is a temporary file'\nprint 'IPython version control at work :)'\n"
288
299
289
300
290 This section was written after a contribution by Alexander Belchenko on
301 This section was written after a contribution by Alexander Belchenko on
291 the IPython user list.
302 the IPython user list.
292
303
293
304
294 Effective logging
305 Effective logging
295 =================
306 =================
296
307
297 A very useful suggestion sent in by Robert Kern follows:
308 A very useful suggestion sent in by Robert Kern follows:
298
309
299 I recently happened on a nifty way to keep tidy per-project log files. I
310 I recently happened on a nifty way to keep tidy per-project log files. I
300 made a profile for my project (which is called "parkfield")::
311 made a profile for my project (which is called "parkfield")::
301
312
302 include ipythonrc
313 include ipythonrc
303
314
304 # cancel earlier logfile invocation:
315 # cancel earlier logfile invocation:
305
316
306 logfile ''
317 logfile ''
307
318
308 execute import time
319 execute import time
309
320
310 execute __cmd = '/Users/kern/research/logfiles/parkfield-%s.log rotate'
321 execute __cmd = '/Users/kern/research/logfiles/parkfield-%s.log rotate'
311
322
312 execute __IP.magic_logstart(__cmd % time.strftime('%Y-%m-%d'))
323 execute __IP.magic_logstart(__cmd % time.strftime('%Y-%m-%d'))
313
324
314 I also added a shell alias for convenience::
325 I also added a shell alias for convenience::
315
326
316 alias parkfield="ipython -pylab -profile parkfield"
327 alias parkfield="ipython -pylab -profile parkfield"
317
328
318 Now I have a nice little directory with everything I ever type in,
329 Now I have a nice little directory with everything I ever type in,
319 organized by project and date.
330 organized by project and date.
320
331
321 Contribute your own: If you have your own favorite tip on using IPython
332 Contribute your own: If you have your own favorite tip on using IPython
322 efficiently for a certain task (especially things which can't be done in
333 efficiently for a certain task (especially things which can't be done in
323 the normal Python interpreter), don't hesitate to send it!
334 the normal Python interpreter), don't hesitate to send it!
324
335
325
336
General Comments 0
You need to be logged in to leave comments. Login now