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