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