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