##// END OF EJS Templates
One more pass on the docs....
Matthias Bussonnier -
Show More
@@ -1,19 +1,31 b''
1 1 ==================================
2 2 Using IPython for interactive work
3 3 ==================================
4 4
5 This section of IPython documentation walk you through most of the IPython
6 functionality. You do not need to have any deep knowledge of Python to read this
7 tutorial, though some section might make slightly more sens if you have already
8 done some work in the REPL.
9
10 .. note::
11
12 Some part of this documentation are more than a decade old so might be out
13 of date, we welcome any report of inacuracy, and Pull Requests that make
14 that up to date.
15
5 16 .. toctree::
6 17 :maxdepth: 2
18 :hidden:
7 19
8 20 tutorial
9 magics
10 21 plotting
11 22 reference
12 23 shell
13 24 tips
14 25 python-ipython-diff
26 magics
15 27
16 28 .. seealso::
17 29
18 30 `A Qt Console for Jupyter <http://jupyter.org/qtconsole/>`__
19 31 `The Jupyter Notebook <http://jupyter-notebook.readthedocs.io/en/latest/>`__
@@ -1,5 +1,22 b''
1 1 =======================
2 2 Built-in magic commands
3 3 =======================
4 4
5 .. note::
6
7 To Jupyter users: Magics are specifit to the IPython kernel. Other kernels
8 may be implementing magics but this decision is a per-kernel one. To be able
9 to work, Magics need to use a syntax which is not valid in the language they
10 are implemented. IPython choosed the `%` as it is not a valid unary operator
11 in Python. It is in other languages.
12
13
14 Here is the help auto generated from the docstrings of all the available magics
15 function that IPython ships with.
16
17 You can create an register your own magics with IPython. You can find many user
18 defined magics on `PyPI <https://pypi.io>`_. Feel free to publish your own and
19 use the ``Framework :: IPython`` trove classifier.
20
21
5 22 .. include:: magics-generated.txt
@@ -1,36 +1,42 b''
1 1 .. _plotting:
2 2
3 3 Plotting
4 4 --------
5 5 One major feature of the IPython kernel is the ability to display plots that
6 6 are the output of running code cells. The IPython kernel is designed to work
7 7 seamlessly with the matplotlib_ plotting library to provide this functionality.
8 8
9 To set this up, before any plotting is performed you must execute the
10 ``%matplotlib`` :ref:`magic command <magics_explained>`. This performs the
11 necessary behind-the-scenes setup for IPython to work correctly hand in hand
12 with ``matplotlib``; it does *not*, however, actually execute any Python
13 ``import`` commands, that is, no names are added to the namespace.
9 To set this up, before any plotting or import of matplotlib is performed you
10 must execute the ``%matplotlib`` :ref:`magic command <magics_explained>`. This
11 performs the necessary behind-the-scenes setup for IPython to work correctly
12 hand in hand with ``matplotlib``; it does *not*, however, actually execute any
13 Python ``import`` commands, that is, no names are added to the namespace.
14 14
15 15 If the ``%matplotlib`` magic is called without an argument, the
16 16 output of a plotting command is displayed using the default ``matplotlib``
17 17 backend in a separate window. Alternatively, the backend can be explicitly
18 18 requested using, for example::
19 19
20 20 %matplotlib gtk
21 21
22 22 A particularly interesting backend, provided by IPython, is the ``inline``
23 23 backend. This is available only for the Jupyter Notebook and the
24 24 Jupyter QtConsole. It can be invoked as follows::
25 25
26 26 %matplotlib inline
27 27
28 With this backend, the output of plotting commands is displayed *inline*
29 within the notebook, directly below the code cell that produced it. The
30 resulting plots will then also be stored in the notebook document.
28 With this backend, the output of plotting commands is displayed *inline* within
29 frontends like the Jupyter notebook, directly below the code cell that produced
30 it. The resulting plots will then also be stored in the notebook document.
31 31
32 32 .. seealso::
33 33
34 34 `Plotting with Matplotlib`_ example notebook
35 35
36
37 The matplotlib_ library also ships with ``%matplotlib notebook`` command that
38 allows interactive figures if your environment allows it.
39
40 See the matplotlib_ documentation for more information.
41
36 42 .. include:: ../links.txt
@@ -1,1000 +1,1008 b''
1 1 =================
2 2 IPython reference
3 3 =================
4 4
5 5 .. _command_line_options:
6 6
7 7 Command-line usage
8 8 ==================
9 9
10 10 You start IPython with the command::
11 11
12 12 $ ipython [options] files
13 13
14 If invoked with no options, it executes all the files listed in sequence
15 and drops you into the interpreter while still acknowledging any options
16 you may have set in your ipython_config.py. This behavior is different from
17 standard Python, which when called as python -i will only execute one
18 file and ignore your configuration setup.
19
20 Please note that some of the configuration options are not available at
21 the command line, simply because they are not practical here. Look into
22 your configuration files for details on those. There are separate configuration
23 files for each profile, and the files look like :file:`ipython_config.py` or
14 If invoked with no options, it executes all the files listed in sequence and
15 exit. If you add the ``-i`` flag, it drops you into the interpreter while still
16 acknowledging any options you may have set in your ``ipython_config.py``. This
17 behavior is different from standard Python, which when called as python ``-i``
18 will only execute one file and ignore your configuration setup.
19
20 Please note that some of the configuration options are not available at the
21 command line, simply because they are not practical here. Look into your
22 configuration files for details on those. There are separate configuration files
23 for each profile, and the files look like :file:`ipython_config.py` or
24 24 :file:`ipython_config_{frontendname}.py`. Profile directories look like
25 :file:`profile_{profilename}` and are typically installed in the :envvar:`IPYTHONDIR` directory,
26 which defaults to :file:`$HOME/.ipython`. For Windows users, :envvar:`HOME`
27 resolves to :file:`C:\\Users\\{YourUserName}` in most instances.
25 :file:`profile_{profilename}` and are typically installed in the
26 :envvar:`IPYTHONDIR` directory, which defaults to :file:`$HOME/.ipython`. For
27 Windows users, :envvar:`HOME` resolves to :file:`C:\\Users\\{YourUserName}` in
28 most instances.
28 29
29 30 Command-line Options
30 31 --------------------
31 32
32 33 To see the options IPython accepts, use ``ipython --help`` (and you probably
33 34 should run the output through a pager such as ``ipython --help | less`` for
34 35 more convenient reading). This shows all the options that have a single-word
35 36 alias to control them, but IPython lets you configure all of its objects from
36 37 the command-line by passing the full class name and a corresponding value; type
37 38 ``ipython --help-all`` to see this full list. For example::
38 39
40 ::
41 $ ipython --help-all
42 <...snip...>
43 --matplotlib=<CaselessStrEnum> (InteractiveShellApp.matplotlib)
44 Default: None
45 Choices: ['auto', 'gtk', 'gtk3', 'inline', 'nbagg', 'notebook', 'osx', 'qt', 'qt4', 'qt5', 'tk', 'wx']
46 Configure matplotlib for interactive use with the default matplotlib
47 backend.
48 <...snip...>
49
50
51 Indicate that the following::
52
53
39 54 ipython --matplotlib qt
40 55
41 56 is equivalent to::
42 57
43 58 ipython --TerminalIPythonApp.matplotlib='qt'
44 59
45 60 Note that in the second form, you *must* use the equal sign, as the expression
46 61 is evaluated as an actual Python assignment. While in the above example the
47 62 short form is more convenient, only the most common options have a short form,
48 63 while any configurable variable in IPython can be set at the command-line by
49 64 using the long form. This long form is the same syntax used in the
50 65 configuration files, if you want to set these options permanently.
51 66
52 67
53 68 Interactive use
54 69 ===============
55 70
56 71 IPython is meant to work as a drop-in replacement for the standard interactive
57 72 interpreter. As such, any code which is valid python should execute normally
58 73 under IPython (cases where this is not true should be reported as bugs). It
59 74 does, however, offer many features which are not available at a standard python
60 75 prompt. What follows is a list of these.
61 76
62 77
63 78 Caution for Windows users
64 79 -------------------------
65 80
66 81 Windows, unfortunately, uses the '\\' character as a path separator. This is a
67 82 terrible choice, because '\\' also represents the escape character in most
68 83 modern programming languages, including Python. For this reason, using '/'
69 84 character is recommended if you have problems with ``\``. However, in Windows
70 85 commands '/' flags options, so you can not use it for the root directory. This
71 86 means that paths beginning at the root must be typed in a contrived manner
72 87 like: ``%copy \opt/foo/bar.txt \tmp``
73 88
74 89 .. _magic:
75 90
76 91 Magic command system
77 92 --------------------
78 93
79 94 IPython will treat any line whose first character is a % as a special
80 95 call to a 'magic' function. These allow you to control the behavior of
81 96 IPython itself, plus a lot of system-type features. They are all
82 97 prefixed with a % character, but parameters are given without
83 98 parentheses or quotes.
84 99
85 100 Lines that begin with ``%%`` signal a *cell magic*: they take as arguments not
86 101 only the rest of the current line, but all lines below them as well, in the
87 102 current execution block. Cell magics can in fact make arbitrary modifications
88 103 to the input they receive, which need not even be valid Python code at all.
89 104 They receive the whole block as a single string.
90 105
91 106 As a line magic example, the :magic:`cd` magic works just like the OS command of
92 107 the same name::
93 108
94 109 In [8]: %cd
95 110 /home/fperez
96 111
97 112 The following uses the builtin :magic:`timeit` in cell mode::
98 113
99 114 In [10]: %%timeit x = range(10000)
100 115 ...: min(x)
101 116 ...: max(x)
102 117 ...:
103 118 1000 loops, best of 3: 438 us per loop
104 119
105 120 In this case, ``x = range(10000)`` is called as the line argument, and the
106 121 block with ``min(x)`` and ``max(x)`` is called as the cell body. The
107 122 :magic:`timeit` magic receives both.
108 123
109 124 If you have 'automagic' enabled (as it is by default), you don't need to type in
110 125 the single ``%`` explicitly for line magics; IPython will scan its internal
111 126 list of magic functions and call one if it exists. With automagic on you can
112 127 then just type ``cd mydir`` to go to directory 'mydir'::
113 128
114 129 In [9]: cd mydir
115 130 /home/fperez/mydir
116 131
117 132 Cell magics *always* require an explicit ``%%`` prefix, automagic
118 133 calling only works for line magics.
119 134
120 135 The automagic system has the lowest possible precedence in name searches, so
121 136 you can freely use variables with the same names as magic commands. If a magic
122 137 command is 'shadowed' by a variable, you will need the explicit ``%`` prefix to
123 138 use it:
124 139
125 140 .. sourcecode:: ipython
126 141
127 142 In [1]: cd ipython # %cd is called by automagic
128 143 /home/fperez/ipython
129 144
130 145 In [2]: cd=1 # now cd is just a variable
131 146
132 147 In [3]: cd .. # and doesn't work as a function anymore
133 148 File "<ipython-input-3-9fedb3aff56c>", line 1
134 149 cd ..
135 150 ^
136 151 SyntaxError: invalid syntax
137 152
138 153
139 154 In [4]: %cd .. # but %cd always works
140 155 /home/fperez
141 156
142 157 In [5]: del cd # if you remove the cd variable, automagic works again
143 158
144 159 In [6]: cd ipython
145 160
146 161 /home/fperez/ipython
147 162
148 Line magics, if they return a value, can be assigned to a variable using the syntax
149 ``l = %sx ls`` (which in this particular case returns the result of `ls` as a python list).
150 See :ref:`below <manual_capture>` for more information.
163 Line magics, if they return a value, can be assigned to a variable using the
164 syntax ``l = %sx ls`` (which in this particular case returns the result of `ls`
165 as a python list). See :ref:`below <manual_capture>` for more information.
151 166
152 167 Type ``%magic`` for more information, including a list of all available magic
153 168 functions at any time and their docstrings. You can also type
154 169 ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for
155 170 information on the '?' system) to get information about any particular magic
156 171 function you are interested in.
157 172
158 173 The API documentation for the :mod:`IPython.core.magic` module contains the full
159 174 docstrings of all currently available magic commands.
160 175
161 176 .. seealso::
162 177
163 178 :doc:`magics`
164 179 A list of the line and cell magics available in IPython by default
165 180
166 181 :ref:`defining_magics`
167 182 How to define and register additional magic functions
168 183
169 184
170 185 Access to the standard Python help
171 186 ----------------------------------
172 187
173 188 Simply type ``help()`` to access Python's standard help system. You can
174 189 also type ``help(object)`` for information about a given object, or
175 190 ``help('keyword')`` for information on a keyword. You may need to configure your
176 191 PYTHONDOCS environment variable for this feature to work correctly.
177 192
178 193 .. _dynamic_object_info:
179 194
180 195 Dynamic object information
181 196 --------------------------
182 197
183 198 Typing ``?word`` or ``word?`` prints detailed information about an object. If
184 199 certain strings in the object are too long (e.g. function signatures) they get
185 200 snipped in the center for brevity. This system gives access variable types and
186 201 values, docstrings, function prototypes and other useful information.
187 202
188 203 If the information will not fit in the terminal, it is displayed in a pager
189 204 (``less`` if available, otherwise a basic internal pager).
190 205
191 206 Typing ``??word`` or ``word??`` gives access to the full information, including
192 207 the source code where possible. Long strings are not snipped.
193 208
194 209 The following magic functions are particularly useful for gathering
195 210 information about your working environment:
196 211
197 212 * :magic:`pdoc` **<object>**: Print (or run through a pager if too long) the
198 213 docstring for an object. If the given object is a class, it will
199 214 print both the class and the constructor docstrings.
200 215 * :magic:`pdef` **<object>**: Print the call signature for any callable
201 216 object. If the object is a class, print the constructor information.
202 217 * :magic:`psource` **<object>**: Print (or run through a pager if too long)
203 218 the source code for an object.
204 219 * :magic:`pfile` **<object>**: Show the entire source file where an object was
205 220 defined via a pager, opening it at the line where the object
206 221 definition begins.
207 222 * :magic:`who`/:magic:`whos`: These functions give information about identifiers
208 223 you have defined interactively (not things you loaded or defined
209 224 in your configuration files). %who just prints a list of
210 225 identifiers and %whos prints a table with some basic details about
211 226 each identifier.
212 227
213 228 The dynamic object information functions (?/??, ``%pdoc``,
214 229 ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as
215 230 directly on variables. For example, after doing ``import os``, you can use
216 231 ``os.path.abspath??``.
217 232
218 .. _readline:
219
220 Readline-based features
221 -----------------------
222
223 These features require the GNU readline library, so they won't work if your
224 Python installation lacks readline support. We will first describe the default
225 behavior IPython uses, and then how to change it to suit your preferences.
226
227 233
228 234 Command line completion
229 235 +++++++++++++++++++++++
230 236
231 237 At any time, hitting TAB will complete any available python commands or
232 238 variable names, and show you a list of the possible completions if
233 239 there's no unambiguous one. It will also complete filenames in the
234 240 current directory if no python names match what you've typed so far.
235 241
236 242
237 243 Search command history
238 244 ++++++++++++++++++++++
239 245
240 246 IPython provides two ways for searching through previous input and thus
241 247 reduce the need for repetitive typing:
242 248
243 249 1. Start typing, and then use the up and down arrow keys (or :kbd:`Ctrl-p`
244 250 and :kbd:`Ctrl-n`) to search through only the history items that match
245 251 what you've typed so far.
246 252 2. Hit :kbd:`Ctrl-r`: to open a search prompt. Begin typing and the system
247 253 searches your history for lines that contain what you've typed so
248 254 far, completing as much as it can.
249 255
250 256 IPython will save your input history when it leaves and reload it next
251 257 time you restart it. By default, the history file is named
252 258 :file:`.ipython/profile_{name}/history.sqlite`.
253 259
254 260 Autoindent
255 261 ++++++++++
256 262
257 263 Starting with 5.0, IPython uses `prompt_toolkit` in place of ``readline``,
258 264 it thus can recognize lines ending in ':' and indent the next line,
259 265 while also un-indenting automatically after 'raise' or 'return',
260 266 and support real multi-line editing as well as syntactic coloration
261 267 during edition.
262 268
263 269 This feature does not use the ``readline`` library anymore, so it will
264 270 not honor your :file:`~/.inputrc` configuration (or whatever
265 271 file your :envvar:`INPUTRC` environment variable points to).
266 272
267 273 In particular if you want to change the input mode to ``vi``, you will need to
268 274 set the ``TerminalInteractiveShell.editing_mode`` configuration option of IPython.
269 275
270 276 Session logging and restoring
271 277 -----------------------------
272 278
273 279 You can log all input from a session either by starting IPython with the
274 280 command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`)
275 281 or by activating the logging at any moment with the magic function :magic:`logstart`.
276 282
277 283 Log files can later be reloaded by running them as scripts and IPython
278 284 will attempt to 'replay' the log by executing all the lines in it, thus
279 285 restoring the state of a previous session. This feature is not quite
280 286 perfect, but can still be useful in many cases.
281 287
282 288 The log files can also be used as a way to have a permanent record of
283 289 any code you wrote while experimenting. Log files are regular text files
284 290 which you can later open in your favorite text editor to extract code or
285 291 to 'clean them up' before using them to replay a session.
286 292
287 293 The :magic:`logstart` function for activating logging in mid-session is used as
288 294 follows::
289 295
290 296 %logstart [log_name [log_mode]]
291 297
292 298 If no name is given, it defaults to a file named 'ipython_log.py' in your
293 299 current working directory, in 'rotate' mode (see below).
294 300
295 301 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
296 302 history up to that point and then continues logging.
297 303
298 304 %logstart takes a second optional parameter: logging mode. This can be
299 305 one of (note that the modes are given unquoted):
300 306
301 307 * [over:] overwrite existing log_name.
302 308 * [backup:] rename (if exists) to log_name~ and start log_name.
303 309 * [append:] well, that says it.
304 310 * [rotate:] create rotating logs log_name.1~, log_name.2~, etc.
305 311
306 312 The :magic:`logoff` and :magic:`logon` functions allow you to temporarily stop and
307 313 resume logging to a file which had previously been started with
308 314 %logstart. They will fail (with an explanation) if you try to use them
309 315 before logging has been started.
310 316
311 317 .. _system_shell_access:
312 318
313 319 System shell access
314 320 -------------------
315 321
316 Any input line beginning with a ! character is passed verbatim (minus
317 the !, of course) to the underlying operating system. For example,
322 Any input line beginning with a ``!`` character is passed verbatim (minus
323 the ``!``, of course) to the underlying operating system. For example,
318 324 typing ``!ls`` will run 'ls' in the current directory.
319 325
320 326 .. _manual_capture:
321 327
322 328 Manual capture of command output and magic output
323 329 -------------------------------------------------
324 330
325 331 You can assign the result of a system command to a Python variable with the
326 332 syntax ``myfiles = !ls``. Similarly, the result of a magic (as long as it returns
327 333 a value) can be assigned to a variable. For example, the syntax ``myfiles = %sx ls``
328 334 is equivalent to the above system command example (the :magic:`sx` magic runs a shell command
329 335 and captures the output). Each of these gets machine
330 336 readable output from stdout (e.g. without colours), and splits on newlines. To
331 337 explicitly get this sort of output without assigning to a variable, use two
332 338 exclamation marks (``!!ls``) or the :magic:`sx` magic command without an assignment.
333 339 (However, ``!!`` commands cannot be assigned to a variable.)
334 340
335 341 The captured list in this example has some convenience features. ``myfiles.n`` or ``myfiles.s``
336 342 returns a string delimited by newlines or spaces, respectively. ``myfiles.p``
337 343 produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items.
338 344 See :ref:`string_lists` for details.
339 345
340 346 IPython also allows you to expand the value of python variables when
341 347 making system calls. Wrap variables or expressions in {braces}::
342 348
343 349 In [1]: pyvar = 'Hello world'
344 350 In [2]: !echo "A python variable: {pyvar}"
345 351 A python variable: Hello world
346 352 In [3]: import math
347 353 In [4]: x = 8
348 354 In [5]: !echo {math.factorial(x)}
349 355 40320
350 356
351 357 For simple cases, you can alternatively prepend $ to a variable name::
352 358
353 359 In [6]: !echo $sys.argv
354 360 [/home/fperez/usr/bin/ipython]
355 361 In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $
356 362 A system variable: /home/fperez
357 363
358 364 Note that `$$` is used to represent a literal `$`.
359 365
360 366 System command aliases
361 367 ----------------------
362 368
363 369 The :magic:`alias` magic function allows you to define magic functions which are in fact
364 370 system shell commands. These aliases can have parameters.
365 371
366 372 ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd'
367 373
368 374 Then, typing ``alias_name params`` will execute the system command 'cmd
369 375 params' (from your underlying operating system).
370 376
371 You can also define aliases with parameters using %s specifiers (one per
377 You can also define aliases with parameters using ``%s`` specifiers (one per
372 378 parameter). The following example defines the parts function as an
373 alias to the command 'echo first %s second %s' where each %s will be
379 alias to the command ``echo first %s second %s`` where each ``%s`` will be
374 380 replaced by a positional parameter to the call to %parts::
375 381
376 382 In [1]: %alias parts echo first %s second %s
377 383 In [2]: parts A B
378 384 first A second B
379 385 In [3]: parts A
380 386 ERROR: Alias <parts> requires 2 arguments, 1 given.
381 387
382 388 If called with no parameters, :magic:`alias` prints the table of currently
383 389 defined aliases.
384 390
385 391 The :magic:`rehashx` magic allows you to load your entire $PATH as
386 392 ipython aliases. See its docstring for further details.
387 393
388 394
389 395 .. _dreload:
390 396
391 397 Recursive reload
392 398 ----------------
393 399
394 400 The :mod:`IPython.lib.deepreload` module allows you to recursively reload a
395 401 module: changes made to any of its dependencies will be reloaded without
396 402 having to exit. To start using it, do::
397 403
398 404 from IPython.lib.deepreload import reload as dreload
399 405
400 406
401 407 Verbose and colored exception traceback printouts
402 408 -------------------------------------------------
403 409
404 410 IPython provides the option to see very detailed exception tracebacks,
405 411 which can be especially useful when debugging large programs. You can
406 412 run any Python file with the %run function to benefit from these
407 413 detailed tracebacks. Furthermore, both normal and verbose tracebacks can
408 414 be colored (if your terminal supports it) which makes them much easier
409 415 to parse visually.
410 416
411 417 See the magic :magic:`xmode` and :magic:`colors` functions for details.
412 418
413 419 These features are basically a terminal version of Ka-Ping Yee's cgitb
414 420 module, now part of the standard Python library.
415 421
416 422
417 423 .. _input_caching:
418 424
419 425 Input caching system
420 426 --------------------
421 427
422 428 IPython offers numbered prompts (In/Out) with input and output caching
423 429 (also referred to as 'input history'). All input is saved and can be
424 430 retrieved as variables (besides the usual arrow key recall), in
425 431 addition to the :magic:`rep` magic command that brings a history entry
426 432 up for editing on the next command line.
427 433
428 434 The following variables always exist:
429 435
430 * _i, _ii, _iii: store previous, next previous and next-next previous inputs.
431 * In, _ih : a list of all inputs; _ih[n] is the input from line n. If you
432 overwrite In with a variable of your own, you can remake the assignment to the
433 internal list with a simple ``In=_ih``.
436 * ``_i``, ``_ii``, ``_iii``: store previous, next previous and next-next
437 previous inputs.
438
439 * ``In``, ``_ih`` : a list of all inputs; ``_ih[n]`` is the input from line
440 ``n``. If you overwrite In with a variable of your own, you can remake the
441 assignment to the internal list with a simple ``In=_ih``.
434 442
435 Additionally, global variables named _i<n> are dynamically created (<n>
443 Additionally, global variables named ``_i<n>`` are dynamically created (``<n>``
436 444 being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``.
437 445
438 446 For example, what you typed at prompt 14 is available as ``_i14``, ``_ih[14]``
439 447 and ``In[14]``.
440 448
441 449 This allows you to easily cut and paste multi line interactive prompts
442 450 by printing them out: they print like a clean string, without prompt
443 451 characters. You can also manipulate them like regular variables (they
444 452 are strings), modify or exec them.
445 453
446 You can also re-execute multiple lines of input easily by using the
447 magic :magic:`rerun` or :magic:`macro` functions. The macro system also allows you to re-execute
448 previous lines which include magic function calls (which require special
449 processing). Type %macro? for more details on the macro system.
454 You can also re-execute multiple lines of input easily by using the magic
455 :magic:`rerun` or :magic:`macro` functions. The macro system also allows you to
456 re-execute previous lines which include magic function calls (which require
457 special processing). Type %macro? for more details on the macro system.
450 458
451 459 A history function :magic:`history` allows you to see any part of your input
452 460 history by printing a range of the _i variables.
453 461
454 462 You can also search ('grep') through your history by typing
455 463 ``%hist -g somestring``. This is handy for searching for URLs, IP addresses,
456 464 etc. You can bring history entries listed by '%hist -g' up for editing
457 465 with the %recall command, or run them immediately with :magic:`rerun`.
458 466
459 467 .. _output_caching:
460 468
461 469 Output caching system
462 470 ---------------------
463 471
464 472 For output that is returned from actions, a system similar to the input
465 473 cache exists but using _ instead of _i. Only actions that produce a
466 474 result (NOT assignments, for example) are cached. If you are familiar
467 475 with Mathematica, IPython's _ variables behave exactly like
468 476 Mathematica's % variables.
469 477
470 478 The following variables always exist:
471 479
472 480 * [_] (a single underscore): stores previous output, like Python's
473 481 default interpreter.
474 482 * [__] (two underscores): next previous.
475 483 * [___] (three underscores): next-next previous.
476 484
477 485 Additionally, global variables named _<n> are dynamically created (<n>
478 486 being the prompt counter), such that the result of output <n> is always
479 487 available as _<n> (don't use the angle brackets, just the number, e.g.
480 488 ``_21``).
481 489
482 490 These variables are also stored in a global dictionary (not a
483 491 list, since it only has entries for lines which returned a result)
484 492 available under the names _oh and Out (similar to _ih and In). So the
485 493 output from line 12 can be obtained as ``_12``, ``Out[12]`` or ``_oh[12]``. If you
486 494 accidentally overwrite the Out variable you can recover it by typing
487 495 ``Out=_oh`` at the prompt.
488 496
489 497 This system obviously can potentially put heavy memory demands on your
490 498 system, since it prevents Python's garbage collector from removing any
491 499 previously computed results. You can control how many results are kept
492 500 in memory with the configuration option ``InteractiveShell.cache_size``.
493 501 If you set it to 0, output caching is disabled. You can also use the :magic:`reset`
494 502 and :magic:`xdel` magics to clear large items from memory.
495 503
496 504 Directory history
497 505 -----------------
498 506
499 507 Your history of visited directories is kept in the global list _dh, and
500 508 the magic :magic:`cd` command can be used to go to any entry in that list. The
501 509 :magic:`dhist` command allows you to view this history. Do ``cd -<TAB>`` to
502 510 conveniently view the directory history.
503 511
504 512
505 513 Automatic parentheses and quotes
506 514 --------------------------------
507 515
508 516 These features were adapted from Nathan Gray's LazyPython. They are
509 517 meant to allow less typing for common situations.
510 518
511 519 Callable objects (i.e. functions, methods, etc) can be invoked like this
512 520 (notice the commas between the arguments)::
513 521
514 522 In [1]: callable_ob arg1, arg2, arg3
515 523 ------> callable_ob(arg1, arg2, arg3)
516 524
517 525 .. note::
518 526 This feature is disabled by default. To enable it, use the ``%autocall``
519 527 magic command. The commands below with special prefixes will always work,
520 528 however.
521 529
522 530 You can force automatic parentheses by using '/' as the first character
523 531 of a line. For example::
524 532
525 533 In [2]: /globals # becomes 'globals()'
526 534
527 535 Note that the '/' MUST be the first character on the line! This won't work::
528 536
529 537 In [3]: print /globals # syntax error
530 538
531 539 In most cases the automatic algorithm should work, so you should rarely
532 540 need to explicitly invoke /. One notable exception is if you are trying
533 541 to call a function with a list of tuples as arguments (the parenthesis
534 542 will confuse IPython)::
535 543
536 544 In [4]: zip (1,2,3),(4,5,6) # won't work
537 545
538 546 but this will work::
539 547
540 548 In [5]: /zip (1,2,3),(4,5,6)
541 549 ------> zip ((1,2,3),(4,5,6))
542 550 Out[5]: [(1, 4), (2, 5), (3, 6)]
543 551
544 552 IPython tells you that it has altered your command line by displaying
545 553 the new command line preceded by ``--->``.
546 554
547 555 You can force automatic quoting of a function's arguments by using ``,``
548 556 or ``;`` as the first character of a line. For example::
549 557
550 558 In [1]: ,my_function /home/me # becomes my_function("/home/me")
551 559
552 560 If you use ';' the whole argument is quoted as a single string, while ',' splits
553 561 on whitespace::
554 562
555 563 In [2]: ,my_function a b c # becomes my_function("a","b","c")
556 564
557 565 In [3]: ;my_function a b c # becomes my_function("a b c")
558 566
559 567 Note that the ',' or ';' MUST be the first character on the line! This
560 568 won't work::
561 569
562 570 In [4]: x = ,my_function /home/me # syntax error
563 571
564 572 IPython as your default Python environment
565 573 ==========================================
566 574
567 575 Python honors the environment variable :envvar:`PYTHONSTARTUP` and will
568 576 execute at startup the file referenced by this variable. If you put the
569 577 following code at the end of that file, then IPython will be your working
570 578 environment anytime you start Python::
571 579
572 580 import os, IPython
573 581 os.environ['PYTHONSTARTUP'] = '' # Prevent running this again
574 582 IPython.start_ipython()
575 583 raise SystemExit
576 584
577 585 The ``raise SystemExit`` is needed to exit Python when
578 586 it finishes, otherwise you'll be back at the normal Python ``>>>``
579 587 prompt.
580 588
581 589 This is probably useful to developers who manage multiple Python
582 590 versions and don't want to have correspondingly multiple IPython
583 591 versions. Note that in this mode, there is no way to pass IPython any
584 592 command-line options, as those are trapped first by Python itself.
585 593
586 594 .. _Embedding:
587 595
588 596 Embedding IPython
589 597 =================
590 598
591 599 You can start a regular IPython session with
592 600
593 601 .. sourcecode:: python
594 602
595 603 import IPython
596 604 IPython.start_ipython(argv=[])
597 605
598 606 at any point in your program. This will load IPython configuration,
599 607 startup files, and everything, just as if it were a normal IPython session.
600 608
601 609 It is also possible to embed an IPython shell in a namespace in your Python code.
602 610 This allows you to evaluate dynamically the state of your code,
603 611 operate with your variables, analyze them, etc. Note however that
604 612 any changes you make to values while in the shell do not propagate back
605 613 to the running code, so it is safe to modify your values because you
606 614 won't break your code in bizarre ways by doing so.
607 615
608 616 .. note::
609 617
610 618 At present, embedding IPython cannot be done from inside IPython.
611 619 Run the code samples below outside IPython.
612 620
613 621 This feature allows you to easily have a fully functional python
614 622 environment for doing object introspection anywhere in your code with a
615 623 simple function call. In some cases a simple print statement is enough,
616 624 but if you need to do more detailed analysis of a code fragment this
617 625 feature can be very valuable.
618 626
619 627 It can also be useful in scientific computing situations where it is
620 628 common to need to do some automatic, computationally intensive part and
621 629 then stop to look at data, plots, etc.
622 630 Opening an IPython instance will give you full access to your data and
623 631 functions, and you can resume program execution once you are done with
624 632 the interactive part (perhaps to stop again later, as many times as
625 633 needed).
626 634
627 635 The following code snippet is the bare minimum you need to include in
628 636 your Python programs for this to work (detailed examples follow later)::
629 637
630 638 from IPython import embed
631 639
632 640 embed() # this call anywhere in your program will start IPython
633 641
634 642 You can also embed an IPython *kernel*, for use with qtconsole, etc. via
635 643 ``IPython.embed_kernel()``. This should function work the same way, but you can
636 644 connect an external frontend (``ipython qtconsole`` or ``ipython console``),
637 645 rather than interacting with it in the terminal.
638 646
639 647 You can run embedded instances even in code which is itself being run at
640 648 the IPython interactive prompt with '%run <filename>'. Since it's easy
641 649 to get lost as to where you are (in your top-level IPython or in your
642 650 embedded one), it's a good idea in such cases to set the in/out prompts
643 651 to something different for the embedded instances. The code examples
644 652 below illustrate this.
645 653
646 654 You can also have multiple IPython instances in your program and open
647 655 them separately, for example with different options for data
648 656 presentation. If you close and open the same instance multiple times,
649 657 its prompt counters simply continue from each execution to the next.
650 658
651 659 Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed`
652 660 module for more details on the use of this system.
653 661
654 662 The following sample file illustrating how to use the embedding
655 663 functionality is provided in the examples directory as embed_class_long.py.
656 664 It should be fairly self-explanatory:
657 665
658 666 .. literalinclude:: ../../../examples/Embedding/embed_class_long.py
659 667 :language: python
660 668
661 669 Once you understand how the system functions, you can use the following
662 670 code fragments in your programs which are ready for cut and paste:
663 671
664 672 .. literalinclude:: ../../../examples/Embedding/embed_class_short.py
665 673 :language: python
666 674
667 675 Using the Python debugger (pdb)
668 676 ===============================
669 677
670 678 Running entire programs via pdb
671 679 -------------------------------
672 680
673 681 pdb, the Python debugger, is a powerful interactive debugger which
674 682 allows you to step through code, set breakpoints, watch variables,
675 683 etc. IPython makes it very easy to start any script under the control
676 684 of pdb, regardless of whether you have wrapped it into a 'main()'
677 685 function or not. For this, simply type ``%run -d myscript`` at an
678 686 IPython prompt. See the :magic:`run` command's documentation for more details, including
679 687 how to control where pdb will stop execution first.
680 688
681 689 For more information on the use of the pdb debugger, see :ref:`debugger-commands`
682 690 in the Python documentation.
683 691
684 692 IPython extends the debugger with a few useful additions, like coloring of
685 693 tracebacks. The debugger will adopt the color scheme selected for IPython.
686 694
687 695 The ``where`` command has also been extended to take as argument the number of
688 696 context line to show. This allows to a many line of context on shallow stack trace:
689 697
690 698 .. code::
691 699
692 700 In [5]: def foo(x):
693 701 ...: 1
694 702 ...: 2
695 703 ...: 3
696 704 ...: return 1/x+foo(x-1)
697 705 ...: 5
698 706 ...: 6
699 707 ...: 7
700 708 ...:
701 709
702 710 In[6]: foo(1)
703 711 # ...
704 712 ipdb> where 8
705 713 <ipython-input-6-9e45007b2b59>(1)<module>()
706 714 ----> 1 foo(1)
707 715
708 716 <ipython-input-5-7baadc3d1465>(5)foo()
709 717 1 def foo(x):
710 718 2 1
711 719 3 2
712 720 4 3
713 721 ----> 5 return 1/x+foo(x-1)
714 722 6 5
715 723 7 6
716 724 8 7
717 725
718 726 > <ipython-input-5-7baadc3d1465>(5)foo()
719 727 1 def foo(x):
720 728 2 1
721 729 3 2
722 730 4 3
723 731 ----> 5 return 1/x+foo(x-1)
724 732 6 5
725 733 7 6
726 734 8 7
727 735
728 736
729 737 And less context on shallower Stack Trace:
730 738
731 739 .. code::
732 740
733 741 ipdb> where 1
734 742 <ipython-input-13-afa180a57233>(1)<module>()
735 743 ----> 1 foo(7)
736 744
737 745 <ipython-input-5-7baadc3d1465>(5)foo()
738 746 ----> 5 return 1/x+foo(x-1)
739 747
740 748 <ipython-input-5-7baadc3d1465>(5)foo()
741 749 ----> 5 return 1/x+foo(x-1)
742 750
743 751 <ipython-input-5-7baadc3d1465>(5)foo()
744 752 ----> 5 return 1/x+foo(x-1)
745 753
746 754 <ipython-input-5-7baadc3d1465>(5)foo()
747 755 ----> 5 return 1/x+foo(x-1)
748 756
749 757
750 758 Post-mortem debugging
751 759 ---------------------
752 760
753 761 Going into a debugger when an exception occurs can be
754 762 extremely useful in order to find the origin of subtle bugs, because pdb
755 763 opens up at the point in your code which triggered the exception, and
756 764 while your program is at this point 'dead', all the data is still
757 765 available and you can walk up and down the stack frame and understand
758 766 the origin of the problem.
759 767
760 768 You can use the :magic:`debug` magic after an exception has occurred to start
761 769 post-mortem debugging. IPython can also call debugger every time your code
762 770 triggers an uncaught exception. This feature can be toggled with the :magic:`pdb` magic
763 771 command, or you can start IPython with the ``--pdb`` option.
764 772
765 773 For a post-mortem debugger in your programs outside IPython,
766 774 put the following lines toward the top of your 'main' routine::
767 775
768 776 import sys
769 777 from IPython.core import ultratb
770 778 sys.excepthook = ultratb.FormattedTB(mode='Verbose',
771 779 color_scheme='Linux', call_pdb=1)
772 780
773 781 The mode keyword can be either 'Verbose' or 'Plain', giving either very
774 782 detailed or normal tracebacks respectively. The color_scheme keyword can
775 783 be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same
776 784 options which can be set in IPython with ``--colors`` and ``--xmode``.
777 785
778 786 This will give any of your programs detailed, colored tracebacks with
779 787 automatic invocation of pdb.
780 788
781 789 .. _pasting_with_prompts:
782 790
783 791 Pasting of code starting with Python or IPython prompts
784 792 =======================================================
785 793
786 794 IPython is smart enough to filter out input prompts, be they plain Python ones
787 795 (``>>>`` and ``...``) or IPython ones (``In [N]:`` and ``...:``). You can
788 796 therefore copy and paste from existing interactive sessions without worry.
789 797
790 798 The following is a 'screenshot' of how things work, copying an example from the
791 799 standard Python tutorial::
792 800
793 801 In [1]: >>> # Fibonacci series:
794 802
795 803 In [2]: ... # the sum of two elements defines the next
796 804
797 805 In [3]: ... a, b = 0, 1
798 806
799 807 In [4]: >>> while b < 10:
800 808 ...: ... print(b)
801 809 ...: ... a, b = b, a+b
802 810 ...:
803 811 1
804 812 1
805 813 2
806 814 3
807 815 5
808 816 8
809 817
810 818 And pasting from IPython sessions works equally well::
811 819
812 820 In [1]: In [5]: def f(x):
813 821 ...: ...: "A simple function"
814 822 ...: ...: return x**2
815 823 ...: ...:
816 824
817 825 In [2]: f(3)
818 826 Out[2]: 9
819 827
820 828 .. _gui_support:
821 829
822 830 GUI event loop support
823 831 ======================
824 832
825 833 .. versionadded:: 0.11
826 834 The ``%gui`` magic and :mod:`IPython.lib.inputhook`.
827 835
828 836 IPython has excellent support for working interactively with Graphical User
829 837 Interface (GUI) toolkits, such as wxPython, PyQt4/PySide, PyGTK and Tk. This is
830 838 implemented using Python's builtin ``PyOSInputHook`` hook. This implementation
831 839 is extremely robust compared to our previous thread-based version. The
832 840 advantages of this are:
833 841
834 842 * GUIs can be enabled and disabled dynamically at runtime.
835 843 * The active GUI can be switched dynamically at runtime.
836 844 * In some cases, multiple GUIs can run simultaneously with no problems.
837 845 * There is a developer API in :mod:`IPython.lib.inputhook` for customizing
838 846 all of these things.
839 847
840 848 For users, enabling GUI event loop integration is simple. You simple use the
841 849 :magic:`gui` magic as follows::
842 850
843 851 %gui [GUINAME]
844 852
845 853 With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME``
846 854 arguments are ``wx``, ``qt``, ``gtk`` and ``tk``.
847 855
848 856 Thus, to use wxPython interactively and create a running :class:`wx.App`
849 857 object, do::
850 858
851 859 %gui wx
852 860
853 861 You can also start IPython with an event loop set up using the `--gui`
854 862 flag::
855 863
856 864 $ ipython --gui=qt
857 865
858 866 For information on IPython's matplotlib_ integration (and the ``matplotlib``
859 867 mode) see :ref:`this section <matplotlib_support>`.
860 868
861 869 For developers that want to use IPython's GUI event loop integration in the
862 870 form of a library, these capabilities are exposed in library form in the
863 871 :mod:`IPython.lib.inputhook` and :mod:`IPython.lib.guisupport` modules.
864 872 Interested developers should see the module docstrings for more information,
865 873 but there are a few points that should be mentioned here.
866 874
867 875 First, the ``PyOSInputHook`` approach only works in command line settings
868 876 where readline is activated. The integration with various eventloops
869 877 is handled somewhat differently (and more simply) when using the standalone
870 878 kernel, as in the qtconsole and notebook.
871 879
872 880 Second, when using the ``PyOSInputHook`` approach, a GUI application should
873 881 *not* start its event loop. Instead all of this is handled by the
874 882 ``PyOSInputHook``. This means that applications that are meant to be used both
875 883 in IPython and as standalone apps need to have special code to detects how the
876 884 application is being run. We highly recommend using IPython's support for this.
877 885 Since the details vary slightly between toolkits, we point you to the various
878 886 examples in our source directory :file:`examples/Embedding` that demonstrate
879 887 these capabilities.
880 888
881 889 Third, unlike previous versions of IPython, we no longer "hijack" (replace
882 890 them with no-ops) the event loops. This is done to allow applications that
883 891 actually need to run the real event loops to do so. This is often needed to
884 892 process pending events at critical points.
885 893
886 894 Finally, we also have a number of examples in our source directory
887 895 :file:`examples/Embedding` that demonstrate these capabilities.
888 896
889 897 PyQt and PySide
890 898 ---------------
891 899
892 900 .. attempt at explanation of the complete mess that is Qt support
893 901
894 902 When you use ``--gui=qt`` or ``--matplotlib=qt``, IPython can work with either
895 903 PyQt4 or PySide. There are three options for configuration here, because
896 904 PyQt4 has two APIs for QString and QVariant: v1, which is the default on
897 905 Python 2, and the more natural v2, which is the only API supported by PySide.
898 906 v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole
899 907 uses v2, but you can still use any interface in your code, since the
900 908 Qt frontend is in a different process.
901 909
902 910 The default will be to import PyQt4 without configuration of the APIs, thus
903 911 matching what most applications would expect. It will fall back to PySide if
904 912 PyQt4 is unavailable.
905 913
906 914 If specified, IPython will respect the environment variable ``QT_API`` used
907 915 by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires
908 916 PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used,
909 917 and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for
910 918 QString and QVariant, so ETS codes like MayaVi will also work with IPython.
911 919
912 920 If you launch IPython in matplotlib mode with ``ipython --matplotlib=qt``,
913 921 then IPython will ask matplotlib which Qt library to use (only if QT_API is
914 922 *not set*), via the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or
915 923 older, then IPython will always use PyQt4 without setting the v2 APIs, since
916 924 neither v2 PyQt nor PySide work.
917 925
918 926 .. warning::
919 927
920 928 Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set
921 929 to work with IPython's qt integration, because otherwise PyQt4 will be
922 930 loaded in an incompatible mode.
923 931
924 932 It also means that you must *not* have ``QT_API`` set if you want to
925 933 use ``--gui=qt`` with code that requires PyQt4 API v1.
926 934
927 935
928 936 .. _matplotlib_support:
929 937
930 938 Plotting with matplotlib
931 939 ========================
932 940
933 941 matplotlib_ provides high quality 2D and 3D plotting for Python. matplotlib_
934 942 can produce plots on screen using a variety of GUI toolkits, including Tk,
935 943 PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for
936 944 scientific computing, all with a syntax compatible with that of the popular
937 945 Matlab program.
938 946
939 947 To start IPython with matplotlib support, use the ``--matplotlib`` switch. If
940 948 IPython is already running, you can run the :magic:`matplotlib` magic. If no
941 949 arguments are given, IPython will automatically detect your choice of
942 950 matplotlib backend. You can also request a specific backend with
943 951 ``%matplotlib backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx',
944 952 'gtk', 'osx'. In the web notebook and Qt console, 'inline' is also a valid
945 953 backend value, which produces static figures inlined inside the application
946 954 window instead of matplotlib's interactive figures that live in separate
947 955 windows.
948 956
949 957 .. _interactive_demos:
950 958
951 959 Interactive demos with IPython
952 960 ==============================
953 961
954 962 IPython ships with a basic system for running scripts interactively in
955 963 sections, useful when presenting code to audiences. A few tags embedded
956 964 in comments (so that the script remains valid Python code) divide a file
957 965 into separate blocks, and the demo can be run one block at a time, with
958 966 IPython printing (with syntax highlighting) the block before executing
959 967 it, and returning to the interactive prompt after each block. The
960 968 interactive namespace is updated after each block is run with the
961 969 contents of the demo's namespace.
962 970
963 971 This allows you to show a piece of code, run it and then execute
964 972 interactively commands based on the variables just created. Once you
965 973 want to continue, you simply execute the next block of the demo. The
966 974 following listing shows the markup necessary for dividing a script into
967 975 sections for execution as a demo:
968 976
969 977 .. literalinclude:: ../../../examples/IPython Kernel/example-demo.py
970 978 :language: python
971 979
972 980 In order to run a file as a demo, you must first make a Demo object out
973 981 of it. If the file is named myscript.py, the following code will make a
974 982 demo::
975 983
976 984 from IPython.lib.demo import Demo
977 985
978 986 mydemo = Demo('myscript.py')
979 987
980 988 This creates the mydemo object, whose blocks you run one at a time by
981 989 simply calling the object with no arguments. Then call it to run each step
982 990 of the demo::
983 991
984 992 mydemo()
985 993
986 994 Demo objects can be
987 995 restarted, you can move forward or back skipping blocks, re-execute the
988 996 last block, etc. See the :mod:`IPython.lib.demo` module and the
989 997 :class:`~IPython.lib.demo.Demo` class for details.
990 998
991 999 Limitations: These demos are limited to
992 1000 fairly simple uses. In particular, you cannot break up sections within
993 1001 indented code (loops, if statements, function definitions, etc.)
994 1002 Supporting something like this would basically require tracking the
995 1003 internal execution state of the Python interpreter, so only top-level
996 1004 divisions are allowed. If you want to be able to open an IPython
997 1005 instance at an arbitrary point in a program, you can use IPython's
998 1006 :ref:`embedding facilities <Embedding>`.
999 1007
1000 1008 .. include:: ../links.txt
@@ -1,205 +1,216 b''
1 1 .. _tutorial:
2 2
3 3 ======================
4 4 Introducing IPython
5 5 ======================
6 6
7 7 You don't need to know anything beyond Python to start using IPython – just type
8 8 commands as you would at the standard Python prompt. But IPython can do much
9 9 more than the standard prompt. Some key features are described here. For more
10 10 information, check the :ref:`tips page <tips>`, or look at examples in the
11 11 `IPython cookbook <https://github.com/ipython/ipython/wiki/Cookbook%3A-Index>`_.
12 12
13 13 If you've never used Python before, you might want to look at `the official
14 14 tutorial <http://docs.python.org/tutorial/>`_ or an alternative, `Dive into
15 15 Python <http://diveintopython.net/toc/index.html>`_.
16 16
17 17 The four most helpful commands
18 18 ===============================
19 19
20 20 The four most helpful commands, as well as their brief description, is shown
21 21 to you in a banner, every time you start IPython:
22 22
23 23 ========== =========================================================
24 24 command description
25 25 ========== =========================================================
26 26 ? Introduction and overview of IPython's features.
27 27 %quickref Quick reference.
28 28 help Python's own help system.
29 29 object? Details about 'object', use 'object??' for extra details.
30 30 ========== =========================================================
31 31
32 32 Tab completion
33 33 ==============
34 34
35 35 Tab completion, especially for attributes, is a convenient way to explore the
36 36 structure of any object you're dealing with. Simply type ``object_name.<TAB>``
37 to view the object's attributes (see :ref:`the readline section <readline>` for
38 more). Besides Python objects and keywords, tab completion also works on file
39 and directory names.
37 to view the object's attributes. Besides Python objects and keywords, tab
38 completion also works on file and directory names.
40 39
41 40 Exploring your objects
42 41 ======================
43 42
44 43 Typing ``object_name?`` will print all sorts of details about any object,
45 44 including docstrings, function definition lines (for call arguments) and
46 45 constructor details for classes. To get specific information on an object, you
47 46 can use the magic commands ``%pdoc``, ``%pdef``, ``%psource`` and ``%pfile``
48 47
49 48 .. _magics_explained:
50 49
51 50 Magic functions
52 51 ===============
53 52
54 53 IPython has a set of predefined 'magic functions' that you can call with a
55 54 command line style syntax. There are two kinds of magics, line-oriented and
56 cell-oriented. **Line magics** are prefixed with the ``%`` character and work much
57 like OS command-line calls: they get as an argument the rest of the line, where
58 arguments are passed without parentheses or quotes. **Cell magics** are
59 prefixed with a double ``%%``, and they are functions that get as an argument
60 not only the rest of the line, but also the lines below it in a separate
61 argument.
55 cell-oriented. **Line magics** are prefixed with the ``%`` character and work
56 much like OS command-line calls: they get as an argument the rest of the line,
57 where arguments are passed without parentheses or quotes. **Lines magics** can
58 return results and can be use in the right and side of an assignment. **Cell
59 magics** are prefixed with a double ``%%``, and they are functions that get as
60 an argument not only the rest of the line, but also the lines below it in a
61 separate argument.
62 62
63 The following examples show how to call the builtin :magic:`timeit` magic, both in
64 line and cell mode::
63 Magics are useful as convenient functions where Python syntax is not the most
64 natural one, or when one want to embed invalid python syntax in their work flow.
65
66 The following examples show how to call the builtin :magic:`timeit` magic, both
67 in line and cell mode::
65 68
66 69 In [1]: %timeit range(1000)
67 70 100000 loops, best of 3: 7.76 us per loop
68 71
69 72 In [2]: %%timeit x = range(10000)
70 73 ...: max(x)
71 74 ...:
72 75 1000 loops, best of 3: 223 us per loop
73 76
74 77 The builtin magics include:
75 78
76 - Functions that work with code: :magic:`run`, :magic:`edit`, :magic:`save`, :magic:`macro`,
77 :magic:`recall`, etc.
78 - Functions which affect the shell: :magic:`colors`, :magic:`xmode`, :magic:`autoindent`,
79 :magic:`automagic`, etc.
80 - Other functions such as :magic:`reset`, :magic:`timeit`, :cellmagic:`writefile`, :magic:`load`, or
81 :magic:`paste`.
79 - Functions that work with code: :magic:`run`, :magic:`edit`, :magic:`save`,
80 :magic:`macro`, :magic:`recall`, etc.
81
82 - Functions which affect the shell: :magic:`colors`, :magic:`xmode`,
83 :magic:`autoindent`, :magic:`automagic`, etc.
84
85 - Other functions such as :magic:`reset`, :magic:`timeit`,
86 :cellmagic:`writefile`, :magic:`load`, or :magic:`paste`.
82 87
83 You can always call them using the ``%`` prefix, and if you're calling a line
84 magic on a line by itself, you can omit even that::
88 You can always call magics using the ``%`` prefix, and if you're calling a line
89 magic on a line by itself, as long as the identifier is not defined in your
90 namespace, you can omit even that::
85 91
86 92 run thescript.py
87 93
88 You can toggle this behavior by running the :magic:`automagic` magic. Cell magics
89 must always have the ``%%`` prefix.
94 You can toggle this behavior by running the :magic:`automagic` magic. Cell
95 magics must always have the ``%%`` prefix.
90 96
91 97 A more detailed explanation of the magic system can be obtained by calling
92 98 ``%magic``, and for more details on any magic function, call ``%somemagic?`` to
93 99 read its docstring. To see all the available magic functions, call
94 100 ``%lsmagic``.
95 101
96 102 .. seealso::
97 103
98 :doc:`magics`
104 The :ref:`magic` section of the documentation goes more in depth into how
105 the magics works and how to define your own, and :doc:`magics` for a list of
106 built-in magics.
99 107
100 108 `Cell magics`_ example notebook
101 109
102 110 Running and Editing
103 111 -------------------
104 112
105 The :magic:`run` magic command allows you to run any python script and load all of
106 its data directly into the interactive namespace. Since the file is re-read
113 The :magic:`run` magic command allows you to run any python script and load all
114 of its data directly into the interactive namespace. Since the file is re-read
107 115 from disk each time, changes you make to it are reflected immediately (unlike
108 imported modules, which have to be specifically reloaded). IPython also
109 includes :ref:`dreload <dreload>`, a recursive reload function.
116 imported modules, which have to be specifically reloaded). IPython also includes
117 :ref:`dreload <dreload>`, a recursive reload function.
110 118
111 119 ``%run`` has special flags for timing the execution of your scripts (-t), or
112 120 for running them under the control of either Python's pdb debugger (-d) or
113 121 profiler (-p).
114 122
115 123 The :magic:`edit` command gives a reasonable approximation of multiline editing,
116 124 by invoking your favorite editor on the spot. IPython will execute the
117 code you type in there as if it were typed interactively.
125 code you type in there as if it were typed interactively. Note that for
126 :magic:`edit` to work, the call to startup your editor have to be a blocking
127 call. In a GUI environment, your editor likely have such an option.
118 128
119 129 Debugging
120 130 ---------
121 131
122 132 After an exception occurs, you can call :magic:`debug` to jump into the Python
123 133 debugger (pdb) and examine the problem. Alternatively, if you call :magic:`pdb`,
124 134 IPython will automatically start the debugger on any uncaught exception. You can
125 print variables, see code, execute statements and even walk up and down the
126 call stack to track down the true source of the problem. This can be an efficient
127 way to develop and debug code, in many cases eliminating the need for print
135 print variables, see code, execute statements and even walk up and down the call
136 stack to track down the true source of the problem. This can be an efficient way
137 to develop and debug code, in many cases eliminating the need for print
128 138 statements or external debugging tools.
129 139
130 140 You can also step through a program from the beginning by calling
131 141 ``%run -d theprogram.py``.
132 142
133 143 History
134 144 =======
135 145
136 146 IPython stores both the commands you enter, and the results it produces. You
137 147 can easily go through previous commands with the up- and down-arrow keys, or
138 148 access your history in more sophisticated ways.
139 149
140 150 Input and output history are kept in variables called ``In`` and ``Out``, keyed
141 151 by the prompt numbers, e.g. ``In[4]``. The last three objects in output history
142 152 are also kept in variables named ``_``, ``__`` and ``___``.
143 153
144 154 You can use the ``%history`` magic function to examine past input and output.
145 155 Input history from previous sessions is saved in a database, and IPython can be
146 156 configured to save output history.
147 157
148 158 Several other magic functions can use your input history, including ``%edit``,
149 159 ``%rerun``, ``%recall``, ``%macro``, ``%save`` and ``%pastebin``. You can use a
150 160 standard format to refer to lines::
151 161
152 162 %pastebin 3 18-20 ~1/1-5
153 163
154 164 This will take line 3 and lines 18 to 20 from the current session, and lines
155 165 1-5 from the previous session.
156 166
157 167 System shell commands
158 168 =====================
159 169
160 To run any command at the system shell, simply prefix it with !, e.g.::
170 To run any command at the system shell, simply prefix it with ``!``, e.g.::
161 171
162 172 !ping www.bbc.co.uk
163 173
164 174 You can capture the output into a Python list, e.g.: ``files = !ls``. To pass
165 175 the values of Python variables or expressions to system commands, prefix them
166 176 with $: ``!grep -rF $pattern ipython/*``. See :ref:`our shell section
167 177 <system_shell_access>` for more details.
168 178
169 179 Define your own system aliases
170 180 ------------------------------
171 181
172 It's convenient to have aliases to the system commands you use most often.
173 This allows you to work seamlessly from inside IPython with the same commands
174 you are used to in your system shell. IPython comes with some pre-defined
175 aliases and a complete system for changing directories, both via a stack (see
176 :magic:`pushd`, :magic:`popd` and :magic:`dhist`) and via direct :magic:`cd`. The latter keeps a history of
177 visited directories and allows you to go to any previously visited one.
182 It's convenient to have aliases to the system commands you use most often. This
183 allows you to work seamlessly from inside IPython with the same commands you are
184 used to in your system shell. IPython comes with some pre-defined aliases and a
185 complete system for changing directories, both via a stack (see :magic:`pushd`,
186 :magic:`popd` and :magic:`dhist`) and via direct :magic:`cd`. The latter keeps a
187 history of visited directories and allows you to go to any previously visited
188 one.
178 189
179 190
180 191 Configuration
181 192 =============
182 193
183 194 Much of IPython can be tweaked through :doc:`configuration </config/intro>`.
184 195 To get started, use the command ``ipython profile create`` to produce the
185 196 default config files. These will be placed in
186 197 :file:`~/.ipython/profile_default`, and contain comments explaining
187 198 what the various options do.
188 199
189 200 Profiles allow you to use IPython for different tasks, keeping separate config
190 201 files and history for each one. More details in :ref:`the profiles section
191 202 <profiles>`.
192 203
193 204 .. _startup_files:
194 205
195 206 Startup Files
196 207 -------------
197 208
198 209 If you want some code to be run at the beginning of every IPython session, the
199 210 easiest way is to add Python (.py) or IPython (.ipy) scripts to your
200 211 :file:`profile_default/startup/` directory. Files here will be executed as soon
201 212 as the IPython shell is constructed, before any other code or scripts you have
202 213 specified. The files will be run in order of their names, so you can control the
203 214 ordering with prefixes, like ``10-myimports.py``.
204 215
205 216 .. include:: ../links.txt
General Comments 0
You need to be logged in to leave comments. Login now