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