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