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