##// END OF EJS Templates
Merge pull request #13062 from meeseeksmachine/auto-backport-of-pr-13024-on-7.x...
Blazej Michalik -
r26667:4184b399 merge
parent child Browse files
Show More
@@ -1,249 +1,240 b''
1 =================
1 =================
2 Python vs IPython
2 Python vs IPython
3 =================
3 =================
4
4
5 This document is meant to highlight the main differences between the Python
5 This document is meant to highlight the main differences between the Python
6 language and what are the specific construct you can do only in IPython.
6 language and what are the specific construct you can do only in IPython.
7
7
8 Unless expressed otherwise all of the construct you will see here will raise a
8 Unless expressed otherwise all of the construct you will see here will raise a
9 ``SyntaxError`` if run in a pure Python shell, or if executing in a Python
9 ``SyntaxError`` if run in a pure Python shell, or if executing in a Python
10 script.
10 script.
11
11
12 Each of these features are describe more in details in further part of the documentation.
12 Each of these features are describe more in details in further part of the documentation.
13
13
14
14
15 Quick overview:
15 Quick overview:
16 ===============
16 ===============
17
17
18
18
19 All the following construct are valid IPython syntax:
19 All the following construct are valid IPython syntax:
20
20
21 .. code-block:: ipython
21 .. code-block:: ipython
22
22
23 In [1]: ?
23 In [1]: ?
24
24
25 .. code-block:: ipython
25 .. code-block:: ipython
26
26
27 In [1]: ?object
27 In [1]: ?object
28
28
29
29
30 .. code-block:: ipython
30 .. code-block:: ipython
31
31
32 In [1]: object?
32 In [1]: object?
33
33
34 .. code-block:: ipython
34 .. code-block:: ipython
35
35
36 In [1]: *pattern*?
36 In [1]: *pattern*?
37
37
38 .. code-block:: ipython
38 .. code-block:: ipython
39
39
40 In [1]: %shell like --syntax
40 In [1]: %shell like --syntax
41
41
42 .. code-block:: ipython
42 .. code-block:: ipython
43
43
44 In [1]: !ls
44 In [1]: !ls
45
45
46 .. code-block:: ipython
46 .. code-block:: ipython
47
47
48 In [1]: my_files = !ls ~/
48 In [1]: my_files = !ls ~/
49 In [1]: for i,file in enumerate(my_file):
49 In [1]: for i, file in enumerate(my_files):
50 ...: raw = !echo $file
50 ...: raw = !echo $file
51 ...: !echo {files[0].upper()} $raw
51 ...: !echo {file[0].upper()} $raw
52
52
53
53
54 .. code-block:: ipython
54 .. code-block:: ipython
55
55
56 In [1]: %%perl magic --function
56 In [1]: %%perl magic --function
57 ...: @months = ("July", "August", "September");
57 ...: @months = ("July", "August", "September");
58 ...: print $months[0];
58 ...: print $months[0];
59
59
60
60
61 Each of these construct is compile by IPython into valid python code and will
61 Each of these construct is compile by IPython into valid python code and will
62 do most of the time what you expect it will do. Let see each of these example
62 do most of the time what you expect it will do. Let see each of these example
63 in more detail.
63 in more detail.
64
64
65
65
66 Accessing help
66 Accessing help
67 ==============
67 ==============
68
68
69 As IPython is mostly an interactive shell, the question mark is a simple
69 As IPython is mostly an interactive shell, the question mark is a simple
70 shortcut to get help. A question mark alone will bring up the IPython help:
70 shortcut to get help. A question mark alone will bring up the IPython help:
71
71
72 .. code-block:: ipython
72 .. code-block:: ipython
73
73
74 In [1]: ?
74 In [1]: ?
75
75
76 IPython -- An enhanced Interactive Python
76 IPython -- An enhanced Interactive Python
77 =========================================
77 =========================================
78
78
79 IPython offers a combination of convenient shell features, special commands
79 IPython offers a combination of convenient shell features, special commands
80 and a history mechanism for both input (command history) and output (results
80 and a history mechanism for both input (command history) and output (results
81 caching, similar to Mathematica). It is intended to be a fully compatible
81 caching, similar to Mathematica). It is intended to be a fully compatible
82 replacement for the standard Python interpreter, while offering vastly
82 replacement for the standard Python interpreter, while offering vastly
83 improved functionality and flexibility.
83 improved functionality and flexibility.
84
84
85 At your system command line, type 'ipython -h' to see the command line
85 At your system command line, type 'ipython -h' to see the command line
86 options available. This document only describes interactive features.
86 options available. This document only describes interactive features.
87
87
88 MAIN FEATURES
88 MAIN FEATURES
89 -------------
89 -------------
90 ...
90 ...
91
91
92 A single question mark before, or after an object available in current
92 A single question mark before, or after an object available in current
93 namespace will show help relative to this object:
93 namespace will show help relative to this object:
94
94
95 .. code-block:: ipython
95 .. code-block:: ipython
96
96
97 In [6]: object?
97 In [6]: object?
98 Docstring: The most base type
98 Docstring: The most base type
99 Type: type
99 Type: type
100
100
101
101
102 A double question mark will try to pull out more information about the object,
102 A double question mark will try to pull out more information about the object,
103 and if possible display the python source code of this object.
103 and if possible display the python source code of this object.
104
104
105 .. code-block:: ipython
105 .. code-block:: ipython
106
106
107 In[1]: import collections
107 In[1]: import collections
108 In[2]: collections.Counter??
108 In[2]: collections.Counter??
109
109
110 Init signature: collections.Counter(*args, **kwds)
110 Init signature: collections.Counter(*args, **kwds)
111 Source:
111 Source:
112 class Counter(dict):
112 class Counter(dict):
113 '''Dict subclass for counting hashable items. Sometimes called a bag
113 '''Dict subclass for counting hashable items. Sometimes called a bag
114 or multiset. Elements are stored as dictionary keys and their counts
114 or multiset. Elements are stored as dictionary keys and their counts
115 are stored as dictionary values.
115 are stored as dictionary values.
116
116
117 >>> c = Counter('abcdeabcdabcaba') # count elements from a string
117 >>> c = Counter('abcdeabcdabcaba') # count elements from a string
118
118
119 >>> c.most_common(3) # three most common elements
119 >>> c.most_common(3) # three most common elements
120 [('a', 5), ('b', 4), ('c', 3)]
120 [('a', 5), ('b', 4), ('c', 3)]
121 >>> sorted(c) # list all unique elements
121 >>> sorted(c) # list all unique elements
122 ['a', 'b', 'c', 'd', 'e']
122 ['a', 'b', 'c', 'd', 'e']
123 >>> ''.join(sorted(c.elements())) # list elements with repetitions
123 >>> ''.join(sorted(c.elements())) # list elements with repetitions
124 'aaaaabbbbcccdde'
124 'aaaaabbbbcccdde'
125 ...
125 ...
126
126
127
127
128
128
129 If you are looking for an object, the use of wildcards ``*`` in conjunction
129 If you are looking for an object, the use of wildcards ``*`` in conjunction
130 with question mark will allow you to search current namespace for object with
130 with question mark will allow you to search current namespace for object with
131 matching names:
131 matching names:
132
132
133 .. code-block:: ipython
133 .. code-block:: ipython
134
134
135 In [24]: *int*?
135 In [24]: *int*?
136 FloatingPointError
136 FloatingPointError
137 int
137 int
138 print
138 print
139
139
140
140
141 Shell Assignment
141 Shell Assignment
142 ================
142 ================
143
143
144
144
145 When doing interactive computing it is common to need to access the underlying shell.
145 When doing interactive computing it is common to need to access the underlying shell.
146 This is doable through the use of the exclamation mark ``!`` (or bang).
146 This is doable through the use of the exclamation mark ``!`` (or bang).
147
147
148 This allow to execute simple command when present in beginning of line:
148 This allow to execute simple command when present in beginning of line:
149
149
150 .. code-block:: ipython
150 .. code-block:: ipython
151
151
152 In[1]: !pwd
152 In[1]: !pwd
153 /User/home/
153 /User/home/
154
154
155 Change directory:
155 Change directory:
156
156
157 .. code-block:: ipython
157 .. code-block:: ipython
158
158
159 In[1]: !cd /var/etc
159 In[1]: !cd /var/etc
160
160
161 Or edit file:
161 Or edit file:
162
162
163 .. code-block:: ipython
163 .. code-block:: ipython
164
164
165 In[1]: !mvim myfile.txt
165 In[1]: !mvim myfile.txt
166
166
167
167
168 The line after the bang can call any program installed in the underlying
168 The line after the bang can call any program installed in the underlying
169 shell, and support variable expansion in the form of ``$variable`` or ``{variable}``.
169 shell, and support variable expansion in the form of ``$variable`` or ``{variable}``.
170 The later form of expansion supports arbitrary python expression:
170 The later form of expansion supports arbitrary python expression:
171
171
172 .. code-block:: ipython
172 .. code-block:: ipython
173
173
174 In[1]: file = 'myfile.txt'
174 In[1]: file = 'myfile.txt'
175
175
176 In[2]: !mv $file {file.upper()}
176 In[2]: !mv $file {file.upper()}
177
177
178
178
179 The bang can also be present in the right hand side of an assignment, just
179 The bang can also be present in the right hand side of an assignment, just
180 after the equal sign, or separated from it by a white space. In which case the
180 after the equal sign, or separated from it by a white space. In which case the
181 standard output of the command after the bang ``!`` will be split out into lines
181 standard output of the command after the bang ``!`` will be split out into lines
182 in a list-like object and assign to the left hand side.
182 in a list-like object and assign to the left hand side.
183
183
184 This allow you for example to put the list of files of the current working directory in a variable:
184 This allow you for example to put the list of files of the current working directory in a variable:
185
185
186 .. code-block:: ipython
186 .. code-block:: ipython
187
187
188 In[1]: my_files = !ls
188 In[1]: my_files = !ls
189
189
190
190
191 You can combine the different possibilities in for loops, condition, functions...:
191 You can combine the different possibilities in for loops, condition, functions...:
192
192
193 .. code-block:: ipython
193 .. code-block:: ipython
194
194
195 my_files = !ls ~/
195 my_files = !ls ~/
196 b = "backup file"
196 for i, file in enumerate(my_files):
197 for i,file in enumerate(my_file):
198 raw = !echo $backup $file
197 raw = !echo $backup $file
199 !cp $file {file.split('.')[0]+'.bak'}
198 !cp $file {file.split('.')[0] + '.bak'}
200
199
201
200
202 Magics
201 Magics
203 ------
202 ------
204
203
205 Magics function are often present in the form of shell-like syntax, but are
204 Magics function are often present in the form of shell-like syntax, but are
206 under the hood python function. The syntax and assignment possibility are
205 under the hood python function. The syntax and assignment possibility are
207 similar to the one with the bang (``!``) syntax, but with more flexibility and
206 similar to the one with the bang (``!``) syntax, but with more flexibility and
208 power. Magic function start with a percent sign (``%``) or double percent (``%%``).
207 power. Magic function start with a percent sign (``%``) or double percent (``%%``).
209
208
210 A magic call with a sign percent will act only one line:
209 A magic call with a sign percent will act only one line:
211
210
212 .. code-block:: ipython
211 .. code-block:: ipython
213
212
214 In[1]: %xmode
213 In[1]: %xmode
215 Exception reporting mode: Verbose
214 Exception reporting mode: Verbose
216
215
217 And support assignment:
216 And support assignment:
218
217
219 .. code-block:: ipython
218 .. code-block:: ipython
220
219
221 In [1]: results = %timeit -r1 -n1 -o list(range(1000))
220 In [1]: results = %timeit -r1 -n1 -o list(range(1000))
222 1 loops, best of 1: 21.1 Β΅s per loop
221 1 loops, best of 1: 21.1 Β΅s per loop
223
222
224 In [2]: results
223 In [2]: results
225 Out[2]: <TimeitResult : 1 loops, best of 1: 21.1 Β΅s per loop>
224 Out[2]: <TimeitResult : 1 loops, best of 1: 21.1 Β΅s per loop>
226
225
227 Magic with two percent sign can spread over multiple lines, but do not support assignment:
226 Magic with two percent sign can spread over multiple lines, but do not support assignment:
228
227
229 .. code-block:: ipython
228 .. code-block:: ipython
230
229
231 In[1]: %%bash
230 In[1]: %%bash
232 ... : echo "My shell is:" $SHELL
231 ... : echo "My shell is:" $SHELL
233 ... : echo "My disk usage is:"
232 ... : echo "My disk usage is:"
234 ... : df -h
233 ... : df -h
235 My shell is: /usr/local/bin/bash
234 My shell is: /usr/local/bin/bash
236 My disk usage is:
235 My disk usage is:
237 Filesystem Size Used Avail Capacity iused ifree %iused Mounted on
236 Filesystem Size Used Avail Capacity iused ifree %iused Mounted on
238 /dev/disk1 233Gi 216Gi 16Gi 94% 56788108 4190706 93% /
237 /dev/disk1 233Gi 216Gi 16Gi 94% 56788108 4190706 93% /
239 devfs 190Ki 190Ki 0Bi 100% 656 0 100% /dev
238 devfs 190Ki 190Ki 0Bi 100% 656 0 100% /dev
240 map -hosts 0Bi 0Bi 0Bi 100% 0 0 100% /net
239 map -hosts 0Bi 0Bi 0Bi 100% 0 0 100% /net
241 map auto_home 0Bi 0Bi 0Bi 100% 0 0 100% /hom
240 map auto_home 0Bi 0Bi 0Bi 100% 0 0 100% /hom
242
243
244 Combining it all
245 ----------------
246
247 ::
248
249 find a snippet that combine all that into one thing!
@@ -1,282 +1,282 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 :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/>`_ or an alternative, `Dive into
17 Python <https://www.diveinto.org/python3/table-of-contents.html>`_.
17 Python <https://www.diveinto.org/python3/table-of-contents.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 :kbd:`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 sometimes
59 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
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 :kbd:`Esc` and :kbd:`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 :kbd:`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 allows 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 need to get this to work, simply use tab
93 code. There is nothing particular needed to get this to work, simply use tab
94 completion on more complex expressions like the following::
94 completion on more complex expressions like the following::
95
95
96 >>> data = ['Number of users', 123456]
96 >>> data = ['Number of users', 123456]
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 :kbd:`Tab` key to cycle through completions,
101 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.
102 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
103 When the type of the completion is a function, the completer will also show the
104 signature of the function when highlighted.
104 signature of the function when highlighted.
105
105
106 Exploring your objects
106 Exploring your objects
107 ======================
107 ======================
108
108
109 Typing ``object_name?`` will print all sorts of details about any object,
109 Typing ``object_name?`` will print all sorts of details about any object,
110 including docstrings, function definition lines (for call arguments) and
110 including docstrings, function definition lines (for call arguments) and
111 constructor details for classes. To get specific information on an object, you
111 constructor details for classes. To get specific information on an object, you
112 can use the magic commands ``%pdoc``, ``%pdef``, ``%psource`` and ``%pfile``
112 can use the magic commands ``%pdoc``, ``%pdef``, ``%psource`` and ``%pfile``
113
113
114 .. _magics_explained:
114 .. _magics_explained:
115
115
116 Magic functions
116 Magic functions
117 ===============
117 ===============
118
118
119 IPython has a set of predefined 'magic functions' that you can call with a
119 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
120 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
121 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,
122 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. **Lines magics** can
123 where arguments are passed without parentheses or quotes. **Lines magics** can
124 return results and can be used in the right hand side of an assignment. **Cell
124 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
125 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
126 an argument not only the rest of the line, but also the lines below it in a
127 separate argument.
127 separate argument.
128
128
129 Magics are useful as convenient functions where Python syntax is not the most
129 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.
130 natural one, or when one want to embed invalid python syntax in their work flow.
131
131
132 The following examples show how to call the built-in :magic:`timeit` magic, both
132 The following examples show how to call the built-in :magic:`timeit` magic, both
133 in line and cell mode::
133 in line and cell mode::
134
134
135 In [1]: %timeit range(1000)
135 In [1]: %timeit range(1000)
136 100000 loops, best of 3: 7.76 us per loop
136 100000 loops, best of 3: 7.76 us per loop
137
137
138 In [2]: %%timeit x = range(10000)
138 In [2]: %%timeit x = range(10000)
139 ...: max(x)
139 ...: max(x)
140 ...:
140 ...:
141 1000 loops, best of 3: 223 us per loop
141 1000 loops, best of 3: 223 us per loop
142
142
143 The built-in magics include:
143 The built-in magics include:
144
144
145 - Functions that work with code: :magic:`run`, :magic:`edit`, :magic:`save`,
145 - Functions that work with code: :magic:`run`, :magic:`edit`, :magic:`save`,
146 :magic:`macro`, :magic:`recall`, etc.
146 :magic:`macro`, :magic:`recall`, etc.
147
147
148 - Functions which affect the shell: :magic:`colors`, :magic:`xmode`,
148 - Functions which affect the shell: :magic:`colors`, :magic:`xmode`,
149 :magic:`automagic`, etc.
149 :magic:`automagic`, etc.
150
150
151 - Other functions such as :magic:`reset`, :magic:`timeit`,
151 - Other functions such as :magic:`reset`, :magic:`timeit`,
152 :cellmagic:`writefile`, :magic:`load`, or :magic:`paste`.
152 :cellmagic:`writefile`, :magic:`load`, or :magic:`paste`.
153
153
154 You can always call magics using the ``%`` prefix, and if you're calling a line
154 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
155 magic on a line by itself, as long as the identifier is not defined in your
156 namespace, you can omit even that::
156 namespace, you can omit even that::
157
157
158 run thescript.py
158 run thescript.py
159
159
160 You can toggle this behavior by running the :magic:`automagic` magic. Cell
160 You can toggle this behavior by running the :magic:`automagic` magic. Cell
161 magics must always have the ``%%`` prefix.
161 magics must always have the ``%%`` prefix.
162
162
163 A more detailed explanation of the magic system can be obtained by calling
163 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
164 ``%magic``, and for more details on any magic function, call ``%somemagic?`` to
165 read its docstring. To see all the available magic functions, call
165 read its docstring. To see all the available magic functions, call
166 ``%lsmagic``.
166 ``%lsmagic``.
167
167
168 .. seealso::
168 .. seealso::
169
169
170 The :ref:`magic` section of the documentation goes more in depth into how
170 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
171 the magics works and how to define your own, and :doc:`magics` for a list of
172 built-in magics.
172 built-in magics.
173
173
174 `Cell magics`_ example notebook
174 `Cell magics`_ example notebook
175
175
176 Running and Editing
176 Running and Editing
177 -------------------
177 -------------------
178
178
179 The :magic:`run` magic command allows you to run any python script and load all
179 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
180 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
181 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
182 imported modules, which have to be specifically reloaded). IPython also includes
183 :ref:`dreload <dreload>`, a recursive reload function.
183 :ref:`dreload <dreload>`, a recursive reload function.
184
184
185 ``%run`` has special flags for timing the execution of your scripts (-t), or
185 ``%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
186 for running them under the control of either Python's pdb debugger (-d) or
187 profiler (-p).
187 profiler (-p).
188
188
189 The :magic:`edit` command gives a reasonable approximation of multi-line editing,
189 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
190 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
191 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
192 :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.
193 call. In a GUI environment, your editor likely will have such an option.
194
194
195 Debugging
195 Debugging
196 ---------
196 ---------
197
197
198 After an exception occurs, you can call :magic:`debug` to jump into the Python
198 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`,
199 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
200 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
201 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
202 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
203 to develop and debug code, in many cases eliminating the need for print
204 statements or external debugging tools.
204 statements or external debugging tools.
205
205
206 You can also step through a program from the beginning by calling
206 You can also step through a program from the beginning by calling
207 ``%run -d theprogram.py``.
207 ``%run -d theprogram.py``.
208
208
209 History
209 History
210 =======
210 =======
211
211
212 IPython stores both the commands you enter, and the results it produces. You
212 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
213 can easily go through previous commands with the up- and down-arrow keys, or
214 access your history in more sophisticated ways.
214 access your history in more sophisticated ways.
215
215
216 Input and output history are kept in variables called ``In`` and ``Out``, keyed
216 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
217 by the prompt numbers, e.g. ``In[4]``. The last three objects in output history
218 are also kept in variables named ``_``, ``__`` and ``___``.
218 are also kept in variables named ``_``, ``__`` and ``___``.
219
219
220 You can use the ``%history`` magic function to examine past input and output.
220 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
221 Input history from previous sessions is saved in a database, and IPython can be
222 configured to save output history.
222 configured to save output history.
223
223
224 Several other magic functions can use your input history, including ``%edit``,
224 Several other magic functions can use your input history, including ``%edit``,
225 ``%rerun``, ``%recall``, ``%macro``, ``%save`` and ``%pastebin``. You can use a
225 ``%rerun``, ``%recall``, ``%macro``, ``%save`` and ``%pastebin``. You can use a
226 standard format to refer to lines::
226 standard format to refer to lines::
227
227
228 %pastebin 3 18-20 ~1/1-5
228 %pastebin 3 18-20 ~1/1-5
229
229
230 This will take line 3 and lines 18 to 20 from the current session, and lines
230 This will take line 3 and lines 18 to 20 from the current session, and lines
231 1-5 from the previous session.
231 1-5 from the previous session.
232
232
233 System shell commands
233 System shell commands
234 =====================
234 =====================
235
235
236 To run any command at the system shell, simply prefix it with ``!``, e.g.::
236 To run any command at the system shell, simply prefix it with ``!``, e.g.::
237
237
238 !ping www.bbc.co.uk
238 !ping www.bbc.co.uk
239
239
240 You can capture the output into a Python list, e.g.: ``files = !ls``. To pass
240 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
241 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
242 with $: ``!grep -rF $pattern ipython/*`` or wrap in `{braces}`. See :ref:`our
243 shell section <system_shell_access>` for more details.
243 shell section <system_shell_access>` for more details.
244
244
245 Define your own system aliases
245 Define your own system aliases
246 ------------------------------
246 ------------------------------
247
247
248 It's convenient to have aliases to the system commands you use most often. This
248 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
249 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
250 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`,
251 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
252 :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
253 history of visited directories and allows you to go to any previously visited
254 one.
254 one.
255
255
256
256
257 Configuration
257 Configuration
258 =============
258 =============
259
259
260 Much of IPython can be tweaked through :doc:`configuration </config/intro>`.
260 Much of IPython can be tweaked through :doc:`configuration </config/intro>`.
261 To get started, use the command ``ipython profile create`` to produce the
261 To get started, use the command ``ipython profile create`` to produce the
262 default config files. These will be placed in
262 default config files. These will be placed in
263 :file:`~/.ipython/profile_default`, and contain comments explaining
263 :file:`~/.ipython/profile_default`, and contain comments explaining
264 what the various options do.
264 what the various options do.
265
265
266 Profiles allow you to use IPython for different tasks, keeping separate config
266 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
267 files and history for each one. More details in :ref:`the profiles section
268 <profiles>`.
268 <profiles>`.
269
269
270 .. _startup_files:
270 .. _startup_files:
271
271
272 Startup Files
272 Startup Files
273 -------------
273 -------------
274
274
275 If you want some code to be run at the beginning of every IPython session, the
275 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
276 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
277 :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
278 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
279 specified. The files will be run in order of their names, so you can control the
280 ordering with prefixes, like ``10-myimports.py``.
280 ordering with prefixes, like ``10-myimports.py``.
281
281
282 .. include:: ../links.txt
282 .. include:: ../links.txt
General Comments 0
You need to be logged in to leave comments. Login now