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