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