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