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