##// END OF EJS Templates
remove broken link
Liam Connors -
Show More
@@ -1,282 +1,281
1 .. _tutorial:
1 .. _tutorial:
2
2
3 ======================
3 ======================
4 Introducing IPython
4 Introducing IPython
5 ======================
5 ======================
6
6
7 You don't need to know anything beyond Python to start using IPython – just type
7 You don't need to know anything beyond Python to start using IPython – just type
8 commands as you would at the standard Python prompt. But IPython can do much
8 commands as you would at the standard Python prompt. But IPython can do much
9 more than the standard prompt. Some key features are described here. For more
9 more than the standard prompt. Some key features are described here. For more
10 information, check the :ref:`tips page <tips>`, or look at examples in the
10 information, check the :ref:`tips page <tips>`, or look at examples in the
11 `IPython cookbook <https://github.com/ipython/ipython/wiki/Cookbook%3A-Index>`_.
11 `IPython cookbook <https://github.com/ipython/ipython/wiki/Cookbook%3A-Index>`_.
12
12
13 If you haven't done that yet see :ref:`how to install ipython <install>`.
13 If you haven't done that yet see :ref:`how to install ipython <install>`.
14
14
15 If you've never used Python before, you might want to look at `the official
15 If you've never used Python before, you might want to look at `the official
16 tutorial <http://docs.python.org/tutorial/>`_ or an alternative, `Dive into
16 tutorial <http://docs.python.org/tutorial/>`_.
17 Python <https://www.diveinto.org/python3/table-of-contents.html>`_.
18
17
19 Start IPython by issuing the ``ipython`` command from your shell, you should be
18 Start IPython by issuing the ``ipython`` command from your shell, you should be
20 greeted by the following::
19 greeted by the following::
21
20
22 Python 3.6.0
21 Python 3.6.0
23 Type 'copyright', 'credits' or 'license' for more information
22 Type 'copyright', 'credits' or 'license' for more information
24 IPython 6.0.0.dev -- An enhanced Interactive Python. Type '?' for help.
23 IPython 6.0.0.dev -- An enhanced Interactive Python. Type '?' for help.
25
24
26 In [1]:
25 In [1]:
27
26
28
27
29 Unlike the Python REPL, you will see that the input prompt is ``In [N]:``
28 Unlike the Python REPL, you will see that the input prompt is ``In [N]:``
30 instead of ``>>>``. The number ``N`` in the prompt will be used later in this
29 instead of ``>>>``. The number ``N`` in the prompt will be used later in this
31 tutorial but should usually not impact the computation.
30 tutorial but should usually not impact the computation.
32
31
33 You should be able to type single line expressions and press enter to evaluate
32 You should be able to type single line expressions and press enter to evaluate
34 them. If an expression is incomplete, IPython will automatically detect this and
33 them. If an expression is incomplete, IPython will automatically detect this and
35 add a new line when you press :kbd:`Enter` instead of executing right away.
34 add a new line when you press :kbd:`Enter` instead of executing right away.
36
35
37 Feel free to explore multi-line text input. Unlike many other REPLs, with
36 Feel free to explore multi-line text input. Unlike many other REPLs, with
38 IPython you can use the up and down arrow keys when editing multi-line
37 IPython you can use the up and down arrow keys when editing multi-line
39 code blocks.
38 code blocks.
40
39
41 Here is an example of a longer interaction with the IPython REPL,
40 Here is an example of a longer interaction with the IPython REPL,
42 which we often refer to as an IPython *session* ::
41 which we often refer to as an IPython *session* ::
43
42
44 In [1]: print('Hello IPython')
43 In [1]: print('Hello IPython')
45 Hello IPython
44 Hello IPython
46
45
47 In [2]: 21 * 2
46 In [2]: 21 * 2
48 Out[2]: 42
47 Out[2]: 42
49
48
50 In [3]: def say_hello(name):
49 In [3]: def say_hello(name):
51 ...: print('Hello {name}'.format(name=name))
50 ...: print('Hello {name}'.format(name=name))
52 ...:
51 ...:
53
52
54 We won't get into details right now, but you may notice a few differences to
53 We won't get into details right now, but you may notice a few differences to
55 the standard Python REPL. First, your code should be syntax-highlighted as you
54 the standard Python REPL. First, your code should be syntax-highlighted as you
56 type. Second, you will see that some results will have an ``Out[N]:`` prompt,
55 type. Second, you will see that some results will have an ``Out[N]:`` prompt,
57 while some other do not. We'll come to this later.
56 while some other do not. We'll come to this later.
58
57
59 Depending on the exact command you are typing you might realize that sometimes
58 Depending on the exact command you are typing you might realize that sometimes
60 :kbd:`Enter` will add a new line, and sometimes it will execute the current
59 :kbd:`Enter` will add a new line, and sometimes it will execute the current
61 statement. IPython tries to guess what you are doing, so most of the time you
60 statement. IPython tries to guess what you are doing, so most of the time you
62 should not have to care. Though if by any chance IPython does not do the right
61 should not have to care. Though if by any chance IPython does not do the right
63 thing you can force execution of the current code block by pressing in sequence
62 thing you can force execution of the current code block by pressing in sequence
64 :kbd:`Esc` and :kbd:`Enter`. You can also force the insertion of a new line at
63 :kbd:`Esc` and :kbd:`Enter`. You can also force the insertion of a new line at
65 the position of the cursor by using :kbd:`Ctrl-o`.
64 the position of the cursor by using :kbd:`Ctrl-o`.
66
65
67 The four most helpful commands
66 The four most helpful commands
68 ==============================
67 ==============================
69
68
70 The four most helpful commands, as well as their brief description, is shown
69 The four most helpful commands, as well as their brief description, is shown
71 to you in a banner, every time you start IPython:
70 to you in a banner, every time you start IPython:
72
71
73 ========== =========================================================
72 ========== =========================================================
74 command description
73 command description
75 ========== =========================================================
74 ========== =========================================================
76 ? Introduction and overview of IPython's features.
75 ? Introduction and overview of IPython's features.
77 %quickref Quick reference.
76 %quickref Quick reference.
78 help Python's own help system.
77 help Python's own help system.
79 object? Details about 'object', use 'object??' for extra details.
78 object? Details about 'object', use 'object??' for extra details.
80 ========== =========================================================
79 ========== =========================================================
81
80
82 Tab completion
81 Tab completion
83 ==============
82 ==============
84
83
85 Tab completion, especially for attributes, is a convenient way to explore the
84 Tab completion, especially for attributes, is a convenient way to explore the
86 structure of any object you're dealing with. Simply type ``object_name.<TAB>``
85 structure of any object you're dealing with. Simply type ``object_name.<TAB>``
87 to view the object's attributes. Besides Python objects and keywords, tab
86 to view the object's attributes. Besides Python objects and keywords, tab
88 completion also works on file and directory names.
87 completion also works on file and directory names.
89
88
90 Starting with IPython 6.0, if ``jedi`` is installed, IPython will try to pull
89 Starting with IPython 6.0, if ``jedi`` is installed, IPython will try to pull
91 completions from Jedi as well. This allows to not only inspect currently
90 completions from Jedi as well. This allows to not only inspect currently
92 existing objects, but also to infer completion statically without executing
91 existing objects, but also to infer completion statically without executing
93 code. There is nothing particular needed to get this to work, simply use tab
92 code. There is nothing particular needed to get this to work, simply use tab
94 completion on more complex expressions like the following::
93 completion on more complex expressions like the following::
95
94
96 >>> data = ['Number of users', 123456]
95 >>> data = ['Number of users', 123456]
97 ... data[0].<tab>
96 ... data[0].<tab>
98
97
99 IPython and Jedi will be able to infer that ``data[0]`` is actually a string
98 IPython and Jedi will be able to infer that ``data[0]`` is actually a string
100 and should show relevant completions like ``upper()``, ``lower()`` and other
99 and should show relevant completions like ``upper()``, ``lower()`` and other
101 string methods. You can use the :kbd:`Tab` key to cycle through completions,
100 string methods. You can use the :kbd:`Tab` key to cycle through completions,
102 and while a completion is highlighted, its type will be shown as well.
101 and while a completion is highlighted, its type will be shown as well.
103 When the type of the completion is a function, the completer will also show the
102 When the type of the completion is a function, the completer will also show the
104 signature of the function when highlighted.
103 signature of the function when highlighted.
105
104
106 Exploring your objects
105 Exploring your objects
107 ======================
106 ======================
108
107
109 Typing ``object_name?`` will print all sorts of details about any object,
108 Typing ``object_name?`` will print all sorts of details about any object,
110 including docstrings, function definition lines (for call arguments) and
109 including docstrings, function definition lines (for call arguments) and
111 constructor details for classes. To get specific information on an object, you
110 constructor details for classes. To get specific information on an object, you
112 can use the magic commands ``%pdoc``, ``%pdef``, ``%psource`` and ``%pfile``
111 can use the magic commands ``%pdoc``, ``%pdef``, ``%psource`` and ``%pfile``
113
112
114 .. _magics_explained:
113 .. _magics_explained:
115
114
116 Magic functions
115 Magic functions
117 ===============
116 ===============
118
117
119 IPython has a set of predefined 'magic functions' that you can call with a
118 IPython has a set of predefined 'magic functions' that you can call with a
120 command line style syntax. There are two kinds of magics, line-oriented and
119 command line style syntax. There are two kinds of magics, line-oriented and
121 cell-oriented. **Line magics** are prefixed with the ``%`` character and work
120 cell-oriented. **Line magics** are prefixed with the ``%`` character and work
122 much like OS command-line calls: they get as an argument the rest of the line,
121 much like OS command-line calls: they get as an argument the rest of the line,
123 where arguments are passed without parentheses or quotes. **Line magics** can
122 where arguments are passed without parentheses or quotes. **Line magics** can
124 return results and can be used in the right hand side of an assignment. **Cell
123 return results and can be used in the right hand side of an assignment. **Cell
125 magics** are prefixed with a double ``%%``, and they are functions that get as
124 magics** are prefixed with a double ``%%``, and they are functions that get as
126 an argument not only the rest of the line, but also the lines below it in a
125 an argument not only the rest of the line, but also the lines below it in a
127 separate argument.
126 separate argument.
128
127
129 Magics are useful as convenient functions where Python syntax is not the most
128 Magics are useful as convenient functions where Python syntax is not the most
130 natural one, or when one want to embed invalid python syntax in their work flow.
129 natural one, or when one want to embed invalid python syntax in their work flow.
131
130
132 The following examples show how to call the built-in :magic:`timeit` magic, both
131 The following examples show how to call the built-in :magic:`timeit` magic, both
133 in line and cell mode::
132 in line and cell mode::
134
133
135 In [1]: %timeit range(1000)
134 In [1]: %timeit range(1000)
136 179 ns Β± 2.66 ns per loop (mean Β± std. dev. of 7 runs, 10000000 loops each)
135 179 ns Β± 2.66 ns per loop (mean Β± std. dev. of 7 runs, 10000000 loops each)
137
136
138 In [2]: %%timeit x = range(10000)
137 In [2]: %%timeit x = range(10000)
139 ...: max(x)
138 ...: max(x)
140 ...:
139 ...:
141 264 Β΅s Β± 1 Β΅s per loop (mean Β± std. dev. of 7 runs, 1000 loops each)
140 264 Β΅s Β± 1 Β΅s per loop (mean Β± std. dev. of 7 runs, 1000 loops each)
142
141
143 The built-in magics include:
142 The built-in magics include:
144
143
145 - Functions that work with code: :magic:`run`, :magic:`edit`, :magic:`save`,
144 - Functions that work with code: :magic:`run`, :magic:`edit`, :magic:`save`,
146 :magic:`macro`, :magic:`recall`, etc.
145 :magic:`macro`, :magic:`recall`, etc.
147
146
148 - Functions which affect the shell: :magic:`colors`, :magic:`xmode`,
147 - Functions which affect the shell: :magic:`colors`, :magic:`xmode`,
149 :magic:`automagic`, etc.
148 :magic:`automagic`, etc.
150
149
151 - Other functions such as :magic:`reset`, :magic:`timeit`,
150 - Other functions such as :magic:`reset`, :magic:`timeit`,
152 :cellmagic:`writefile`, :magic:`load`, or :magic:`paste`.
151 :cellmagic:`writefile`, :magic:`load`, or :magic:`paste`.
153
152
154 You can always call magics using the ``%`` prefix, and if you're calling a line
153 You can always call magics using the ``%`` prefix, and if you're calling a line
155 magic on a line by itself, as long as the identifier is not defined in your
154 magic on a line by itself, as long as the identifier is not defined in your
156 namespace, you can omit even that::
155 namespace, you can omit even that::
157
156
158 run thescript.py
157 run thescript.py
159
158
160 You can toggle this behavior by running the :magic:`automagic` magic. Cell
159 You can toggle this behavior by running the :magic:`automagic` magic. Cell
161 magics must always have the ``%%`` prefix.
160 magics must always have the ``%%`` prefix.
162
161
163 A more detailed explanation of the magic system can be obtained by calling
162 A more detailed explanation of the magic system can be obtained by calling
164 ``%magic``, and for more details on any magic function, call ``%somemagic?`` to
163 ``%magic``, and for more details on any magic function, call ``%somemagic?`` to
165 read its docstring. To see all the available magic functions, call
164 read its docstring. To see all the available magic functions, call
166 ``%lsmagic``.
165 ``%lsmagic``.
167
166
168 .. seealso::
167 .. seealso::
169
168
170 The :ref:`magic` section of the documentation goes more in depth into how
169 The :ref:`magic` section of the documentation goes more in depth into how
171 the magics works and how to define your own, and :doc:`magics` for a list of
170 the magics works and how to define your own, and :doc:`magics` for a list of
172 built-in magics.
171 built-in magics.
173
172
174 `Cell magics`_ example notebook
173 `Cell magics`_ example notebook
175
174
176 Running and Editing
175 Running and Editing
177 -------------------
176 -------------------
178
177
179 The :magic:`run` magic command allows you to run any python script and load all
178 The :magic:`run` magic command allows you to run any python script and load all
180 of its data directly into the interactive namespace. Since the file is re-read
179 of its data directly into the interactive namespace. Since the file is re-read
181 from disk each time, changes you make to it are reflected immediately (unlike
180 from disk each time, changes you make to it are reflected immediately (unlike
182 imported modules, which have to be specifically reloaded). IPython also includes
181 imported modules, which have to be specifically reloaded). IPython also includes
183 :ref:`dreload <dreload>`, a recursive reload function.
182 :ref:`dreload <dreload>`, a recursive reload function.
184
183
185 ``%run`` has special flags for timing the execution of your scripts (-t), or
184 ``%run`` has special flags for timing the execution of your scripts (-t), or
186 for running them under the control of either Python's pdb debugger (-d) or
185 for running them under the control of either Python's pdb debugger (-d) or
187 profiler (-p).
186 profiler (-p).
188
187
189 The :magic:`edit` command gives a reasonable approximation of multi-line editing,
188 The :magic:`edit` command gives a reasonable approximation of multi-line editing,
190 by invoking your favorite editor on the spot. IPython will execute the
189 by invoking your favorite editor on the spot. IPython will execute the
191 code you type in there as if it were typed interactively. Note that for
190 code you type in there as if it were typed interactively. Note that for
192 :magic:`edit` to work, the call to startup your editor has to be a blocking
191 :magic:`edit` to work, the call to startup your editor has to be a blocking
193 call. In a GUI environment, your editor likely will have such an option.
192 call. In a GUI environment, your editor likely will have such an option.
194
193
195 Debugging
194 Debugging
196 ---------
195 ---------
197
196
198 After an exception occurs, you can call :magic:`debug` to jump into the Python
197 After an exception occurs, you can call :magic:`debug` to jump into the Python
199 debugger (pdb) and examine the problem. Alternatively, if you call :magic:`pdb`,
198 debugger (pdb) and examine the problem. Alternatively, if you call :magic:`pdb`,
200 IPython will automatically start the debugger on any uncaught exception. You can
199 IPython will automatically start the debugger on any uncaught exception. You can
201 print variables, see code, execute statements and even walk up and down the call
200 print variables, see code, execute statements and even walk up and down the call
202 stack to track down the true source of the problem. This can be an efficient way
201 stack to track down the true source of the problem. This can be an efficient way
203 to develop and debug code, in many cases eliminating the need for print
202 to develop and debug code, in many cases eliminating the need for print
204 statements or external debugging tools.
203 statements or external debugging tools.
205
204
206 You can also step through a program from the beginning by calling
205 You can also step through a program from the beginning by calling
207 ``%run -d theprogram.py``.
206 ``%run -d theprogram.py``.
208
207
209 History
208 History
210 =======
209 =======
211
210
212 IPython stores both the commands you enter, and the results it produces. You
211 IPython stores both the commands you enter, and the results it produces. You
213 can easily go through previous commands with the up- and down-arrow keys, or
212 can easily go through previous commands with the up- and down-arrow keys, or
214 access your history in more sophisticated ways.
213 access your history in more sophisticated ways.
215
214
216 Input and output history are kept in variables called ``In`` and ``Out``, keyed
215 Input and output history are kept in variables called ``In`` and ``Out``, keyed
217 by the prompt numbers, e.g. ``In[4]``. The last three objects in output history
216 by the prompt numbers, e.g. ``In[4]``. The last three objects in output history
218 are also kept in variables named ``_``, ``__`` and ``___``.
217 are also kept in variables named ``_``, ``__`` and ``___``.
219
218
220 You can use the ``%history`` magic function to examine past input and output.
219 You can use the ``%history`` magic function to examine past input and output.
221 Input history from previous sessions is saved in a database, and IPython can be
220 Input history from previous sessions is saved in a database, and IPython can be
222 configured to save output history.
221 configured to save output history.
223
222
224 Several other magic functions can use your input history, including ``%edit``,
223 Several other magic functions can use your input history, including ``%edit``,
225 ``%rerun``, ``%recall``, ``%macro``, ``%save`` and ``%pastebin``. You can use a
224 ``%rerun``, ``%recall``, ``%macro``, ``%save`` and ``%pastebin``. You can use a
226 standard format to refer to lines::
225 standard format to refer to lines::
227
226
228 %pastebin 3 18-20 ~1/1-5
227 %pastebin 3 18-20 ~1/1-5
229
228
230 This will take line 3 and lines 18 to 20 from the current session, and lines
229 This will take line 3 and lines 18 to 20 from the current session, and lines
231 1-5 from the previous session.
230 1-5 from the previous session.
232
231
233 System shell commands
232 System shell commands
234 =====================
233 =====================
235
234
236 To run any command at the system shell, simply prefix it with ``!``, e.g.::
235 To run any command at the system shell, simply prefix it with ``!``, e.g.::
237
236
238 !ping www.bbc.co.uk
237 !ping www.bbc.co.uk
239
238
240 You can capture the output into a Python list, e.g.: ``files = !ls``. To pass
239 You can capture the output into a Python list, e.g.: ``files = !ls``. To pass
241 the values of Python variables or expressions to system commands, prefix them
240 the values of Python variables or expressions to system commands, prefix them
242 with $: ``!grep -rF $pattern ipython/*`` or wrap in `{braces}`. See :ref:`our
241 with $: ``!grep -rF $pattern ipython/*`` or wrap in `{braces}`. See :ref:`our
243 shell section <system_shell_access>` for more details.
242 shell section <system_shell_access>` for more details.
244
243
245 Define your own system aliases
244 Define your own system aliases
246 ------------------------------
245 ------------------------------
247
246
248 It's convenient to have aliases to the system commands you use most often. This
247 It's convenient to have aliases to the system commands you use most often. This
249 allows you to work seamlessly from inside IPython with the same commands you are
248 allows you to work seamlessly from inside IPython with the same commands you are
250 used to in your system shell. IPython comes with some pre-defined aliases and a
249 used to in your system shell. IPython comes with some pre-defined aliases and a
251 complete system for changing directories, both via a stack (see :magic:`pushd`,
250 complete system for changing directories, both via a stack (see :magic:`pushd`,
252 :magic:`popd` and :magic:`dhist`) and via direct :magic:`cd`. The latter keeps a
251 :magic:`popd` and :magic:`dhist`) and via direct :magic:`cd`. The latter keeps a
253 history of visited directories and allows you to go to any previously visited
252 history of visited directories and allows you to go to any previously visited
254 one.
253 one.
255
254
256
255
257 Configuration
256 Configuration
258 =============
257 =============
259
258
260 Much of IPython can be tweaked through :doc:`configuration </config/intro>`.
259 Much of IPython can be tweaked through :doc:`configuration </config/intro>`.
261 To get started, use the command ``ipython profile create`` to produce the
260 To get started, use the command ``ipython profile create`` to produce the
262 default config files. These will be placed in
261 default config files. These will be placed in
263 :file:`~/.ipython/profile_default`, and contain comments explaining
262 :file:`~/.ipython/profile_default`, and contain comments explaining
264 what the various options do.
263 what the various options do.
265
264
266 Profiles allow you to use IPython for different tasks, keeping separate config
265 Profiles allow you to use IPython for different tasks, keeping separate config
267 files and history for each one. More details in :ref:`the profiles section
266 files and history for each one. More details in :ref:`the profiles section
268 <profiles>`.
267 <profiles>`.
269
268
270 .. _startup_files:
269 .. _startup_files:
271
270
272 Startup Files
271 Startup Files
273 -------------
272 -------------
274
273
275 If you want some code to be run at the beginning of every IPython session, the
274 If you want some code to be run at the beginning of every IPython session, the
276 easiest way is to add Python (.py) or IPython (.ipy) scripts to your
275 easiest way is to add Python (.py) or IPython (.ipy) scripts to your
277 :file:`profile_default/startup/` directory. Files here will be executed as soon
276 :file:`profile_default/startup/` directory. Files here will be executed as soon
278 as the IPython shell is constructed, before any other code or scripts you have
277 as the IPython shell is constructed, before any other code or scripts you have
279 specified. The files will be run in order of their names, so you can control the
278 specified. The files will be run in order of their names, so you can control the
280 ordering with prefixes, like ``10-myimports.py``.
279 ordering with prefixes, like ``10-myimports.py``.
281
280
282 .. include:: ../links.txt
281 .. include:: ../links.txt
General Comments 0
You need to be logged in to leave comments. Login now