##// END OF EJS Templates
Merge pull request #10144 from takluyver/rm-compat-builtin-mod...
Thomas Kluyver -
r23157:157fd3a2 merge
parent child Browse files
Show More
@@ -1,103 +1,86 b''
1 """
1 """
2 A context manager for managing things injected into :mod:`__builtin__`.
2 A context manager for managing things injected into :mod:`builtins`.
3
4 Authors:
5
6 * Brian Granger
7 * Fernando Perez
8 """
3 """
9 #-----------------------------------------------------------------------------
4 # Copyright (c) IPython Development Team.
10 # Copyright (C) 2010-2011 The IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
11 #
6 import builtins as builtin_mod
12 # Distributed under the terms of the BSD License.
13 #
14 # Complete license in the file COPYING.txt, distributed with this software.
15 #-----------------------------------------------------------------------------
16
17 #-----------------------------------------------------------------------------
18 # Imports
19 #-----------------------------------------------------------------------------
20
7
21 from traitlets.config.configurable import Configurable
8 from traitlets.config.configurable import Configurable
22
9
23 from IPython.utils.py3compat import builtin_mod
24 from traitlets import Instance
10 from traitlets import Instance
25
11
26 #-----------------------------------------------------------------------------
27 # Classes and functions
28 #-----------------------------------------------------------------------------
29
12
30 class __BuiltinUndefined(object): pass
13 class __BuiltinUndefined(object): pass
31 BuiltinUndefined = __BuiltinUndefined()
14 BuiltinUndefined = __BuiltinUndefined()
32
15
33 class __HideBuiltin(object): pass
16 class __HideBuiltin(object): pass
34 HideBuiltin = __HideBuiltin()
17 HideBuiltin = __HideBuiltin()
35
18
36
19
37 class BuiltinTrap(Configurable):
20 class BuiltinTrap(Configurable):
38
21
39 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
22 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
40 allow_none=True)
23 allow_none=True)
41
24
42 def __init__(self, shell=None):
25 def __init__(self, shell=None):
43 super(BuiltinTrap, self).__init__(shell=shell, config=None)
26 super(BuiltinTrap, self).__init__(shell=shell, config=None)
44 self._orig_builtins = {}
27 self._orig_builtins = {}
45 # We define this to track if a single BuiltinTrap is nested.
28 # We define this to track if a single BuiltinTrap is nested.
46 # Only turn off the trap when the outermost call to __exit__ is made.
29 # Only turn off the trap when the outermost call to __exit__ is made.
47 self._nested_level = 0
30 self._nested_level = 0
48 self.shell = shell
31 self.shell = shell
49 # builtins we always add - if set to HideBuiltin, they will just
32 # builtins we always add - if set to HideBuiltin, they will just
50 # be removed instead of being replaced by something else
33 # be removed instead of being replaced by something else
51 self.auto_builtins = {'exit': HideBuiltin,
34 self.auto_builtins = {'exit': HideBuiltin,
52 'quit': HideBuiltin,
35 'quit': HideBuiltin,
53 'get_ipython': self.shell.get_ipython,
36 'get_ipython': self.shell.get_ipython,
54 }
37 }
55
38
56 def __enter__(self):
39 def __enter__(self):
57 if self._nested_level == 0:
40 if self._nested_level == 0:
58 self.activate()
41 self.activate()
59 self._nested_level += 1
42 self._nested_level += 1
60 # I return self, so callers can use add_builtin in a with clause.
43 # I return self, so callers can use add_builtin in a with clause.
61 return self
44 return self
62
45
63 def __exit__(self, type, value, traceback):
46 def __exit__(self, type, value, traceback):
64 if self._nested_level == 1:
47 if self._nested_level == 1:
65 self.deactivate()
48 self.deactivate()
66 self._nested_level -= 1
49 self._nested_level -= 1
67 # Returning False will cause exceptions to propagate
50 # Returning False will cause exceptions to propagate
68 return False
51 return False
69
52
70 def add_builtin(self, key, value):
53 def add_builtin(self, key, value):
71 """Add a builtin and save the original."""
54 """Add a builtin and save the original."""
72 bdict = builtin_mod.__dict__
55 bdict = builtin_mod.__dict__
73 orig = bdict.get(key, BuiltinUndefined)
56 orig = bdict.get(key, BuiltinUndefined)
74 if value is HideBuiltin:
57 if value is HideBuiltin:
75 if orig is not BuiltinUndefined: #same as 'key in bdict'
58 if orig is not BuiltinUndefined: #same as 'key in bdict'
76 self._orig_builtins[key] = orig
59 self._orig_builtins[key] = orig
77 del bdict[key]
60 del bdict[key]
78 else:
61 else:
79 self._orig_builtins[key] = orig
62 self._orig_builtins[key] = orig
80 bdict[key] = value
63 bdict[key] = value
81
64
82 def remove_builtin(self, key, orig):
65 def remove_builtin(self, key, orig):
83 """Remove an added builtin and re-set the original."""
66 """Remove an added builtin and re-set the original."""
84 if orig is BuiltinUndefined:
67 if orig is BuiltinUndefined:
85 del builtin_mod.__dict__[key]
68 del builtin_mod.__dict__[key]
86 else:
69 else:
87 builtin_mod.__dict__[key] = orig
70 builtin_mod.__dict__[key] = orig
88
71
89 def activate(self):
72 def activate(self):
90 """Store ipython references in the __builtin__ namespace."""
73 """Store ipython references in the __builtin__ namespace."""
91
74
92 add_builtin = self.add_builtin
75 add_builtin = self.add_builtin
93 for name, func in self.auto_builtins.items():
76 for name, func in self.auto_builtins.items():
94 add_builtin(name, func)
77 add_builtin(name, func)
95
78
96 def deactivate(self):
79 def deactivate(self):
97 """Remove any builtins which might have been added by add_builtins, or
80 """Remove any builtins which might have been added by add_builtins, or
98 restore overwritten ones to their previous values."""
81 restore overwritten ones to their previous values."""
99 remove_builtin = self.remove_builtin
82 remove_builtin = self.remove_builtin
100 for key, val in self._orig_builtins.items():
83 for key, val in self._orig_builtins.items():
101 remove_builtin(key, val)
84 remove_builtin(key, val)
102 self._orig_builtins.clear()
85 self._orig_builtins.clear()
103 self._builtins_added = False
86 self._builtins_added = False
@@ -1,1227 +1,1228 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Word completion for IPython.
2 """Word completion for IPython.
3
3
4 This module started as fork of the rlcompleter module in the Python standard
4 This module started as fork of the rlcompleter module in the Python standard
5 library. The original enhancements made to rlcompleter have been sent
5 library. The original enhancements made to rlcompleter have been sent
6 upstream and were accepted as of Python 2.3,
6 upstream and were accepted as of Python 2.3,
7
7
8 """
8 """
9
9
10 # Copyright (c) IPython Development Team.
10 # Copyright (c) IPython Development Team.
11 # Distributed under the terms of the Modified BSD License.
11 # Distributed under the terms of the Modified BSD License.
12 #
12 #
13 # Some of this code originated from rlcompleter in the Python standard library
13 # Some of this code originated from rlcompleter in the Python standard library
14 # Copyright (C) 2001 Python Software Foundation, www.python.org
14 # Copyright (C) 2001 Python Software Foundation, www.python.org
15
15
16
16
17 import __main__
17 import __main__
18 import builtins as builtin_mod
18 import glob
19 import glob
19 import inspect
20 import inspect
20 import itertools
21 import itertools
21 import keyword
22 import keyword
22 import os
23 import os
23 import re
24 import re
24 import sys
25 import sys
25 import unicodedata
26 import unicodedata
26 import string
27 import string
27 import warnings
28 import warnings
28 from importlib import import_module
29 from importlib import import_module
29
30
30 from traitlets.config.configurable import Configurable
31 from traitlets.config.configurable import Configurable
31 from IPython.core.error import TryNext
32 from IPython.core.error import TryNext
32 from IPython.core.inputsplitter import ESC_MAGIC
33 from IPython.core.inputsplitter import ESC_MAGIC
33 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
34 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
34 from IPython.utils import generics
35 from IPython.utils import generics
35 from IPython.utils.decorators import undoc
36 from IPython.utils.decorators import undoc
36 from IPython.utils.dir2 import dir2, get_real_method
37 from IPython.utils.dir2 import dir2, get_real_method
37 from IPython.utils.process import arg_split
38 from IPython.utils.process import arg_split
38 from IPython.utils.py3compat import builtin_mod, cast_unicode_py2
39 from IPython.utils.py3compat import cast_unicode_py2
39 from traitlets import Bool, Enum, observe
40 from traitlets import Bool, Enum, observe
40
41
41 from functools import wraps
42 from functools import wraps
42
43
43 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
44 # Globals
45 # Globals
45 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
46
47
47 # Public API
48 # Public API
48 __all__ = ['Completer','IPCompleter']
49 __all__ = ['Completer','IPCompleter']
49
50
50 if sys.platform == 'win32':
51 if sys.platform == 'win32':
51 PROTECTABLES = ' '
52 PROTECTABLES = ' '
52 else:
53 else:
53 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
54 PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
54
55
55
56
56 #-----------------------------------------------------------------------------
57 #-----------------------------------------------------------------------------
57 # Work around BUG decorators.
58 # Work around BUG decorators.
58 #-----------------------------------------------------------------------------
59 #-----------------------------------------------------------------------------
59
60
60 def _strip_single_trailing_space(complete):
61 def _strip_single_trailing_space(complete):
61 """
62 """
62 This is a workaround for a weird IPython/Prompt_toolkit behavior,
63 This is a workaround for a weird IPython/Prompt_toolkit behavior,
63 that can be removed once we rely on a slightly more recent prompt_toolkit
64 that can be removed once we rely on a slightly more recent prompt_toolkit
64 version (likely > 1.0.3). So this can likely be removed in IPython 6.0
65 version (likely > 1.0.3). So this can likely be removed in IPython 6.0
65
66
66 cf https://github.com/ipython/ipython/issues/9658
67 cf https://github.com/ipython/ipython/issues/9658
67 and https://github.com/jonathanslenders/python-prompt-toolkit/pull/328
68 and https://github.com/jonathanslenders/python-prompt-toolkit/pull/328
68
69
69 The bug is due to the fact that in PTK the completer will reinvoke itself
70 The bug is due to the fact that in PTK the completer will reinvoke itself
70 after trying to completer to the longuest common prefix of all the
71 after trying to completer to the longuest common prefix of all the
71 completions, unless only one completion is available.
72 completions, unless only one completion is available.
72
73
73 This logic is faulty if the completion ends with space, which can happen in
74 This logic is faulty if the completion ends with space, which can happen in
74 case like::
75 case like::
75
76
76 from foo import im<ta>
77 from foo import im<ta>
77
78
78 which only matching completion is `import `. Note the leading space at the
79 which only matching completion is `import `. Note the leading space at the
79 end. So leaving a space at the end is a reasonable request, but for now
80 end. So leaving a space at the end is a reasonable request, but for now
80 we'll strip it.
81 we'll strip it.
81 """
82 """
82
83
83 @wraps(complete)
84 @wraps(complete)
84 def comp(*args, **kwargs):
85 def comp(*args, **kwargs):
85 text, matches = complete(*args, **kwargs)
86 text, matches = complete(*args, **kwargs)
86 if len(matches) == 1:
87 if len(matches) == 1:
87 return text, [matches[0].rstrip()]
88 return text, [matches[0].rstrip()]
88 return text, matches
89 return text, matches
89
90
90 return comp
91 return comp
91
92
92
93
93
94
94 #-----------------------------------------------------------------------------
95 #-----------------------------------------------------------------------------
95 # Main functions and classes
96 # Main functions and classes
96 #-----------------------------------------------------------------------------
97 #-----------------------------------------------------------------------------
97
98
98 def has_open_quotes(s):
99 def has_open_quotes(s):
99 """Return whether a string has open quotes.
100 """Return whether a string has open quotes.
100
101
101 This simply counts whether the number of quote characters of either type in
102 This simply counts whether the number of quote characters of either type in
102 the string is odd.
103 the string is odd.
103
104
104 Returns
105 Returns
105 -------
106 -------
106 If there is an open quote, the quote character is returned. Else, return
107 If there is an open quote, the quote character is returned. Else, return
107 False.
108 False.
108 """
109 """
109 # We check " first, then ', so complex cases with nested quotes will get
110 # We check " first, then ', so complex cases with nested quotes will get
110 # the " to take precedence.
111 # the " to take precedence.
111 if s.count('"') % 2:
112 if s.count('"') % 2:
112 return '"'
113 return '"'
113 elif s.count("'") % 2:
114 elif s.count("'") % 2:
114 return "'"
115 return "'"
115 else:
116 else:
116 return False
117 return False
117
118
118
119
119 def protect_filename(s):
120 def protect_filename(s):
120 """Escape a string to protect certain characters."""
121 """Escape a string to protect certain characters."""
121 if set(s) & set(PROTECTABLES):
122 if set(s) & set(PROTECTABLES):
122 if sys.platform == "win32":
123 if sys.platform == "win32":
123 return '"' + s + '"'
124 return '"' + s + '"'
124 else:
125 else:
125 return "".join(("\\" + c if c in PROTECTABLES else c) for c in s)
126 return "".join(("\\" + c if c in PROTECTABLES else c) for c in s)
126 else:
127 else:
127 return s
128 return s
128
129
129
130
130 def expand_user(path):
131 def expand_user(path):
131 """Expand '~'-style usernames in strings.
132 """Expand '~'-style usernames in strings.
132
133
133 This is similar to :func:`os.path.expanduser`, but it computes and returns
134 This is similar to :func:`os.path.expanduser`, but it computes and returns
134 extra information that will be useful if the input was being used in
135 extra information that will be useful if the input was being used in
135 computing completions, and you wish to return the completions with the
136 computing completions, and you wish to return the completions with the
136 original '~' instead of its expanded value.
137 original '~' instead of its expanded value.
137
138
138 Parameters
139 Parameters
139 ----------
140 ----------
140 path : str
141 path : str
141 String to be expanded. If no ~ is present, the output is the same as the
142 String to be expanded. If no ~ is present, the output is the same as the
142 input.
143 input.
143
144
144 Returns
145 Returns
145 -------
146 -------
146 newpath : str
147 newpath : str
147 Result of ~ expansion in the input path.
148 Result of ~ expansion in the input path.
148 tilde_expand : bool
149 tilde_expand : bool
149 Whether any expansion was performed or not.
150 Whether any expansion was performed or not.
150 tilde_val : str
151 tilde_val : str
151 The value that ~ was replaced with.
152 The value that ~ was replaced with.
152 """
153 """
153 # Default values
154 # Default values
154 tilde_expand = False
155 tilde_expand = False
155 tilde_val = ''
156 tilde_val = ''
156 newpath = path
157 newpath = path
157
158
158 if path.startswith('~'):
159 if path.startswith('~'):
159 tilde_expand = True
160 tilde_expand = True
160 rest = len(path)-1
161 rest = len(path)-1
161 newpath = os.path.expanduser(path)
162 newpath = os.path.expanduser(path)
162 if rest:
163 if rest:
163 tilde_val = newpath[:-rest]
164 tilde_val = newpath[:-rest]
164 else:
165 else:
165 tilde_val = newpath
166 tilde_val = newpath
166
167
167 return newpath, tilde_expand, tilde_val
168 return newpath, tilde_expand, tilde_val
168
169
169
170
170 def compress_user(path, tilde_expand, tilde_val):
171 def compress_user(path, tilde_expand, tilde_val):
171 """Does the opposite of expand_user, with its outputs.
172 """Does the opposite of expand_user, with its outputs.
172 """
173 """
173 if tilde_expand:
174 if tilde_expand:
174 return path.replace(tilde_val, '~')
175 return path.replace(tilde_val, '~')
175 else:
176 else:
176 return path
177 return path
177
178
178
179
179 def completions_sorting_key(word):
180 def completions_sorting_key(word):
180 """key for sorting completions
181 """key for sorting completions
181
182
182 This does several things:
183 This does several things:
183
184
184 - Lowercase all completions, so they are sorted alphabetically with
185 - Lowercase all completions, so they are sorted alphabetically with
185 upper and lower case words mingled
186 upper and lower case words mingled
186 - Demote any completions starting with underscores to the end
187 - Demote any completions starting with underscores to the end
187 - Insert any %magic and %%cellmagic completions in the alphabetical order
188 - Insert any %magic and %%cellmagic completions in the alphabetical order
188 by their name
189 by their name
189 """
190 """
190 # Case insensitive sort
191 # Case insensitive sort
191 word = word.lower()
192 word = word.lower()
192
193
193 prio1, prio2 = 0, 0
194 prio1, prio2 = 0, 0
194
195
195 if word.startswith('__'):
196 if word.startswith('__'):
196 prio1 = 2
197 prio1 = 2
197 elif word.startswith('_'):
198 elif word.startswith('_'):
198 prio1 = 1
199 prio1 = 1
199
200
200 if word.endswith('='):
201 if word.endswith('='):
201 prio1 = -1
202 prio1 = -1
202
203
203 if word.startswith('%%'):
204 if word.startswith('%%'):
204 # If there's another % in there, this is something else, so leave it alone
205 # If there's another % in there, this is something else, so leave it alone
205 if not "%" in word[2:]:
206 if not "%" in word[2:]:
206 word = word[2:]
207 word = word[2:]
207 prio2 = 2
208 prio2 = 2
208 elif word.startswith('%'):
209 elif word.startswith('%'):
209 if not "%" in word[1:]:
210 if not "%" in word[1:]:
210 word = word[1:]
211 word = word[1:]
211 prio2 = 1
212 prio2 = 1
212
213
213 return prio1, word, prio2
214 return prio1, word, prio2
214
215
215
216
216 @undoc
217 @undoc
217 class Bunch(object): pass
218 class Bunch(object): pass
218
219
219
220
220 if sys.platform == 'win32':
221 if sys.platform == 'win32':
221 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
222 DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
222 else:
223 else:
223 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
224 DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
224
225
225 GREEDY_DELIMS = ' =\r\n'
226 GREEDY_DELIMS = ' =\r\n'
226
227
227
228
228 class CompletionSplitter(object):
229 class CompletionSplitter(object):
229 """An object to split an input line in a manner similar to readline.
230 """An object to split an input line in a manner similar to readline.
230
231
231 By having our own implementation, we can expose readline-like completion in
232 By having our own implementation, we can expose readline-like completion in
232 a uniform manner to all frontends. This object only needs to be given the
233 a uniform manner to all frontends. This object only needs to be given the
233 line of text to be split and the cursor position on said line, and it
234 line of text to be split and the cursor position on said line, and it
234 returns the 'word' to be completed on at the cursor after splitting the
235 returns the 'word' to be completed on at the cursor after splitting the
235 entire line.
236 entire line.
236
237
237 What characters are used as splitting delimiters can be controlled by
238 What characters are used as splitting delimiters can be controlled by
238 setting the `delims` attribute (this is a property that internally
239 setting the `delims` attribute (this is a property that internally
239 automatically builds the necessary regular expression)"""
240 automatically builds the necessary regular expression)"""
240
241
241 # Private interface
242 # Private interface
242
243
243 # A string of delimiter characters. The default value makes sense for
244 # A string of delimiter characters. The default value makes sense for
244 # IPython's most typical usage patterns.
245 # IPython's most typical usage patterns.
245 _delims = DELIMS
246 _delims = DELIMS
246
247
247 # The expression (a normal string) to be compiled into a regular expression
248 # The expression (a normal string) to be compiled into a regular expression
248 # for actual splitting. We store it as an attribute mostly for ease of
249 # for actual splitting. We store it as an attribute mostly for ease of
249 # debugging, since this type of code can be so tricky to debug.
250 # debugging, since this type of code can be so tricky to debug.
250 _delim_expr = None
251 _delim_expr = None
251
252
252 # The regular expression that does the actual splitting
253 # The regular expression that does the actual splitting
253 _delim_re = None
254 _delim_re = None
254
255
255 def __init__(self, delims=None):
256 def __init__(self, delims=None):
256 delims = CompletionSplitter._delims if delims is None else delims
257 delims = CompletionSplitter._delims if delims is None else delims
257 self.delims = delims
258 self.delims = delims
258
259
259 @property
260 @property
260 def delims(self):
261 def delims(self):
261 """Return the string of delimiter characters."""
262 """Return the string of delimiter characters."""
262 return self._delims
263 return self._delims
263
264
264 @delims.setter
265 @delims.setter
265 def delims(self, delims):
266 def delims(self, delims):
266 """Set the delimiters for line splitting."""
267 """Set the delimiters for line splitting."""
267 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
268 expr = '[' + ''.join('\\'+ c for c in delims) + ']'
268 self._delim_re = re.compile(expr)
269 self._delim_re = re.compile(expr)
269 self._delims = delims
270 self._delims = delims
270 self._delim_expr = expr
271 self._delim_expr = expr
271
272
272 def split_line(self, line, cursor_pos=None):
273 def split_line(self, line, cursor_pos=None):
273 """Split a line of text with a cursor at the given position.
274 """Split a line of text with a cursor at the given position.
274 """
275 """
275 l = line if cursor_pos is None else line[:cursor_pos]
276 l = line if cursor_pos is None else line[:cursor_pos]
276 return self._delim_re.split(l)[-1]
277 return self._delim_re.split(l)[-1]
277
278
278
279
279 class Completer(Configurable):
280 class Completer(Configurable):
280
281
281 greedy = Bool(False,
282 greedy = Bool(False,
282 help="""Activate greedy completion
283 help="""Activate greedy completion
283 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
284 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
284
285
285 This will enable completion on elements of lists, results of function calls, etc.,
286 This will enable completion on elements of lists, results of function calls, etc.,
286 but can be unsafe because the code is actually evaluated on TAB.
287 but can be unsafe because the code is actually evaluated on TAB.
287 """
288 """
288 ).tag(config=True)
289 ).tag(config=True)
289
290
290
291
291 def __init__(self, namespace=None, global_namespace=None, **kwargs):
292 def __init__(self, namespace=None, global_namespace=None, **kwargs):
292 """Create a new completer for the command line.
293 """Create a new completer for the command line.
293
294
294 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
295 Completer(namespace=ns, global_namespace=ns2) -> completer instance.
295
296
296 If unspecified, the default namespace where completions are performed
297 If unspecified, the default namespace where completions are performed
297 is __main__ (technically, __main__.__dict__). Namespaces should be
298 is __main__ (technically, __main__.__dict__). Namespaces should be
298 given as dictionaries.
299 given as dictionaries.
299
300
300 An optional second namespace can be given. This allows the completer
301 An optional second namespace can be given. This allows the completer
301 to handle cases where both the local and global scopes need to be
302 to handle cases where both the local and global scopes need to be
302 distinguished.
303 distinguished.
303
304
304 Completer instances should be used as the completion mechanism of
305 Completer instances should be used as the completion mechanism of
305 readline via the set_completer() call:
306 readline via the set_completer() call:
306
307
307 readline.set_completer(Completer(my_namespace).complete)
308 readline.set_completer(Completer(my_namespace).complete)
308 """
309 """
309
310
310 # Don't bind to namespace quite yet, but flag whether the user wants a
311 # Don't bind to namespace quite yet, but flag whether the user wants a
311 # specific namespace or to use __main__.__dict__. This will allow us
312 # specific namespace or to use __main__.__dict__. This will allow us
312 # to bind to __main__.__dict__ at completion time, not now.
313 # to bind to __main__.__dict__ at completion time, not now.
313 if namespace is None:
314 if namespace is None:
314 self.use_main_ns = 1
315 self.use_main_ns = 1
315 else:
316 else:
316 self.use_main_ns = 0
317 self.use_main_ns = 0
317 self.namespace = namespace
318 self.namespace = namespace
318
319
319 # The global namespace, if given, can be bound directly
320 # The global namespace, if given, can be bound directly
320 if global_namespace is None:
321 if global_namespace is None:
321 self.global_namespace = {}
322 self.global_namespace = {}
322 else:
323 else:
323 self.global_namespace = global_namespace
324 self.global_namespace = global_namespace
324
325
325 super(Completer, self).__init__(**kwargs)
326 super(Completer, self).__init__(**kwargs)
326
327
327 def complete(self, text, state):
328 def complete(self, text, state):
328 """Return the next possible completion for 'text'.
329 """Return the next possible completion for 'text'.
329
330
330 This is called successively with state == 0, 1, 2, ... until it
331 This is called successively with state == 0, 1, 2, ... until it
331 returns None. The completion should begin with 'text'.
332 returns None. The completion should begin with 'text'.
332
333
333 """
334 """
334 if self.use_main_ns:
335 if self.use_main_ns:
335 self.namespace = __main__.__dict__
336 self.namespace = __main__.__dict__
336
337
337 if state == 0:
338 if state == 0:
338 if "." in text:
339 if "." in text:
339 self.matches = self.attr_matches(text)
340 self.matches = self.attr_matches(text)
340 else:
341 else:
341 self.matches = self.global_matches(text)
342 self.matches = self.global_matches(text)
342 try:
343 try:
343 return self.matches[state]
344 return self.matches[state]
344 except IndexError:
345 except IndexError:
345 return None
346 return None
346
347
347 def global_matches(self, text):
348 def global_matches(self, text):
348 """Compute matches when text is a simple name.
349 """Compute matches when text is a simple name.
349
350
350 Return a list of all keywords, built-in functions and names currently
351 Return a list of all keywords, built-in functions and names currently
351 defined in self.namespace or self.global_namespace that match.
352 defined in self.namespace or self.global_namespace that match.
352
353
353 """
354 """
354 matches = []
355 matches = []
355 match_append = matches.append
356 match_append = matches.append
356 n = len(text)
357 n = len(text)
357 for lst in [keyword.kwlist,
358 for lst in [keyword.kwlist,
358 builtin_mod.__dict__.keys(),
359 builtin_mod.__dict__.keys(),
359 self.namespace.keys(),
360 self.namespace.keys(),
360 self.global_namespace.keys()]:
361 self.global_namespace.keys()]:
361 for word in lst:
362 for word in lst:
362 if word[:n] == text and word != "__builtins__":
363 if word[:n] == text and word != "__builtins__":
363 match_append(word)
364 match_append(word)
364 return [cast_unicode_py2(m) for m in matches]
365 return [cast_unicode_py2(m) for m in matches]
365
366
366 def attr_matches(self, text):
367 def attr_matches(self, text):
367 """Compute matches when text contains a dot.
368 """Compute matches when text contains a dot.
368
369
369 Assuming the text is of the form NAME.NAME....[NAME], and is
370 Assuming the text is of the form NAME.NAME....[NAME], and is
370 evaluatable in self.namespace or self.global_namespace, it will be
371 evaluatable in self.namespace or self.global_namespace, it will be
371 evaluated and its attributes (as revealed by dir()) are used as
372 evaluated and its attributes (as revealed by dir()) are used as
372 possible completions. (For class instances, class members are are
373 possible completions. (For class instances, class members are are
373 also considered.)
374 also considered.)
374
375
375 WARNING: this can still invoke arbitrary C code, if an object
376 WARNING: this can still invoke arbitrary C code, if an object
376 with a __getattr__ hook is evaluated.
377 with a __getattr__ hook is evaluated.
377
378
378 """
379 """
379
380
380 # Another option, seems to work great. Catches things like ''.<tab>
381 # Another option, seems to work great. Catches things like ''.<tab>
381 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
382 m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
382
383
383 if m:
384 if m:
384 expr, attr = m.group(1, 3)
385 expr, attr = m.group(1, 3)
385 elif self.greedy:
386 elif self.greedy:
386 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
387 m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
387 if not m2:
388 if not m2:
388 return []
389 return []
389 expr, attr = m2.group(1,2)
390 expr, attr = m2.group(1,2)
390 else:
391 else:
391 return []
392 return []
392
393
393 try:
394 try:
394 obj = eval(expr, self.namespace)
395 obj = eval(expr, self.namespace)
395 except:
396 except:
396 try:
397 try:
397 obj = eval(expr, self.global_namespace)
398 obj = eval(expr, self.global_namespace)
398 except:
399 except:
399 return []
400 return []
400
401
401 if self.limit_to__all__ and hasattr(obj, '__all__'):
402 if self.limit_to__all__ and hasattr(obj, '__all__'):
402 words = get__all__entries(obj)
403 words = get__all__entries(obj)
403 else:
404 else:
404 words = dir2(obj)
405 words = dir2(obj)
405
406
406 try:
407 try:
407 words = generics.complete_object(obj, words)
408 words = generics.complete_object(obj, words)
408 except TryNext:
409 except TryNext:
409 pass
410 pass
410 except Exception:
411 except Exception:
411 # Silence errors from completion function
412 # Silence errors from completion function
412 #raise # dbg
413 #raise # dbg
413 pass
414 pass
414 # Build match list to return
415 # Build match list to return
415 n = len(attr)
416 n = len(attr)
416 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
417 return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
417
418
418
419
419 def get__all__entries(obj):
420 def get__all__entries(obj):
420 """returns the strings in the __all__ attribute"""
421 """returns the strings in the __all__ attribute"""
421 try:
422 try:
422 words = getattr(obj, '__all__')
423 words = getattr(obj, '__all__')
423 except:
424 except:
424 return []
425 return []
425
426
426 return [cast_unicode_py2(w) for w in words if isinstance(w, str)]
427 return [cast_unicode_py2(w) for w in words if isinstance(w, str)]
427
428
428
429
429 def match_dict_keys(keys, prefix, delims):
430 def match_dict_keys(keys, prefix, delims):
430 """Used by dict_key_matches, matching the prefix to a list of keys"""
431 """Used by dict_key_matches, matching the prefix to a list of keys"""
431 if not prefix:
432 if not prefix:
432 return None, 0, [repr(k) for k in keys
433 return None, 0, [repr(k) for k in keys
433 if isinstance(k, (str, bytes))]
434 if isinstance(k, (str, bytes))]
434 quote_match = re.search('["\']', prefix)
435 quote_match = re.search('["\']', prefix)
435 quote = quote_match.group()
436 quote = quote_match.group()
436 try:
437 try:
437 prefix_str = eval(prefix + quote, {})
438 prefix_str = eval(prefix + quote, {})
438 except Exception:
439 except Exception:
439 return None, 0, []
440 return None, 0, []
440
441
441 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
442 pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
442 token_match = re.search(pattern, prefix, re.UNICODE)
443 token_match = re.search(pattern, prefix, re.UNICODE)
443 token_start = token_match.start()
444 token_start = token_match.start()
444 token_prefix = token_match.group()
445 token_prefix = token_match.group()
445
446
446 # TODO: support bytes in Py3k
447 # TODO: support bytes in Py3k
447 matched = []
448 matched = []
448 for key in keys:
449 for key in keys:
449 try:
450 try:
450 if not key.startswith(prefix_str):
451 if not key.startswith(prefix_str):
451 continue
452 continue
452 except (AttributeError, TypeError, UnicodeError):
453 except (AttributeError, TypeError, UnicodeError):
453 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
454 # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
454 continue
455 continue
455
456
456 # reformat remainder of key to begin with prefix
457 # reformat remainder of key to begin with prefix
457 rem = key[len(prefix_str):]
458 rem = key[len(prefix_str):]
458 # force repr wrapped in '
459 # force repr wrapped in '
459 rem_repr = repr(rem + '"')
460 rem_repr = repr(rem + '"')
460 if rem_repr.startswith('u') and prefix[0] not in 'uU':
461 if rem_repr.startswith('u') and prefix[0] not in 'uU':
461 # Found key is unicode, but prefix is Py2 string.
462 # Found key is unicode, but prefix is Py2 string.
462 # Therefore attempt to interpret key as string.
463 # Therefore attempt to interpret key as string.
463 try:
464 try:
464 rem_repr = repr(rem.encode('ascii') + '"')
465 rem_repr = repr(rem.encode('ascii') + '"')
465 except UnicodeEncodeError:
466 except UnicodeEncodeError:
466 continue
467 continue
467
468
468 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
469 rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
469 if quote == '"':
470 if quote == '"':
470 # The entered prefix is quoted with ",
471 # The entered prefix is quoted with ",
471 # but the match is quoted with '.
472 # but the match is quoted with '.
472 # A contained " hence needs escaping for comparison:
473 # A contained " hence needs escaping for comparison:
473 rem_repr = rem_repr.replace('"', '\\"')
474 rem_repr = rem_repr.replace('"', '\\"')
474
475
475 # then reinsert prefix from start of token
476 # then reinsert prefix from start of token
476 matched.append('%s%s' % (token_prefix, rem_repr))
477 matched.append('%s%s' % (token_prefix, rem_repr))
477 return quote, token_start, matched
478 return quote, token_start, matched
478
479
479
480
480 def _safe_isinstance(obj, module, class_name):
481 def _safe_isinstance(obj, module, class_name):
481 """Checks if obj is an instance of module.class_name if loaded
482 """Checks if obj is an instance of module.class_name if loaded
482 """
483 """
483 return (module in sys.modules and
484 return (module in sys.modules and
484 isinstance(obj, getattr(import_module(module), class_name)))
485 isinstance(obj, getattr(import_module(module), class_name)))
485
486
486
487
487 def back_unicode_name_matches(text):
488 def back_unicode_name_matches(text):
488 u"""Match unicode characters back to unicode name
489 u"""Match unicode characters back to unicode name
489
490
490 This does β˜ƒ -> \\snowman
491 This does β˜ƒ -> \\snowman
491
492
492 Note that snowman is not a valid python3 combining character but will be expanded.
493 Note that snowman is not a valid python3 combining character but will be expanded.
493 Though it will not recombine back to the snowman character by the completion machinery.
494 Though it will not recombine back to the snowman character by the completion machinery.
494
495
495 This will not either back-complete standard sequences like \\n, \\b ...
496 This will not either back-complete standard sequences like \\n, \\b ...
496
497
497 Used on Python 3 only.
498 Used on Python 3 only.
498 """
499 """
499 if len(text)<2:
500 if len(text)<2:
500 return u'', ()
501 return u'', ()
501 maybe_slash = text[-2]
502 maybe_slash = text[-2]
502 if maybe_slash != '\\':
503 if maybe_slash != '\\':
503 return u'', ()
504 return u'', ()
504
505
505 char = text[-1]
506 char = text[-1]
506 # no expand on quote for completion in strings.
507 # no expand on quote for completion in strings.
507 # nor backcomplete standard ascii keys
508 # nor backcomplete standard ascii keys
508 if char in string.ascii_letters or char in ['"',"'"]:
509 if char in string.ascii_letters or char in ['"',"'"]:
509 return u'', ()
510 return u'', ()
510 try :
511 try :
511 unic = unicodedata.name(char)
512 unic = unicodedata.name(char)
512 return '\\'+char,['\\'+unic]
513 return '\\'+char,['\\'+unic]
513 except KeyError:
514 except KeyError:
514 pass
515 pass
515 return u'', ()
516 return u'', ()
516
517
517 def back_latex_name_matches(text):
518 def back_latex_name_matches(text):
518 u"""Match latex characters back to unicode name
519 u"""Match latex characters back to unicode name
519
520
520 This does ->\\sqrt
521 This does ->\\sqrt
521
522
522 Used on Python 3 only.
523 Used on Python 3 only.
523 """
524 """
524 if len(text)<2:
525 if len(text)<2:
525 return u'', ()
526 return u'', ()
526 maybe_slash = text[-2]
527 maybe_slash = text[-2]
527 if maybe_slash != '\\':
528 if maybe_slash != '\\':
528 return u'', ()
529 return u'', ()
529
530
530
531
531 char = text[-1]
532 char = text[-1]
532 # no expand on quote for completion in strings.
533 # no expand on quote for completion in strings.
533 # nor backcomplete standard ascii keys
534 # nor backcomplete standard ascii keys
534 if char in string.ascii_letters or char in ['"',"'"]:
535 if char in string.ascii_letters or char in ['"',"'"]:
535 return u'', ()
536 return u'', ()
536 try :
537 try :
537 latex = reverse_latex_symbol[char]
538 latex = reverse_latex_symbol[char]
538 # '\\' replace the \ as well
539 # '\\' replace the \ as well
539 return '\\'+char,[latex]
540 return '\\'+char,[latex]
540 except KeyError:
541 except KeyError:
541 pass
542 pass
542 return u'', ()
543 return u'', ()
543
544
544
545
545 class IPCompleter(Completer):
546 class IPCompleter(Completer):
546 """Extension of the completer class with IPython-specific features"""
547 """Extension of the completer class with IPython-specific features"""
547
548
548 @observe('greedy')
549 @observe('greedy')
549 def _greedy_changed(self, change):
550 def _greedy_changed(self, change):
550 """update the splitter and readline delims when greedy is changed"""
551 """update the splitter and readline delims when greedy is changed"""
551 if change['new']:
552 if change['new']:
552 self.splitter.delims = GREEDY_DELIMS
553 self.splitter.delims = GREEDY_DELIMS
553 else:
554 else:
554 self.splitter.delims = DELIMS
555 self.splitter.delims = DELIMS
555
556
556 merge_completions = Bool(True,
557 merge_completions = Bool(True,
557 help="""Whether to merge completion results into a single list
558 help="""Whether to merge completion results into a single list
558
559
559 If False, only the completion results from the first non-empty
560 If False, only the completion results from the first non-empty
560 completer will be returned.
561 completer will be returned.
561 """
562 """
562 ).tag(config=True)
563 ).tag(config=True)
563 omit__names = Enum((0,1,2), default_value=2,
564 omit__names = Enum((0,1,2), default_value=2,
564 help="""Instruct the completer to omit private method names
565 help="""Instruct the completer to omit private method names
565
566
566 Specifically, when completing on ``object.<tab>``.
567 Specifically, when completing on ``object.<tab>``.
567
568
568 When 2 [default]: all names that start with '_' will be excluded.
569 When 2 [default]: all names that start with '_' will be excluded.
569
570
570 When 1: all 'magic' names (``__foo__``) will be excluded.
571 When 1: all 'magic' names (``__foo__``) will be excluded.
571
572
572 When 0: nothing will be excluded.
573 When 0: nothing will be excluded.
573 """
574 """
574 ).tag(config=True)
575 ).tag(config=True)
575 limit_to__all__ = Bool(False,
576 limit_to__all__ = Bool(False,
576 help="""
577 help="""
577 DEPRECATED as of version 5.0.
578 DEPRECATED as of version 5.0.
578
579
579 Instruct the completer to use __all__ for the completion
580 Instruct the completer to use __all__ for the completion
580
581
581 Specifically, when completing on ``object.<tab>``.
582 Specifically, when completing on ``object.<tab>``.
582
583
583 When True: only those names in obj.__all__ will be included.
584 When True: only those names in obj.__all__ will be included.
584
585
585 When False [default]: the __all__ attribute is ignored
586 When False [default]: the __all__ attribute is ignored
586 """,
587 """,
587 ).tag(config=True)
588 ).tag(config=True)
588
589
589 def __init__(self, shell=None, namespace=None, global_namespace=None,
590 def __init__(self, shell=None, namespace=None, global_namespace=None,
590 use_readline=False, config=None, **kwargs):
591 use_readline=False, config=None, **kwargs):
591 """IPCompleter() -> completer
592 """IPCompleter() -> completer
592
593
593 Return a completer object suitable for use by the readline library
594 Return a completer object suitable for use by the readline library
594 via readline.set_completer().
595 via readline.set_completer().
595
596
596 Inputs:
597 Inputs:
597
598
598 - shell: a pointer to the ipython shell itself. This is needed
599 - shell: a pointer to the ipython shell itself. This is needed
599 because this completer knows about magic functions, and those can
600 because this completer knows about magic functions, and those can
600 only be accessed via the ipython instance.
601 only be accessed via the ipython instance.
601
602
602 - namespace: an optional dict where completions are performed.
603 - namespace: an optional dict where completions are performed.
603
604
604 - global_namespace: secondary optional dict for completions, to
605 - global_namespace: secondary optional dict for completions, to
605 handle cases (such as IPython embedded inside functions) where
606 handle cases (such as IPython embedded inside functions) where
606 both Python scopes are visible.
607 both Python scopes are visible.
607
608
608 use_readline : bool, optional
609 use_readline : bool, optional
609 DEPRECATED, ignored.
610 DEPRECATED, ignored.
610 """
611 """
611
612
612 self.magic_escape = ESC_MAGIC
613 self.magic_escape = ESC_MAGIC
613 self.splitter = CompletionSplitter()
614 self.splitter = CompletionSplitter()
614
615
615 if use_readline:
616 if use_readline:
616 warnings.warn('The use_readline parameter is deprecated and ignored since IPython 6.0.',
617 warnings.warn('The use_readline parameter is deprecated and ignored since IPython 6.0.',
617 DeprecationWarning, stacklevel=2)
618 DeprecationWarning, stacklevel=2)
618
619
619 # _greedy_changed() depends on splitter and readline being defined:
620 # _greedy_changed() depends on splitter and readline being defined:
620 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
621 Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
621 config=config, **kwargs)
622 config=config, **kwargs)
622
623
623 # List where completion matches will be stored
624 # List where completion matches will be stored
624 self.matches = []
625 self.matches = []
625 self.shell = shell
626 self.shell = shell
626 # Regexp to split filenames with spaces in them
627 # Regexp to split filenames with spaces in them
627 self.space_name_re = re.compile(r'([^\\] )')
628 self.space_name_re = re.compile(r'([^\\] )')
628 # Hold a local ref. to glob.glob for speed
629 # Hold a local ref. to glob.glob for speed
629 self.glob = glob.glob
630 self.glob = glob.glob
630
631
631 # Determine if we are running on 'dumb' terminals, like (X)Emacs
632 # Determine if we are running on 'dumb' terminals, like (X)Emacs
632 # buffers, to avoid completion problems.
633 # buffers, to avoid completion problems.
633 term = os.environ.get('TERM','xterm')
634 term = os.environ.get('TERM','xterm')
634 self.dumb_terminal = term in ['dumb','emacs']
635 self.dumb_terminal = term in ['dumb','emacs']
635
636
636 # Special handling of backslashes needed in win32 platforms
637 # Special handling of backslashes needed in win32 platforms
637 if sys.platform == "win32":
638 if sys.platform == "win32":
638 self.clean_glob = self._clean_glob_win32
639 self.clean_glob = self._clean_glob_win32
639 else:
640 else:
640 self.clean_glob = self._clean_glob
641 self.clean_glob = self._clean_glob
641
642
642 #regexp to parse docstring for function signature
643 #regexp to parse docstring for function signature
643 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
644 self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
644 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
645 self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
645 #use this if positional argument name is also needed
646 #use this if positional argument name is also needed
646 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
647 #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
647
648
648 # All active matcher routines for completion
649 # All active matcher routines for completion
649 self.matchers = [
650 self.matchers = [
650 self.python_matches,
651 self.python_matches,
651 self.file_matches,
652 self.file_matches,
652 self.magic_matches,
653 self.magic_matches,
653 self.python_func_kw_matches,
654 self.python_func_kw_matches,
654 self.dict_key_matches,
655 self.dict_key_matches,
655 ]
656 ]
656
657
657 # This is set externally by InteractiveShell
658 # This is set externally by InteractiveShell
658 self.custom_completers = None
659 self.custom_completers = None
659
660
660 def all_completions(self, text):
661 def all_completions(self, text):
661 """
662 """
662 Wrapper around the complete method for the benefit of emacs.
663 Wrapper around the complete method for the benefit of emacs.
663 """
664 """
664 return self.complete(text)[1]
665 return self.complete(text)[1]
665
666
666 def _clean_glob(self, text):
667 def _clean_glob(self, text):
667 return self.glob("%s*" % text)
668 return self.glob("%s*" % text)
668
669
669 def _clean_glob_win32(self,text):
670 def _clean_glob_win32(self,text):
670 return [f.replace("\\","/")
671 return [f.replace("\\","/")
671 for f in self.glob("%s*" % text)]
672 for f in self.glob("%s*" % text)]
672
673
673 def file_matches(self, text):
674 def file_matches(self, text):
674 """Match filenames, expanding ~USER type strings.
675 """Match filenames, expanding ~USER type strings.
675
676
676 Most of the seemingly convoluted logic in this completer is an
677 Most of the seemingly convoluted logic in this completer is an
677 attempt to handle filenames with spaces in them. And yet it's not
678 attempt to handle filenames with spaces in them. And yet it's not
678 quite perfect, because Python's readline doesn't expose all of the
679 quite perfect, because Python's readline doesn't expose all of the
679 GNU readline details needed for this to be done correctly.
680 GNU readline details needed for this to be done correctly.
680
681
681 For a filename with a space in it, the printed completions will be
682 For a filename with a space in it, the printed completions will be
682 only the parts after what's already been typed (instead of the
683 only the parts after what's already been typed (instead of the
683 full completions, as is normally done). I don't think with the
684 full completions, as is normally done). I don't think with the
684 current (as of Python 2.3) Python readline it's possible to do
685 current (as of Python 2.3) Python readline it's possible to do
685 better."""
686 better."""
686
687
687 # chars that require escaping with backslash - i.e. chars
688 # chars that require escaping with backslash - i.e. chars
688 # that readline treats incorrectly as delimiters, but we
689 # that readline treats incorrectly as delimiters, but we
689 # don't want to treat as delimiters in filename matching
690 # don't want to treat as delimiters in filename matching
690 # when escaped with backslash
691 # when escaped with backslash
691 if text.startswith('!'):
692 if text.startswith('!'):
692 text = text[1:]
693 text = text[1:]
693 text_prefix = u'!'
694 text_prefix = u'!'
694 else:
695 else:
695 text_prefix = u''
696 text_prefix = u''
696
697
697 text_until_cursor = self.text_until_cursor
698 text_until_cursor = self.text_until_cursor
698 # track strings with open quotes
699 # track strings with open quotes
699 open_quotes = has_open_quotes(text_until_cursor)
700 open_quotes = has_open_quotes(text_until_cursor)
700
701
701 if '(' in text_until_cursor or '[' in text_until_cursor:
702 if '(' in text_until_cursor or '[' in text_until_cursor:
702 lsplit = text
703 lsplit = text
703 else:
704 else:
704 try:
705 try:
705 # arg_split ~ shlex.split, but with unicode bugs fixed by us
706 # arg_split ~ shlex.split, but with unicode bugs fixed by us
706 lsplit = arg_split(text_until_cursor)[-1]
707 lsplit = arg_split(text_until_cursor)[-1]
707 except ValueError:
708 except ValueError:
708 # typically an unmatched ", or backslash without escaped char.
709 # typically an unmatched ", or backslash without escaped char.
709 if open_quotes:
710 if open_quotes:
710 lsplit = text_until_cursor.split(open_quotes)[-1]
711 lsplit = text_until_cursor.split(open_quotes)[-1]
711 else:
712 else:
712 return []
713 return []
713 except IndexError:
714 except IndexError:
714 # tab pressed on empty line
715 # tab pressed on empty line
715 lsplit = ""
716 lsplit = ""
716
717
717 if not open_quotes and lsplit != protect_filename(lsplit):
718 if not open_quotes and lsplit != protect_filename(lsplit):
718 # if protectables are found, do matching on the whole escaped name
719 # if protectables are found, do matching on the whole escaped name
719 has_protectables = True
720 has_protectables = True
720 text0,text = text,lsplit
721 text0,text = text,lsplit
721 else:
722 else:
722 has_protectables = False
723 has_protectables = False
723 text = os.path.expanduser(text)
724 text = os.path.expanduser(text)
724
725
725 if text == "":
726 if text == "":
726 return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
727 return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
727
728
728 # Compute the matches from the filesystem
729 # Compute the matches from the filesystem
729 if sys.platform == 'win32':
730 if sys.platform == 'win32':
730 m0 = self.clean_glob(text)
731 m0 = self.clean_glob(text)
731 else:
732 else:
732 m0 = self.clean_glob(text.replace('\\', ''))
733 m0 = self.clean_glob(text.replace('\\', ''))
733
734
734 if has_protectables:
735 if has_protectables:
735 # If we had protectables, we need to revert our changes to the
736 # If we had protectables, we need to revert our changes to the
736 # beginning of filename so that we don't double-write the part
737 # beginning of filename so that we don't double-write the part
737 # of the filename we have so far
738 # of the filename we have so far
738 len_lsplit = len(lsplit)
739 len_lsplit = len(lsplit)
739 matches = [text_prefix + text0 +
740 matches = [text_prefix + text0 +
740 protect_filename(f[len_lsplit:]) for f in m0]
741 protect_filename(f[len_lsplit:]) for f in m0]
741 else:
742 else:
742 if open_quotes:
743 if open_quotes:
743 # if we have a string with an open quote, we don't need to
744 # if we have a string with an open quote, we don't need to
744 # protect the names at all (and we _shouldn't_, as it
745 # protect the names at all (and we _shouldn't_, as it
745 # would cause bugs when the filesystem call is made).
746 # would cause bugs when the filesystem call is made).
746 matches = m0
747 matches = m0
747 else:
748 else:
748 matches = [text_prefix +
749 matches = [text_prefix +
749 protect_filename(f) for f in m0]
750 protect_filename(f) for f in m0]
750
751
751 # Mark directories in input list by appending '/' to their names.
752 # Mark directories in input list by appending '/' to their names.
752 return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
753 return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
753
754
754 def magic_matches(self, text):
755 def magic_matches(self, text):
755 """Match magics"""
756 """Match magics"""
756 # Get all shell magics now rather than statically, so magics loaded at
757 # Get all shell magics now rather than statically, so magics loaded at
757 # runtime show up too.
758 # runtime show up too.
758 lsm = self.shell.magics_manager.lsmagic()
759 lsm = self.shell.magics_manager.lsmagic()
759 line_magics = lsm['line']
760 line_magics = lsm['line']
760 cell_magics = lsm['cell']
761 cell_magics = lsm['cell']
761 pre = self.magic_escape
762 pre = self.magic_escape
762 pre2 = pre+pre
763 pre2 = pre+pre
763
764
764 # Completion logic:
765 # Completion logic:
765 # - user gives %%: only do cell magics
766 # - user gives %%: only do cell magics
766 # - user gives %: do both line and cell magics
767 # - user gives %: do both line and cell magics
767 # - no prefix: do both
768 # - no prefix: do both
768 # In other words, line magics are skipped if the user gives %% explicitly
769 # In other words, line magics are skipped if the user gives %% explicitly
769 bare_text = text.lstrip(pre)
770 bare_text = text.lstrip(pre)
770 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
771 comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
771 if not text.startswith(pre2):
772 if not text.startswith(pre2):
772 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
773 comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
773 return [cast_unicode_py2(c) for c in comp]
774 return [cast_unicode_py2(c) for c in comp]
774
775
775
776
776 def python_matches(self, text):
777 def python_matches(self, text):
777 """Match attributes or global python names"""
778 """Match attributes or global python names"""
778 if "." in text:
779 if "." in text:
779 try:
780 try:
780 matches = self.attr_matches(text)
781 matches = self.attr_matches(text)
781 if text.endswith('.') and self.omit__names:
782 if text.endswith('.') and self.omit__names:
782 if self.omit__names == 1:
783 if self.omit__names == 1:
783 # true if txt is _not_ a __ name, false otherwise:
784 # true if txt is _not_ a __ name, false otherwise:
784 no__name = (lambda txt:
785 no__name = (lambda txt:
785 re.match(r'.*\.__.*?__',txt) is None)
786 re.match(r'.*\.__.*?__',txt) is None)
786 else:
787 else:
787 # true if txt is _not_ a _ name, false otherwise:
788 # true if txt is _not_ a _ name, false otherwise:
788 no__name = (lambda txt:
789 no__name = (lambda txt:
789 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
790 re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
790 matches = filter(no__name, matches)
791 matches = filter(no__name, matches)
791 except NameError:
792 except NameError:
792 # catches <undefined attributes>.<tab>
793 # catches <undefined attributes>.<tab>
793 matches = []
794 matches = []
794 else:
795 else:
795 matches = self.global_matches(text)
796 matches = self.global_matches(text)
796 return matches
797 return matches
797
798
798 def _default_arguments_from_docstring(self, doc):
799 def _default_arguments_from_docstring(self, doc):
799 """Parse the first line of docstring for call signature.
800 """Parse the first line of docstring for call signature.
800
801
801 Docstring should be of the form 'min(iterable[, key=func])\n'.
802 Docstring should be of the form 'min(iterable[, key=func])\n'.
802 It can also parse cython docstring of the form
803 It can also parse cython docstring of the form
803 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
804 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
804 """
805 """
805 if doc is None:
806 if doc is None:
806 return []
807 return []
807
808
808 #care only the firstline
809 #care only the firstline
809 line = doc.lstrip().splitlines()[0]
810 line = doc.lstrip().splitlines()[0]
810
811
811 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
812 #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
812 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
813 #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
813 sig = self.docstring_sig_re.search(line)
814 sig = self.docstring_sig_re.search(line)
814 if sig is None:
815 if sig is None:
815 return []
816 return []
816 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
817 # iterable[, key=func]' -> ['iterable[' ,' key=func]']
817 sig = sig.groups()[0].split(',')
818 sig = sig.groups()[0].split(',')
818 ret = []
819 ret = []
819 for s in sig:
820 for s in sig:
820 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
821 #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
821 ret += self.docstring_kwd_re.findall(s)
822 ret += self.docstring_kwd_re.findall(s)
822 return ret
823 return ret
823
824
824 def _default_arguments(self, obj):
825 def _default_arguments(self, obj):
825 """Return the list of default arguments of obj if it is callable,
826 """Return the list of default arguments of obj if it is callable,
826 or empty list otherwise."""
827 or empty list otherwise."""
827 call_obj = obj
828 call_obj = obj
828 ret = []
829 ret = []
829 if inspect.isbuiltin(obj):
830 if inspect.isbuiltin(obj):
830 pass
831 pass
831 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
832 elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
832 if inspect.isclass(obj):
833 if inspect.isclass(obj):
833 #for cython embededsignature=True the constructor docstring
834 #for cython embededsignature=True the constructor docstring
834 #belongs to the object itself not __init__
835 #belongs to the object itself not __init__
835 ret += self._default_arguments_from_docstring(
836 ret += self._default_arguments_from_docstring(
836 getattr(obj, '__doc__', ''))
837 getattr(obj, '__doc__', ''))
837 # for classes, check for __init__,__new__
838 # for classes, check for __init__,__new__
838 call_obj = (getattr(obj, '__init__', None) or
839 call_obj = (getattr(obj, '__init__', None) or
839 getattr(obj, '__new__', None))
840 getattr(obj, '__new__', None))
840 # for all others, check if they are __call__able
841 # for all others, check if they are __call__able
841 elif hasattr(obj, '__call__'):
842 elif hasattr(obj, '__call__'):
842 call_obj = obj.__call__
843 call_obj = obj.__call__
843 ret += self._default_arguments_from_docstring(
844 ret += self._default_arguments_from_docstring(
844 getattr(call_obj, '__doc__', ''))
845 getattr(call_obj, '__doc__', ''))
845
846
846 _keeps = (inspect.Parameter.KEYWORD_ONLY,
847 _keeps = (inspect.Parameter.KEYWORD_ONLY,
847 inspect.Parameter.POSITIONAL_OR_KEYWORD)
848 inspect.Parameter.POSITIONAL_OR_KEYWORD)
848
849
849 try:
850 try:
850 sig = inspect.signature(call_obj)
851 sig = inspect.signature(call_obj)
851 ret.extend(k for k, v in sig.parameters.items() if
852 ret.extend(k for k, v in sig.parameters.items() if
852 v.kind in _keeps)
853 v.kind in _keeps)
853 except ValueError:
854 except ValueError:
854 pass
855 pass
855
856
856 return list(set(ret))
857 return list(set(ret))
857
858
858 def python_func_kw_matches(self,text):
859 def python_func_kw_matches(self,text):
859 """Match named parameters (kwargs) of the last open function"""
860 """Match named parameters (kwargs) of the last open function"""
860
861
861 if "." in text: # a parameter cannot be dotted
862 if "." in text: # a parameter cannot be dotted
862 return []
863 return []
863 try: regexp = self.__funcParamsRegex
864 try: regexp = self.__funcParamsRegex
864 except AttributeError:
865 except AttributeError:
865 regexp = self.__funcParamsRegex = re.compile(r'''
866 regexp = self.__funcParamsRegex = re.compile(r'''
866 '.*?(?<!\\)' | # single quoted strings or
867 '.*?(?<!\\)' | # single quoted strings or
867 ".*?(?<!\\)" | # double quoted strings or
868 ".*?(?<!\\)" | # double quoted strings or
868 \w+ | # identifier
869 \w+ | # identifier
869 \S # other characters
870 \S # other characters
870 ''', re.VERBOSE | re.DOTALL)
871 ''', re.VERBOSE | re.DOTALL)
871 # 1. find the nearest identifier that comes before an unclosed
872 # 1. find the nearest identifier that comes before an unclosed
872 # parenthesis before the cursor
873 # parenthesis before the cursor
873 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
874 # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
874 tokens = regexp.findall(self.text_until_cursor)
875 tokens = regexp.findall(self.text_until_cursor)
875 iterTokens = reversed(tokens); openPar = 0
876 iterTokens = reversed(tokens); openPar = 0
876
877
877 for token in iterTokens:
878 for token in iterTokens:
878 if token == ')':
879 if token == ')':
879 openPar -= 1
880 openPar -= 1
880 elif token == '(':
881 elif token == '(':
881 openPar += 1
882 openPar += 1
882 if openPar > 0:
883 if openPar > 0:
883 # found the last unclosed parenthesis
884 # found the last unclosed parenthesis
884 break
885 break
885 else:
886 else:
886 return []
887 return []
887 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
888 # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
888 ids = []
889 ids = []
889 isId = re.compile(r'\w+$').match
890 isId = re.compile(r'\w+$').match
890
891
891 while True:
892 while True:
892 try:
893 try:
893 ids.append(next(iterTokens))
894 ids.append(next(iterTokens))
894 if not isId(ids[-1]):
895 if not isId(ids[-1]):
895 ids.pop(); break
896 ids.pop(); break
896 if not next(iterTokens) == '.':
897 if not next(iterTokens) == '.':
897 break
898 break
898 except StopIteration:
899 except StopIteration:
899 break
900 break
900
901
901 # Find all named arguments already assigned to, as to avoid suggesting
902 # Find all named arguments already assigned to, as to avoid suggesting
902 # them again
903 # them again
903 usedNamedArgs = set()
904 usedNamedArgs = set()
904 par_level = -1
905 par_level = -1
905 for token, next_token in zip(tokens, tokens[1:]):
906 for token, next_token in zip(tokens, tokens[1:]):
906 if token == '(':
907 if token == '(':
907 par_level += 1
908 par_level += 1
908 elif token == ')':
909 elif token == ')':
909 par_level -= 1
910 par_level -= 1
910
911
911 if par_level != 0:
912 if par_level != 0:
912 continue
913 continue
913
914
914 if next_token != '=':
915 if next_token != '=':
915 continue
916 continue
916
917
917 usedNamedArgs.add(token)
918 usedNamedArgs.add(token)
918
919
919 # lookup the candidate callable matches either using global_matches
920 # lookup the candidate callable matches either using global_matches
920 # or attr_matches for dotted names
921 # or attr_matches for dotted names
921 if len(ids) == 1:
922 if len(ids) == 1:
922 callableMatches = self.global_matches(ids[0])
923 callableMatches = self.global_matches(ids[0])
923 else:
924 else:
924 callableMatches = self.attr_matches('.'.join(ids[::-1]))
925 callableMatches = self.attr_matches('.'.join(ids[::-1]))
925 argMatches = []
926 argMatches = []
926 for callableMatch in callableMatches:
927 for callableMatch in callableMatches:
927 try:
928 try:
928 namedArgs = self._default_arguments(eval(callableMatch,
929 namedArgs = self._default_arguments(eval(callableMatch,
929 self.namespace))
930 self.namespace))
930 except:
931 except:
931 continue
932 continue
932
933
933 # Remove used named arguments from the list, no need to show twice
934 # Remove used named arguments from the list, no need to show twice
934 for namedArg in set(namedArgs) - usedNamedArgs:
935 for namedArg in set(namedArgs) - usedNamedArgs:
935 if namedArg.startswith(text):
936 if namedArg.startswith(text):
936 argMatches.append(u"%s=" %namedArg)
937 argMatches.append(u"%s=" %namedArg)
937 return argMatches
938 return argMatches
938
939
939 def dict_key_matches(self, text):
940 def dict_key_matches(self, text):
940 "Match string keys in a dictionary, after e.g. 'foo[' "
941 "Match string keys in a dictionary, after e.g. 'foo[' "
941 def get_keys(obj):
942 def get_keys(obj):
942 # Objects can define their own completions by defining an
943 # Objects can define their own completions by defining an
943 # _ipy_key_completions_() method.
944 # _ipy_key_completions_() method.
944 method = get_real_method(obj, '_ipython_key_completions_')
945 method = get_real_method(obj, '_ipython_key_completions_')
945 if method is not None:
946 if method is not None:
946 return method()
947 return method()
947
948
948 # Special case some common in-memory dict-like types
949 # Special case some common in-memory dict-like types
949 if isinstance(obj, dict) or\
950 if isinstance(obj, dict) or\
950 _safe_isinstance(obj, 'pandas', 'DataFrame'):
951 _safe_isinstance(obj, 'pandas', 'DataFrame'):
951 try:
952 try:
952 return list(obj.keys())
953 return list(obj.keys())
953 except Exception:
954 except Exception:
954 return []
955 return []
955 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
956 elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
956 _safe_isinstance(obj, 'numpy', 'void'):
957 _safe_isinstance(obj, 'numpy', 'void'):
957 return obj.dtype.names or []
958 return obj.dtype.names or []
958 return []
959 return []
959
960
960 try:
961 try:
961 regexps = self.__dict_key_regexps
962 regexps = self.__dict_key_regexps
962 except AttributeError:
963 except AttributeError:
963 dict_key_re_fmt = r'''(?x)
964 dict_key_re_fmt = r'''(?x)
964 ( # match dict-referring expression wrt greedy setting
965 ( # match dict-referring expression wrt greedy setting
965 %s
966 %s
966 )
967 )
967 \[ # open bracket
968 \[ # open bracket
968 \s* # and optional whitespace
969 \s* # and optional whitespace
969 ([uUbB]? # string prefix (r not handled)
970 ([uUbB]? # string prefix (r not handled)
970 (?: # unclosed string
971 (?: # unclosed string
971 '(?:[^']|(?<!\\)\\')*
972 '(?:[^']|(?<!\\)\\')*
972 |
973 |
973 "(?:[^"]|(?<!\\)\\")*
974 "(?:[^"]|(?<!\\)\\")*
974 )
975 )
975 )?
976 )?
976 $
977 $
977 '''
978 '''
978 regexps = self.__dict_key_regexps = {
979 regexps = self.__dict_key_regexps = {
979 False: re.compile(dict_key_re_fmt % '''
980 False: re.compile(dict_key_re_fmt % '''
980 # identifiers separated by .
981 # identifiers separated by .
981 (?!\d)\w+
982 (?!\d)\w+
982 (?:\.(?!\d)\w+)*
983 (?:\.(?!\d)\w+)*
983 '''),
984 '''),
984 True: re.compile(dict_key_re_fmt % '''
985 True: re.compile(dict_key_re_fmt % '''
985 .+
986 .+
986 ''')
987 ''')
987 }
988 }
988
989
989 match = regexps[self.greedy].search(self.text_until_cursor)
990 match = regexps[self.greedy].search(self.text_until_cursor)
990 if match is None:
991 if match is None:
991 return []
992 return []
992
993
993 expr, prefix = match.groups()
994 expr, prefix = match.groups()
994 try:
995 try:
995 obj = eval(expr, self.namespace)
996 obj = eval(expr, self.namespace)
996 except Exception:
997 except Exception:
997 try:
998 try:
998 obj = eval(expr, self.global_namespace)
999 obj = eval(expr, self.global_namespace)
999 except Exception:
1000 except Exception:
1000 return []
1001 return []
1001
1002
1002 keys = get_keys(obj)
1003 keys = get_keys(obj)
1003 if not keys:
1004 if not keys:
1004 return keys
1005 return keys
1005 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
1006 closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
1006 if not matches:
1007 if not matches:
1007 return matches
1008 return matches
1008
1009
1009 # get the cursor position of
1010 # get the cursor position of
1010 # - the text being completed
1011 # - the text being completed
1011 # - the start of the key text
1012 # - the start of the key text
1012 # - the start of the completion
1013 # - the start of the completion
1013 text_start = len(self.text_until_cursor) - len(text)
1014 text_start = len(self.text_until_cursor) - len(text)
1014 if prefix:
1015 if prefix:
1015 key_start = match.start(2)
1016 key_start = match.start(2)
1016 completion_start = key_start + token_offset
1017 completion_start = key_start + token_offset
1017 else:
1018 else:
1018 key_start = completion_start = match.end()
1019 key_start = completion_start = match.end()
1019
1020
1020 # grab the leading prefix, to make sure all completions start with `text`
1021 # grab the leading prefix, to make sure all completions start with `text`
1021 if text_start > key_start:
1022 if text_start > key_start:
1022 leading = ''
1023 leading = ''
1023 else:
1024 else:
1024 leading = text[text_start:completion_start]
1025 leading = text[text_start:completion_start]
1025
1026
1026 # the index of the `[` character
1027 # the index of the `[` character
1027 bracket_idx = match.end(1)
1028 bracket_idx = match.end(1)
1028
1029
1029 # append closing quote and bracket as appropriate
1030 # append closing quote and bracket as appropriate
1030 # this is *not* appropriate if the opening quote or bracket is outside
1031 # this is *not* appropriate if the opening quote or bracket is outside
1031 # the text given to this method
1032 # the text given to this method
1032 suf = ''
1033 suf = ''
1033 continuation = self.line_buffer[len(self.text_until_cursor):]
1034 continuation = self.line_buffer[len(self.text_until_cursor):]
1034 if key_start > text_start and closing_quote:
1035 if key_start > text_start and closing_quote:
1035 # quotes were opened inside text, maybe close them
1036 # quotes were opened inside text, maybe close them
1036 if continuation.startswith(closing_quote):
1037 if continuation.startswith(closing_quote):
1037 continuation = continuation[len(closing_quote):]
1038 continuation = continuation[len(closing_quote):]
1038 else:
1039 else:
1039 suf += closing_quote
1040 suf += closing_quote
1040 if bracket_idx > text_start:
1041 if bracket_idx > text_start:
1041 # brackets were opened inside text, maybe close them
1042 # brackets were opened inside text, maybe close them
1042 if not continuation.startswith(']'):
1043 if not continuation.startswith(']'):
1043 suf += ']'
1044 suf += ']'
1044
1045
1045 return [leading + k + suf for k in matches]
1046 return [leading + k + suf for k in matches]
1046
1047
1047 def unicode_name_matches(self, text):
1048 def unicode_name_matches(self, text):
1048 u"""Match Latex-like syntax for unicode characters base
1049 u"""Match Latex-like syntax for unicode characters base
1049 on the name of the character.
1050 on the name of the character.
1050
1051
1051 This does \\GREEK SMALL LETTER ETA -> Ξ·
1052 This does \\GREEK SMALL LETTER ETA -> Ξ·
1052
1053
1053 Works only on valid python 3 identifier, or on combining characters that
1054 Works only on valid python 3 identifier, or on combining characters that
1054 will combine to form a valid identifier.
1055 will combine to form a valid identifier.
1055
1056
1056 Used on Python 3 only.
1057 Used on Python 3 only.
1057 """
1058 """
1058 slashpos = text.rfind('\\')
1059 slashpos = text.rfind('\\')
1059 if slashpos > -1:
1060 if slashpos > -1:
1060 s = text[slashpos+1:]
1061 s = text[slashpos+1:]
1061 try :
1062 try :
1062 unic = unicodedata.lookup(s)
1063 unic = unicodedata.lookup(s)
1063 # allow combining chars
1064 # allow combining chars
1064 if ('a'+unic).isidentifier():
1065 if ('a'+unic).isidentifier():
1065 return '\\'+s,[unic]
1066 return '\\'+s,[unic]
1066 except KeyError:
1067 except KeyError:
1067 pass
1068 pass
1068 return u'', []
1069 return u'', []
1069
1070
1070
1071
1071
1072
1072
1073
1073 def latex_matches(self, text):
1074 def latex_matches(self, text):
1074 u"""Match Latex syntax for unicode characters.
1075 u"""Match Latex syntax for unicode characters.
1075
1076
1076 This does both \\alp -> \\alpha and \\alpha -> Ξ±
1077 This does both \\alp -> \\alpha and \\alpha -> Ξ±
1077
1078
1078 Used on Python 3 only.
1079 Used on Python 3 only.
1079 """
1080 """
1080 slashpos = text.rfind('\\')
1081 slashpos = text.rfind('\\')
1081 if slashpos > -1:
1082 if slashpos > -1:
1082 s = text[slashpos:]
1083 s = text[slashpos:]
1083 if s in latex_symbols:
1084 if s in latex_symbols:
1084 # Try to complete a full latex symbol to unicode
1085 # Try to complete a full latex symbol to unicode
1085 # \\alpha -> Ξ±
1086 # \\alpha -> Ξ±
1086 return s, [latex_symbols[s]]
1087 return s, [latex_symbols[s]]
1087 else:
1088 else:
1088 # If a user has partially typed a latex symbol, give them
1089 # If a user has partially typed a latex symbol, give them
1089 # a full list of options \al -> [\aleph, \alpha]
1090 # a full list of options \al -> [\aleph, \alpha]
1090 matches = [k for k in latex_symbols if k.startswith(s)]
1091 matches = [k for k in latex_symbols if k.startswith(s)]
1091 return s, matches
1092 return s, matches
1092 return u'', []
1093 return u'', []
1093
1094
1094 def dispatch_custom_completer(self, text):
1095 def dispatch_custom_completer(self, text):
1095 if not self.custom_completers:
1096 if not self.custom_completers:
1096 return
1097 return
1097
1098
1098 line = self.line_buffer
1099 line = self.line_buffer
1099 if not line.strip():
1100 if not line.strip():
1100 return None
1101 return None
1101
1102
1102 # Create a little structure to pass all the relevant information about
1103 # Create a little structure to pass all the relevant information about
1103 # the current completion to any custom completer.
1104 # the current completion to any custom completer.
1104 event = Bunch()
1105 event = Bunch()
1105 event.line = line
1106 event.line = line
1106 event.symbol = text
1107 event.symbol = text
1107 cmd = line.split(None,1)[0]
1108 cmd = line.split(None,1)[0]
1108 event.command = cmd
1109 event.command = cmd
1109 event.text_until_cursor = self.text_until_cursor
1110 event.text_until_cursor = self.text_until_cursor
1110
1111
1111 # for foo etc, try also to find completer for %foo
1112 # for foo etc, try also to find completer for %foo
1112 if not cmd.startswith(self.magic_escape):
1113 if not cmd.startswith(self.magic_escape):
1113 try_magic = self.custom_completers.s_matches(
1114 try_magic = self.custom_completers.s_matches(
1114 self.magic_escape + cmd)
1115 self.magic_escape + cmd)
1115 else:
1116 else:
1116 try_magic = []
1117 try_magic = []
1117
1118
1118 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1119 for c in itertools.chain(self.custom_completers.s_matches(cmd),
1119 try_magic,
1120 try_magic,
1120 self.custom_completers.flat_matches(self.text_until_cursor)):
1121 self.custom_completers.flat_matches(self.text_until_cursor)):
1121 try:
1122 try:
1122 res = c(event)
1123 res = c(event)
1123 if res:
1124 if res:
1124 # first, try case sensitive match
1125 # first, try case sensitive match
1125 withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
1126 withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
1126 if withcase:
1127 if withcase:
1127 return withcase
1128 return withcase
1128 # if none, then case insensitive ones are ok too
1129 # if none, then case insensitive ones are ok too
1129 text_low = text.lower()
1130 text_low = text.lower()
1130 return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
1131 return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
1131 except TryNext:
1132 except TryNext:
1132 pass
1133 pass
1133
1134
1134 return None
1135 return None
1135
1136
1136 @_strip_single_trailing_space
1137 @_strip_single_trailing_space
1137 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1138 def complete(self, text=None, line_buffer=None, cursor_pos=None):
1138 """Find completions for the given text and line context.
1139 """Find completions for the given text and line context.
1139
1140
1140 Note that both the text and the line_buffer are optional, but at least
1141 Note that both the text and the line_buffer are optional, but at least
1141 one of them must be given.
1142 one of them must be given.
1142
1143
1143 Parameters
1144 Parameters
1144 ----------
1145 ----------
1145 text : string, optional
1146 text : string, optional
1146 Text to perform the completion on. If not given, the line buffer
1147 Text to perform the completion on. If not given, the line buffer
1147 is split using the instance's CompletionSplitter object.
1148 is split using the instance's CompletionSplitter object.
1148
1149
1149 line_buffer : string, optional
1150 line_buffer : string, optional
1150 If not given, the completer attempts to obtain the current line
1151 If not given, the completer attempts to obtain the current line
1151 buffer via readline. This keyword allows clients which are
1152 buffer via readline. This keyword allows clients which are
1152 requesting for text completions in non-readline contexts to inform
1153 requesting for text completions in non-readline contexts to inform
1153 the completer of the entire text.
1154 the completer of the entire text.
1154
1155
1155 cursor_pos : int, optional
1156 cursor_pos : int, optional
1156 Index of the cursor in the full line buffer. Should be provided by
1157 Index of the cursor in the full line buffer. Should be provided by
1157 remote frontends where kernel has no access to frontend state.
1158 remote frontends where kernel has no access to frontend state.
1158
1159
1159 Returns
1160 Returns
1160 -------
1161 -------
1161 text : str
1162 text : str
1162 Text that was actually used in the completion.
1163 Text that was actually used in the completion.
1163
1164
1164 matches : list
1165 matches : list
1165 A list of completion matches.
1166 A list of completion matches.
1166 """
1167 """
1167 # if the cursor position isn't given, the only sane assumption we can
1168 # if the cursor position isn't given, the only sane assumption we can
1168 # make is that it's at the end of the line (the common case)
1169 # make is that it's at the end of the line (the common case)
1169 if cursor_pos is None:
1170 if cursor_pos is None:
1170 cursor_pos = len(line_buffer) if text is None else len(text)
1171 cursor_pos = len(line_buffer) if text is None else len(text)
1171
1172
1172 if self.use_main_ns:
1173 if self.use_main_ns:
1173 self.namespace = __main__.__dict__
1174 self.namespace = __main__.__dict__
1174
1175
1175 base_text = text if not line_buffer else line_buffer[:cursor_pos]
1176 base_text = text if not line_buffer else line_buffer[:cursor_pos]
1176 latex_text, latex_matches = self.latex_matches(base_text)
1177 latex_text, latex_matches = self.latex_matches(base_text)
1177 if latex_matches:
1178 if latex_matches:
1178 return latex_text, latex_matches
1179 return latex_text, latex_matches
1179 name_text = ''
1180 name_text = ''
1180 name_matches = []
1181 name_matches = []
1181 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
1182 for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
1182 name_text, name_matches = meth(base_text)
1183 name_text, name_matches = meth(base_text)
1183 if name_text:
1184 if name_text:
1184 return name_text, name_matches
1185 return name_text, name_matches
1185
1186
1186 # if text is either None or an empty string, rely on the line buffer
1187 # if text is either None or an empty string, rely on the line buffer
1187 if not text:
1188 if not text:
1188 text = self.splitter.split_line(line_buffer, cursor_pos)
1189 text = self.splitter.split_line(line_buffer, cursor_pos)
1189
1190
1190 # If no line buffer is given, assume the input text is all there was
1191 # If no line buffer is given, assume the input text is all there was
1191 if line_buffer is None:
1192 if line_buffer is None:
1192 line_buffer = text
1193 line_buffer = text
1193
1194
1194 self.line_buffer = line_buffer
1195 self.line_buffer = line_buffer
1195 self.text_until_cursor = self.line_buffer[:cursor_pos]
1196 self.text_until_cursor = self.line_buffer[:cursor_pos]
1196
1197
1197 # Start with a clean slate of completions
1198 # Start with a clean slate of completions
1198 self.matches[:] = []
1199 self.matches[:] = []
1199 custom_res = self.dispatch_custom_completer(text)
1200 custom_res = self.dispatch_custom_completer(text)
1200 if custom_res is not None:
1201 if custom_res is not None:
1201 # did custom completers produce something?
1202 # did custom completers produce something?
1202 self.matches = custom_res
1203 self.matches = custom_res
1203 else:
1204 else:
1204 # Extend the list of completions with the results of each
1205 # Extend the list of completions with the results of each
1205 # matcher, so we return results to the user from all
1206 # matcher, so we return results to the user from all
1206 # namespaces.
1207 # namespaces.
1207 if self.merge_completions:
1208 if self.merge_completions:
1208 self.matches = []
1209 self.matches = []
1209 for matcher in self.matchers:
1210 for matcher in self.matchers:
1210 try:
1211 try:
1211 self.matches.extend(matcher(text))
1212 self.matches.extend(matcher(text))
1212 except:
1213 except:
1213 # Show the ugly traceback if the matcher causes an
1214 # Show the ugly traceback if the matcher causes an
1214 # exception, but do NOT crash the kernel!
1215 # exception, but do NOT crash the kernel!
1215 sys.excepthook(*sys.exc_info())
1216 sys.excepthook(*sys.exc_info())
1216 else:
1217 else:
1217 for matcher in self.matchers:
1218 for matcher in self.matchers:
1218 self.matches = matcher(text)
1219 self.matches = matcher(text)
1219 if self.matches:
1220 if self.matches:
1220 break
1221 break
1221 # FIXME: we should extend our api to return a dict with completions for
1222 # FIXME: we should extend our api to return a dict with completions for
1222 # different types of objects. The rlcomplete() method could then
1223 # different types of objects. The rlcomplete() method could then
1223 # simply collapse the dict into a list for readline, but we'd have
1224 # simply collapse the dict into a list for readline, but we'd have
1224 # richer completion semantics in other evironments.
1225 # richer completion semantics in other evironments.
1225 self.matches = sorted(set(self.matches), key=completions_sorting_key)
1226 self.matches = sorted(set(self.matches), key=completions_sorting_key)
1226
1227
1227 return text, self.matches
1228 return text, self.matches
@@ -1,321 +1,321 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Displayhook for IPython.
2 """Displayhook for IPython.
3
3
4 This defines a callable class that IPython uses for `sys.displayhook`.
4 This defines a callable class that IPython uses for `sys.displayhook`.
5 """
5 """
6
6
7 # Copyright (c) IPython Development Team.
7 # Copyright (c) IPython Development Team.
8 # Distributed under the terms of the Modified BSD License.
8 # Distributed under the terms of the Modified BSD License.
9
9
10
10 import builtins as builtin_mod
11 import sys
11 import sys
12 import io as _io
12 import io as _io
13 import tokenize
13 import tokenize
14
14
15 from traitlets.config.configurable import Configurable
15 from traitlets.config.configurable import Configurable
16 from IPython.utils.py3compat import builtin_mod, cast_unicode_py2
16 from IPython.utils.py3compat import cast_unicode_py2
17 from traitlets import Instance, Float
17 from traitlets import Instance, Float
18 from warnings import warn
18 from warnings import warn
19
19
20 # TODO: Move the various attributes (cache_size, [others now moved]). Some
20 # TODO: Move the various attributes (cache_size, [others now moved]). Some
21 # of these are also attributes of InteractiveShell. They should be on ONE object
21 # of these are also attributes of InteractiveShell. They should be on ONE object
22 # only and the other objects should ask that one object for their values.
22 # only and the other objects should ask that one object for their values.
23
23
24 class DisplayHook(Configurable):
24 class DisplayHook(Configurable):
25 """The custom IPython displayhook to replace sys.displayhook.
25 """The custom IPython displayhook to replace sys.displayhook.
26
26
27 This class does many things, but the basic idea is that it is a callable
27 This class does many things, but the basic idea is that it is a callable
28 that gets called anytime user code returns a value.
28 that gets called anytime user code returns a value.
29 """
29 """
30
30
31 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
31 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
32 allow_none=True)
32 allow_none=True)
33 exec_result = Instance('IPython.core.interactiveshell.ExecutionResult',
33 exec_result = Instance('IPython.core.interactiveshell.ExecutionResult',
34 allow_none=True)
34 allow_none=True)
35 cull_fraction = Float(0.2)
35 cull_fraction = Float(0.2)
36
36
37 def __init__(self, shell=None, cache_size=1000, **kwargs):
37 def __init__(self, shell=None, cache_size=1000, **kwargs):
38 super(DisplayHook, self).__init__(shell=shell, **kwargs)
38 super(DisplayHook, self).__init__(shell=shell, **kwargs)
39 cache_size_min = 3
39 cache_size_min = 3
40 if cache_size <= 0:
40 if cache_size <= 0:
41 self.do_full_cache = 0
41 self.do_full_cache = 0
42 cache_size = 0
42 cache_size = 0
43 elif cache_size < cache_size_min:
43 elif cache_size < cache_size_min:
44 self.do_full_cache = 0
44 self.do_full_cache = 0
45 cache_size = 0
45 cache_size = 0
46 warn('caching was disabled (min value for cache size is %s).' %
46 warn('caching was disabled (min value for cache size is %s).' %
47 cache_size_min,stacklevel=3)
47 cache_size_min,stacklevel=3)
48 else:
48 else:
49 self.do_full_cache = 1
49 self.do_full_cache = 1
50
50
51 self.cache_size = cache_size
51 self.cache_size = cache_size
52
52
53 # we need a reference to the user-level namespace
53 # we need a reference to the user-level namespace
54 self.shell = shell
54 self.shell = shell
55
55
56 self._,self.__,self.___ = '','',''
56 self._,self.__,self.___ = '','',''
57
57
58 # these are deliberately global:
58 # these are deliberately global:
59 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
59 to_user_ns = {'_':self._,'__':self.__,'___':self.___}
60 self.shell.user_ns.update(to_user_ns)
60 self.shell.user_ns.update(to_user_ns)
61
61
62 @property
62 @property
63 def prompt_count(self):
63 def prompt_count(self):
64 return self.shell.execution_count
64 return self.shell.execution_count
65
65
66 #-------------------------------------------------------------------------
66 #-------------------------------------------------------------------------
67 # Methods used in __call__. Override these methods to modify the behavior
67 # Methods used in __call__. Override these methods to modify the behavior
68 # of the displayhook.
68 # of the displayhook.
69 #-------------------------------------------------------------------------
69 #-------------------------------------------------------------------------
70
70
71 def check_for_underscore(self):
71 def check_for_underscore(self):
72 """Check if the user has set the '_' variable by hand."""
72 """Check if the user has set the '_' variable by hand."""
73 # If something injected a '_' variable in __builtin__, delete
73 # If something injected a '_' variable in __builtin__, delete
74 # ipython's automatic one so we don't clobber that. gettext() in
74 # ipython's automatic one so we don't clobber that. gettext() in
75 # particular uses _, so we need to stay away from it.
75 # particular uses _, so we need to stay away from it.
76 if '_' in builtin_mod.__dict__:
76 if '_' in builtin_mod.__dict__:
77 try:
77 try:
78 user_value = self.shell.user_ns['_']
78 user_value = self.shell.user_ns['_']
79 if user_value is not self._:
79 if user_value is not self._:
80 return
80 return
81 del self.shell.user_ns['_']
81 del self.shell.user_ns['_']
82 except KeyError:
82 except KeyError:
83 pass
83 pass
84
84
85 def quiet(self):
85 def quiet(self):
86 """Should we silence the display hook because of ';'?"""
86 """Should we silence the display hook because of ';'?"""
87 # do not print output if input ends in ';'
87 # do not print output if input ends in ';'
88
88
89 try:
89 try:
90 cell = cast_unicode_py2(self.shell.history_manager.input_hist_parsed[-1])
90 cell = cast_unicode_py2(self.shell.history_manager.input_hist_parsed[-1])
91 except IndexError:
91 except IndexError:
92 # some uses of ipshellembed may fail here
92 # some uses of ipshellembed may fail here
93 return False
93 return False
94
94
95 sio = _io.StringIO(cell)
95 sio = _io.StringIO(cell)
96 tokens = list(tokenize.generate_tokens(sio.readline))
96 tokens = list(tokenize.generate_tokens(sio.readline))
97
97
98 for token in reversed(tokens):
98 for token in reversed(tokens):
99 if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT):
99 if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT):
100 continue
100 continue
101 if (token[0] == tokenize.OP) and (token[1] == ';'):
101 if (token[0] == tokenize.OP) and (token[1] == ';'):
102 return True
102 return True
103 else:
103 else:
104 return False
104 return False
105
105
106 def start_displayhook(self):
106 def start_displayhook(self):
107 """Start the displayhook, initializing resources."""
107 """Start the displayhook, initializing resources."""
108 pass
108 pass
109
109
110 def write_output_prompt(self):
110 def write_output_prompt(self):
111 """Write the output prompt.
111 """Write the output prompt.
112
112
113 The default implementation simply writes the prompt to
113 The default implementation simply writes the prompt to
114 ``sys.stdout``.
114 ``sys.stdout``.
115 """
115 """
116 # Use write, not print which adds an extra space.
116 # Use write, not print which adds an extra space.
117 sys.stdout.write(self.shell.separate_out)
117 sys.stdout.write(self.shell.separate_out)
118 outprompt = 'Out[{}]: '.format(self.shell.execution_count)
118 outprompt = 'Out[{}]: '.format(self.shell.execution_count)
119 if self.do_full_cache:
119 if self.do_full_cache:
120 sys.stdout.write(outprompt)
120 sys.stdout.write(outprompt)
121
121
122 def compute_format_data(self, result):
122 def compute_format_data(self, result):
123 """Compute format data of the object to be displayed.
123 """Compute format data of the object to be displayed.
124
124
125 The format data is a generalization of the :func:`repr` of an object.
125 The format data is a generalization of the :func:`repr` of an object.
126 In the default implementation the format data is a :class:`dict` of
126 In the default implementation the format data is a :class:`dict` of
127 key value pair where the keys are valid MIME types and the values
127 key value pair where the keys are valid MIME types and the values
128 are JSON'able data structure containing the raw data for that MIME
128 are JSON'able data structure containing the raw data for that MIME
129 type. It is up to frontends to determine pick a MIME to to use and
129 type. It is up to frontends to determine pick a MIME to to use and
130 display that data in an appropriate manner.
130 display that data in an appropriate manner.
131
131
132 This method only computes the format data for the object and should
132 This method only computes the format data for the object and should
133 NOT actually print or write that to a stream.
133 NOT actually print or write that to a stream.
134
134
135 Parameters
135 Parameters
136 ----------
136 ----------
137 result : object
137 result : object
138 The Python object passed to the display hook, whose format will be
138 The Python object passed to the display hook, whose format will be
139 computed.
139 computed.
140
140
141 Returns
141 Returns
142 -------
142 -------
143 (format_dict, md_dict) : dict
143 (format_dict, md_dict) : dict
144 format_dict is a :class:`dict` whose keys are valid MIME types and values are
144 format_dict is a :class:`dict` whose keys are valid MIME types and values are
145 JSON'able raw data for that MIME type. It is recommended that
145 JSON'able raw data for that MIME type. It is recommended that
146 all return values of this should always include the "text/plain"
146 all return values of this should always include the "text/plain"
147 MIME type representation of the object.
147 MIME type representation of the object.
148 md_dict is a :class:`dict` with the same MIME type keys
148 md_dict is a :class:`dict` with the same MIME type keys
149 of metadata associated with each output.
149 of metadata associated with each output.
150
150
151 """
151 """
152 return self.shell.display_formatter.format(result)
152 return self.shell.display_formatter.format(result)
153
153
154 # This can be set to True by the write_output_prompt method in a subclass
154 # This can be set to True by the write_output_prompt method in a subclass
155 prompt_end_newline = False
155 prompt_end_newline = False
156
156
157 def write_format_data(self, format_dict, md_dict=None):
157 def write_format_data(self, format_dict, md_dict=None):
158 """Write the format data dict to the frontend.
158 """Write the format data dict to the frontend.
159
159
160 This default version of this method simply writes the plain text
160 This default version of this method simply writes the plain text
161 representation of the object to ``sys.stdout``. Subclasses should
161 representation of the object to ``sys.stdout``. Subclasses should
162 override this method to send the entire `format_dict` to the
162 override this method to send the entire `format_dict` to the
163 frontends.
163 frontends.
164
164
165 Parameters
165 Parameters
166 ----------
166 ----------
167 format_dict : dict
167 format_dict : dict
168 The format dict for the object passed to `sys.displayhook`.
168 The format dict for the object passed to `sys.displayhook`.
169 md_dict : dict (optional)
169 md_dict : dict (optional)
170 The metadata dict to be associated with the display data.
170 The metadata dict to be associated with the display data.
171 """
171 """
172 if 'text/plain' not in format_dict:
172 if 'text/plain' not in format_dict:
173 # nothing to do
173 # nothing to do
174 return
174 return
175 # We want to print because we want to always make sure we have a
175 # We want to print because we want to always make sure we have a
176 # newline, even if all the prompt separators are ''. This is the
176 # newline, even if all the prompt separators are ''. This is the
177 # standard IPython behavior.
177 # standard IPython behavior.
178 result_repr = format_dict['text/plain']
178 result_repr = format_dict['text/plain']
179 if '\n' in result_repr:
179 if '\n' in result_repr:
180 # So that multi-line strings line up with the left column of
180 # So that multi-line strings line up with the left column of
181 # the screen, instead of having the output prompt mess up
181 # the screen, instead of having the output prompt mess up
182 # their first line.
182 # their first line.
183 # We use the prompt template instead of the expanded prompt
183 # We use the prompt template instead of the expanded prompt
184 # because the expansion may add ANSI escapes that will interfere
184 # because the expansion may add ANSI escapes that will interfere
185 # with our ability to determine whether or not we should add
185 # with our ability to determine whether or not we should add
186 # a newline.
186 # a newline.
187 if not self.prompt_end_newline:
187 if not self.prompt_end_newline:
188 # But avoid extraneous empty lines.
188 # But avoid extraneous empty lines.
189 result_repr = '\n' + result_repr
189 result_repr = '\n' + result_repr
190
190
191 print(result_repr)
191 print(result_repr)
192
192
193 def update_user_ns(self, result):
193 def update_user_ns(self, result):
194 """Update user_ns with various things like _, __, _1, etc."""
194 """Update user_ns with various things like _, __, _1, etc."""
195
195
196 # Avoid recursive reference when displaying _oh/Out
196 # Avoid recursive reference when displaying _oh/Out
197 if result is not self.shell.user_ns['_oh']:
197 if result is not self.shell.user_ns['_oh']:
198 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
198 if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache:
199 self.cull_cache()
199 self.cull_cache()
200
200
201 # Don't overwrite '_' and friends if '_' is in __builtin__
201 # Don't overwrite '_' and friends if '_' is in __builtin__
202 # (otherwise we cause buggy behavior for things like gettext). and
202 # (otherwise we cause buggy behavior for things like gettext). and
203 # do not overwrite _, __ or ___ if one of these has been assigned
203 # do not overwrite _, __ or ___ if one of these has been assigned
204 # by the user.
204 # by the user.
205 update_unders = True
205 update_unders = True
206 for unders in ['_'*i for i in range(1,4)]:
206 for unders in ['_'*i for i in range(1,4)]:
207 if not unders in self.shell.user_ns:
207 if not unders in self.shell.user_ns:
208 continue
208 continue
209 if getattr(self, unders) is not self.shell.user_ns.get(unders):
209 if getattr(self, unders) is not self.shell.user_ns.get(unders):
210 update_unders = False
210 update_unders = False
211
211
212 self.___ = self.__
212 self.___ = self.__
213 self.__ = self._
213 self.__ = self._
214 self._ = result
214 self._ = result
215
215
216 if ('_' not in builtin_mod.__dict__) and (update_unders):
216 if ('_' not in builtin_mod.__dict__) and (update_unders):
217 self.shell.push({'_':self._,
217 self.shell.push({'_':self._,
218 '__':self.__,
218 '__':self.__,
219 '___':self.___}, interactive=False)
219 '___':self.___}, interactive=False)
220
220
221 # hackish access to top-level namespace to create _1,_2... dynamically
221 # hackish access to top-level namespace to create _1,_2... dynamically
222 to_main = {}
222 to_main = {}
223 if self.do_full_cache:
223 if self.do_full_cache:
224 new_result = '_%s' % self.prompt_count
224 new_result = '_%s' % self.prompt_count
225 to_main[new_result] = result
225 to_main[new_result] = result
226 self.shell.push(to_main, interactive=False)
226 self.shell.push(to_main, interactive=False)
227 self.shell.user_ns['_oh'][self.prompt_count] = result
227 self.shell.user_ns['_oh'][self.prompt_count] = result
228
228
229 def fill_exec_result(self, result):
229 def fill_exec_result(self, result):
230 if self.exec_result is not None:
230 if self.exec_result is not None:
231 self.exec_result.result = result
231 self.exec_result.result = result
232
232
233 def log_output(self, format_dict):
233 def log_output(self, format_dict):
234 """Log the output."""
234 """Log the output."""
235 if 'text/plain' not in format_dict:
235 if 'text/plain' not in format_dict:
236 # nothing to do
236 # nothing to do
237 return
237 return
238 if self.shell.logger.log_output:
238 if self.shell.logger.log_output:
239 self.shell.logger.log_write(format_dict['text/plain'], 'output')
239 self.shell.logger.log_write(format_dict['text/plain'], 'output')
240 self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
240 self.shell.history_manager.output_hist_reprs[self.prompt_count] = \
241 format_dict['text/plain']
241 format_dict['text/plain']
242
242
243 def finish_displayhook(self):
243 def finish_displayhook(self):
244 """Finish up all displayhook activities."""
244 """Finish up all displayhook activities."""
245 sys.stdout.write(self.shell.separate_out2)
245 sys.stdout.write(self.shell.separate_out2)
246 sys.stdout.flush()
246 sys.stdout.flush()
247
247
248 def __call__(self, result=None):
248 def __call__(self, result=None):
249 """Printing with history cache management.
249 """Printing with history cache management.
250
250
251 This is invoked everytime the interpreter needs to print, and is
251 This is invoked everytime the interpreter needs to print, and is
252 activated by setting the variable sys.displayhook to it.
252 activated by setting the variable sys.displayhook to it.
253 """
253 """
254 self.check_for_underscore()
254 self.check_for_underscore()
255 if result is not None and not self.quiet():
255 if result is not None and not self.quiet():
256 self.start_displayhook()
256 self.start_displayhook()
257 self.write_output_prompt()
257 self.write_output_prompt()
258 format_dict, md_dict = self.compute_format_data(result)
258 format_dict, md_dict = self.compute_format_data(result)
259 self.update_user_ns(result)
259 self.update_user_ns(result)
260 self.fill_exec_result(result)
260 self.fill_exec_result(result)
261 if format_dict:
261 if format_dict:
262 self.write_format_data(format_dict, md_dict)
262 self.write_format_data(format_dict, md_dict)
263 self.log_output(format_dict)
263 self.log_output(format_dict)
264 self.finish_displayhook()
264 self.finish_displayhook()
265
265
266 def cull_cache(self):
266 def cull_cache(self):
267 """Output cache is full, cull the oldest entries"""
267 """Output cache is full, cull the oldest entries"""
268 oh = self.shell.user_ns.get('_oh', {})
268 oh = self.shell.user_ns.get('_oh', {})
269 sz = len(oh)
269 sz = len(oh)
270 cull_count = max(int(sz * self.cull_fraction), 2)
270 cull_count = max(int(sz * self.cull_fraction), 2)
271 warn('Output cache limit (currently {sz} entries) hit.\n'
271 warn('Output cache limit (currently {sz} entries) hit.\n'
272 'Flushing oldest {cull_count} entries.'.format(sz=sz, cull_count=cull_count))
272 'Flushing oldest {cull_count} entries.'.format(sz=sz, cull_count=cull_count))
273
273
274 for i, n in enumerate(sorted(oh)):
274 for i, n in enumerate(sorted(oh)):
275 if i >= cull_count:
275 if i >= cull_count:
276 break
276 break
277 self.shell.user_ns.pop('_%i' % n, None)
277 self.shell.user_ns.pop('_%i' % n, None)
278 oh.pop(n, None)
278 oh.pop(n, None)
279
279
280
280
281 def flush(self):
281 def flush(self):
282 if not self.do_full_cache:
282 if not self.do_full_cache:
283 raise ValueError("You shouldn't have reached the cache flush "
283 raise ValueError("You shouldn't have reached the cache flush "
284 "if full caching is not enabled!")
284 "if full caching is not enabled!")
285 # delete auto-generated vars from global namespace
285 # delete auto-generated vars from global namespace
286
286
287 for n in range(1,self.prompt_count + 1):
287 for n in range(1,self.prompt_count + 1):
288 key = '_'+repr(n)
288 key = '_'+repr(n)
289 try:
289 try:
290 del self.shell.user_ns[key]
290 del self.shell.user_ns[key]
291 except: pass
291 except: pass
292 # In some embedded circumstances, the user_ns doesn't have the
292 # In some embedded circumstances, the user_ns doesn't have the
293 # '_oh' key set up.
293 # '_oh' key set up.
294 oh = self.shell.user_ns.get('_oh', None)
294 oh = self.shell.user_ns.get('_oh', None)
295 if oh is not None:
295 if oh is not None:
296 oh.clear()
296 oh.clear()
297
297
298 # Release our own references to objects:
298 # Release our own references to objects:
299 self._, self.__, self.___ = '', '', ''
299 self._, self.__, self.___ = '', '', ''
300
300
301 if '_' not in builtin_mod.__dict__:
301 if '_' not in builtin_mod.__dict__:
302 self.shell.user_ns.update({'_':None,'__':None, '___':None})
302 self.shell.user_ns.update({'_':None,'__':None, '___':None})
303 import gc
303 import gc
304 # TODO: Is this really needed?
304 # TODO: Is this really needed?
305 # IronPython blocks here forever
305 # IronPython blocks here forever
306 if sys.platform != "cli":
306 if sys.platform != "cli":
307 gc.collect()
307 gc.collect()
308
308
309
309
310 class CapturingDisplayHook(object):
310 class CapturingDisplayHook(object):
311 def __init__(self, shell, outputs=None):
311 def __init__(self, shell, outputs=None):
312 self.shell = shell
312 self.shell = shell
313 if outputs is None:
313 if outputs is None:
314 outputs = []
314 outputs = []
315 self.outputs = outputs
315 self.outputs = outputs
316
316
317 def __call__(self, result=None):
317 def __call__(self, result=None):
318 if result is None:
318 if result is None:
319 return
319 return
320 format_dict, md_dict = self.shell.display_formatter.format(result)
320 format_dict, md_dict = self.shell.display_formatter.format(result)
321 self.outputs.append((format_dict, md_dict))
321 self.outputs.append((format_dict, md_dict))
@@ -1,3212 +1,3212 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Main IPython class."""
2 """Main IPython class."""
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13
13
14 import __future__
14 import __future__
15 import abc
15 import abc
16 import ast
16 import ast
17 import atexit
17 import atexit
18 import builtins as builtin_mod
18 import functools
19 import functools
19 import os
20 import os
20 import re
21 import re
21 import runpy
22 import runpy
22 import sys
23 import sys
23 import tempfile
24 import tempfile
24 import traceback
25 import traceback
25 import types
26 import types
26 import subprocess
27 import subprocess
27 import warnings
28 import warnings
28 from io import open as io_open
29 from io import open as io_open
29
30
30 from pickleshare import PickleShareDB
31 from pickleshare import PickleShareDB
31
32
32 from traitlets.config.configurable import SingletonConfigurable
33 from traitlets.config.configurable import SingletonConfigurable
33 from IPython.core import oinspect
34 from IPython.core import oinspect
34 from IPython.core import magic
35 from IPython.core import magic
35 from IPython.core import page
36 from IPython.core import page
36 from IPython.core import prefilter
37 from IPython.core import prefilter
37 from IPython.core import shadowns
38 from IPython.core import shadowns
38 from IPython.core import ultratb
39 from IPython.core import ultratb
39 from IPython.core.alias import Alias, AliasManager
40 from IPython.core.alias import Alias, AliasManager
40 from IPython.core.autocall import ExitAutocall
41 from IPython.core.autocall import ExitAutocall
41 from IPython.core.builtin_trap import BuiltinTrap
42 from IPython.core.builtin_trap import BuiltinTrap
42 from IPython.core.events import EventManager, available_events
43 from IPython.core.events import EventManager, available_events
43 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
44 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
44 from IPython.core.debugger import Pdb
45 from IPython.core.debugger import Pdb
45 from IPython.core.display_trap import DisplayTrap
46 from IPython.core.display_trap import DisplayTrap
46 from IPython.core.displayhook import DisplayHook
47 from IPython.core.displayhook import DisplayHook
47 from IPython.core.displaypub import DisplayPublisher
48 from IPython.core.displaypub import DisplayPublisher
48 from IPython.core.error import InputRejected, UsageError
49 from IPython.core.error import InputRejected, UsageError
49 from IPython.core.extensions import ExtensionManager
50 from IPython.core.extensions import ExtensionManager
50 from IPython.core.formatters import DisplayFormatter
51 from IPython.core.formatters import DisplayFormatter
51 from IPython.core.history import HistoryManager
52 from IPython.core.history import HistoryManager
52 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
53 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
53 from IPython.core.logger import Logger
54 from IPython.core.logger import Logger
54 from IPython.core.macro import Macro
55 from IPython.core.macro import Macro
55 from IPython.core.payload import PayloadManager
56 from IPython.core.payload import PayloadManager
56 from IPython.core.prefilter import PrefilterManager
57 from IPython.core.prefilter import PrefilterManager
57 from IPython.core.profiledir import ProfileDir
58 from IPython.core.profiledir import ProfileDir
58 from IPython.core.usage import default_banner
59 from IPython.core.usage import default_banner
59 from IPython.testing.skipdoctest import skip_doctest
60 from IPython.testing.skipdoctest import skip_doctest
60 from IPython.utils import PyColorize
61 from IPython.utils import PyColorize
61 from IPython.utils import io
62 from IPython.utils import io
62 from IPython.utils import py3compat
63 from IPython.utils import py3compat
63 from IPython.utils import openpy
64 from IPython.utils import openpy
64 from IPython.utils.decorators import undoc
65 from IPython.utils.decorators import undoc
65 from IPython.utils.io import ask_yes_no
66 from IPython.utils.io import ask_yes_no
66 from IPython.utils.ipstruct import Struct
67 from IPython.utils.ipstruct import Struct
67 from IPython.paths import get_ipython_dir
68 from IPython.paths import get_ipython_dir
68 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
69 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
69 from IPython.utils.process import system, getoutput
70 from IPython.utils.process import system, getoutput
70 from IPython.utils.py3compat import builtin_mod
71 from IPython.utils.strdispatch import StrDispatch
71 from IPython.utils.strdispatch import StrDispatch
72 from IPython.utils.syspathcontext import prepended_to_syspath
72 from IPython.utils.syspathcontext import prepended_to_syspath
73 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
73 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
74 from IPython.utils.tempdir import TemporaryDirectory
74 from IPython.utils.tempdir import TemporaryDirectory
75 from traitlets import (
75 from traitlets import (
76 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
76 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
77 observe, default,
77 observe, default,
78 )
78 )
79 from warnings import warn
79 from warnings import warn
80 from logging import error
80 from logging import error
81 import IPython.core.hooks
81 import IPython.core.hooks
82
82
83 # NoOpContext is deprecated, but ipykernel imports it from here.
83 # NoOpContext is deprecated, but ipykernel imports it from here.
84 # See https://github.com/ipython/ipykernel/issues/157
84 # See https://github.com/ipython/ipykernel/issues/157
85 from IPython.utils.contexts import NoOpContext
85 from IPython.utils.contexts import NoOpContext
86
86
87 try:
87 try:
88 import docrepr.sphinxify as sphx
88 import docrepr.sphinxify as sphx
89
89
90 def sphinxify(doc):
90 def sphinxify(doc):
91 with TemporaryDirectory() as dirname:
91 with TemporaryDirectory() as dirname:
92 return {
92 return {
93 'text/html': sphx.sphinxify(doc, dirname),
93 'text/html': sphx.sphinxify(doc, dirname),
94 'text/plain': doc
94 'text/plain': doc
95 }
95 }
96 except ImportError:
96 except ImportError:
97 sphinxify = None
97 sphinxify = None
98
98
99
99
100 class ProvisionalWarning(DeprecationWarning):
100 class ProvisionalWarning(DeprecationWarning):
101 """
101 """
102 Warning class for unstable features
102 Warning class for unstable features
103 """
103 """
104 pass
104 pass
105
105
106 #-----------------------------------------------------------------------------
106 #-----------------------------------------------------------------------------
107 # Globals
107 # Globals
108 #-----------------------------------------------------------------------------
108 #-----------------------------------------------------------------------------
109
109
110 # compiled regexps for autoindent management
110 # compiled regexps for autoindent management
111 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
111 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
112
112
113 #-----------------------------------------------------------------------------
113 #-----------------------------------------------------------------------------
114 # Utilities
114 # Utilities
115 #-----------------------------------------------------------------------------
115 #-----------------------------------------------------------------------------
116
116
117 @undoc
117 @undoc
118 def softspace(file, newvalue):
118 def softspace(file, newvalue):
119 """Copied from code.py, to remove the dependency"""
119 """Copied from code.py, to remove the dependency"""
120
120
121 oldvalue = 0
121 oldvalue = 0
122 try:
122 try:
123 oldvalue = file.softspace
123 oldvalue = file.softspace
124 except AttributeError:
124 except AttributeError:
125 pass
125 pass
126 try:
126 try:
127 file.softspace = newvalue
127 file.softspace = newvalue
128 except (AttributeError, TypeError):
128 except (AttributeError, TypeError):
129 # "attribute-less object" or "read-only attributes"
129 # "attribute-less object" or "read-only attributes"
130 pass
130 pass
131 return oldvalue
131 return oldvalue
132
132
133 @undoc
133 @undoc
134 def no_op(*a, **kw): pass
134 def no_op(*a, **kw): pass
135
135
136
136
137 class SpaceInInput(Exception): pass
137 class SpaceInInput(Exception): pass
138
138
139
139
140 def get_default_colors():
140 def get_default_colors():
141 "DEPRECATED"
141 "DEPRECATED"
142 warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
142 warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
143 DeprecationWarning, stacklevel=2)
143 DeprecationWarning, stacklevel=2)
144 return 'Neutral'
144 return 'Neutral'
145
145
146
146
147 class SeparateUnicode(Unicode):
147 class SeparateUnicode(Unicode):
148 r"""A Unicode subclass to validate separate_in, separate_out, etc.
148 r"""A Unicode subclass to validate separate_in, separate_out, etc.
149
149
150 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
150 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
151 """
151 """
152
152
153 def validate(self, obj, value):
153 def validate(self, obj, value):
154 if value == '0': value = ''
154 if value == '0': value = ''
155 value = value.replace('\\n','\n')
155 value = value.replace('\\n','\n')
156 return super(SeparateUnicode, self).validate(obj, value)
156 return super(SeparateUnicode, self).validate(obj, value)
157
157
158
158
159 @undoc
159 @undoc
160 class DummyMod(object):
160 class DummyMod(object):
161 """A dummy module used for IPython's interactive module when
161 """A dummy module used for IPython's interactive module when
162 a namespace must be assigned to the module's __dict__."""
162 a namespace must be assigned to the module's __dict__."""
163 pass
163 pass
164
164
165
165
166 class ExecutionResult(object):
166 class ExecutionResult(object):
167 """The result of a call to :meth:`InteractiveShell.run_cell`
167 """The result of a call to :meth:`InteractiveShell.run_cell`
168
168
169 Stores information about what took place.
169 Stores information about what took place.
170 """
170 """
171 execution_count = None
171 execution_count = None
172 error_before_exec = None
172 error_before_exec = None
173 error_in_exec = None
173 error_in_exec = None
174 result = None
174 result = None
175
175
176 @property
176 @property
177 def success(self):
177 def success(self):
178 return (self.error_before_exec is None) and (self.error_in_exec is None)
178 return (self.error_before_exec is None) and (self.error_in_exec is None)
179
179
180 def raise_error(self):
180 def raise_error(self):
181 """Reraises error if `success` is `False`, otherwise does nothing"""
181 """Reraises error if `success` is `False`, otherwise does nothing"""
182 if self.error_before_exec is not None:
182 if self.error_before_exec is not None:
183 raise self.error_before_exec
183 raise self.error_before_exec
184 if self.error_in_exec is not None:
184 if self.error_in_exec is not None:
185 raise self.error_in_exec
185 raise self.error_in_exec
186
186
187 def __repr__(self):
187 def __repr__(self):
188 name = self.__class__.__qualname__
188 name = self.__class__.__qualname__
189 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
189 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
190 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
190 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
191
191
192
192
193 class InteractiveShell(SingletonConfigurable):
193 class InteractiveShell(SingletonConfigurable):
194 """An enhanced, interactive shell for Python."""
194 """An enhanced, interactive shell for Python."""
195
195
196 _instance = None
196 _instance = None
197
197
198 ast_transformers = List([], help=
198 ast_transformers = List([], help=
199 """
199 """
200 A list of ast.NodeTransformer subclass instances, which will be applied
200 A list of ast.NodeTransformer subclass instances, which will be applied
201 to user input before code is run.
201 to user input before code is run.
202 """
202 """
203 ).tag(config=True)
203 ).tag(config=True)
204
204
205 autocall = Enum((0,1,2), default_value=0, help=
205 autocall = Enum((0,1,2), default_value=0, help=
206 """
206 """
207 Make IPython automatically call any callable object even if you didn't
207 Make IPython automatically call any callable object even if you didn't
208 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
208 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
209 automatically. The value can be '0' to disable the feature, '1' for
209 automatically. The value can be '0' to disable the feature, '1' for
210 'smart' autocall, where it is not applied if there are no more
210 'smart' autocall, where it is not applied if there are no more
211 arguments on the line, and '2' for 'full' autocall, where all callable
211 arguments on the line, and '2' for 'full' autocall, where all callable
212 objects are automatically called (even if no arguments are present).
212 objects are automatically called (even if no arguments are present).
213 """
213 """
214 ).tag(config=True)
214 ).tag(config=True)
215 # TODO: remove all autoindent logic and put into frontends.
215 # TODO: remove all autoindent logic and put into frontends.
216 # We can't do this yet because even runlines uses the autoindent.
216 # We can't do this yet because even runlines uses the autoindent.
217 autoindent = Bool(True, help=
217 autoindent = Bool(True, help=
218 """
218 """
219 Autoindent IPython code entered interactively.
219 Autoindent IPython code entered interactively.
220 """
220 """
221 ).tag(config=True)
221 ).tag(config=True)
222
222
223 automagic = Bool(True, help=
223 automagic = Bool(True, help=
224 """
224 """
225 Enable magic commands to be called without the leading %.
225 Enable magic commands to be called without the leading %.
226 """
226 """
227 ).tag(config=True)
227 ).tag(config=True)
228
228
229 banner1 = Unicode(default_banner,
229 banner1 = Unicode(default_banner,
230 help="""The part of the banner to be printed before the profile"""
230 help="""The part of the banner to be printed before the profile"""
231 ).tag(config=True)
231 ).tag(config=True)
232 banner2 = Unicode('',
232 banner2 = Unicode('',
233 help="""The part of the banner to be printed after the profile"""
233 help="""The part of the banner to be printed after the profile"""
234 ).tag(config=True)
234 ).tag(config=True)
235
235
236 cache_size = Integer(1000, help=
236 cache_size = Integer(1000, help=
237 """
237 """
238 Set the size of the output cache. The default is 1000, you can
238 Set the size of the output cache. The default is 1000, you can
239 change it permanently in your config file. Setting it to 0 completely
239 change it permanently in your config file. Setting it to 0 completely
240 disables the caching system, and the minimum value accepted is 20 (if
240 disables the caching system, and the minimum value accepted is 20 (if
241 you provide a value less than 20, it is reset to 0 and a warning is
241 you provide a value less than 20, it is reset to 0 and a warning is
242 issued). This limit is defined because otherwise you'll spend more
242 issued). This limit is defined because otherwise you'll spend more
243 time re-flushing a too small cache than working
243 time re-flushing a too small cache than working
244 """
244 """
245 ).tag(config=True)
245 ).tag(config=True)
246 color_info = Bool(True, help=
246 color_info = Bool(True, help=
247 """
247 """
248 Use colors for displaying information about objects. Because this
248 Use colors for displaying information about objects. Because this
249 information is passed through a pager (like 'less'), and some pagers
249 information is passed through a pager (like 'less'), and some pagers
250 get confused with color codes, this capability can be turned off.
250 get confused with color codes, this capability can be turned off.
251 """
251 """
252 ).tag(config=True)
252 ).tag(config=True)
253 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
253 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
254 default_value='Neutral',
254 default_value='Neutral',
255 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
255 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
256 ).tag(config=True)
256 ).tag(config=True)
257 debug = Bool(False).tag(config=True)
257 debug = Bool(False).tag(config=True)
258 disable_failing_post_execute = Bool(False,
258 disable_failing_post_execute = Bool(False,
259 help="Don't call post-execute functions that have failed in the past."
259 help="Don't call post-execute functions that have failed in the past."
260 ).tag(config=True)
260 ).tag(config=True)
261 display_formatter = Instance(DisplayFormatter, allow_none=True)
261 display_formatter = Instance(DisplayFormatter, allow_none=True)
262 displayhook_class = Type(DisplayHook)
262 displayhook_class = Type(DisplayHook)
263 display_pub_class = Type(DisplayPublisher)
263 display_pub_class = Type(DisplayPublisher)
264
264
265 sphinxify_docstring = Bool(False, help=
265 sphinxify_docstring = Bool(False, help=
266 """
266 """
267 Enables rich html representation of docstrings. (This requires the
267 Enables rich html representation of docstrings. (This requires the
268 docrepr module).
268 docrepr module).
269 """).tag(config=True)
269 """).tag(config=True)
270
270
271 @observe("sphinxify_docstring")
271 @observe("sphinxify_docstring")
272 def _sphinxify_docstring_changed(self, change):
272 def _sphinxify_docstring_changed(self, change):
273 if change['new']:
273 if change['new']:
274 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
274 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
275
275
276 enable_html_pager = Bool(False, help=
276 enable_html_pager = Bool(False, help=
277 """
277 """
278 (Provisional API) enables html representation in mime bundles sent
278 (Provisional API) enables html representation in mime bundles sent
279 to pagers.
279 to pagers.
280 """).tag(config=True)
280 """).tag(config=True)
281
281
282 @observe("enable_html_pager")
282 @observe("enable_html_pager")
283 def _enable_html_pager_changed(self, change):
283 def _enable_html_pager_changed(self, change):
284 if change['new']:
284 if change['new']:
285 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
285 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
286
286
287 data_pub_class = None
287 data_pub_class = None
288
288
289 exit_now = Bool(False)
289 exit_now = Bool(False)
290 exiter = Instance(ExitAutocall)
290 exiter = Instance(ExitAutocall)
291 @default('exiter')
291 @default('exiter')
292 def _exiter_default(self):
292 def _exiter_default(self):
293 return ExitAutocall(self)
293 return ExitAutocall(self)
294 # Monotonically increasing execution counter
294 # Monotonically increasing execution counter
295 execution_count = Integer(1)
295 execution_count = Integer(1)
296 filename = Unicode("<ipython console>")
296 filename = Unicode("<ipython console>")
297 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
297 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
298
298
299 # Input splitter, to transform input line by line and detect when a block
299 # Input splitter, to transform input line by line and detect when a block
300 # is ready to be executed.
300 # is ready to be executed.
301 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
301 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
302 (), {'line_input_checker': True})
302 (), {'line_input_checker': True})
303
303
304 # This InputSplitter instance is used to transform completed cells before
304 # This InputSplitter instance is used to transform completed cells before
305 # running them. It allows cell magics to contain blank lines.
305 # running them. It allows cell magics to contain blank lines.
306 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
306 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
307 (), {'line_input_checker': False})
307 (), {'line_input_checker': False})
308
308
309 logstart = Bool(False, help=
309 logstart = Bool(False, help=
310 """
310 """
311 Start logging to the default log file in overwrite mode.
311 Start logging to the default log file in overwrite mode.
312 Use `logappend` to specify a log file to **append** logs to.
312 Use `logappend` to specify a log file to **append** logs to.
313 """
313 """
314 ).tag(config=True)
314 ).tag(config=True)
315 logfile = Unicode('', help=
315 logfile = Unicode('', help=
316 """
316 """
317 The name of the logfile to use.
317 The name of the logfile to use.
318 """
318 """
319 ).tag(config=True)
319 ).tag(config=True)
320 logappend = Unicode('', help=
320 logappend = Unicode('', help=
321 """
321 """
322 Start logging to the given file in append mode.
322 Start logging to the given file in append mode.
323 Use `logfile` to specify a log file to **overwrite** logs to.
323 Use `logfile` to specify a log file to **overwrite** logs to.
324 """
324 """
325 ).tag(config=True)
325 ).tag(config=True)
326 object_info_string_level = Enum((0,1,2), default_value=0,
326 object_info_string_level = Enum((0,1,2), default_value=0,
327 ).tag(config=True)
327 ).tag(config=True)
328 pdb = Bool(False, help=
328 pdb = Bool(False, help=
329 """
329 """
330 Automatically call the pdb debugger after every exception.
330 Automatically call the pdb debugger after every exception.
331 """
331 """
332 ).tag(config=True)
332 ).tag(config=True)
333 display_page = Bool(False,
333 display_page = Bool(False,
334 help="""If True, anything that would be passed to the pager
334 help="""If True, anything that would be passed to the pager
335 will be displayed as regular output instead."""
335 will be displayed as regular output instead."""
336 ).tag(config=True)
336 ).tag(config=True)
337
337
338 # deprecated prompt traits:
338 # deprecated prompt traits:
339
339
340 prompt_in1 = Unicode('In [\\#]: ',
340 prompt_in1 = Unicode('In [\\#]: ',
341 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
341 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
342 ).tag(config=True)
342 ).tag(config=True)
343 prompt_in2 = Unicode(' .\\D.: ',
343 prompt_in2 = Unicode(' .\\D.: ',
344 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
344 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
345 ).tag(config=True)
345 ).tag(config=True)
346 prompt_out = Unicode('Out[\\#]: ',
346 prompt_out = Unicode('Out[\\#]: ',
347 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
347 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
348 ).tag(config=True)
348 ).tag(config=True)
349 prompts_pad_left = Bool(True,
349 prompts_pad_left = Bool(True,
350 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
350 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
351 ).tag(config=True)
351 ).tag(config=True)
352
352
353 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
353 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
354 def _prompt_trait_changed(self, change):
354 def _prompt_trait_changed(self, change):
355 name = change['name']
355 name = change['name']
356 warn("InteractiveShell.{name} is deprecated since IPython 4.0"
356 warn("InteractiveShell.{name} is deprecated since IPython 4.0"
357 " and ignored since 5.0, set TerminalInteractiveShell.prompts"
357 " and ignored since 5.0, set TerminalInteractiveShell.prompts"
358 " object directly.".format(name=name))
358 " object directly.".format(name=name))
359
359
360 # protect against weird cases where self.config may not exist:
360 # protect against weird cases where self.config may not exist:
361
361
362 show_rewritten_input = Bool(True,
362 show_rewritten_input = Bool(True,
363 help="Show rewritten input, e.g. for autocall."
363 help="Show rewritten input, e.g. for autocall."
364 ).tag(config=True)
364 ).tag(config=True)
365
365
366 quiet = Bool(False).tag(config=True)
366 quiet = Bool(False).tag(config=True)
367
367
368 history_length = Integer(10000,
368 history_length = Integer(10000,
369 help='Total length of command history'
369 help='Total length of command history'
370 ).tag(config=True)
370 ).tag(config=True)
371
371
372 history_load_length = Integer(1000, help=
372 history_load_length = Integer(1000, help=
373 """
373 """
374 The number of saved history entries to be loaded
374 The number of saved history entries to be loaded
375 into the history buffer at startup.
375 into the history buffer at startup.
376 """
376 """
377 ).tag(config=True)
377 ).tag(config=True)
378
378
379 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
379 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
380 default_value='last_expr',
380 default_value='last_expr',
381 help="""
381 help="""
382 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
382 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
383 run interactively (displaying output from expressions)."""
383 run interactively (displaying output from expressions)."""
384 ).tag(config=True)
384 ).tag(config=True)
385
385
386 # TODO: this part of prompt management should be moved to the frontends.
386 # TODO: this part of prompt management should be moved to the frontends.
387 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
387 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
388 separate_in = SeparateUnicode('\n').tag(config=True)
388 separate_in = SeparateUnicode('\n').tag(config=True)
389 separate_out = SeparateUnicode('').tag(config=True)
389 separate_out = SeparateUnicode('').tag(config=True)
390 separate_out2 = SeparateUnicode('').tag(config=True)
390 separate_out2 = SeparateUnicode('').tag(config=True)
391 wildcards_case_sensitive = Bool(True).tag(config=True)
391 wildcards_case_sensitive = Bool(True).tag(config=True)
392 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
392 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
393 default_value='Context').tag(config=True)
393 default_value='Context').tag(config=True)
394
394
395 # Subcomponents of InteractiveShell
395 # Subcomponents of InteractiveShell
396 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
396 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
397 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
397 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
398 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
398 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
399 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
399 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
400 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
400 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
401 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
401 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
402 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
402 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
403 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
403 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
404
404
405 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
405 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
406 @property
406 @property
407 def profile(self):
407 def profile(self):
408 if self.profile_dir is not None:
408 if self.profile_dir is not None:
409 name = os.path.basename(self.profile_dir.location)
409 name = os.path.basename(self.profile_dir.location)
410 return name.replace('profile_','')
410 return name.replace('profile_','')
411
411
412
412
413 # Private interface
413 # Private interface
414 _post_execute = Dict()
414 _post_execute = Dict()
415
415
416 # Tracks any GUI loop loaded for pylab
416 # Tracks any GUI loop loaded for pylab
417 pylab_gui_select = None
417 pylab_gui_select = None
418
418
419 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
419 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
420
420
421 def __init__(self, ipython_dir=None, profile_dir=None,
421 def __init__(self, ipython_dir=None, profile_dir=None,
422 user_module=None, user_ns=None,
422 user_module=None, user_ns=None,
423 custom_exceptions=((), None), **kwargs):
423 custom_exceptions=((), None), **kwargs):
424
424
425 # This is where traits with a config_key argument are updated
425 # This is where traits with a config_key argument are updated
426 # from the values on config.
426 # from the values on config.
427 super(InteractiveShell, self).__init__(**kwargs)
427 super(InteractiveShell, self).__init__(**kwargs)
428 if 'PromptManager' in self.config:
428 if 'PromptManager' in self.config:
429 warn('As of IPython 5.0 `PromptManager` config will have no effect'
429 warn('As of IPython 5.0 `PromptManager` config will have no effect'
430 ' and has been replaced by TerminalInteractiveShell.prompts_class')
430 ' and has been replaced by TerminalInteractiveShell.prompts_class')
431 self.configurables = [self]
431 self.configurables = [self]
432
432
433 # These are relatively independent and stateless
433 # These are relatively independent and stateless
434 self.init_ipython_dir(ipython_dir)
434 self.init_ipython_dir(ipython_dir)
435 self.init_profile_dir(profile_dir)
435 self.init_profile_dir(profile_dir)
436 self.init_instance_attrs()
436 self.init_instance_attrs()
437 self.init_environment()
437 self.init_environment()
438
438
439 # Check if we're in a virtualenv, and set up sys.path.
439 # Check if we're in a virtualenv, and set up sys.path.
440 self.init_virtualenv()
440 self.init_virtualenv()
441
441
442 # Create namespaces (user_ns, user_global_ns, etc.)
442 # Create namespaces (user_ns, user_global_ns, etc.)
443 self.init_create_namespaces(user_module, user_ns)
443 self.init_create_namespaces(user_module, user_ns)
444 # This has to be done after init_create_namespaces because it uses
444 # This has to be done after init_create_namespaces because it uses
445 # something in self.user_ns, but before init_sys_modules, which
445 # something in self.user_ns, but before init_sys_modules, which
446 # is the first thing to modify sys.
446 # is the first thing to modify sys.
447 # TODO: When we override sys.stdout and sys.stderr before this class
447 # TODO: When we override sys.stdout and sys.stderr before this class
448 # is created, we are saving the overridden ones here. Not sure if this
448 # is created, we are saving the overridden ones here. Not sure if this
449 # is what we want to do.
449 # is what we want to do.
450 self.save_sys_module_state()
450 self.save_sys_module_state()
451 self.init_sys_modules()
451 self.init_sys_modules()
452
452
453 # While we're trying to have each part of the code directly access what
453 # While we're trying to have each part of the code directly access what
454 # it needs without keeping redundant references to objects, we have too
454 # it needs without keeping redundant references to objects, we have too
455 # much legacy code that expects ip.db to exist.
455 # much legacy code that expects ip.db to exist.
456 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
456 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
457
457
458 self.init_history()
458 self.init_history()
459 self.init_encoding()
459 self.init_encoding()
460 self.init_prefilter()
460 self.init_prefilter()
461
461
462 self.init_syntax_highlighting()
462 self.init_syntax_highlighting()
463 self.init_hooks()
463 self.init_hooks()
464 self.init_events()
464 self.init_events()
465 self.init_pushd_popd_magic()
465 self.init_pushd_popd_magic()
466 self.init_user_ns()
466 self.init_user_ns()
467 self.init_logger()
467 self.init_logger()
468 self.init_builtins()
468 self.init_builtins()
469
469
470 # The following was in post_config_initialization
470 # The following was in post_config_initialization
471 self.init_inspector()
471 self.init_inspector()
472 self.raw_input_original = input
472 self.raw_input_original = input
473 self.init_completer()
473 self.init_completer()
474 # TODO: init_io() needs to happen before init_traceback handlers
474 # TODO: init_io() needs to happen before init_traceback handlers
475 # because the traceback handlers hardcode the stdout/stderr streams.
475 # because the traceback handlers hardcode the stdout/stderr streams.
476 # This logic in in debugger.Pdb and should eventually be changed.
476 # This logic in in debugger.Pdb and should eventually be changed.
477 self.init_io()
477 self.init_io()
478 self.init_traceback_handlers(custom_exceptions)
478 self.init_traceback_handlers(custom_exceptions)
479 self.init_prompts()
479 self.init_prompts()
480 self.init_display_formatter()
480 self.init_display_formatter()
481 self.init_display_pub()
481 self.init_display_pub()
482 self.init_data_pub()
482 self.init_data_pub()
483 self.init_displayhook()
483 self.init_displayhook()
484 self.init_magics()
484 self.init_magics()
485 self.init_alias()
485 self.init_alias()
486 self.init_logstart()
486 self.init_logstart()
487 self.init_pdb()
487 self.init_pdb()
488 self.init_extension_manager()
488 self.init_extension_manager()
489 self.init_payload()
489 self.init_payload()
490 self.init_deprecation_warnings()
490 self.init_deprecation_warnings()
491 self.hooks.late_startup_hook()
491 self.hooks.late_startup_hook()
492 self.events.trigger('shell_initialized', self)
492 self.events.trigger('shell_initialized', self)
493 atexit.register(self.atexit_operations)
493 atexit.register(self.atexit_operations)
494
494
495 def get_ipython(self):
495 def get_ipython(self):
496 """Return the currently running IPython instance."""
496 """Return the currently running IPython instance."""
497 return self
497 return self
498
498
499 #-------------------------------------------------------------------------
499 #-------------------------------------------------------------------------
500 # Trait changed handlers
500 # Trait changed handlers
501 #-------------------------------------------------------------------------
501 #-------------------------------------------------------------------------
502 @observe('ipython_dir')
502 @observe('ipython_dir')
503 def _ipython_dir_changed(self, change):
503 def _ipython_dir_changed(self, change):
504 ensure_dir_exists(change['new'])
504 ensure_dir_exists(change['new'])
505
505
506 def set_autoindent(self,value=None):
506 def set_autoindent(self,value=None):
507 """Set the autoindent flag.
507 """Set the autoindent flag.
508
508
509 If called with no arguments, it acts as a toggle."""
509 If called with no arguments, it acts as a toggle."""
510 if value is None:
510 if value is None:
511 self.autoindent = not self.autoindent
511 self.autoindent = not self.autoindent
512 else:
512 else:
513 self.autoindent = value
513 self.autoindent = value
514
514
515 #-------------------------------------------------------------------------
515 #-------------------------------------------------------------------------
516 # init_* methods called by __init__
516 # init_* methods called by __init__
517 #-------------------------------------------------------------------------
517 #-------------------------------------------------------------------------
518
518
519 def init_ipython_dir(self, ipython_dir):
519 def init_ipython_dir(self, ipython_dir):
520 if ipython_dir is not None:
520 if ipython_dir is not None:
521 self.ipython_dir = ipython_dir
521 self.ipython_dir = ipython_dir
522 return
522 return
523
523
524 self.ipython_dir = get_ipython_dir()
524 self.ipython_dir = get_ipython_dir()
525
525
526 def init_profile_dir(self, profile_dir):
526 def init_profile_dir(self, profile_dir):
527 if profile_dir is not None:
527 if profile_dir is not None:
528 self.profile_dir = profile_dir
528 self.profile_dir = profile_dir
529 return
529 return
530 self.profile_dir =\
530 self.profile_dir =\
531 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
531 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
532
532
533 def init_instance_attrs(self):
533 def init_instance_attrs(self):
534 self.more = False
534 self.more = False
535
535
536 # command compiler
536 # command compiler
537 self.compile = CachingCompiler()
537 self.compile = CachingCompiler()
538
538
539 # Make an empty namespace, which extension writers can rely on both
539 # Make an empty namespace, which extension writers can rely on both
540 # existing and NEVER being used by ipython itself. This gives them a
540 # existing and NEVER being used by ipython itself. This gives them a
541 # convenient location for storing additional information and state
541 # convenient location for storing additional information and state
542 # their extensions may require, without fear of collisions with other
542 # their extensions may require, without fear of collisions with other
543 # ipython names that may develop later.
543 # ipython names that may develop later.
544 self.meta = Struct()
544 self.meta = Struct()
545
545
546 # Temporary files used for various purposes. Deleted at exit.
546 # Temporary files used for various purposes. Deleted at exit.
547 self.tempfiles = []
547 self.tempfiles = []
548 self.tempdirs = []
548 self.tempdirs = []
549
549
550 # keep track of where we started running (mainly for crash post-mortem)
550 # keep track of where we started running (mainly for crash post-mortem)
551 # This is not being used anywhere currently.
551 # This is not being used anywhere currently.
552 self.starting_dir = os.getcwd()
552 self.starting_dir = os.getcwd()
553
553
554 # Indentation management
554 # Indentation management
555 self.indent_current_nsp = 0
555 self.indent_current_nsp = 0
556
556
557 # Dict to track post-execution functions that have been registered
557 # Dict to track post-execution functions that have been registered
558 self._post_execute = {}
558 self._post_execute = {}
559
559
560 def init_environment(self):
560 def init_environment(self):
561 """Any changes we need to make to the user's environment."""
561 """Any changes we need to make to the user's environment."""
562 pass
562 pass
563
563
564 def init_encoding(self):
564 def init_encoding(self):
565 # Get system encoding at startup time. Certain terminals (like Emacs
565 # Get system encoding at startup time. Certain terminals (like Emacs
566 # under Win32 have it set to None, and we need to have a known valid
566 # under Win32 have it set to None, and we need to have a known valid
567 # encoding to use in the raw_input() method
567 # encoding to use in the raw_input() method
568 try:
568 try:
569 self.stdin_encoding = sys.stdin.encoding or 'ascii'
569 self.stdin_encoding = sys.stdin.encoding or 'ascii'
570 except AttributeError:
570 except AttributeError:
571 self.stdin_encoding = 'ascii'
571 self.stdin_encoding = 'ascii'
572
572
573
573
574 @observe('colors')
574 @observe('colors')
575 def init_syntax_highlighting(self, changes=None):
575 def init_syntax_highlighting(self, changes=None):
576 # Python source parser/formatter for syntax highlighting
576 # Python source parser/formatter for syntax highlighting
577 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
577 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
578 self.pycolorize = lambda src: pyformat(src,'str')
578 self.pycolorize = lambda src: pyformat(src,'str')
579
579
580 def refresh_style(self):
580 def refresh_style(self):
581 # No-op here, used in subclass
581 # No-op here, used in subclass
582 pass
582 pass
583
583
584 def init_pushd_popd_magic(self):
584 def init_pushd_popd_magic(self):
585 # for pushd/popd management
585 # for pushd/popd management
586 self.home_dir = get_home_dir()
586 self.home_dir = get_home_dir()
587
587
588 self.dir_stack = []
588 self.dir_stack = []
589
589
590 def init_logger(self):
590 def init_logger(self):
591 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
591 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
592 logmode='rotate')
592 logmode='rotate')
593
593
594 def init_logstart(self):
594 def init_logstart(self):
595 """Initialize logging in case it was requested at the command line.
595 """Initialize logging in case it was requested at the command line.
596 """
596 """
597 if self.logappend:
597 if self.logappend:
598 self.magic('logstart %s append' % self.logappend)
598 self.magic('logstart %s append' % self.logappend)
599 elif self.logfile:
599 elif self.logfile:
600 self.magic('logstart %s' % self.logfile)
600 self.magic('logstart %s' % self.logfile)
601 elif self.logstart:
601 elif self.logstart:
602 self.magic('logstart')
602 self.magic('logstart')
603
603
604 def init_deprecation_warnings(self):
604 def init_deprecation_warnings(self):
605 """
605 """
606 register default filter for deprecation warning.
606 register default filter for deprecation warning.
607
607
608 This will allow deprecation warning of function used interactively to show
608 This will allow deprecation warning of function used interactively to show
609 warning to users, and still hide deprecation warning from libraries import.
609 warning to users, and still hide deprecation warning from libraries import.
610 """
610 """
611 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
611 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
612
612
613 def init_builtins(self):
613 def init_builtins(self):
614 # A single, static flag that we set to True. Its presence indicates
614 # A single, static flag that we set to True. Its presence indicates
615 # that an IPython shell has been created, and we make no attempts at
615 # that an IPython shell has been created, and we make no attempts at
616 # removing on exit or representing the existence of more than one
616 # removing on exit or representing the existence of more than one
617 # IPython at a time.
617 # IPython at a time.
618 builtin_mod.__dict__['__IPYTHON__'] = True
618 builtin_mod.__dict__['__IPYTHON__'] = True
619
619
620 self.builtin_trap = BuiltinTrap(shell=self)
620 self.builtin_trap = BuiltinTrap(shell=self)
621
621
622 def init_inspector(self):
622 def init_inspector(self):
623 # Object inspector
623 # Object inspector
624 self.inspector = oinspect.Inspector(oinspect.InspectColors,
624 self.inspector = oinspect.Inspector(oinspect.InspectColors,
625 PyColorize.ANSICodeColors,
625 PyColorize.ANSICodeColors,
626 'NoColor',
626 'NoColor',
627 self.object_info_string_level)
627 self.object_info_string_level)
628
628
629 def init_io(self):
629 def init_io(self):
630 # This will just use sys.stdout and sys.stderr. If you want to
630 # This will just use sys.stdout and sys.stderr. If you want to
631 # override sys.stdout and sys.stderr themselves, you need to do that
631 # override sys.stdout and sys.stderr themselves, you need to do that
632 # *before* instantiating this class, because io holds onto
632 # *before* instantiating this class, because io holds onto
633 # references to the underlying streams.
633 # references to the underlying streams.
634 # io.std* are deprecated, but don't show our own deprecation warnings
634 # io.std* are deprecated, but don't show our own deprecation warnings
635 # during initialization of the deprecated API.
635 # during initialization of the deprecated API.
636 with warnings.catch_warnings():
636 with warnings.catch_warnings():
637 warnings.simplefilter('ignore', DeprecationWarning)
637 warnings.simplefilter('ignore', DeprecationWarning)
638 io.stdout = io.IOStream(sys.stdout)
638 io.stdout = io.IOStream(sys.stdout)
639 io.stderr = io.IOStream(sys.stderr)
639 io.stderr = io.IOStream(sys.stderr)
640
640
641 def init_prompts(self):
641 def init_prompts(self):
642 # Set system prompts, so that scripts can decide if they are running
642 # Set system prompts, so that scripts can decide if they are running
643 # interactively.
643 # interactively.
644 sys.ps1 = 'In : '
644 sys.ps1 = 'In : '
645 sys.ps2 = '...: '
645 sys.ps2 = '...: '
646 sys.ps3 = 'Out: '
646 sys.ps3 = 'Out: '
647
647
648 def init_display_formatter(self):
648 def init_display_formatter(self):
649 self.display_formatter = DisplayFormatter(parent=self)
649 self.display_formatter = DisplayFormatter(parent=self)
650 self.configurables.append(self.display_formatter)
650 self.configurables.append(self.display_formatter)
651
651
652 def init_display_pub(self):
652 def init_display_pub(self):
653 self.display_pub = self.display_pub_class(parent=self)
653 self.display_pub = self.display_pub_class(parent=self)
654 self.configurables.append(self.display_pub)
654 self.configurables.append(self.display_pub)
655
655
656 def init_data_pub(self):
656 def init_data_pub(self):
657 if not self.data_pub_class:
657 if not self.data_pub_class:
658 self.data_pub = None
658 self.data_pub = None
659 return
659 return
660 self.data_pub = self.data_pub_class(parent=self)
660 self.data_pub = self.data_pub_class(parent=self)
661 self.configurables.append(self.data_pub)
661 self.configurables.append(self.data_pub)
662
662
663 def init_displayhook(self):
663 def init_displayhook(self):
664 # Initialize displayhook, set in/out prompts and printing system
664 # Initialize displayhook, set in/out prompts and printing system
665 self.displayhook = self.displayhook_class(
665 self.displayhook = self.displayhook_class(
666 parent=self,
666 parent=self,
667 shell=self,
667 shell=self,
668 cache_size=self.cache_size,
668 cache_size=self.cache_size,
669 )
669 )
670 self.configurables.append(self.displayhook)
670 self.configurables.append(self.displayhook)
671 # This is a context manager that installs/revmoes the displayhook at
671 # This is a context manager that installs/revmoes the displayhook at
672 # the appropriate time.
672 # the appropriate time.
673 self.display_trap = DisplayTrap(hook=self.displayhook)
673 self.display_trap = DisplayTrap(hook=self.displayhook)
674
674
675 def init_virtualenv(self):
675 def init_virtualenv(self):
676 """Add a virtualenv to sys.path so the user can import modules from it.
676 """Add a virtualenv to sys.path so the user can import modules from it.
677 This isn't perfect: it doesn't use the Python interpreter with which the
677 This isn't perfect: it doesn't use the Python interpreter with which the
678 virtualenv was built, and it ignores the --no-site-packages option. A
678 virtualenv was built, and it ignores the --no-site-packages option. A
679 warning will appear suggesting the user installs IPython in the
679 warning will appear suggesting the user installs IPython in the
680 virtualenv, but for many cases, it probably works well enough.
680 virtualenv, but for many cases, it probably works well enough.
681
681
682 Adapted from code snippets online.
682 Adapted from code snippets online.
683
683
684 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
684 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
685 """
685 """
686 if 'VIRTUAL_ENV' not in os.environ:
686 if 'VIRTUAL_ENV' not in os.environ:
687 # Not in a virtualenv
687 # Not in a virtualenv
688 return
688 return
689
689
690 # venv detection:
690 # venv detection:
691 # stdlib venv may symlink sys.executable, so we can't use realpath.
691 # stdlib venv may symlink sys.executable, so we can't use realpath.
692 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
692 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
693 # So we just check every item in the symlink tree (generally <= 3)
693 # So we just check every item in the symlink tree (generally <= 3)
694 p = os.path.normcase(sys.executable)
694 p = os.path.normcase(sys.executable)
695 paths = [p]
695 paths = [p]
696 while os.path.islink(p):
696 while os.path.islink(p):
697 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
697 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
698 paths.append(p)
698 paths.append(p)
699 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
699 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
700 if any(p.startswith(p_venv) for p in paths):
700 if any(p.startswith(p_venv) for p in paths):
701 # Running properly in the virtualenv, don't need to do anything
701 # Running properly in the virtualenv, don't need to do anything
702 return
702 return
703
703
704 warn("Attempting to work in a virtualenv. If you encounter problems, please "
704 warn("Attempting to work in a virtualenv. If you encounter problems, please "
705 "install IPython inside the virtualenv.")
705 "install IPython inside the virtualenv.")
706 if sys.platform == "win32":
706 if sys.platform == "win32":
707 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
707 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
708 else:
708 else:
709 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
709 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
710 'python%d.%d' % sys.version_info[:2], 'site-packages')
710 'python%d.%d' % sys.version_info[:2], 'site-packages')
711
711
712 import site
712 import site
713 sys.path.insert(0, virtual_env)
713 sys.path.insert(0, virtual_env)
714 site.addsitedir(virtual_env)
714 site.addsitedir(virtual_env)
715
715
716 #-------------------------------------------------------------------------
716 #-------------------------------------------------------------------------
717 # Things related to injections into the sys module
717 # Things related to injections into the sys module
718 #-------------------------------------------------------------------------
718 #-------------------------------------------------------------------------
719
719
720 def save_sys_module_state(self):
720 def save_sys_module_state(self):
721 """Save the state of hooks in the sys module.
721 """Save the state of hooks in the sys module.
722
722
723 This has to be called after self.user_module is created.
723 This has to be called after self.user_module is created.
724 """
724 """
725 self._orig_sys_module_state = {'stdin': sys.stdin,
725 self._orig_sys_module_state = {'stdin': sys.stdin,
726 'stdout': sys.stdout,
726 'stdout': sys.stdout,
727 'stderr': sys.stderr,
727 'stderr': sys.stderr,
728 'excepthook': sys.excepthook}
728 'excepthook': sys.excepthook}
729 self._orig_sys_modules_main_name = self.user_module.__name__
729 self._orig_sys_modules_main_name = self.user_module.__name__
730 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
730 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
731
731
732 def restore_sys_module_state(self):
732 def restore_sys_module_state(self):
733 """Restore the state of the sys module."""
733 """Restore the state of the sys module."""
734 try:
734 try:
735 for k, v in self._orig_sys_module_state.items():
735 for k, v in self._orig_sys_module_state.items():
736 setattr(sys, k, v)
736 setattr(sys, k, v)
737 except AttributeError:
737 except AttributeError:
738 pass
738 pass
739 # Reset what what done in self.init_sys_modules
739 # Reset what what done in self.init_sys_modules
740 if self._orig_sys_modules_main_mod is not None:
740 if self._orig_sys_modules_main_mod is not None:
741 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
741 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
742
742
743 #-------------------------------------------------------------------------
743 #-------------------------------------------------------------------------
744 # Things related to the banner
744 # Things related to the banner
745 #-------------------------------------------------------------------------
745 #-------------------------------------------------------------------------
746
746
747 @property
747 @property
748 def banner(self):
748 def banner(self):
749 banner = self.banner1
749 banner = self.banner1
750 if self.profile and self.profile != 'default':
750 if self.profile and self.profile != 'default':
751 banner += '\nIPython profile: %s\n' % self.profile
751 banner += '\nIPython profile: %s\n' % self.profile
752 if self.banner2:
752 if self.banner2:
753 banner += '\n' + self.banner2
753 banner += '\n' + self.banner2
754 return banner
754 return banner
755
755
756 def show_banner(self, banner=None):
756 def show_banner(self, banner=None):
757 if banner is None:
757 if banner is None:
758 banner = self.banner
758 banner = self.banner
759 sys.stdout.write(banner)
759 sys.stdout.write(banner)
760
760
761 #-------------------------------------------------------------------------
761 #-------------------------------------------------------------------------
762 # Things related to hooks
762 # Things related to hooks
763 #-------------------------------------------------------------------------
763 #-------------------------------------------------------------------------
764
764
765 def init_hooks(self):
765 def init_hooks(self):
766 # hooks holds pointers used for user-side customizations
766 # hooks holds pointers used for user-side customizations
767 self.hooks = Struct()
767 self.hooks = Struct()
768
768
769 self.strdispatchers = {}
769 self.strdispatchers = {}
770
770
771 # Set all default hooks, defined in the IPython.hooks module.
771 # Set all default hooks, defined in the IPython.hooks module.
772 hooks = IPython.core.hooks
772 hooks = IPython.core.hooks
773 for hook_name in hooks.__all__:
773 for hook_name in hooks.__all__:
774 # default hooks have priority 100, i.e. low; user hooks should have
774 # default hooks have priority 100, i.e. low; user hooks should have
775 # 0-100 priority
775 # 0-100 priority
776 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
776 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
777
777
778 if self.display_page:
778 if self.display_page:
779 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
779 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
780
780
781 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
781 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
782 _warn_deprecated=True):
782 _warn_deprecated=True):
783 """set_hook(name,hook) -> sets an internal IPython hook.
783 """set_hook(name,hook) -> sets an internal IPython hook.
784
784
785 IPython exposes some of its internal API as user-modifiable hooks. By
785 IPython exposes some of its internal API as user-modifiable hooks. By
786 adding your function to one of these hooks, you can modify IPython's
786 adding your function to one of these hooks, you can modify IPython's
787 behavior to call at runtime your own routines."""
787 behavior to call at runtime your own routines."""
788
788
789 # At some point in the future, this should validate the hook before it
789 # At some point in the future, this should validate the hook before it
790 # accepts it. Probably at least check that the hook takes the number
790 # accepts it. Probably at least check that the hook takes the number
791 # of args it's supposed to.
791 # of args it's supposed to.
792
792
793 f = types.MethodType(hook,self)
793 f = types.MethodType(hook,self)
794
794
795 # check if the hook is for strdispatcher first
795 # check if the hook is for strdispatcher first
796 if str_key is not None:
796 if str_key is not None:
797 sdp = self.strdispatchers.get(name, StrDispatch())
797 sdp = self.strdispatchers.get(name, StrDispatch())
798 sdp.add_s(str_key, f, priority )
798 sdp.add_s(str_key, f, priority )
799 self.strdispatchers[name] = sdp
799 self.strdispatchers[name] = sdp
800 return
800 return
801 if re_key is not None:
801 if re_key is not None:
802 sdp = self.strdispatchers.get(name, StrDispatch())
802 sdp = self.strdispatchers.get(name, StrDispatch())
803 sdp.add_re(re.compile(re_key), f, priority )
803 sdp.add_re(re.compile(re_key), f, priority )
804 self.strdispatchers[name] = sdp
804 self.strdispatchers[name] = sdp
805 return
805 return
806
806
807 dp = getattr(self.hooks, name, None)
807 dp = getattr(self.hooks, name, None)
808 if name not in IPython.core.hooks.__all__:
808 if name not in IPython.core.hooks.__all__:
809 print("Warning! Hook '%s' is not one of %s" % \
809 print("Warning! Hook '%s' is not one of %s" % \
810 (name, IPython.core.hooks.__all__ ))
810 (name, IPython.core.hooks.__all__ ))
811
811
812 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
812 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
813 alternative = IPython.core.hooks.deprecated[name]
813 alternative = IPython.core.hooks.deprecated[name]
814 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2)
814 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2)
815
815
816 if not dp:
816 if not dp:
817 dp = IPython.core.hooks.CommandChainDispatcher()
817 dp = IPython.core.hooks.CommandChainDispatcher()
818
818
819 try:
819 try:
820 dp.add(f,priority)
820 dp.add(f,priority)
821 except AttributeError:
821 except AttributeError:
822 # it was not commandchain, plain old func - replace
822 # it was not commandchain, plain old func - replace
823 dp = f
823 dp = f
824
824
825 setattr(self.hooks,name, dp)
825 setattr(self.hooks,name, dp)
826
826
827 #-------------------------------------------------------------------------
827 #-------------------------------------------------------------------------
828 # Things related to events
828 # Things related to events
829 #-------------------------------------------------------------------------
829 #-------------------------------------------------------------------------
830
830
831 def init_events(self):
831 def init_events(self):
832 self.events = EventManager(self, available_events)
832 self.events = EventManager(self, available_events)
833
833
834 self.events.register("pre_execute", self._clear_warning_registry)
834 self.events.register("pre_execute", self._clear_warning_registry)
835
835
836 def register_post_execute(self, func):
836 def register_post_execute(self, func):
837 """DEPRECATED: Use ip.events.register('post_run_cell', func)
837 """DEPRECATED: Use ip.events.register('post_run_cell', func)
838
838
839 Register a function for calling after code execution.
839 Register a function for calling after code execution.
840 """
840 """
841 warn("ip.register_post_execute is deprecated, use "
841 warn("ip.register_post_execute is deprecated, use "
842 "ip.events.register('post_run_cell', func) instead.", stacklevel=2)
842 "ip.events.register('post_run_cell', func) instead.", stacklevel=2)
843 self.events.register('post_run_cell', func)
843 self.events.register('post_run_cell', func)
844
844
845 def _clear_warning_registry(self):
845 def _clear_warning_registry(self):
846 # clear the warning registry, so that different code blocks with
846 # clear the warning registry, so that different code blocks with
847 # overlapping line number ranges don't cause spurious suppression of
847 # overlapping line number ranges don't cause spurious suppression of
848 # warnings (see gh-6611 for details)
848 # warnings (see gh-6611 for details)
849 if "__warningregistry__" in self.user_global_ns:
849 if "__warningregistry__" in self.user_global_ns:
850 del self.user_global_ns["__warningregistry__"]
850 del self.user_global_ns["__warningregistry__"]
851
851
852 #-------------------------------------------------------------------------
852 #-------------------------------------------------------------------------
853 # Things related to the "main" module
853 # Things related to the "main" module
854 #-------------------------------------------------------------------------
854 #-------------------------------------------------------------------------
855
855
856 def new_main_mod(self, filename, modname):
856 def new_main_mod(self, filename, modname):
857 """Return a new 'main' module object for user code execution.
857 """Return a new 'main' module object for user code execution.
858
858
859 ``filename`` should be the path of the script which will be run in the
859 ``filename`` should be the path of the script which will be run in the
860 module. Requests with the same filename will get the same module, with
860 module. Requests with the same filename will get the same module, with
861 its namespace cleared.
861 its namespace cleared.
862
862
863 ``modname`` should be the module name - normally either '__main__' or
863 ``modname`` should be the module name - normally either '__main__' or
864 the basename of the file without the extension.
864 the basename of the file without the extension.
865
865
866 When scripts are executed via %run, we must keep a reference to their
866 When scripts are executed via %run, we must keep a reference to their
867 __main__ module around so that Python doesn't
867 __main__ module around so that Python doesn't
868 clear it, rendering references to module globals useless.
868 clear it, rendering references to module globals useless.
869
869
870 This method keeps said reference in a private dict, keyed by the
870 This method keeps said reference in a private dict, keyed by the
871 absolute path of the script. This way, for multiple executions of the
871 absolute path of the script. This way, for multiple executions of the
872 same script we only keep one copy of the namespace (the last one),
872 same script we only keep one copy of the namespace (the last one),
873 thus preventing memory leaks from old references while allowing the
873 thus preventing memory leaks from old references while allowing the
874 objects from the last execution to be accessible.
874 objects from the last execution to be accessible.
875 """
875 """
876 filename = os.path.abspath(filename)
876 filename = os.path.abspath(filename)
877 try:
877 try:
878 main_mod = self._main_mod_cache[filename]
878 main_mod = self._main_mod_cache[filename]
879 except KeyError:
879 except KeyError:
880 main_mod = self._main_mod_cache[filename] = types.ModuleType(
880 main_mod = self._main_mod_cache[filename] = types.ModuleType(
881 py3compat.cast_bytes_py2(modname),
881 py3compat.cast_bytes_py2(modname),
882 doc="Module created for script run in IPython")
882 doc="Module created for script run in IPython")
883 else:
883 else:
884 main_mod.__dict__.clear()
884 main_mod.__dict__.clear()
885 main_mod.__name__ = modname
885 main_mod.__name__ = modname
886
886
887 main_mod.__file__ = filename
887 main_mod.__file__ = filename
888 # It seems pydoc (and perhaps others) needs any module instance to
888 # It seems pydoc (and perhaps others) needs any module instance to
889 # implement a __nonzero__ method
889 # implement a __nonzero__ method
890 main_mod.__nonzero__ = lambda : True
890 main_mod.__nonzero__ = lambda : True
891
891
892 return main_mod
892 return main_mod
893
893
894 def clear_main_mod_cache(self):
894 def clear_main_mod_cache(self):
895 """Clear the cache of main modules.
895 """Clear the cache of main modules.
896
896
897 Mainly for use by utilities like %reset.
897 Mainly for use by utilities like %reset.
898
898
899 Examples
899 Examples
900 --------
900 --------
901
901
902 In [15]: import IPython
902 In [15]: import IPython
903
903
904 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
904 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
905
905
906 In [17]: len(_ip._main_mod_cache) > 0
906 In [17]: len(_ip._main_mod_cache) > 0
907 Out[17]: True
907 Out[17]: True
908
908
909 In [18]: _ip.clear_main_mod_cache()
909 In [18]: _ip.clear_main_mod_cache()
910
910
911 In [19]: len(_ip._main_mod_cache) == 0
911 In [19]: len(_ip._main_mod_cache) == 0
912 Out[19]: True
912 Out[19]: True
913 """
913 """
914 self._main_mod_cache.clear()
914 self._main_mod_cache.clear()
915
915
916 #-------------------------------------------------------------------------
916 #-------------------------------------------------------------------------
917 # Things related to debugging
917 # Things related to debugging
918 #-------------------------------------------------------------------------
918 #-------------------------------------------------------------------------
919
919
920 def init_pdb(self):
920 def init_pdb(self):
921 # Set calling of pdb on exceptions
921 # Set calling of pdb on exceptions
922 # self.call_pdb is a property
922 # self.call_pdb is a property
923 self.call_pdb = self.pdb
923 self.call_pdb = self.pdb
924
924
925 def _get_call_pdb(self):
925 def _get_call_pdb(self):
926 return self._call_pdb
926 return self._call_pdb
927
927
928 def _set_call_pdb(self,val):
928 def _set_call_pdb(self,val):
929
929
930 if val not in (0,1,False,True):
930 if val not in (0,1,False,True):
931 raise ValueError('new call_pdb value must be boolean')
931 raise ValueError('new call_pdb value must be boolean')
932
932
933 # store value in instance
933 # store value in instance
934 self._call_pdb = val
934 self._call_pdb = val
935
935
936 # notify the actual exception handlers
936 # notify the actual exception handlers
937 self.InteractiveTB.call_pdb = val
937 self.InteractiveTB.call_pdb = val
938
938
939 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
939 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
940 'Control auto-activation of pdb at exceptions')
940 'Control auto-activation of pdb at exceptions')
941
941
942 def debugger(self,force=False):
942 def debugger(self,force=False):
943 """Call the pdb debugger.
943 """Call the pdb debugger.
944
944
945 Keywords:
945 Keywords:
946
946
947 - force(False): by default, this routine checks the instance call_pdb
947 - force(False): by default, this routine checks the instance call_pdb
948 flag and does not actually invoke the debugger if the flag is false.
948 flag and does not actually invoke the debugger if the flag is false.
949 The 'force' option forces the debugger to activate even if the flag
949 The 'force' option forces the debugger to activate even if the flag
950 is false.
950 is false.
951 """
951 """
952
952
953 if not (force or self.call_pdb):
953 if not (force or self.call_pdb):
954 return
954 return
955
955
956 if not hasattr(sys,'last_traceback'):
956 if not hasattr(sys,'last_traceback'):
957 error('No traceback has been produced, nothing to debug.')
957 error('No traceback has been produced, nothing to debug.')
958 return
958 return
959
959
960 self.InteractiveTB.debugger(force=True)
960 self.InteractiveTB.debugger(force=True)
961
961
962 #-------------------------------------------------------------------------
962 #-------------------------------------------------------------------------
963 # Things related to IPython's various namespaces
963 # Things related to IPython's various namespaces
964 #-------------------------------------------------------------------------
964 #-------------------------------------------------------------------------
965 default_user_namespaces = True
965 default_user_namespaces = True
966
966
967 def init_create_namespaces(self, user_module=None, user_ns=None):
967 def init_create_namespaces(self, user_module=None, user_ns=None):
968 # Create the namespace where the user will operate. user_ns is
968 # Create the namespace where the user will operate. user_ns is
969 # normally the only one used, and it is passed to the exec calls as
969 # normally the only one used, and it is passed to the exec calls as
970 # the locals argument. But we do carry a user_global_ns namespace
970 # the locals argument. But we do carry a user_global_ns namespace
971 # given as the exec 'globals' argument, This is useful in embedding
971 # given as the exec 'globals' argument, This is useful in embedding
972 # situations where the ipython shell opens in a context where the
972 # situations where the ipython shell opens in a context where the
973 # distinction between locals and globals is meaningful. For
973 # distinction between locals and globals is meaningful. For
974 # non-embedded contexts, it is just the same object as the user_ns dict.
974 # non-embedded contexts, it is just the same object as the user_ns dict.
975
975
976 # FIXME. For some strange reason, __builtins__ is showing up at user
976 # FIXME. For some strange reason, __builtins__ is showing up at user
977 # level as a dict instead of a module. This is a manual fix, but I
977 # level as a dict instead of a module. This is a manual fix, but I
978 # should really track down where the problem is coming from. Alex
978 # should really track down where the problem is coming from. Alex
979 # Schmolck reported this problem first.
979 # Schmolck reported this problem first.
980
980
981 # A useful post by Alex Martelli on this topic:
981 # A useful post by Alex Martelli on this topic:
982 # Re: inconsistent value from __builtins__
982 # Re: inconsistent value from __builtins__
983 # Von: Alex Martelli <aleaxit@yahoo.com>
983 # Von: Alex Martelli <aleaxit@yahoo.com>
984 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
984 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
985 # Gruppen: comp.lang.python
985 # Gruppen: comp.lang.python
986
986
987 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
987 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
988 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
988 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
989 # > <type 'dict'>
989 # > <type 'dict'>
990 # > >>> print type(__builtins__)
990 # > >>> print type(__builtins__)
991 # > <type 'module'>
991 # > <type 'module'>
992 # > Is this difference in return value intentional?
992 # > Is this difference in return value intentional?
993
993
994 # Well, it's documented that '__builtins__' can be either a dictionary
994 # Well, it's documented that '__builtins__' can be either a dictionary
995 # or a module, and it's been that way for a long time. Whether it's
995 # or a module, and it's been that way for a long time. Whether it's
996 # intentional (or sensible), I don't know. In any case, the idea is
996 # intentional (or sensible), I don't know. In any case, the idea is
997 # that if you need to access the built-in namespace directly, you
997 # that if you need to access the built-in namespace directly, you
998 # should start with "import __builtin__" (note, no 's') which will
998 # should start with "import __builtin__" (note, no 's') which will
999 # definitely give you a module. Yeah, it's somewhat confusing:-(.
999 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1000
1000
1001 # These routines return a properly built module and dict as needed by
1001 # These routines return a properly built module and dict as needed by
1002 # the rest of the code, and can also be used by extension writers to
1002 # the rest of the code, and can also be used by extension writers to
1003 # generate properly initialized namespaces.
1003 # generate properly initialized namespaces.
1004 if (user_ns is not None) or (user_module is not None):
1004 if (user_ns is not None) or (user_module is not None):
1005 self.default_user_namespaces = False
1005 self.default_user_namespaces = False
1006 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1006 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1007
1007
1008 # A record of hidden variables we have added to the user namespace, so
1008 # A record of hidden variables we have added to the user namespace, so
1009 # we can list later only variables defined in actual interactive use.
1009 # we can list later only variables defined in actual interactive use.
1010 self.user_ns_hidden = {}
1010 self.user_ns_hidden = {}
1011
1011
1012 # Now that FakeModule produces a real module, we've run into a nasty
1012 # Now that FakeModule produces a real module, we've run into a nasty
1013 # problem: after script execution (via %run), the module where the user
1013 # problem: after script execution (via %run), the module where the user
1014 # code ran is deleted. Now that this object is a true module (needed
1014 # code ran is deleted. Now that this object is a true module (needed
1015 # so doctest and other tools work correctly), the Python module
1015 # so doctest and other tools work correctly), the Python module
1016 # teardown mechanism runs over it, and sets to None every variable
1016 # teardown mechanism runs over it, and sets to None every variable
1017 # present in that module. Top-level references to objects from the
1017 # present in that module. Top-level references to objects from the
1018 # script survive, because the user_ns is updated with them. However,
1018 # script survive, because the user_ns is updated with them. However,
1019 # calling functions defined in the script that use other things from
1019 # calling functions defined in the script that use other things from
1020 # the script will fail, because the function's closure had references
1020 # the script will fail, because the function's closure had references
1021 # to the original objects, which are now all None. So we must protect
1021 # to the original objects, which are now all None. So we must protect
1022 # these modules from deletion by keeping a cache.
1022 # these modules from deletion by keeping a cache.
1023 #
1023 #
1024 # To avoid keeping stale modules around (we only need the one from the
1024 # To avoid keeping stale modules around (we only need the one from the
1025 # last run), we use a dict keyed with the full path to the script, so
1025 # last run), we use a dict keyed with the full path to the script, so
1026 # only the last version of the module is held in the cache. Note,
1026 # only the last version of the module is held in the cache. Note,
1027 # however, that we must cache the module *namespace contents* (their
1027 # however, that we must cache the module *namespace contents* (their
1028 # __dict__). Because if we try to cache the actual modules, old ones
1028 # __dict__). Because if we try to cache the actual modules, old ones
1029 # (uncached) could be destroyed while still holding references (such as
1029 # (uncached) could be destroyed while still holding references (such as
1030 # those held by GUI objects that tend to be long-lived)>
1030 # those held by GUI objects that tend to be long-lived)>
1031 #
1031 #
1032 # The %reset command will flush this cache. See the cache_main_mod()
1032 # The %reset command will flush this cache. See the cache_main_mod()
1033 # and clear_main_mod_cache() methods for details on use.
1033 # and clear_main_mod_cache() methods for details on use.
1034
1034
1035 # This is the cache used for 'main' namespaces
1035 # This is the cache used for 'main' namespaces
1036 self._main_mod_cache = {}
1036 self._main_mod_cache = {}
1037
1037
1038 # A table holding all the namespaces IPython deals with, so that
1038 # A table holding all the namespaces IPython deals with, so that
1039 # introspection facilities can search easily.
1039 # introspection facilities can search easily.
1040 self.ns_table = {'user_global':self.user_module.__dict__,
1040 self.ns_table = {'user_global':self.user_module.__dict__,
1041 'user_local':self.user_ns,
1041 'user_local':self.user_ns,
1042 'builtin':builtin_mod.__dict__
1042 'builtin':builtin_mod.__dict__
1043 }
1043 }
1044
1044
1045 @property
1045 @property
1046 def user_global_ns(self):
1046 def user_global_ns(self):
1047 return self.user_module.__dict__
1047 return self.user_module.__dict__
1048
1048
1049 def prepare_user_module(self, user_module=None, user_ns=None):
1049 def prepare_user_module(self, user_module=None, user_ns=None):
1050 """Prepare the module and namespace in which user code will be run.
1050 """Prepare the module and namespace in which user code will be run.
1051
1051
1052 When IPython is started normally, both parameters are None: a new module
1052 When IPython is started normally, both parameters are None: a new module
1053 is created automatically, and its __dict__ used as the namespace.
1053 is created automatically, and its __dict__ used as the namespace.
1054
1054
1055 If only user_module is provided, its __dict__ is used as the namespace.
1055 If only user_module is provided, its __dict__ is used as the namespace.
1056 If only user_ns is provided, a dummy module is created, and user_ns
1056 If only user_ns is provided, a dummy module is created, and user_ns
1057 becomes the global namespace. If both are provided (as they may be
1057 becomes the global namespace. If both are provided (as they may be
1058 when embedding), user_ns is the local namespace, and user_module
1058 when embedding), user_ns is the local namespace, and user_module
1059 provides the global namespace.
1059 provides the global namespace.
1060
1060
1061 Parameters
1061 Parameters
1062 ----------
1062 ----------
1063 user_module : module, optional
1063 user_module : module, optional
1064 The current user module in which IPython is being run. If None,
1064 The current user module in which IPython is being run. If None,
1065 a clean module will be created.
1065 a clean module will be created.
1066 user_ns : dict, optional
1066 user_ns : dict, optional
1067 A namespace in which to run interactive commands.
1067 A namespace in which to run interactive commands.
1068
1068
1069 Returns
1069 Returns
1070 -------
1070 -------
1071 A tuple of user_module and user_ns, each properly initialised.
1071 A tuple of user_module and user_ns, each properly initialised.
1072 """
1072 """
1073 if user_module is None and user_ns is not None:
1073 if user_module is None and user_ns is not None:
1074 user_ns.setdefault("__name__", "__main__")
1074 user_ns.setdefault("__name__", "__main__")
1075 user_module = DummyMod()
1075 user_module = DummyMod()
1076 user_module.__dict__ = user_ns
1076 user_module.__dict__ = user_ns
1077
1077
1078 if user_module is None:
1078 if user_module is None:
1079 user_module = types.ModuleType("__main__",
1079 user_module = types.ModuleType("__main__",
1080 doc="Automatically created module for IPython interactive environment")
1080 doc="Automatically created module for IPython interactive environment")
1081
1081
1082 # We must ensure that __builtin__ (without the final 's') is always
1082 # We must ensure that __builtin__ (without the final 's') is always
1083 # available and pointing to the __builtin__ *module*. For more details:
1083 # available and pointing to the __builtin__ *module*. For more details:
1084 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1084 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1085 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1085 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1086 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1086 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1087
1087
1088 if user_ns is None:
1088 if user_ns is None:
1089 user_ns = user_module.__dict__
1089 user_ns = user_module.__dict__
1090
1090
1091 return user_module, user_ns
1091 return user_module, user_ns
1092
1092
1093 def init_sys_modules(self):
1093 def init_sys_modules(self):
1094 # We need to insert into sys.modules something that looks like a
1094 # We need to insert into sys.modules something that looks like a
1095 # module but which accesses the IPython namespace, for shelve and
1095 # module but which accesses the IPython namespace, for shelve and
1096 # pickle to work interactively. Normally they rely on getting
1096 # pickle to work interactively. Normally they rely on getting
1097 # everything out of __main__, but for embedding purposes each IPython
1097 # everything out of __main__, but for embedding purposes each IPython
1098 # instance has its own private namespace, so we can't go shoving
1098 # instance has its own private namespace, so we can't go shoving
1099 # everything into __main__.
1099 # everything into __main__.
1100
1100
1101 # note, however, that we should only do this for non-embedded
1101 # note, however, that we should only do this for non-embedded
1102 # ipythons, which really mimic the __main__.__dict__ with their own
1102 # ipythons, which really mimic the __main__.__dict__ with their own
1103 # namespace. Embedded instances, on the other hand, should not do
1103 # namespace. Embedded instances, on the other hand, should not do
1104 # this because they need to manage the user local/global namespaces
1104 # this because they need to manage the user local/global namespaces
1105 # only, but they live within a 'normal' __main__ (meaning, they
1105 # only, but they live within a 'normal' __main__ (meaning, they
1106 # shouldn't overtake the execution environment of the script they're
1106 # shouldn't overtake the execution environment of the script they're
1107 # embedded in).
1107 # embedded in).
1108
1108
1109 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1109 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1110 main_name = self.user_module.__name__
1110 main_name = self.user_module.__name__
1111 sys.modules[main_name] = self.user_module
1111 sys.modules[main_name] = self.user_module
1112
1112
1113 def init_user_ns(self):
1113 def init_user_ns(self):
1114 """Initialize all user-visible namespaces to their minimum defaults.
1114 """Initialize all user-visible namespaces to their minimum defaults.
1115
1115
1116 Certain history lists are also initialized here, as they effectively
1116 Certain history lists are also initialized here, as they effectively
1117 act as user namespaces.
1117 act as user namespaces.
1118
1118
1119 Notes
1119 Notes
1120 -----
1120 -----
1121 All data structures here are only filled in, they are NOT reset by this
1121 All data structures here are only filled in, they are NOT reset by this
1122 method. If they were not empty before, data will simply be added to
1122 method. If they were not empty before, data will simply be added to
1123 therm.
1123 therm.
1124 """
1124 """
1125 # This function works in two parts: first we put a few things in
1125 # This function works in two parts: first we put a few things in
1126 # user_ns, and we sync that contents into user_ns_hidden so that these
1126 # user_ns, and we sync that contents into user_ns_hidden so that these
1127 # initial variables aren't shown by %who. After the sync, we add the
1127 # initial variables aren't shown by %who. After the sync, we add the
1128 # rest of what we *do* want the user to see with %who even on a new
1128 # rest of what we *do* want the user to see with %who even on a new
1129 # session (probably nothing, so they really only see their own stuff)
1129 # session (probably nothing, so they really only see their own stuff)
1130
1130
1131 # The user dict must *always* have a __builtin__ reference to the
1131 # The user dict must *always* have a __builtin__ reference to the
1132 # Python standard __builtin__ namespace, which must be imported.
1132 # Python standard __builtin__ namespace, which must be imported.
1133 # This is so that certain operations in prompt evaluation can be
1133 # This is so that certain operations in prompt evaluation can be
1134 # reliably executed with builtins. Note that we can NOT use
1134 # reliably executed with builtins. Note that we can NOT use
1135 # __builtins__ (note the 's'), because that can either be a dict or a
1135 # __builtins__ (note the 's'), because that can either be a dict or a
1136 # module, and can even mutate at runtime, depending on the context
1136 # module, and can even mutate at runtime, depending on the context
1137 # (Python makes no guarantees on it). In contrast, __builtin__ is
1137 # (Python makes no guarantees on it). In contrast, __builtin__ is
1138 # always a module object, though it must be explicitly imported.
1138 # always a module object, though it must be explicitly imported.
1139
1139
1140 # For more details:
1140 # For more details:
1141 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1141 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1142 ns = dict()
1142 ns = dict()
1143
1143
1144 # make global variables for user access to the histories
1144 # make global variables for user access to the histories
1145 ns['_ih'] = self.history_manager.input_hist_parsed
1145 ns['_ih'] = self.history_manager.input_hist_parsed
1146 ns['_oh'] = self.history_manager.output_hist
1146 ns['_oh'] = self.history_manager.output_hist
1147 ns['_dh'] = self.history_manager.dir_hist
1147 ns['_dh'] = self.history_manager.dir_hist
1148
1148
1149 ns['_sh'] = shadowns
1149 ns['_sh'] = shadowns
1150
1150
1151 # user aliases to input and output histories. These shouldn't show up
1151 # user aliases to input and output histories. These shouldn't show up
1152 # in %who, as they can have very large reprs.
1152 # in %who, as they can have very large reprs.
1153 ns['In'] = self.history_manager.input_hist_parsed
1153 ns['In'] = self.history_manager.input_hist_parsed
1154 ns['Out'] = self.history_manager.output_hist
1154 ns['Out'] = self.history_manager.output_hist
1155
1155
1156 # Store myself as the public api!!!
1156 # Store myself as the public api!!!
1157 ns['get_ipython'] = self.get_ipython
1157 ns['get_ipython'] = self.get_ipython
1158
1158
1159 ns['exit'] = self.exiter
1159 ns['exit'] = self.exiter
1160 ns['quit'] = self.exiter
1160 ns['quit'] = self.exiter
1161
1161
1162 # Sync what we've added so far to user_ns_hidden so these aren't seen
1162 # Sync what we've added so far to user_ns_hidden so these aren't seen
1163 # by %who
1163 # by %who
1164 self.user_ns_hidden.update(ns)
1164 self.user_ns_hidden.update(ns)
1165
1165
1166 # Anything put into ns now would show up in %who. Think twice before
1166 # Anything put into ns now would show up in %who. Think twice before
1167 # putting anything here, as we really want %who to show the user their
1167 # putting anything here, as we really want %who to show the user their
1168 # stuff, not our variables.
1168 # stuff, not our variables.
1169
1169
1170 # Finally, update the real user's namespace
1170 # Finally, update the real user's namespace
1171 self.user_ns.update(ns)
1171 self.user_ns.update(ns)
1172
1172
1173 @property
1173 @property
1174 def all_ns_refs(self):
1174 def all_ns_refs(self):
1175 """Get a list of references to all the namespace dictionaries in which
1175 """Get a list of references to all the namespace dictionaries in which
1176 IPython might store a user-created object.
1176 IPython might store a user-created object.
1177
1177
1178 Note that this does not include the displayhook, which also caches
1178 Note that this does not include the displayhook, which also caches
1179 objects from the output."""
1179 objects from the output."""
1180 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1180 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1181 [m.__dict__ for m in self._main_mod_cache.values()]
1181 [m.__dict__ for m in self._main_mod_cache.values()]
1182
1182
1183 def reset(self, new_session=True):
1183 def reset(self, new_session=True):
1184 """Clear all internal namespaces, and attempt to release references to
1184 """Clear all internal namespaces, and attempt to release references to
1185 user objects.
1185 user objects.
1186
1186
1187 If new_session is True, a new history session will be opened.
1187 If new_session is True, a new history session will be opened.
1188 """
1188 """
1189 # Clear histories
1189 # Clear histories
1190 self.history_manager.reset(new_session)
1190 self.history_manager.reset(new_session)
1191 # Reset counter used to index all histories
1191 # Reset counter used to index all histories
1192 if new_session:
1192 if new_session:
1193 self.execution_count = 1
1193 self.execution_count = 1
1194
1194
1195 # Flush cached output items
1195 # Flush cached output items
1196 if self.displayhook.do_full_cache:
1196 if self.displayhook.do_full_cache:
1197 self.displayhook.flush()
1197 self.displayhook.flush()
1198
1198
1199 # The main execution namespaces must be cleared very carefully,
1199 # The main execution namespaces must be cleared very carefully,
1200 # skipping the deletion of the builtin-related keys, because doing so
1200 # skipping the deletion of the builtin-related keys, because doing so
1201 # would cause errors in many object's __del__ methods.
1201 # would cause errors in many object's __del__ methods.
1202 if self.user_ns is not self.user_global_ns:
1202 if self.user_ns is not self.user_global_ns:
1203 self.user_ns.clear()
1203 self.user_ns.clear()
1204 ns = self.user_global_ns
1204 ns = self.user_global_ns
1205 drop_keys = set(ns.keys())
1205 drop_keys = set(ns.keys())
1206 drop_keys.discard('__builtin__')
1206 drop_keys.discard('__builtin__')
1207 drop_keys.discard('__builtins__')
1207 drop_keys.discard('__builtins__')
1208 drop_keys.discard('__name__')
1208 drop_keys.discard('__name__')
1209 for k in drop_keys:
1209 for k in drop_keys:
1210 del ns[k]
1210 del ns[k]
1211
1211
1212 self.user_ns_hidden.clear()
1212 self.user_ns_hidden.clear()
1213
1213
1214 # Restore the user namespaces to minimal usability
1214 # Restore the user namespaces to minimal usability
1215 self.init_user_ns()
1215 self.init_user_ns()
1216
1216
1217 # Restore the default and user aliases
1217 # Restore the default and user aliases
1218 self.alias_manager.clear_aliases()
1218 self.alias_manager.clear_aliases()
1219 self.alias_manager.init_aliases()
1219 self.alias_manager.init_aliases()
1220
1220
1221 # Flush the private list of module references kept for script
1221 # Flush the private list of module references kept for script
1222 # execution protection
1222 # execution protection
1223 self.clear_main_mod_cache()
1223 self.clear_main_mod_cache()
1224
1224
1225 def del_var(self, varname, by_name=False):
1225 def del_var(self, varname, by_name=False):
1226 """Delete a variable from the various namespaces, so that, as
1226 """Delete a variable from the various namespaces, so that, as
1227 far as possible, we're not keeping any hidden references to it.
1227 far as possible, we're not keeping any hidden references to it.
1228
1228
1229 Parameters
1229 Parameters
1230 ----------
1230 ----------
1231 varname : str
1231 varname : str
1232 The name of the variable to delete.
1232 The name of the variable to delete.
1233 by_name : bool
1233 by_name : bool
1234 If True, delete variables with the given name in each
1234 If True, delete variables with the given name in each
1235 namespace. If False (default), find the variable in the user
1235 namespace. If False (default), find the variable in the user
1236 namespace, and delete references to it.
1236 namespace, and delete references to it.
1237 """
1237 """
1238 if varname in ('__builtin__', '__builtins__'):
1238 if varname in ('__builtin__', '__builtins__'):
1239 raise ValueError("Refusing to delete %s" % varname)
1239 raise ValueError("Refusing to delete %s" % varname)
1240
1240
1241 ns_refs = self.all_ns_refs
1241 ns_refs = self.all_ns_refs
1242
1242
1243 if by_name: # Delete by name
1243 if by_name: # Delete by name
1244 for ns in ns_refs:
1244 for ns in ns_refs:
1245 try:
1245 try:
1246 del ns[varname]
1246 del ns[varname]
1247 except KeyError:
1247 except KeyError:
1248 pass
1248 pass
1249 else: # Delete by object
1249 else: # Delete by object
1250 try:
1250 try:
1251 obj = self.user_ns[varname]
1251 obj = self.user_ns[varname]
1252 except KeyError:
1252 except KeyError:
1253 raise NameError("name '%s' is not defined" % varname)
1253 raise NameError("name '%s' is not defined" % varname)
1254 # Also check in output history
1254 # Also check in output history
1255 ns_refs.append(self.history_manager.output_hist)
1255 ns_refs.append(self.history_manager.output_hist)
1256 for ns in ns_refs:
1256 for ns in ns_refs:
1257 to_delete = [n for n, o in ns.items() if o is obj]
1257 to_delete = [n for n, o in ns.items() if o is obj]
1258 for name in to_delete:
1258 for name in to_delete:
1259 del ns[name]
1259 del ns[name]
1260
1260
1261 # displayhook keeps extra references, but not in a dictionary
1261 # displayhook keeps extra references, but not in a dictionary
1262 for name in ('_', '__', '___'):
1262 for name in ('_', '__', '___'):
1263 if getattr(self.displayhook, name) is obj:
1263 if getattr(self.displayhook, name) is obj:
1264 setattr(self.displayhook, name, None)
1264 setattr(self.displayhook, name, None)
1265
1265
1266 def reset_selective(self, regex=None):
1266 def reset_selective(self, regex=None):
1267 """Clear selective variables from internal namespaces based on a
1267 """Clear selective variables from internal namespaces based on a
1268 specified regular expression.
1268 specified regular expression.
1269
1269
1270 Parameters
1270 Parameters
1271 ----------
1271 ----------
1272 regex : string or compiled pattern, optional
1272 regex : string or compiled pattern, optional
1273 A regular expression pattern that will be used in searching
1273 A regular expression pattern that will be used in searching
1274 variable names in the users namespaces.
1274 variable names in the users namespaces.
1275 """
1275 """
1276 if regex is not None:
1276 if regex is not None:
1277 try:
1277 try:
1278 m = re.compile(regex)
1278 m = re.compile(regex)
1279 except TypeError:
1279 except TypeError:
1280 raise TypeError('regex must be a string or compiled pattern')
1280 raise TypeError('regex must be a string or compiled pattern')
1281 # Search for keys in each namespace that match the given regex
1281 # Search for keys in each namespace that match the given regex
1282 # If a match is found, delete the key/value pair.
1282 # If a match is found, delete the key/value pair.
1283 for ns in self.all_ns_refs:
1283 for ns in self.all_ns_refs:
1284 for var in ns:
1284 for var in ns:
1285 if m.search(var):
1285 if m.search(var):
1286 del ns[var]
1286 del ns[var]
1287
1287
1288 def push(self, variables, interactive=True):
1288 def push(self, variables, interactive=True):
1289 """Inject a group of variables into the IPython user namespace.
1289 """Inject a group of variables into the IPython user namespace.
1290
1290
1291 Parameters
1291 Parameters
1292 ----------
1292 ----------
1293 variables : dict, str or list/tuple of str
1293 variables : dict, str or list/tuple of str
1294 The variables to inject into the user's namespace. If a dict, a
1294 The variables to inject into the user's namespace. If a dict, a
1295 simple update is done. If a str, the string is assumed to have
1295 simple update is done. If a str, the string is assumed to have
1296 variable names separated by spaces. A list/tuple of str can also
1296 variable names separated by spaces. A list/tuple of str can also
1297 be used to give the variable names. If just the variable names are
1297 be used to give the variable names. If just the variable names are
1298 give (list/tuple/str) then the variable values looked up in the
1298 give (list/tuple/str) then the variable values looked up in the
1299 callers frame.
1299 callers frame.
1300 interactive : bool
1300 interactive : bool
1301 If True (default), the variables will be listed with the ``who``
1301 If True (default), the variables will be listed with the ``who``
1302 magic.
1302 magic.
1303 """
1303 """
1304 vdict = None
1304 vdict = None
1305
1305
1306 # We need a dict of name/value pairs to do namespace updates.
1306 # We need a dict of name/value pairs to do namespace updates.
1307 if isinstance(variables, dict):
1307 if isinstance(variables, dict):
1308 vdict = variables
1308 vdict = variables
1309 elif isinstance(variables, (str, list, tuple)):
1309 elif isinstance(variables, (str, list, tuple)):
1310 if isinstance(variables, str):
1310 if isinstance(variables, str):
1311 vlist = variables.split()
1311 vlist = variables.split()
1312 else:
1312 else:
1313 vlist = variables
1313 vlist = variables
1314 vdict = {}
1314 vdict = {}
1315 cf = sys._getframe(1)
1315 cf = sys._getframe(1)
1316 for name in vlist:
1316 for name in vlist:
1317 try:
1317 try:
1318 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1318 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1319 except:
1319 except:
1320 print('Could not get variable %s from %s' %
1320 print('Could not get variable %s from %s' %
1321 (name,cf.f_code.co_name))
1321 (name,cf.f_code.co_name))
1322 else:
1322 else:
1323 raise ValueError('variables must be a dict/str/list/tuple')
1323 raise ValueError('variables must be a dict/str/list/tuple')
1324
1324
1325 # Propagate variables to user namespace
1325 # Propagate variables to user namespace
1326 self.user_ns.update(vdict)
1326 self.user_ns.update(vdict)
1327
1327
1328 # And configure interactive visibility
1328 # And configure interactive visibility
1329 user_ns_hidden = self.user_ns_hidden
1329 user_ns_hidden = self.user_ns_hidden
1330 if interactive:
1330 if interactive:
1331 for name in vdict:
1331 for name in vdict:
1332 user_ns_hidden.pop(name, None)
1332 user_ns_hidden.pop(name, None)
1333 else:
1333 else:
1334 user_ns_hidden.update(vdict)
1334 user_ns_hidden.update(vdict)
1335
1335
1336 def drop_by_id(self, variables):
1336 def drop_by_id(self, variables):
1337 """Remove a dict of variables from the user namespace, if they are the
1337 """Remove a dict of variables from the user namespace, if they are the
1338 same as the values in the dictionary.
1338 same as the values in the dictionary.
1339
1339
1340 This is intended for use by extensions: variables that they've added can
1340 This is intended for use by extensions: variables that they've added can
1341 be taken back out if they are unloaded, without removing any that the
1341 be taken back out if they are unloaded, without removing any that the
1342 user has overwritten.
1342 user has overwritten.
1343
1343
1344 Parameters
1344 Parameters
1345 ----------
1345 ----------
1346 variables : dict
1346 variables : dict
1347 A dictionary mapping object names (as strings) to the objects.
1347 A dictionary mapping object names (as strings) to the objects.
1348 """
1348 """
1349 for name, obj in variables.items():
1349 for name, obj in variables.items():
1350 if name in self.user_ns and self.user_ns[name] is obj:
1350 if name in self.user_ns and self.user_ns[name] is obj:
1351 del self.user_ns[name]
1351 del self.user_ns[name]
1352 self.user_ns_hidden.pop(name, None)
1352 self.user_ns_hidden.pop(name, None)
1353
1353
1354 #-------------------------------------------------------------------------
1354 #-------------------------------------------------------------------------
1355 # Things related to object introspection
1355 # Things related to object introspection
1356 #-------------------------------------------------------------------------
1356 #-------------------------------------------------------------------------
1357
1357
1358 def _ofind(self, oname, namespaces=None):
1358 def _ofind(self, oname, namespaces=None):
1359 """Find an object in the available namespaces.
1359 """Find an object in the available namespaces.
1360
1360
1361 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1361 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1362
1362
1363 Has special code to detect magic functions.
1363 Has special code to detect magic functions.
1364 """
1364 """
1365 oname = oname.strip()
1365 oname = oname.strip()
1366 #print '1- oname: <%r>' % oname # dbg
1366 #print '1- oname: <%r>' % oname # dbg
1367 if not oname.startswith(ESC_MAGIC) and \
1367 if not oname.startswith(ESC_MAGIC) and \
1368 not oname.startswith(ESC_MAGIC2) and \
1368 not oname.startswith(ESC_MAGIC2) and \
1369 not py3compat.isidentifier(oname, dotted=True):
1369 not py3compat.isidentifier(oname, dotted=True):
1370 return dict(found=False)
1370 return dict(found=False)
1371
1371
1372 if namespaces is None:
1372 if namespaces is None:
1373 # Namespaces to search in:
1373 # Namespaces to search in:
1374 # Put them in a list. The order is important so that we
1374 # Put them in a list. The order is important so that we
1375 # find things in the same order that Python finds them.
1375 # find things in the same order that Python finds them.
1376 namespaces = [ ('Interactive', self.user_ns),
1376 namespaces = [ ('Interactive', self.user_ns),
1377 ('Interactive (global)', self.user_global_ns),
1377 ('Interactive (global)', self.user_global_ns),
1378 ('Python builtin', builtin_mod.__dict__),
1378 ('Python builtin', builtin_mod.__dict__),
1379 ]
1379 ]
1380
1380
1381 # initialize results to 'null'
1381 # initialize results to 'null'
1382 found = False; obj = None; ospace = None;
1382 found = False; obj = None; ospace = None;
1383 ismagic = False; isalias = False; parent = None
1383 ismagic = False; isalias = False; parent = None
1384
1384
1385 # Look for the given name by splitting it in parts. If the head is
1385 # Look for the given name by splitting it in parts. If the head is
1386 # found, then we look for all the remaining parts as members, and only
1386 # found, then we look for all the remaining parts as members, and only
1387 # declare success if we can find them all.
1387 # declare success if we can find them all.
1388 oname_parts = oname.split('.')
1388 oname_parts = oname.split('.')
1389 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1389 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1390 for nsname,ns in namespaces:
1390 for nsname,ns in namespaces:
1391 try:
1391 try:
1392 obj = ns[oname_head]
1392 obj = ns[oname_head]
1393 except KeyError:
1393 except KeyError:
1394 continue
1394 continue
1395 else:
1395 else:
1396 #print 'oname_rest:', oname_rest # dbg
1396 #print 'oname_rest:', oname_rest # dbg
1397 for idx, part in enumerate(oname_rest):
1397 for idx, part in enumerate(oname_rest):
1398 try:
1398 try:
1399 parent = obj
1399 parent = obj
1400 # The last part is looked up in a special way to avoid
1400 # The last part is looked up in a special way to avoid
1401 # descriptor invocation as it may raise or have side
1401 # descriptor invocation as it may raise or have side
1402 # effects.
1402 # effects.
1403 if idx == len(oname_rest) - 1:
1403 if idx == len(oname_rest) - 1:
1404 obj = self._getattr_property(obj, part)
1404 obj = self._getattr_property(obj, part)
1405 else:
1405 else:
1406 obj = getattr(obj, part)
1406 obj = getattr(obj, part)
1407 except:
1407 except:
1408 # Blanket except b/c some badly implemented objects
1408 # Blanket except b/c some badly implemented objects
1409 # allow __getattr__ to raise exceptions other than
1409 # allow __getattr__ to raise exceptions other than
1410 # AttributeError, which then crashes IPython.
1410 # AttributeError, which then crashes IPython.
1411 break
1411 break
1412 else:
1412 else:
1413 # If we finish the for loop (no break), we got all members
1413 # If we finish the for loop (no break), we got all members
1414 found = True
1414 found = True
1415 ospace = nsname
1415 ospace = nsname
1416 break # namespace loop
1416 break # namespace loop
1417
1417
1418 # Try to see if it's magic
1418 # Try to see if it's magic
1419 if not found:
1419 if not found:
1420 obj = None
1420 obj = None
1421 if oname.startswith(ESC_MAGIC2):
1421 if oname.startswith(ESC_MAGIC2):
1422 oname = oname.lstrip(ESC_MAGIC2)
1422 oname = oname.lstrip(ESC_MAGIC2)
1423 obj = self.find_cell_magic(oname)
1423 obj = self.find_cell_magic(oname)
1424 elif oname.startswith(ESC_MAGIC):
1424 elif oname.startswith(ESC_MAGIC):
1425 oname = oname.lstrip(ESC_MAGIC)
1425 oname = oname.lstrip(ESC_MAGIC)
1426 obj = self.find_line_magic(oname)
1426 obj = self.find_line_magic(oname)
1427 else:
1427 else:
1428 # search without prefix, so run? will find %run?
1428 # search without prefix, so run? will find %run?
1429 obj = self.find_line_magic(oname)
1429 obj = self.find_line_magic(oname)
1430 if obj is None:
1430 if obj is None:
1431 obj = self.find_cell_magic(oname)
1431 obj = self.find_cell_magic(oname)
1432 if obj is not None:
1432 if obj is not None:
1433 found = True
1433 found = True
1434 ospace = 'IPython internal'
1434 ospace = 'IPython internal'
1435 ismagic = True
1435 ismagic = True
1436 isalias = isinstance(obj, Alias)
1436 isalias = isinstance(obj, Alias)
1437
1437
1438 # Last try: special-case some literals like '', [], {}, etc:
1438 # Last try: special-case some literals like '', [], {}, etc:
1439 if not found and oname_head in ["''",'""','[]','{}','()']:
1439 if not found and oname_head in ["''",'""','[]','{}','()']:
1440 obj = eval(oname_head)
1440 obj = eval(oname_head)
1441 found = True
1441 found = True
1442 ospace = 'Interactive'
1442 ospace = 'Interactive'
1443
1443
1444 return {'found':found, 'obj':obj, 'namespace':ospace,
1444 return {'found':found, 'obj':obj, 'namespace':ospace,
1445 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1445 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1446
1446
1447 @staticmethod
1447 @staticmethod
1448 def _getattr_property(obj, attrname):
1448 def _getattr_property(obj, attrname):
1449 """Property-aware getattr to use in object finding.
1449 """Property-aware getattr to use in object finding.
1450
1450
1451 If attrname represents a property, return it unevaluated (in case it has
1451 If attrname represents a property, return it unevaluated (in case it has
1452 side effects or raises an error.
1452 side effects or raises an error.
1453
1453
1454 """
1454 """
1455 if not isinstance(obj, type):
1455 if not isinstance(obj, type):
1456 try:
1456 try:
1457 # `getattr(type(obj), attrname)` is not guaranteed to return
1457 # `getattr(type(obj), attrname)` is not guaranteed to return
1458 # `obj`, but does so for property:
1458 # `obj`, but does so for property:
1459 #
1459 #
1460 # property.__get__(self, None, cls) -> self
1460 # property.__get__(self, None, cls) -> self
1461 #
1461 #
1462 # The universal alternative is to traverse the mro manually
1462 # The universal alternative is to traverse the mro manually
1463 # searching for attrname in class dicts.
1463 # searching for attrname in class dicts.
1464 attr = getattr(type(obj), attrname)
1464 attr = getattr(type(obj), attrname)
1465 except AttributeError:
1465 except AttributeError:
1466 pass
1466 pass
1467 else:
1467 else:
1468 # This relies on the fact that data descriptors (with both
1468 # This relies on the fact that data descriptors (with both
1469 # __get__ & __set__ magic methods) take precedence over
1469 # __get__ & __set__ magic methods) take precedence over
1470 # instance-level attributes:
1470 # instance-level attributes:
1471 #
1471 #
1472 # class A(object):
1472 # class A(object):
1473 # @property
1473 # @property
1474 # def foobar(self): return 123
1474 # def foobar(self): return 123
1475 # a = A()
1475 # a = A()
1476 # a.__dict__['foobar'] = 345
1476 # a.__dict__['foobar'] = 345
1477 # a.foobar # == 123
1477 # a.foobar # == 123
1478 #
1478 #
1479 # So, a property may be returned right away.
1479 # So, a property may be returned right away.
1480 if isinstance(attr, property):
1480 if isinstance(attr, property):
1481 return attr
1481 return attr
1482
1482
1483 # Nothing helped, fall back.
1483 # Nothing helped, fall back.
1484 return getattr(obj, attrname)
1484 return getattr(obj, attrname)
1485
1485
1486 def _object_find(self, oname, namespaces=None):
1486 def _object_find(self, oname, namespaces=None):
1487 """Find an object and return a struct with info about it."""
1487 """Find an object and return a struct with info about it."""
1488 return Struct(self._ofind(oname, namespaces))
1488 return Struct(self._ofind(oname, namespaces))
1489
1489
1490 def _inspect(self, meth, oname, namespaces=None, **kw):
1490 def _inspect(self, meth, oname, namespaces=None, **kw):
1491 """Generic interface to the inspector system.
1491 """Generic interface to the inspector system.
1492
1492
1493 This function is meant to be called by pdef, pdoc & friends.
1493 This function is meant to be called by pdef, pdoc & friends.
1494 """
1494 """
1495 info = self._object_find(oname, namespaces)
1495 info = self._object_find(oname, namespaces)
1496 docformat = sphinxify if self.sphinxify_docstring else None
1496 docformat = sphinxify if self.sphinxify_docstring else None
1497 if info.found:
1497 if info.found:
1498 pmethod = getattr(self.inspector, meth)
1498 pmethod = getattr(self.inspector, meth)
1499 # TODO: only apply format_screen to the plain/text repr of the mime
1499 # TODO: only apply format_screen to the plain/text repr of the mime
1500 # bundle.
1500 # bundle.
1501 formatter = format_screen if info.ismagic else docformat
1501 formatter = format_screen if info.ismagic else docformat
1502 if meth == 'pdoc':
1502 if meth == 'pdoc':
1503 pmethod(info.obj, oname, formatter)
1503 pmethod(info.obj, oname, formatter)
1504 elif meth == 'pinfo':
1504 elif meth == 'pinfo':
1505 pmethod(info.obj, oname, formatter, info,
1505 pmethod(info.obj, oname, formatter, info,
1506 enable_html_pager=self.enable_html_pager, **kw)
1506 enable_html_pager=self.enable_html_pager, **kw)
1507 else:
1507 else:
1508 pmethod(info.obj, oname)
1508 pmethod(info.obj, oname)
1509 else:
1509 else:
1510 print('Object `%s` not found.' % oname)
1510 print('Object `%s` not found.' % oname)
1511 return 'not found' # so callers can take other action
1511 return 'not found' # so callers can take other action
1512
1512
1513 def object_inspect(self, oname, detail_level=0):
1513 def object_inspect(self, oname, detail_level=0):
1514 """Get object info about oname"""
1514 """Get object info about oname"""
1515 with self.builtin_trap:
1515 with self.builtin_trap:
1516 info = self._object_find(oname)
1516 info = self._object_find(oname)
1517 if info.found:
1517 if info.found:
1518 return self.inspector.info(info.obj, oname, info=info,
1518 return self.inspector.info(info.obj, oname, info=info,
1519 detail_level=detail_level
1519 detail_level=detail_level
1520 )
1520 )
1521 else:
1521 else:
1522 return oinspect.object_info(name=oname, found=False)
1522 return oinspect.object_info(name=oname, found=False)
1523
1523
1524 def object_inspect_text(self, oname, detail_level=0):
1524 def object_inspect_text(self, oname, detail_level=0):
1525 """Get object info as formatted text"""
1525 """Get object info as formatted text"""
1526 return self.object_inspect_mime(oname, detail_level)['text/plain']
1526 return self.object_inspect_mime(oname, detail_level)['text/plain']
1527
1527
1528 def object_inspect_mime(self, oname, detail_level=0):
1528 def object_inspect_mime(self, oname, detail_level=0):
1529 """Get object info as a mimebundle of formatted representations.
1529 """Get object info as a mimebundle of formatted representations.
1530
1530
1531 A mimebundle is a dictionary, keyed by mime-type.
1531 A mimebundle is a dictionary, keyed by mime-type.
1532 It must always have the key `'text/plain'`.
1532 It must always have the key `'text/plain'`.
1533 """
1533 """
1534 with self.builtin_trap:
1534 with self.builtin_trap:
1535 info = self._object_find(oname)
1535 info = self._object_find(oname)
1536 if info.found:
1536 if info.found:
1537 return self.inspector._get_info(info.obj, oname, info=info,
1537 return self.inspector._get_info(info.obj, oname, info=info,
1538 detail_level=detail_level
1538 detail_level=detail_level
1539 )
1539 )
1540 else:
1540 else:
1541 raise KeyError(oname)
1541 raise KeyError(oname)
1542
1542
1543 #-------------------------------------------------------------------------
1543 #-------------------------------------------------------------------------
1544 # Things related to history management
1544 # Things related to history management
1545 #-------------------------------------------------------------------------
1545 #-------------------------------------------------------------------------
1546
1546
1547 def init_history(self):
1547 def init_history(self):
1548 """Sets up the command history, and starts regular autosaves."""
1548 """Sets up the command history, and starts regular autosaves."""
1549 self.history_manager = HistoryManager(shell=self, parent=self)
1549 self.history_manager = HistoryManager(shell=self, parent=self)
1550 self.configurables.append(self.history_manager)
1550 self.configurables.append(self.history_manager)
1551
1551
1552 #-------------------------------------------------------------------------
1552 #-------------------------------------------------------------------------
1553 # Things related to exception handling and tracebacks (not debugging)
1553 # Things related to exception handling and tracebacks (not debugging)
1554 #-------------------------------------------------------------------------
1554 #-------------------------------------------------------------------------
1555
1555
1556 debugger_cls = Pdb
1556 debugger_cls = Pdb
1557
1557
1558 def init_traceback_handlers(self, custom_exceptions):
1558 def init_traceback_handlers(self, custom_exceptions):
1559 # Syntax error handler.
1559 # Syntax error handler.
1560 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1560 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1561
1561
1562 # The interactive one is initialized with an offset, meaning we always
1562 # The interactive one is initialized with an offset, meaning we always
1563 # want to remove the topmost item in the traceback, which is our own
1563 # want to remove the topmost item in the traceback, which is our own
1564 # internal code. Valid modes: ['Plain','Context','Verbose']
1564 # internal code. Valid modes: ['Plain','Context','Verbose']
1565 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1565 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1566 color_scheme='NoColor',
1566 color_scheme='NoColor',
1567 tb_offset = 1,
1567 tb_offset = 1,
1568 check_cache=check_linecache_ipython,
1568 check_cache=check_linecache_ipython,
1569 debugger_cls=self.debugger_cls, parent=self)
1569 debugger_cls=self.debugger_cls, parent=self)
1570
1570
1571 # The instance will store a pointer to the system-wide exception hook,
1571 # The instance will store a pointer to the system-wide exception hook,
1572 # so that runtime code (such as magics) can access it. This is because
1572 # so that runtime code (such as magics) can access it. This is because
1573 # during the read-eval loop, it may get temporarily overwritten.
1573 # during the read-eval loop, it may get temporarily overwritten.
1574 self.sys_excepthook = sys.excepthook
1574 self.sys_excepthook = sys.excepthook
1575
1575
1576 # and add any custom exception handlers the user may have specified
1576 # and add any custom exception handlers the user may have specified
1577 self.set_custom_exc(*custom_exceptions)
1577 self.set_custom_exc(*custom_exceptions)
1578
1578
1579 # Set the exception mode
1579 # Set the exception mode
1580 self.InteractiveTB.set_mode(mode=self.xmode)
1580 self.InteractiveTB.set_mode(mode=self.xmode)
1581
1581
1582 def set_custom_exc(self, exc_tuple, handler):
1582 def set_custom_exc(self, exc_tuple, handler):
1583 """set_custom_exc(exc_tuple, handler)
1583 """set_custom_exc(exc_tuple, handler)
1584
1584
1585 Set a custom exception handler, which will be called if any of the
1585 Set a custom exception handler, which will be called if any of the
1586 exceptions in exc_tuple occur in the mainloop (specifically, in the
1586 exceptions in exc_tuple occur in the mainloop (specifically, in the
1587 run_code() method).
1587 run_code() method).
1588
1588
1589 Parameters
1589 Parameters
1590 ----------
1590 ----------
1591
1591
1592 exc_tuple : tuple of exception classes
1592 exc_tuple : tuple of exception classes
1593 A *tuple* of exception classes, for which to call the defined
1593 A *tuple* of exception classes, for which to call the defined
1594 handler. It is very important that you use a tuple, and NOT A
1594 handler. It is very important that you use a tuple, and NOT A
1595 LIST here, because of the way Python's except statement works. If
1595 LIST here, because of the way Python's except statement works. If
1596 you only want to trap a single exception, use a singleton tuple::
1596 you only want to trap a single exception, use a singleton tuple::
1597
1597
1598 exc_tuple == (MyCustomException,)
1598 exc_tuple == (MyCustomException,)
1599
1599
1600 handler : callable
1600 handler : callable
1601 handler must have the following signature::
1601 handler must have the following signature::
1602
1602
1603 def my_handler(self, etype, value, tb, tb_offset=None):
1603 def my_handler(self, etype, value, tb, tb_offset=None):
1604 ...
1604 ...
1605 return structured_traceback
1605 return structured_traceback
1606
1606
1607 Your handler must return a structured traceback (a list of strings),
1607 Your handler must return a structured traceback (a list of strings),
1608 or None.
1608 or None.
1609
1609
1610 This will be made into an instance method (via types.MethodType)
1610 This will be made into an instance method (via types.MethodType)
1611 of IPython itself, and it will be called if any of the exceptions
1611 of IPython itself, and it will be called if any of the exceptions
1612 listed in the exc_tuple are caught. If the handler is None, an
1612 listed in the exc_tuple are caught. If the handler is None, an
1613 internal basic one is used, which just prints basic info.
1613 internal basic one is used, which just prints basic info.
1614
1614
1615 To protect IPython from crashes, if your handler ever raises an
1615 To protect IPython from crashes, if your handler ever raises an
1616 exception or returns an invalid result, it will be immediately
1616 exception or returns an invalid result, it will be immediately
1617 disabled.
1617 disabled.
1618
1618
1619 WARNING: by putting in your own exception handler into IPython's main
1619 WARNING: by putting in your own exception handler into IPython's main
1620 execution loop, you run a very good chance of nasty crashes. This
1620 execution loop, you run a very good chance of nasty crashes. This
1621 facility should only be used if you really know what you are doing."""
1621 facility should only be used if you really know what you are doing."""
1622
1622
1623 assert type(exc_tuple)==type(()) , \
1623 assert type(exc_tuple)==type(()) , \
1624 "The custom exceptions must be given AS A TUPLE."
1624 "The custom exceptions must be given AS A TUPLE."
1625
1625
1626 def dummy_handler(self, etype, value, tb, tb_offset=None):
1626 def dummy_handler(self, etype, value, tb, tb_offset=None):
1627 print('*** Simple custom exception handler ***')
1627 print('*** Simple custom exception handler ***')
1628 print('Exception type :',etype)
1628 print('Exception type :',etype)
1629 print('Exception value:',value)
1629 print('Exception value:',value)
1630 print('Traceback :',tb)
1630 print('Traceback :',tb)
1631 #print 'Source code :','\n'.join(self.buffer)
1631 #print 'Source code :','\n'.join(self.buffer)
1632
1632
1633 def validate_stb(stb):
1633 def validate_stb(stb):
1634 """validate structured traceback return type
1634 """validate structured traceback return type
1635
1635
1636 return type of CustomTB *should* be a list of strings, but allow
1636 return type of CustomTB *should* be a list of strings, but allow
1637 single strings or None, which are harmless.
1637 single strings or None, which are harmless.
1638
1638
1639 This function will *always* return a list of strings,
1639 This function will *always* return a list of strings,
1640 and will raise a TypeError if stb is inappropriate.
1640 and will raise a TypeError if stb is inappropriate.
1641 """
1641 """
1642 msg = "CustomTB must return list of strings, not %r" % stb
1642 msg = "CustomTB must return list of strings, not %r" % stb
1643 if stb is None:
1643 if stb is None:
1644 return []
1644 return []
1645 elif isinstance(stb, str):
1645 elif isinstance(stb, str):
1646 return [stb]
1646 return [stb]
1647 elif not isinstance(stb, list):
1647 elif not isinstance(stb, list):
1648 raise TypeError(msg)
1648 raise TypeError(msg)
1649 # it's a list
1649 # it's a list
1650 for line in stb:
1650 for line in stb:
1651 # check every element
1651 # check every element
1652 if not isinstance(line, str):
1652 if not isinstance(line, str):
1653 raise TypeError(msg)
1653 raise TypeError(msg)
1654 return stb
1654 return stb
1655
1655
1656 if handler is None:
1656 if handler is None:
1657 wrapped = dummy_handler
1657 wrapped = dummy_handler
1658 else:
1658 else:
1659 def wrapped(self,etype,value,tb,tb_offset=None):
1659 def wrapped(self,etype,value,tb,tb_offset=None):
1660 """wrap CustomTB handler, to protect IPython from user code
1660 """wrap CustomTB handler, to protect IPython from user code
1661
1661
1662 This makes it harder (but not impossible) for custom exception
1662 This makes it harder (but not impossible) for custom exception
1663 handlers to crash IPython.
1663 handlers to crash IPython.
1664 """
1664 """
1665 try:
1665 try:
1666 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1666 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1667 return validate_stb(stb)
1667 return validate_stb(stb)
1668 except:
1668 except:
1669 # clear custom handler immediately
1669 # clear custom handler immediately
1670 self.set_custom_exc((), None)
1670 self.set_custom_exc((), None)
1671 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1671 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1672 # show the exception in handler first
1672 # show the exception in handler first
1673 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1673 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1674 print(self.InteractiveTB.stb2text(stb))
1674 print(self.InteractiveTB.stb2text(stb))
1675 print("The original exception:")
1675 print("The original exception:")
1676 stb = self.InteractiveTB.structured_traceback(
1676 stb = self.InteractiveTB.structured_traceback(
1677 (etype,value,tb), tb_offset=tb_offset
1677 (etype,value,tb), tb_offset=tb_offset
1678 )
1678 )
1679 return stb
1679 return stb
1680
1680
1681 self.CustomTB = types.MethodType(wrapped,self)
1681 self.CustomTB = types.MethodType(wrapped,self)
1682 self.custom_exceptions = exc_tuple
1682 self.custom_exceptions = exc_tuple
1683
1683
1684 def excepthook(self, etype, value, tb):
1684 def excepthook(self, etype, value, tb):
1685 """One more defense for GUI apps that call sys.excepthook.
1685 """One more defense for GUI apps that call sys.excepthook.
1686
1686
1687 GUI frameworks like wxPython trap exceptions and call
1687 GUI frameworks like wxPython trap exceptions and call
1688 sys.excepthook themselves. I guess this is a feature that
1688 sys.excepthook themselves. I guess this is a feature that
1689 enables them to keep running after exceptions that would
1689 enables them to keep running after exceptions that would
1690 otherwise kill their mainloop. This is a bother for IPython
1690 otherwise kill their mainloop. This is a bother for IPython
1691 which excepts to catch all of the program exceptions with a try:
1691 which excepts to catch all of the program exceptions with a try:
1692 except: statement.
1692 except: statement.
1693
1693
1694 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1694 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1695 any app directly invokes sys.excepthook, it will look to the user like
1695 any app directly invokes sys.excepthook, it will look to the user like
1696 IPython crashed. In order to work around this, we can disable the
1696 IPython crashed. In order to work around this, we can disable the
1697 CrashHandler and replace it with this excepthook instead, which prints a
1697 CrashHandler and replace it with this excepthook instead, which prints a
1698 regular traceback using our InteractiveTB. In this fashion, apps which
1698 regular traceback using our InteractiveTB. In this fashion, apps which
1699 call sys.excepthook will generate a regular-looking exception from
1699 call sys.excepthook will generate a regular-looking exception from
1700 IPython, and the CrashHandler will only be triggered by real IPython
1700 IPython, and the CrashHandler will only be triggered by real IPython
1701 crashes.
1701 crashes.
1702
1702
1703 This hook should be used sparingly, only in places which are not likely
1703 This hook should be used sparingly, only in places which are not likely
1704 to be true IPython errors.
1704 to be true IPython errors.
1705 """
1705 """
1706 self.showtraceback((etype, value, tb), tb_offset=0)
1706 self.showtraceback((etype, value, tb), tb_offset=0)
1707
1707
1708 def _get_exc_info(self, exc_tuple=None):
1708 def _get_exc_info(self, exc_tuple=None):
1709 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1709 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1710
1710
1711 Ensures sys.last_type,value,traceback hold the exc_info we found,
1711 Ensures sys.last_type,value,traceback hold the exc_info we found,
1712 from whichever source.
1712 from whichever source.
1713
1713
1714 raises ValueError if none of these contain any information
1714 raises ValueError if none of these contain any information
1715 """
1715 """
1716 if exc_tuple is None:
1716 if exc_tuple is None:
1717 etype, value, tb = sys.exc_info()
1717 etype, value, tb = sys.exc_info()
1718 else:
1718 else:
1719 etype, value, tb = exc_tuple
1719 etype, value, tb = exc_tuple
1720
1720
1721 if etype is None:
1721 if etype is None:
1722 if hasattr(sys, 'last_type'):
1722 if hasattr(sys, 'last_type'):
1723 etype, value, tb = sys.last_type, sys.last_value, \
1723 etype, value, tb = sys.last_type, sys.last_value, \
1724 sys.last_traceback
1724 sys.last_traceback
1725
1725
1726 if etype is None:
1726 if etype is None:
1727 raise ValueError("No exception to find")
1727 raise ValueError("No exception to find")
1728
1728
1729 # Now store the exception info in sys.last_type etc.
1729 # Now store the exception info in sys.last_type etc.
1730 # WARNING: these variables are somewhat deprecated and not
1730 # WARNING: these variables are somewhat deprecated and not
1731 # necessarily safe to use in a threaded environment, but tools
1731 # necessarily safe to use in a threaded environment, but tools
1732 # like pdb depend on their existence, so let's set them. If we
1732 # like pdb depend on their existence, so let's set them. If we
1733 # find problems in the field, we'll need to revisit their use.
1733 # find problems in the field, we'll need to revisit their use.
1734 sys.last_type = etype
1734 sys.last_type = etype
1735 sys.last_value = value
1735 sys.last_value = value
1736 sys.last_traceback = tb
1736 sys.last_traceback = tb
1737
1737
1738 return etype, value, tb
1738 return etype, value, tb
1739
1739
1740 def show_usage_error(self, exc):
1740 def show_usage_error(self, exc):
1741 """Show a short message for UsageErrors
1741 """Show a short message for UsageErrors
1742
1742
1743 These are special exceptions that shouldn't show a traceback.
1743 These are special exceptions that shouldn't show a traceback.
1744 """
1744 """
1745 print("UsageError: %s" % exc, file=sys.stderr)
1745 print("UsageError: %s" % exc, file=sys.stderr)
1746
1746
1747 def get_exception_only(self, exc_tuple=None):
1747 def get_exception_only(self, exc_tuple=None):
1748 """
1748 """
1749 Return as a string (ending with a newline) the exception that
1749 Return as a string (ending with a newline) the exception that
1750 just occurred, without any traceback.
1750 just occurred, without any traceback.
1751 """
1751 """
1752 etype, value, tb = self._get_exc_info(exc_tuple)
1752 etype, value, tb = self._get_exc_info(exc_tuple)
1753 msg = traceback.format_exception_only(etype, value)
1753 msg = traceback.format_exception_only(etype, value)
1754 return ''.join(msg)
1754 return ''.join(msg)
1755
1755
1756 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1756 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1757 exception_only=False):
1757 exception_only=False):
1758 """Display the exception that just occurred.
1758 """Display the exception that just occurred.
1759
1759
1760 If nothing is known about the exception, this is the method which
1760 If nothing is known about the exception, this is the method which
1761 should be used throughout the code for presenting user tracebacks,
1761 should be used throughout the code for presenting user tracebacks,
1762 rather than directly invoking the InteractiveTB object.
1762 rather than directly invoking the InteractiveTB object.
1763
1763
1764 A specific showsyntaxerror() also exists, but this method can take
1764 A specific showsyntaxerror() also exists, but this method can take
1765 care of calling it if needed, so unless you are explicitly catching a
1765 care of calling it if needed, so unless you are explicitly catching a
1766 SyntaxError exception, don't try to analyze the stack manually and
1766 SyntaxError exception, don't try to analyze the stack manually and
1767 simply call this method."""
1767 simply call this method."""
1768
1768
1769 try:
1769 try:
1770 try:
1770 try:
1771 etype, value, tb = self._get_exc_info(exc_tuple)
1771 etype, value, tb = self._get_exc_info(exc_tuple)
1772 except ValueError:
1772 except ValueError:
1773 print('No traceback available to show.', file=sys.stderr)
1773 print('No traceback available to show.', file=sys.stderr)
1774 return
1774 return
1775
1775
1776 if issubclass(etype, SyntaxError):
1776 if issubclass(etype, SyntaxError):
1777 # Though this won't be called by syntax errors in the input
1777 # Though this won't be called by syntax errors in the input
1778 # line, there may be SyntaxError cases with imported code.
1778 # line, there may be SyntaxError cases with imported code.
1779 self.showsyntaxerror(filename)
1779 self.showsyntaxerror(filename)
1780 elif etype is UsageError:
1780 elif etype is UsageError:
1781 self.show_usage_error(value)
1781 self.show_usage_error(value)
1782 else:
1782 else:
1783 if exception_only:
1783 if exception_only:
1784 stb = ['An exception has occurred, use %tb to see '
1784 stb = ['An exception has occurred, use %tb to see '
1785 'the full traceback.\n']
1785 'the full traceback.\n']
1786 stb.extend(self.InteractiveTB.get_exception_only(etype,
1786 stb.extend(self.InteractiveTB.get_exception_only(etype,
1787 value))
1787 value))
1788 else:
1788 else:
1789 try:
1789 try:
1790 # Exception classes can customise their traceback - we
1790 # Exception classes can customise their traceback - we
1791 # use this in IPython.parallel for exceptions occurring
1791 # use this in IPython.parallel for exceptions occurring
1792 # in the engines. This should return a list of strings.
1792 # in the engines. This should return a list of strings.
1793 stb = value._render_traceback_()
1793 stb = value._render_traceback_()
1794 except Exception:
1794 except Exception:
1795 stb = self.InteractiveTB.structured_traceback(etype,
1795 stb = self.InteractiveTB.structured_traceback(etype,
1796 value, tb, tb_offset=tb_offset)
1796 value, tb, tb_offset=tb_offset)
1797
1797
1798 self._showtraceback(etype, value, stb)
1798 self._showtraceback(etype, value, stb)
1799 if self.call_pdb:
1799 if self.call_pdb:
1800 # drop into debugger
1800 # drop into debugger
1801 self.debugger(force=True)
1801 self.debugger(force=True)
1802 return
1802 return
1803
1803
1804 # Actually show the traceback
1804 # Actually show the traceback
1805 self._showtraceback(etype, value, stb)
1805 self._showtraceback(etype, value, stb)
1806
1806
1807 except KeyboardInterrupt:
1807 except KeyboardInterrupt:
1808 print('\n' + self.get_exception_only(), file=sys.stderr)
1808 print('\n' + self.get_exception_only(), file=sys.stderr)
1809
1809
1810 def _showtraceback(self, etype, evalue, stb):
1810 def _showtraceback(self, etype, evalue, stb):
1811 """Actually show a traceback.
1811 """Actually show a traceback.
1812
1812
1813 Subclasses may override this method to put the traceback on a different
1813 Subclasses may override this method to put the traceback on a different
1814 place, like a side channel.
1814 place, like a side channel.
1815 """
1815 """
1816 print(self.InteractiveTB.stb2text(stb))
1816 print(self.InteractiveTB.stb2text(stb))
1817
1817
1818 def showsyntaxerror(self, filename=None):
1818 def showsyntaxerror(self, filename=None):
1819 """Display the syntax error that just occurred.
1819 """Display the syntax error that just occurred.
1820
1820
1821 This doesn't display a stack trace because there isn't one.
1821 This doesn't display a stack trace because there isn't one.
1822
1822
1823 If a filename is given, it is stuffed in the exception instead
1823 If a filename is given, it is stuffed in the exception instead
1824 of what was there before (because Python's parser always uses
1824 of what was there before (because Python's parser always uses
1825 "<string>" when reading from a string).
1825 "<string>" when reading from a string).
1826 """
1826 """
1827 etype, value, last_traceback = self._get_exc_info()
1827 etype, value, last_traceback = self._get_exc_info()
1828
1828
1829 if filename and issubclass(etype, SyntaxError):
1829 if filename and issubclass(etype, SyntaxError):
1830 try:
1830 try:
1831 value.filename = filename
1831 value.filename = filename
1832 except:
1832 except:
1833 # Not the format we expect; leave it alone
1833 # Not the format we expect; leave it alone
1834 pass
1834 pass
1835
1835
1836 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1836 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1837 self._showtraceback(etype, value, stb)
1837 self._showtraceback(etype, value, stb)
1838
1838
1839 # This is overridden in TerminalInteractiveShell to show a message about
1839 # This is overridden in TerminalInteractiveShell to show a message about
1840 # the %paste magic.
1840 # the %paste magic.
1841 def showindentationerror(self):
1841 def showindentationerror(self):
1842 """Called by run_cell when there's an IndentationError in code entered
1842 """Called by run_cell when there's an IndentationError in code entered
1843 at the prompt.
1843 at the prompt.
1844
1844
1845 This is overridden in TerminalInteractiveShell to show a message about
1845 This is overridden in TerminalInteractiveShell to show a message about
1846 the %paste magic."""
1846 the %paste magic."""
1847 self.showsyntaxerror()
1847 self.showsyntaxerror()
1848
1848
1849 #-------------------------------------------------------------------------
1849 #-------------------------------------------------------------------------
1850 # Things related to readline
1850 # Things related to readline
1851 #-------------------------------------------------------------------------
1851 #-------------------------------------------------------------------------
1852
1852
1853 def init_readline(self):
1853 def init_readline(self):
1854 """DEPRECATED
1854 """DEPRECATED
1855
1855
1856 Moved to terminal subclass, here only to simplify the init logic."""
1856 Moved to terminal subclass, here only to simplify the init logic."""
1857 # Set a number of methods that depend on readline to be no-op
1857 # Set a number of methods that depend on readline to be no-op
1858 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
1858 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
1859 DeprecationWarning, stacklevel=2)
1859 DeprecationWarning, stacklevel=2)
1860 self.set_custom_completer = no_op
1860 self.set_custom_completer = no_op
1861
1861
1862 @skip_doctest
1862 @skip_doctest
1863 def set_next_input(self, s, replace=False):
1863 def set_next_input(self, s, replace=False):
1864 """ Sets the 'default' input string for the next command line.
1864 """ Sets the 'default' input string for the next command line.
1865
1865
1866 Example::
1866 Example::
1867
1867
1868 In [1]: _ip.set_next_input("Hello Word")
1868 In [1]: _ip.set_next_input("Hello Word")
1869 In [2]: Hello Word_ # cursor is here
1869 In [2]: Hello Word_ # cursor is here
1870 """
1870 """
1871 self.rl_next_input = py3compat.cast_bytes_py2(s)
1871 self.rl_next_input = py3compat.cast_bytes_py2(s)
1872
1872
1873 def _indent_current_str(self):
1873 def _indent_current_str(self):
1874 """return the current level of indentation as a string"""
1874 """return the current level of indentation as a string"""
1875 return self.input_splitter.indent_spaces * ' '
1875 return self.input_splitter.indent_spaces * ' '
1876
1876
1877 #-------------------------------------------------------------------------
1877 #-------------------------------------------------------------------------
1878 # Things related to text completion
1878 # Things related to text completion
1879 #-------------------------------------------------------------------------
1879 #-------------------------------------------------------------------------
1880
1880
1881 def init_completer(self):
1881 def init_completer(self):
1882 """Initialize the completion machinery.
1882 """Initialize the completion machinery.
1883
1883
1884 This creates completion machinery that can be used by client code,
1884 This creates completion machinery that can be used by client code,
1885 either interactively in-process (typically triggered by the readline
1885 either interactively in-process (typically triggered by the readline
1886 library), programmatically (such as in test suites) or out-of-process
1886 library), programmatically (such as in test suites) or out-of-process
1887 (typically over the network by remote frontends).
1887 (typically over the network by remote frontends).
1888 """
1888 """
1889 from IPython.core.completer import IPCompleter
1889 from IPython.core.completer import IPCompleter
1890 from IPython.core.completerlib import (module_completer,
1890 from IPython.core.completerlib import (module_completer,
1891 magic_run_completer, cd_completer, reset_completer)
1891 magic_run_completer, cd_completer, reset_completer)
1892
1892
1893 self.Completer = IPCompleter(shell=self,
1893 self.Completer = IPCompleter(shell=self,
1894 namespace=self.user_ns,
1894 namespace=self.user_ns,
1895 global_namespace=self.user_global_ns,
1895 global_namespace=self.user_global_ns,
1896 parent=self,
1896 parent=self,
1897 )
1897 )
1898 self.configurables.append(self.Completer)
1898 self.configurables.append(self.Completer)
1899
1899
1900 # Add custom completers to the basic ones built into IPCompleter
1900 # Add custom completers to the basic ones built into IPCompleter
1901 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1901 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1902 self.strdispatchers['complete_command'] = sdisp
1902 self.strdispatchers['complete_command'] = sdisp
1903 self.Completer.custom_completers = sdisp
1903 self.Completer.custom_completers = sdisp
1904
1904
1905 self.set_hook('complete_command', module_completer, str_key = 'import')
1905 self.set_hook('complete_command', module_completer, str_key = 'import')
1906 self.set_hook('complete_command', module_completer, str_key = 'from')
1906 self.set_hook('complete_command', module_completer, str_key = 'from')
1907 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1907 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1908 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1908 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1909 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1909 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1910 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1910 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1911
1911
1912
1912
1913 def complete(self, text, line=None, cursor_pos=None):
1913 def complete(self, text, line=None, cursor_pos=None):
1914 """Return the completed text and a list of completions.
1914 """Return the completed text and a list of completions.
1915
1915
1916 Parameters
1916 Parameters
1917 ----------
1917 ----------
1918
1918
1919 text : string
1919 text : string
1920 A string of text to be completed on. It can be given as empty and
1920 A string of text to be completed on. It can be given as empty and
1921 instead a line/position pair are given. In this case, the
1921 instead a line/position pair are given. In this case, the
1922 completer itself will split the line like readline does.
1922 completer itself will split the line like readline does.
1923
1923
1924 line : string, optional
1924 line : string, optional
1925 The complete line that text is part of.
1925 The complete line that text is part of.
1926
1926
1927 cursor_pos : int, optional
1927 cursor_pos : int, optional
1928 The position of the cursor on the input line.
1928 The position of the cursor on the input line.
1929
1929
1930 Returns
1930 Returns
1931 -------
1931 -------
1932 text : string
1932 text : string
1933 The actual text that was completed.
1933 The actual text that was completed.
1934
1934
1935 matches : list
1935 matches : list
1936 A sorted list with all possible completions.
1936 A sorted list with all possible completions.
1937
1937
1938 The optional arguments allow the completion to take more context into
1938 The optional arguments allow the completion to take more context into
1939 account, and are part of the low-level completion API.
1939 account, and are part of the low-level completion API.
1940
1940
1941 This is a wrapper around the completion mechanism, similar to what
1941 This is a wrapper around the completion mechanism, similar to what
1942 readline does at the command line when the TAB key is hit. By
1942 readline does at the command line when the TAB key is hit. By
1943 exposing it as a method, it can be used by other non-readline
1943 exposing it as a method, it can be used by other non-readline
1944 environments (such as GUIs) for text completion.
1944 environments (such as GUIs) for text completion.
1945
1945
1946 Simple usage example:
1946 Simple usage example:
1947
1947
1948 In [1]: x = 'hello'
1948 In [1]: x = 'hello'
1949
1949
1950 In [2]: _ip.complete('x.l')
1950 In [2]: _ip.complete('x.l')
1951 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1951 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1952 """
1952 """
1953
1953
1954 # Inject names into __builtin__ so we can complete on the added names.
1954 # Inject names into __builtin__ so we can complete on the added names.
1955 with self.builtin_trap:
1955 with self.builtin_trap:
1956 return self.Completer.complete(text, line, cursor_pos)
1956 return self.Completer.complete(text, line, cursor_pos)
1957
1957
1958 def set_custom_completer(self, completer, pos=0):
1958 def set_custom_completer(self, completer, pos=0):
1959 """Adds a new custom completer function.
1959 """Adds a new custom completer function.
1960
1960
1961 The position argument (defaults to 0) is the index in the completers
1961 The position argument (defaults to 0) is the index in the completers
1962 list where you want the completer to be inserted."""
1962 list where you want the completer to be inserted."""
1963
1963
1964 newcomp = types.MethodType(completer,self.Completer)
1964 newcomp = types.MethodType(completer,self.Completer)
1965 self.Completer.matchers.insert(pos,newcomp)
1965 self.Completer.matchers.insert(pos,newcomp)
1966
1966
1967 def set_completer_frame(self, frame=None):
1967 def set_completer_frame(self, frame=None):
1968 """Set the frame of the completer."""
1968 """Set the frame of the completer."""
1969 if frame:
1969 if frame:
1970 self.Completer.namespace = frame.f_locals
1970 self.Completer.namespace = frame.f_locals
1971 self.Completer.global_namespace = frame.f_globals
1971 self.Completer.global_namespace = frame.f_globals
1972 else:
1972 else:
1973 self.Completer.namespace = self.user_ns
1973 self.Completer.namespace = self.user_ns
1974 self.Completer.global_namespace = self.user_global_ns
1974 self.Completer.global_namespace = self.user_global_ns
1975
1975
1976 #-------------------------------------------------------------------------
1976 #-------------------------------------------------------------------------
1977 # Things related to magics
1977 # Things related to magics
1978 #-------------------------------------------------------------------------
1978 #-------------------------------------------------------------------------
1979
1979
1980 def init_magics(self):
1980 def init_magics(self):
1981 from IPython.core import magics as m
1981 from IPython.core import magics as m
1982 self.magics_manager = magic.MagicsManager(shell=self,
1982 self.magics_manager = magic.MagicsManager(shell=self,
1983 parent=self,
1983 parent=self,
1984 user_magics=m.UserMagics(self))
1984 user_magics=m.UserMagics(self))
1985 self.configurables.append(self.magics_manager)
1985 self.configurables.append(self.magics_manager)
1986
1986
1987 # Expose as public API from the magics manager
1987 # Expose as public API from the magics manager
1988 self.register_magics = self.magics_manager.register
1988 self.register_magics = self.magics_manager.register
1989
1989
1990 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
1990 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
1991 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
1991 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
1992 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
1992 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
1993 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
1993 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
1994 )
1994 )
1995
1995
1996 # Register Magic Aliases
1996 # Register Magic Aliases
1997 mman = self.magics_manager
1997 mman = self.magics_manager
1998 # FIXME: magic aliases should be defined by the Magics classes
1998 # FIXME: magic aliases should be defined by the Magics classes
1999 # or in MagicsManager, not here
1999 # or in MagicsManager, not here
2000 mman.register_alias('ed', 'edit')
2000 mman.register_alias('ed', 'edit')
2001 mman.register_alias('hist', 'history')
2001 mman.register_alias('hist', 'history')
2002 mman.register_alias('rep', 'recall')
2002 mman.register_alias('rep', 'recall')
2003 mman.register_alias('SVG', 'svg', 'cell')
2003 mman.register_alias('SVG', 'svg', 'cell')
2004 mman.register_alias('HTML', 'html', 'cell')
2004 mman.register_alias('HTML', 'html', 'cell')
2005 mman.register_alias('file', 'writefile', 'cell')
2005 mman.register_alias('file', 'writefile', 'cell')
2006
2006
2007 # FIXME: Move the color initialization to the DisplayHook, which
2007 # FIXME: Move the color initialization to the DisplayHook, which
2008 # should be split into a prompt manager and displayhook. We probably
2008 # should be split into a prompt manager and displayhook. We probably
2009 # even need a centralize colors management object.
2009 # even need a centralize colors management object.
2010 self.magic('colors %s' % self.colors)
2010 self.magic('colors %s' % self.colors)
2011
2011
2012 # Defined here so that it's included in the documentation
2012 # Defined here so that it's included in the documentation
2013 @functools.wraps(magic.MagicsManager.register_function)
2013 @functools.wraps(magic.MagicsManager.register_function)
2014 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2014 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2015 self.magics_manager.register_function(func,
2015 self.magics_manager.register_function(func,
2016 magic_kind=magic_kind, magic_name=magic_name)
2016 magic_kind=magic_kind, magic_name=magic_name)
2017
2017
2018 def run_line_magic(self, magic_name, line):
2018 def run_line_magic(self, magic_name, line):
2019 """Execute the given line magic.
2019 """Execute the given line magic.
2020
2020
2021 Parameters
2021 Parameters
2022 ----------
2022 ----------
2023 magic_name : str
2023 magic_name : str
2024 Name of the desired magic function, without '%' prefix.
2024 Name of the desired magic function, without '%' prefix.
2025
2025
2026 line : str
2026 line : str
2027 The rest of the input line as a single string.
2027 The rest of the input line as a single string.
2028 """
2028 """
2029 fn = self.find_line_magic(magic_name)
2029 fn = self.find_line_magic(magic_name)
2030 if fn is None:
2030 if fn is None:
2031 cm = self.find_cell_magic(magic_name)
2031 cm = self.find_cell_magic(magic_name)
2032 etpl = "Line magic function `%%%s` not found%s."
2032 etpl = "Line magic function `%%%s` not found%s."
2033 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2033 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2034 'did you mean that instead?)' % magic_name )
2034 'did you mean that instead?)' % magic_name )
2035 error(etpl % (magic_name, extra))
2035 error(etpl % (magic_name, extra))
2036 else:
2036 else:
2037 # Note: this is the distance in the stack to the user's frame.
2037 # Note: this is the distance in the stack to the user's frame.
2038 # This will need to be updated if the internal calling logic gets
2038 # This will need to be updated if the internal calling logic gets
2039 # refactored, or else we'll be expanding the wrong variables.
2039 # refactored, or else we'll be expanding the wrong variables.
2040 stack_depth = 2
2040 stack_depth = 2
2041 magic_arg_s = self.var_expand(line, stack_depth)
2041 magic_arg_s = self.var_expand(line, stack_depth)
2042 # Put magic args in a list so we can call with f(*a) syntax
2042 # Put magic args in a list so we can call with f(*a) syntax
2043 args = [magic_arg_s]
2043 args = [magic_arg_s]
2044 kwargs = {}
2044 kwargs = {}
2045 # Grab local namespace if we need it:
2045 # Grab local namespace if we need it:
2046 if getattr(fn, "needs_local_scope", False):
2046 if getattr(fn, "needs_local_scope", False):
2047 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2047 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2048 with self.builtin_trap:
2048 with self.builtin_trap:
2049 result = fn(*args,**kwargs)
2049 result = fn(*args,**kwargs)
2050 return result
2050 return result
2051
2051
2052 def run_cell_magic(self, magic_name, line, cell):
2052 def run_cell_magic(self, magic_name, line, cell):
2053 """Execute the given cell magic.
2053 """Execute the given cell magic.
2054
2054
2055 Parameters
2055 Parameters
2056 ----------
2056 ----------
2057 magic_name : str
2057 magic_name : str
2058 Name of the desired magic function, without '%' prefix.
2058 Name of the desired magic function, without '%' prefix.
2059
2059
2060 line : str
2060 line : str
2061 The rest of the first input line as a single string.
2061 The rest of the first input line as a single string.
2062
2062
2063 cell : str
2063 cell : str
2064 The body of the cell as a (possibly multiline) string.
2064 The body of the cell as a (possibly multiline) string.
2065 """
2065 """
2066 fn = self.find_cell_magic(magic_name)
2066 fn = self.find_cell_magic(magic_name)
2067 if fn is None:
2067 if fn is None:
2068 lm = self.find_line_magic(magic_name)
2068 lm = self.find_line_magic(magic_name)
2069 etpl = "Cell magic `%%{0}` not found{1}."
2069 etpl = "Cell magic `%%{0}` not found{1}."
2070 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2070 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2071 'did you mean that instead?)'.format(magic_name))
2071 'did you mean that instead?)'.format(magic_name))
2072 error(etpl.format(magic_name, extra))
2072 error(etpl.format(magic_name, extra))
2073 elif cell == '':
2073 elif cell == '':
2074 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2074 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2075 if self.find_line_magic(magic_name) is not None:
2075 if self.find_line_magic(magic_name) is not None:
2076 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2076 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2077 raise UsageError(message)
2077 raise UsageError(message)
2078 else:
2078 else:
2079 # Note: this is the distance in the stack to the user's frame.
2079 # Note: this is the distance in the stack to the user's frame.
2080 # This will need to be updated if the internal calling logic gets
2080 # This will need to be updated if the internal calling logic gets
2081 # refactored, or else we'll be expanding the wrong variables.
2081 # refactored, or else we'll be expanding the wrong variables.
2082 stack_depth = 2
2082 stack_depth = 2
2083 magic_arg_s = self.var_expand(line, stack_depth)
2083 magic_arg_s = self.var_expand(line, stack_depth)
2084 with self.builtin_trap:
2084 with self.builtin_trap:
2085 result = fn(magic_arg_s, cell)
2085 result = fn(magic_arg_s, cell)
2086 return result
2086 return result
2087
2087
2088 def find_line_magic(self, magic_name):
2088 def find_line_magic(self, magic_name):
2089 """Find and return a line magic by name.
2089 """Find and return a line magic by name.
2090
2090
2091 Returns None if the magic isn't found."""
2091 Returns None if the magic isn't found."""
2092 return self.magics_manager.magics['line'].get(magic_name)
2092 return self.magics_manager.magics['line'].get(magic_name)
2093
2093
2094 def find_cell_magic(self, magic_name):
2094 def find_cell_magic(self, magic_name):
2095 """Find and return a cell magic by name.
2095 """Find and return a cell magic by name.
2096
2096
2097 Returns None if the magic isn't found."""
2097 Returns None if the magic isn't found."""
2098 return self.magics_manager.magics['cell'].get(magic_name)
2098 return self.magics_manager.magics['cell'].get(magic_name)
2099
2099
2100 def find_magic(self, magic_name, magic_kind='line'):
2100 def find_magic(self, magic_name, magic_kind='line'):
2101 """Find and return a magic of the given type by name.
2101 """Find and return a magic of the given type by name.
2102
2102
2103 Returns None if the magic isn't found."""
2103 Returns None if the magic isn't found."""
2104 return self.magics_manager.magics[magic_kind].get(magic_name)
2104 return self.magics_manager.magics[magic_kind].get(magic_name)
2105
2105
2106 def magic(self, arg_s):
2106 def magic(self, arg_s):
2107 """DEPRECATED. Use run_line_magic() instead.
2107 """DEPRECATED. Use run_line_magic() instead.
2108
2108
2109 Call a magic function by name.
2109 Call a magic function by name.
2110
2110
2111 Input: a string containing the name of the magic function to call and
2111 Input: a string containing the name of the magic function to call and
2112 any additional arguments to be passed to the magic.
2112 any additional arguments to be passed to the magic.
2113
2113
2114 magic('name -opt foo bar') is equivalent to typing at the ipython
2114 magic('name -opt foo bar') is equivalent to typing at the ipython
2115 prompt:
2115 prompt:
2116
2116
2117 In[1]: %name -opt foo bar
2117 In[1]: %name -opt foo bar
2118
2118
2119 To call a magic without arguments, simply use magic('name').
2119 To call a magic without arguments, simply use magic('name').
2120
2120
2121 This provides a proper Python function to call IPython's magics in any
2121 This provides a proper Python function to call IPython's magics in any
2122 valid Python code you can type at the interpreter, including loops and
2122 valid Python code you can type at the interpreter, including loops and
2123 compound statements.
2123 compound statements.
2124 """
2124 """
2125 # TODO: should we issue a loud deprecation warning here?
2125 # TODO: should we issue a loud deprecation warning here?
2126 magic_name, _, magic_arg_s = arg_s.partition(' ')
2126 magic_name, _, magic_arg_s = arg_s.partition(' ')
2127 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2127 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2128 return self.run_line_magic(magic_name, magic_arg_s)
2128 return self.run_line_magic(magic_name, magic_arg_s)
2129
2129
2130 #-------------------------------------------------------------------------
2130 #-------------------------------------------------------------------------
2131 # Things related to macros
2131 # Things related to macros
2132 #-------------------------------------------------------------------------
2132 #-------------------------------------------------------------------------
2133
2133
2134 def define_macro(self, name, themacro):
2134 def define_macro(self, name, themacro):
2135 """Define a new macro
2135 """Define a new macro
2136
2136
2137 Parameters
2137 Parameters
2138 ----------
2138 ----------
2139 name : str
2139 name : str
2140 The name of the macro.
2140 The name of the macro.
2141 themacro : str or Macro
2141 themacro : str or Macro
2142 The action to do upon invoking the macro. If a string, a new
2142 The action to do upon invoking the macro. If a string, a new
2143 Macro object is created by passing the string to it.
2143 Macro object is created by passing the string to it.
2144 """
2144 """
2145
2145
2146 from IPython.core import macro
2146 from IPython.core import macro
2147
2147
2148 if isinstance(themacro, str):
2148 if isinstance(themacro, str):
2149 themacro = macro.Macro(themacro)
2149 themacro = macro.Macro(themacro)
2150 if not isinstance(themacro, macro.Macro):
2150 if not isinstance(themacro, macro.Macro):
2151 raise ValueError('A macro must be a string or a Macro instance.')
2151 raise ValueError('A macro must be a string or a Macro instance.')
2152 self.user_ns[name] = themacro
2152 self.user_ns[name] = themacro
2153
2153
2154 #-------------------------------------------------------------------------
2154 #-------------------------------------------------------------------------
2155 # Things related to the running of system commands
2155 # Things related to the running of system commands
2156 #-------------------------------------------------------------------------
2156 #-------------------------------------------------------------------------
2157
2157
2158 def system_piped(self, cmd):
2158 def system_piped(self, cmd):
2159 """Call the given cmd in a subprocess, piping stdout/err
2159 """Call the given cmd in a subprocess, piping stdout/err
2160
2160
2161 Parameters
2161 Parameters
2162 ----------
2162 ----------
2163 cmd : str
2163 cmd : str
2164 Command to execute (can not end in '&', as background processes are
2164 Command to execute (can not end in '&', as background processes are
2165 not supported. Should not be a command that expects input
2165 not supported. Should not be a command that expects input
2166 other than simple text.
2166 other than simple text.
2167 """
2167 """
2168 if cmd.rstrip().endswith('&'):
2168 if cmd.rstrip().endswith('&'):
2169 # this is *far* from a rigorous test
2169 # this is *far* from a rigorous test
2170 # We do not support backgrounding processes because we either use
2170 # We do not support backgrounding processes because we either use
2171 # pexpect or pipes to read from. Users can always just call
2171 # pexpect or pipes to read from. Users can always just call
2172 # os.system() or use ip.system=ip.system_raw
2172 # os.system() or use ip.system=ip.system_raw
2173 # if they really want a background process.
2173 # if they really want a background process.
2174 raise OSError("Background processes not supported.")
2174 raise OSError("Background processes not supported.")
2175
2175
2176 # we explicitly do NOT return the subprocess status code, because
2176 # we explicitly do NOT return the subprocess status code, because
2177 # a non-None value would trigger :func:`sys.displayhook` calls.
2177 # a non-None value would trigger :func:`sys.displayhook` calls.
2178 # Instead, we store the exit_code in user_ns.
2178 # Instead, we store the exit_code in user_ns.
2179 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2179 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2180
2180
2181 def system_raw(self, cmd):
2181 def system_raw(self, cmd):
2182 """Call the given cmd in a subprocess using os.system on Windows or
2182 """Call the given cmd in a subprocess using os.system on Windows or
2183 subprocess.call using the system shell on other platforms.
2183 subprocess.call using the system shell on other platforms.
2184
2184
2185 Parameters
2185 Parameters
2186 ----------
2186 ----------
2187 cmd : str
2187 cmd : str
2188 Command to execute.
2188 Command to execute.
2189 """
2189 """
2190 cmd = self.var_expand(cmd, depth=1)
2190 cmd = self.var_expand(cmd, depth=1)
2191 # protect os.system from UNC paths on Windows, which it can't handle:
2191 # protect os.system from UNC paths on Windows, which it can't handle:
2192 if sys.platform == 'win32':
2192 if sys.platform == 'win32':
2193 from IPython.utils._process_win32 import AvoidUNCPath
2193 from IPython.utils._process_win32 import AvoidUNCPath
2194 with AvoidUNCPath() as path:
2194 with AvoidUNCPath() as path:
2195 if path is not None:
2195 if path is not None:
2196 cmd = '"pushd %s &&"%s' % (path, cmd)
2196 cmd = '"pushd %s &&"%s' % (path, cmd)
2197 try:
2197 try:
2198 ec = os.system(cmd)
2198 ec = os.system(cmd)
2199 except KeyboardInterrupt:
2199 except KeyboardInterrupt:
2200 print('\n' + self.get_exception_only(), file=sys.stderr)
2200 print('\n' + self.get_exception_only(), file=sys.stderr)
2201 ec = -2
2201 ec = -2
2202 else:
2202 else:
2203 # For posix the result of the subprocess.call() below is an exit
2203 # For posix the result of the subprocess.call() below is an exit
2204 # code, which by convention is zero for success, positive for
2204 # code, which by convention is zero for success, positive for
2205 # program failure. Exit codes above 128 are reserved for signals,
2205 # program failure. Exit codes above 128 are reserved for signals,
2206 # and the formula for converting a signal to an exit code is usually
2206 # and the formula for converting a signal to an exit code is usually
2207 # signal_number+128. To more easily differentiate between exit
2207 # signal_number+128. To more easily differentiate between exit
2208 # codes and signals, ipython uses negative numbers. For instance
2208 # codes and signals, ipython uses negative numbers. For instance
2209 # since control-c is signal 2 but exit code 130, ipython's
2209 # since control-c is signal 2 but exit code 130, ipython's
2210 # _exit_code variable will read -2. Note that some shells like
2210 # _exit_code variable will read -2. Note that some shells like
2211 # csh and fish don't follow sh/bash conventions for exit codes.
2211 # csh and fish don't follow sh/bash conventions for exit codes.
2212 executable = os.environ.get('SHELL', None)
2212 executable = os.environ.get('SHELL', None)
2213 try:
2213 try:
2214 # Use env shell instead of default /bin/sh
2214 # Use env shell instead of default /bin/sh
2215 ec = subprocess.call(cmd, shell=True, executable=executable)
2215 ec = subprocess.call(cmd, shell=True, executable=executable)
2216 except KeyboardInterrupt:
2216 except KeyboardInterrupt:
2217 # intercept control-C; a long traceback is not useful here
2217 # intercept control-C; a long traceback is not useful here
2218 print('\n' + self.get_exception_only(), file=sys.stderr)
2218 print('\n' + self.get_exception_only(), file=sys.stderr)
2219 ec = 130
2219 ec = 130
2220 if ec > 128:
2220 if ec > 128:
2221 ec = -(ec - 128)
2221 ec = -(ec - 128)
2222
2222
2223 # We explicitly do NOT return the subprocess status code, because
2223 # We explicitly do NOT return the subprocess status code, because
2224 # a non-None value would trigger :func:`sys.displayhook` calls.
2224 # a non-None value would trigger :func:`sys.displayhook` calls.
2225 # Instead, we store the exit_code in user_ns. Note the semantics
2225 # Instead, we store the exit_code in user_ns. Note the semantics
2226 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2226 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2227 # but raising SystemExit(_exit_code) will give status 254!
2227 # but raising SystemExit(_exit_code) will give status 254!
2228 self.user_ns['_exit_code'] = ec
2228 self.user_ns['_exit_code'] = ec
2229
2229
2230 # use piped system by default, because it is better behaved
2230 # use piped system by default, because it is better behaved
2231 system = system_piped
2231 system = system_piped
2232
2232
2233 def getoutput(self, cmd, split=True, depth=0):
2233 def getoutput(self, cmd, split=True, depth=0):
2234 """Get output (possibly including stderr) from a subprocess.
2234 """Get output (possibly including stderr) from a subprocess.
2235
2235
2236 Parameters
2236 Parameters
2237 ----------
2237 ----------
2238 cmd : str
2238 cmd : str
2239 Command to execute (can not end in '&', as background processes are
2239 Command to execute (can not end in '&', as background processes are
2240 not supported.
2240 not supported.
2241 split : bool, optional
2241 split : bool, optional
2242 If True, split the output into an IPython SList. Otherwise, an
2242 If True, split the output into an IPython SList. Otherwise, an
2243 IPython LSString is returned. These are objects similar to normal
2243 IPython LSString is returned. These are objects similar to normal
2244 lists and strings, with a few convenience attributes for easier
2244 lists and strings, with a few convenience attributes for easier
2245 manipulation of line-based output. You can use '?' on them for
2245 manipulation of line-based output. You can use '?' on them for
2246 details.
2246 details.
2247 depth : int, optional
2247 depth : int, optional
2248 How many frames above the caller are the local variables which should
2248 How many frames above the caller are the local variables which should
2249 be expanded in the command string? The default (0) assumes that the
2249 be expanded in the command string? The default (0) assumes that the
2250 expansion variables are in the stack frame calling this function.
2250 expansion variables are in the stack frame calling this function.
2251 """
2251 """
2252 if cmd.rstrip().endswith('&'):
2252 if cmd.rstrip().endswith('&'):
2253 # this is *far* from a rigorous test
2253 # this is *far* from a rigorous test
2254 raise OSError("Background processes not supported.")
2254 raise OSError("Background processes not supported.")
2255 out = getoutput(self.var_expand(cmd, depth=depth+1))
2255 out = getoutput(self.var_expand(cmd, depth=depth+1))
2256 if split:
2256 if split:
2257 out = SList(out.splitlines())
2257 out = SList(out.splitlines())
2258 else:
2258 else:
2259 out = LSString(out)
2259 out = LSString(out)
2260 return out
2260 return out
2261
2261
2262 #-------------------------------------------------------------------------
2262 #-------------------------------------------------------------------------
2263 # Things related to aliases
2263 # Things related to aliases
2264 #-------------------------------------------------------------------------
2264 #-------------------------------------------------------------------------
2265
2265
2266 def init_alias(self):
2266 def init_alias(self):
2267 self.alias_manager = AliasManager(shell=self, parent=self)
2267 self.alias_manager = AliasManager(shell=self, parent=self)
2268 self.configurables.append(self.alias_manager)
2268 self.configurables.append(self.alias_manager)
2269
2269
2270 #-------------------------------------------------------------------------
2270 #-------------------------------------------------------------------------
2271 # Things related to extensions
2271 # Things related to extensions
2272 #-------------------------------------------------------------------------
2272 #-------------------------------------------------------------------------
2273
2273
2274 def init_extension_manager(self):
2274 def init_extension_manager(self):
2275 self.extension_manager = ExtensionManager(shell=self, parent=self)
2275 self.extension_manager = ExtensionManager(shell=self, parent=self)
2276 self.configurables.append(self.extension_manager)
2276 self.configurables.append(self.extension_manager)
2277
2277
2278 #-------------------------------------------------------------------------
2278 #-------------------------------------------------------------------------
2279 # Things related to payloads
2279 # Things related to payloads
2280 #-------------------------------------------------------------------------
2280 #-------------------------------------------------------------------------
2281
2281
2282 def init_payload(self):
2282 def init_payload(self):
2283 self.payload_manager = PayloadManager(parent=self)
2283 self.payload_manager = PayloadManager(parent=self)
2284 self.configurables.append(self.payload_manager)
2284 self.configurables.append(self.payload_manager)
2285
2285
2286 #-------------------------------------------------------------------------
2286 #-------------------------------------------------------------------------
2287 # Things related to the prefilter
2287 # Things related to the prefilter
2288 #-------------------------------------------------------------------------
2288 #-------------------------------------------------------------------------
2289
2289
2290 def init_prefilter(self):
2290 def init_prefilter(self):
2291 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2291 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2292 self.configurables.append(self.prefilter_manager)
2292 self.configurables.append(self.prefilter_manager)
2293 # Ultimately this will be refactored in the new interpreter code, but
2293 # Ultimately this will be refactored in the new interpreter code, but
2294 # for now, we should expose the main prefilter method (there's legacy
2294 # for now, we should expose the main prefilter method (there's legacy
2295 # code out there that may rely on this).
2295 # code out there that may rely on this).
2296 self.prefilter = self.prefilter_manager.prefilter_lines
2296 self.prefilter = self.prefilter_manager.prefilter_lines
2297
2297
2298 def auto_rewrite_input(self, cmd):
2298 def auto_rewrite_input(self, cmd):
2299 """Print to the screen the rewritten form of the user's command.
2299 """Print to the screen the rewritten form of the user's command.
2300
2300
2301 This shows visual feedback by rewriting input lines that cause
2301 This shows visual feedback by rewriting input lines that cause
2302 automatic calling to kick in, like::
2302 automatic calling to kick in, like::
2303
2303
2304 /f x
2304 /f x
2305
2305
2306 into::
2306 into::
2307
2307
2308 ------> f(x)
2308 ------> f(x)
2309
2309
2310 after the user's input prompt. This helps the user understand that the
2310 after the user's input prompt. This helps the user understand that the
2311 input line was transformed automatically by IPython.
2311 input line was transformed automatically by IPython.
2312 """
2312 """
2313 if not self.show_rewritten_input:
2313 if not self.show_rewritten_input:
2314 return
2314 return
2315
2315
2316 # This is overridden in TerminalInteractiveShell to use fancy prompts
2316 # This is overridden in TerminalInteractiveShell to use fancy prompts
2317 print("------> " + cmd)
2317 print("------> " + cmd)
2318
2318
2319 #-------------------------------------------------------------------------
2319 #-------------------------------------------------------------------------
2320 # Things related to extracting values/expressions from kernel and user_ns
2320 # Things related to extracting values/expressions from kernel and user_ns
2321 #-------------------------------------------------------------------------
2321 #-------------------------------------------------------------------------
2322
2322
2323 def _user_obj_error(self):
2323 def _user_obj_error(self):
2324 """return simple exception dict
2324 """return simple exception dict
2325
2325
2326 for use in user_expressions
2326 for use in user_expressions
2327 """
2327 """
2328
2328
2329 etype, evalue, tb = self._get_exc_info()
2329 etype, evalue, tb = self._get_exc_info()
2330 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2330 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2331
2331
2332 exc_info = {
2332 exc_info = {
2333 u'status' : 'error',
2333 u'status' : 'error',
2334 u'traceback' : stb,
2334 u'traceback' : stb,
2335 u'ename' : etype.__name__,
2335 u'ename' : etype.__name__,
2336 u'evalue' : py3compat.safe_unicode(evalue),
2336 u'evalue' : py3compat.safe_unicode(evalue),
2337 }
2337 }
2338
2338
2339 return exc_info
2339 return exc_info
2340
2340
2341 def _format_user_obj(self, obj):
2341 def _format_user_obj(self, obj):
2342 """format a user object to display dict
2342 """format a user object to display dict
2343
2343
2344 for use in user_expressions
2344 for use in user_expressions
2345 """
2345 """
2346
2346
2347 data, md = self.display_formatter.format(obj)
2347 data, md = self.display_formatter.format(obj)
2348 value = {
2348 value = {
2349 'status' : 'ok',
2349 'status' : 'ok',
2350 'data' : data,
2350 'data' : data,
2351 'metadata' : md,
2351 'metadata' : md,
2352 }
2352 }
2353 return value
2353 return value
2354
2354
2355 def user_expressions(self, expressions):
2355 def user_expressions(self, expressions):
2356 """Evaluate a dict of expressions in the user's namespace.
2356 """Evaluate a dict of expressions in the user's namespace.
2357
2357
2358 Parameters
2358 Parameters
2359 ----------
2359 ----------
2360 expressions : dict
2360 expressions : dict
2361 A dict with string keys and string values. The expression values
2361 A dict with string keys and string values. The expression values
2362 should be valid Python expressions, each of which will be evaluated
2362 should be valid Python expressions, each of which will be evaluated
2363 in the user namespace.
2363 in the user namespace.
2364
2364
2365 Returns
2365 Returns
2366 -------
2366 -------
2367 A dict, keyed like the input expressions dict, with the rich mime-typed
2367 A dict, keyed like the input expressions dict, with the rich mime-typed
2368 display_data of each value.
2368 display_data of each value.
2369 """
2369 """
2370 out = {}
2370 out = {}
2371 user_ns = self.user_ns
2371 user_ns = self.user_ns
2372 global_ns = self.user_global_ns
2372 global_ns = self.user_global_ns
2373
2373
2374 for key, expr in expressions.items():
2374 for key, expr in expressions.items():
2375 try:
2375 try:
2376 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2376 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2377 except:
2377 except:
2378 value = self._user_obj_error()
2378 value = self._user_obj_error()
2379 out[key] = value
2379 out[key] = value
2380 return out
2380 return out
2381
2381
2382 #-------------------------------------------------------------------------
2382 #-------------------------------------------------------------------------
2383 # Things related to the running of code
2383 # Things related to the running of code
2384 #-------------------------------------------------------------------------
2384 #-------------------------------------------------------------------------
2385
2385
2386 def ex(self, cmd):
2386 def ex(self, cmd):
2387 """Execute a normal python statement in user namespace."""
2387 """Execute a normal python statement in user namespace."""
2388 with self.builtin_trap:
2388 with self.builtin_trap:
2389 exec(cmd, self.user_global_ns, self.user_ns)
2389 exec(cmd, self.user_global_ns, self.user_ns)
2390
2390
2391 def ev(self, expr):
2391 def ev(self, expr):
2392 """Evaluate python expression expr in user namespace.
2392 """Evaluate python expression expr in user namespace.
2393
2393
2394 Returns the result of evaluation
2394 Returns the result of evaluation
2395 """
2395 """
2396 with self.builtin_trap:
2396 with self.builtin_trap:
2397 return eval(expr, self.user_global_ns, self.user_ns)
2397 return eval(expr, self.user_global_ns, self.user_ns)
2398
2398
2399 def safe_execfile(self, fname, *where, **kw):
2399 def safe_execfile(self, fname, *where, **kw):
2400 """A safe version of the builtin execfile().
2400 """A safe version of the builtin execfile().
2401
2401
2402 This version will never throw an exception, but instead print
2402 This version will never throw an exception, but instead print
2403 helpful error messages to the screen. This only works on pure
2403 helpful error messages to the screen. This only works on pure
2404 Python files with the .py extension.
2404 Python files with the .py extension.
2405
2405
2406 Parameters
2406 Parameters
2407 ----------
2407 ----------
2408 fname : string
2408 fname : string
2409 The name of the file to be executed.
2409 The name of the file to be executed.
2410 where : tuple
2410 where : tuple
2411 One or two namespaces, passed to execfile() as (globals,locals).
2411 One or two namespaces, passed to execfile() as (globals,locals).
2412 If only one is given, it is passed as both.
2412 If only one is given, it is passed as both.
2413 exit_ignore : bool (False)
2413 exit_ignore : bool (False)
2414 If True, then silence SystemExit for non-zero status (it is always
2414 If True, then silence SystemExit for non-zero status (it is always
2415 silenced for zero status, as it is so common).
2415 silenced for zero status, as it is so common).
2416 raise_exceptions : bool (False)
2416 raise_exceptions : bool (False)
2417 If True raise exceptions everywhere. Meant for testing.
2417 If True raise exceptions everywhere. Meant for testing.
2418 shell_futures : bool (False)
2418 shell_futures : bool (False)
2419 If True, the code will share future statements with the interactive
2419 If True, the code will share future statements with the interactive
2420 shell. It will both be affected by previous __future__ imports, and
2420 shell. It will both be affected by previous __future__ imports, and
2421 any __future__ imports in the code will affect the shell. If False,
2421 any __future__ imports in the code will affect the shell. If False,
2422 __future__ imports are not shared in either direction.
2422 __future__ imports are not shared in either direction.
2423
2423
2424 """
2424 """
2425 kw.setdefault('exit_ignore', False)
2425 kw.setdefault('exit_ignore', False)
2426 kw.setdefault('raise_exceptions', False)
2426 kw.setdefault('raise_exceptions', False)
2427 kw.setdefault('shell_futures', False)
2427 kw.setdefault('shell_futures', False)
2428
2428
2429 fname = os.path.abspath(os.path.expanduser(fname))
2429 fname = os.path.abspath(os.path.expanduser(fname))
2430
2430
2431 # Make sure we can open the file
2431 # Make sure we can open the file
2432 try:
2432 try:
2433 with open(fname):
2433 with open(fname):
2434 pass
2434 pass
2435 except:
2435 except:
2436 warn('Could not open file <%s> for safe execution.' % fname)
2436 warn('Could not open file <%s> for safe execution.' % fname)
2437 return
2437 return
2438
2438
2439 # Find things also in current directory. This is needed to mimic the
2439 # Find things also in current directory. This is needed to mimic the
2440 # behavior of running a script from the system command line, where
2440 # behavior of running a script from the system command line, where
2441 # Python inserts the script's directory into sys.path
2441 # Python inserts the script's directory into sys.path
2442 dname = os.path.dirname(fname)
2442 dname = os.path.dirname(fname)
2443
2443
2444 with prepended_to_syspath(dname), self.builtin_trap:
2444 with prepended_to_syspath(dname), self.builtin_trap:
2445 try:
2445 try:
2446 glob, loc = (where + (None, ))[:2]
2446 glob, loc = (where + (None, ))[:2]
2447 py3compat.execfile(
2447 py3compat.execfile(
2448 fname, glob, loc,
2448 fname, glob, loc,
2449 self.compile if kw['shell_futures'] else None)
2449 self.compile if kw['shell_futures'] else None)
2450 except SystemExit as status:
2450 except SystemExit as status:
2451 # If the call was made with 0 or None exit status (sys.exit(0)
2451 # If the call was made with 0 or None exit status (sys.exit(0)
2452 # or sys.exit() ), don't bother showing a traceback, as both of
2452 # or sys.exit() ), don't bother showing a traceback, as both of
2453 # these are considered normal by the OS:
2453 # these are considered normal by the OS:
2454 # > python -c'import sys;sys.exit(0)'; echo $?
2454 # > python -c'import sys;sys.exit(0)'; echo $?
2455 # 0
2455 # 0
2456 # > python -c'import sys;sys.exit()'; echo $?
2456 # > python -c'import sys;sys.exit()'; echo $?
2457 # 0
2457 # 0
2458 # For other exit status, we show the exception unless
2458 # For other exit status, we show the exception unless
2459 # explicitly silenced, but only in short form.
2459 # explicitly silenced, but only in short form.
2460 if status.code:
2460 if status.code:
2461 if kw['raise_exceptions']:
2461 if kw['raise_exceptions']:
2462 raise
2462 raise
2463 if not kw['exit_ignore']:
2463 if not kw['exit_ignore']:
2464 self.showtraceback(exception_only=True)
2464 self.showtraceback(exception_only=True)
2465 except:
2465 except:
2466 if kw['raise_exceptions']:
2466 if kw['raise_exceptions']:
2467 raise
2467 raise
2468 # tb offset is 2 because we wrap execfile
2468 # tb offset is 2 because we wrap execfile
2469 self.showtraceback(tb_offset=2)
2469 self.showtraceback(tb_offset=2)
2470
2470
2471 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2471 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2472 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2472 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2473
2473
2474 Parameters
2474 Parameters
2475 ----------
2475 ----------
2476 fname : str
2476 fname : str
2477 The name of the file to execute. The filename must have a
2477 The name of the file to execute. The filename must have a
2478 .ipy or .ipynb extension.
2478 .ipy or .ipynb extension.
2479 shell_futures : bool (False)
2479 shell_futures : bool (False)
2480 If True, the code will share future statements with the interactive
2480 If True, the code will share future statements with the interactive
2481 shell. It will both be affected by previous __future__ imports, and
2481 shell. It will both be affected by previous __future__ imports, and
2482 any __future__ imports in the code will affect the shell. If False,
2482 any __future__ imports in the code will affect the shell. If False,
2483 __future__ imports are not shared in either direction.
2483 __future__ imports are not shared in either direction.
2484 raise_exceptions : bool (False)
2484 raise_exceptions : bool (False)
2485 If True raise exceptions everywhere. Meant for testing.
2485 If True raise exceptions everywhere. Meant for testing.
2486 """
2486 """
2487 fname = os.path.abspath(os.path.expanduser(fname))
2487 fname = os.path.abspath(os.path.expanduser(fname))
2488
2488
2489 # Make sure we can open the file
2489 # Make sure we can open the file
2490 try:
2490 try:
2491 with open(fname):
2491 with open(fname):
2492 pass
2492 pass
2493 except:
2493 except:
2494 warn('Could not open file <%s> for safe execution.' % fname)
2494 warn('Could not open file <%s> for safe execution.' % fname)
2495 return
2495 return
2496
2496
2497 # Find things also in current directory. This is needed to mimic the
2497 # Find things also in current directory. This is needed to mimic the
2498 # behavior of running a script from the system command line, where
2498 # behavior of running a script from the system command line, where
2499 # Python inserts the script's directory into sys.path
2499 # Python inserts the script's directory into sys.path
2500 dname = os.path.dirname(fname)
2500 dname = os.path.dirname(fname)
2501
2501
2502 def get_cells():
2502 def get_cells():
2503 """generator for sequence of code blocks to run"""
2503 """generator for sequence of code blocks to run"""
2504 if fname.endswith('.ipynb'):
2504 if fname.endswith('.ipynb'):
2505 from nbformat import read
2505 from nbformat import read
2506 with io_open(fname) as f:
2506 with io_open(fname) as f:
2507 nb = read(f, as_version=4)
2507 nb = read(f, as_version=4)
2508 if not nb.cells:
2508 if not nb.cells:
2509 return
2509 return
2510 for cell in nb.cells:
2510 for cell in nb.cells:
2511 if cell.cell_type == 'code':
2511 if cell.cell_type == 'code':
2512 yield cell.source
2512 yield cell.source
2513 else:
2513 else:
2514 with open(fname) as f:
2514 with open(fname) as f:
2515 yield f.read()
2515 yield f.read()
2516
2516
2517 with prepended_to_syspath(dname):
2517 with prepended_to_syspath(dname):
2518 try:
2518 try:
2519 for cell in get_cells():
2519 for cell in get_cells():
2520 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2520 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2521 if raise_exceptions:
2521 if raise_exceptions:
2522 result.raise_error()
2522 result.raise_error()
2523 elif not result.success:
2523 elif not result.success:
2524 break
2524 break
2525 except:
2525 except:
2526 if raise_exceptions:
2526 if raise_exceptions:
2527 raise
2527 raise
2528 self.showtraceback()
2528 self.showtraceback()
2529 warn('Unknown failure executing file: <%s>' % fname)
2529 warn('Unknown failure executing file: <%s>' % fname)
2530
2530
2531 def safe_run_module(self, mod_name, where):
2531 def safe_run_module(self, mod_name, where):
2532 """A safe version of runpy.run_module().
2532 """A safe version of runpy.run_module().
2533
2533
2534 This version will never throw an exception, but instead print
2534 This version will never throw an exception, but instead print
2535 helpful error messages to the screen.
2535 helpful error messages to the screen.
2536
2536
2537 `SystemExit` exceptions with status code 0 or None are ignored.
2537 `SystemExit` exceptions with status code 0 or None are ignored.
2538
2538
2539 Parameters
2539 Parameters
2540 ----------
2540 ----------
2541 mod_name : string
2541 mod_name : string
2542 The name of the module to be executed.
2542 The name of the module to be executed.
2543 where : dict
2543 where : dict
2544 The globals namespace.
2544 The globals namespace.
2545 """
2545 """
2546 try:
2546 try:
2547 try:
2547 try:
2548 where.update(
2548 where.update(
2549 runpy.run_module(str(mod_name), run_name="__main__",
2549 runpy.run_module(str(mod_name), run_name="__main__",
2550 alter_sys=True)
2550 alter_sys=True)
2551 )
2551 )
2552 except SystemExit as status:
2552 except SystemExit as status:
2553 if status.code:
2553 if status.code:
2554 raise
2554 raise
2555 except:
2555 except:
2556 self.showtraceback()
2556 self.showtraceback()
2557 warn('Unknown failure executing module: <%s>' % mod_name)
2557 warn('Unknown failure executing module: <%s>' % mod_name)
2558
2558
2559 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2559 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2560 """Run a complete IPython cell.
2560 """Run a complete IPython cell.
2561
2561
2562 Parameters
2562 Parameters
2563 ----------
2563 ----------
2564 raw_cell : str
2564 raw_cell : str
2565 The code (including IPython code such as %magic functions) to run.
2565 The code (including IPython code such as %magic functions) to run.
2566 store_history : bool
2566 store_history : bool
2567 If True, the raw and translated cell will be stored in IPython's
2567 If True, the raw and translated cell will be stored in IPython's
2568 history. For user code calling back into IPython's machinery, this
2568 history. For user code calling back into IPython's machinery, this
2569 should be set to False.
2569 should be set to False.
2570 silent : bool
2570 silent : bool
2571 If True, avoid side-effects, such as implicit displayhooks and
2571 If True, avoid side-effects, such as implicit displayhooks and
2572 and logging. silent=True forces store_history=False.
2572 and logging. silent=True forces store_history=False.
2573 shell_futures : bool
2573 shell_futures : bool
2574 If True, the code will share future statements with the interactive
2574 If True, the code will share future statements with the interactive
2575 shell. It will both be affected by previous __future__ imports, and
2575 shell. It will both be affected by previous __future__ imports, and
2576 any __future__ imports in the code will affect the shell. If False,
2576 any __future__ imports in the code will affect the shell. If False,
2577 __future__ imports are not shared in either direction.
2577 __future__ imports are not shared in either direction.
2578
2578
2579 Returns
2579 Returns
2580 -------
2580 -------
2581 result : :class:`ExecutionResult`
2581 result : :class:`ExecutionResult`
2582 """
2582 """
2583 result = ExecutionResult()
2583 result = ExecutionResult()
2584
2584
2585 if (not raw_cell) or raw_cell.isspace():
2585 if (not raw_cell) or raw_cell.isspace():
2586 self.last_execution_succeeded = True
2586 self.last_execution_succeeded = True
2587 return result
2587 return result
2588
2588
2589 if silent:
2589 if silent:
2590 store_history = False
2590 store_history = False
2591
2591
2592 if store_history:
2592 if store_history:
2593 result.execution_count = self.execution_count
2593 result.execution_count = self.execution_count
2594
2594
2595 def error_before_exec(value):
2595 def error_before_exec(value):
2596 result.error_before_exec = value
2596 result.error_before_exec = value
2597 self.last_execution_succeeded = False
2597 self.last_execution_succeeded = False
2598 return result
2598 return result
2599
2599
2600 self.events.trigger('pre_execute')
2600 self.events.trigger('pre_execute')
2601 if not silent:
2601 if not silent:
2602 self.events.trigger('pre_run_cell')
2602 self.events.trigger('pre_run_cell')
2603
2603
2604 # If any of our input transformation (input_transformer_manager or
2604 # If any of our input transformation (input_transformer_manager or
2605 # prefilter_manager) raises an exception, we store it in this variable
2605 # prefilter_manager) raises an exception, we store it in this variable
2606 # so that we can display the error after logging the input and storing
2606 # so that we can display the error after logging the input and storing
2607 # it in the history.
2607 # it in the history.
2608 preprocessing_exc_tuple = None
2608 preprocessing_exc_tuple = None
2609 try:
2609 try:
2610 # Static input transformations
2610 # Static input transformations
2611 cell = self.input_transformer_manager.transform_cell(raw_cell)
2611 cell = self.input_transformer_manager.transform_cell(raw_cell)
2612 except SyntaxError:
2612 except SyntaxError:
2613 preprocessing_exc_tuple = sys.exc_info()
2613 preprocessing_exc_tuple = sys.exc_info()
2614 cell = raw_cell # cell has to exist so it can be stored/logged
2614 cell = raw_cell # cell has to exist so it can be stored/logged
2615 else:
2615 else:
2616 if len(cell.splitlines()) == 1:
2616 if len(cell.splitlines()) == 1:
2617 # Dynamic transformations - only applied for single line commands
2617 # Dynamic transformations - only applied for single line commands
2618 with self.builtin_trap:
2618 with self.builtin_trap:
2619 try:
2619 try:
2620 # use prefilter_lines to handle trailing newlines
2620 # use prefilter_lines to handle trailing newlines
2621 # restore trailing newline for ast.parse
2621 # restore trailing newline for ast.parse
2622 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2622 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2623 except Exception:
2623 except Exception:
2624 # don't allow prefilter errors to crash IPython
2624 # don't allow prefilter errors to crash IPython
2625 preprocessing_exc_tuple = sys.exc_info()
2625 preprocessing_exc_tuple = sys.exc_info()
2626
2626
2627 # Store raw and processed history
2627 # Store raw and processed history
2628 if store_history:
2628 if store_history:
2629 self.history_manager.store_inputs(self.execution_count,
2629 self.history_manager.store_inputs(self.execution_count,
2630 cell, raw_cell)
2630 cell, raw_cell)
2631 if not silent:
2631 if not silent:
2632 self.logger.log(cell, raw_cell)
2632 self.logger.log(cell, raw_cell)
2633
2633
2634 # Display the exception if input processing failed.
2634 # Display the exception if input processing failed.
2635 if preprocessing_exc_tuple is not None:
2635 if preprocessing_exc_tuple is not None:
2636 self.showtraceback(preprocessing_exc_tuple)
2636 self.showtraceback(preprocessing_exc_tuple)
2637 if store_history:
2637 if store_history:
2638 self.execution_count += 1
2638 self.execution_count += 1
2639 return error_before_exec(preprocessing_exc_tuple[2])
2639 return error_before_exec(preprocessing_exc_tuple[2])
2640
2640
2641 # Our own compiler remembers the __future__ environment. If we want to
2641 # Our own compiler remembers the __future__ environment. If we want to
2642 # run code with a separate __future__ environment, use the default
2642 # run code with a separate __future__ environment, use the default
2643 # compiler
2643 # compiler
2644 compiler = self.compile if shell_futures else CachingCompiler()
2644 compiler = self.compile if shell_futures else CachingCompiler()
2645
2645
2646 with self.builtin_trap:
2646 with self.builtin_trap:
2647 cell_name = self.compile.cache(cell, self.execution_count)
2647 cell_name = self.compile.cache(cell, self.execution_count)
2648
2648
2649 with self.display_trap:
2649 with self.display_trap:
2650 # Compile to bytecode
2650 # Compile to bytecode
2651 try:
2651 try:
2652 code_ast = compiler.ast_parse(cell, filename=cell_name)
2652 code_ast = compiler.ast_parse(cell, filename=cell_name)
2653 except self.custom_exceptions as e:
2653 except self.custom_exceptions as e:
2654 etype, value, tb = sys.exc_info()
2654 etype, value, tb = sys.exc_info()
2655 self.CustomTB(etype, value, tb)
2655 self.CustomTB(etype, value, tb)
2656 return error_before_exec(e)
2656 return error_before_exec(e)
2657 except IndentationError as e:
2657 except IndentationError as e:
2658 self.showindentationerror()
2658 self.showindentationerror()
2659 if store_history:
2659 if store_history:
2660 self.execution_count += 1
2660 self.execution_count += 1
2661 return error_before_exec(e)
2661 return error_before_exec(e)
2662 except (OverflowError, SyntaxError, ValueError, TypeError,
2662 except (OverflowError, SyntaxError, ValueError, TypeError,
2663 MemoryError) as e:
2663 MemoryError) as e:
2664 self.showsyntaxerror()
2664 self.showsyntaxerror()
2665 if store_history:
2665 if store_history:
2666 self.execution_count += 1
2666 self.execution_count += 1
2667 return error_before_exec(e)
2667 return error_before_exec(e)
2668
2668
2669 # Apply AST transformations
2669 # Apply AST transformations
2670 try:
2670 try:
2671 code_ast = self.transform_ast(code_ast)
2671 code_ast = self.transform_ast(code_ast)
2672 except InputRejected as e:
2672 except InputRejected as e:
2673 self.showtraceback()
2673 self.showtraceback()
2674 if store_history:
2674 if store_history:
2675 self.execution_count += 1
2675 self.execution_count += 1
2676 return error_before_exec(e)
2676 return error_before_exec(e)
2677
2677
2678 # Give the displayhook a reference to our ExecutionResult so it
2678 # Give the displayhook a reference to our ExecutionResult so it
2679 # can fill in the output value.
2679 # can fill in the output value.
2680 self.displayhook.exec_result = result
2680 self.displayhook.exec_result = result
2681
2681
2682 # Execute the user code
2682 # Execute the user code
2683 interactivity = "none" if silent else self.ast_node_interactivity
2683 interactivity = "none" if silent else self.ast_node_interactivity
2684 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2684 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2685 interactivity=interactivity, compiler=compiler, result=result)
2685 interactivity=interactivity, compiler=compiler, result=result)
2686
2686
2687 self.last_execution_succeeded = not has_raised
2687 self.last_execution_succeeded = not has_raised
2688
2688
2689 # Reset this so later displayed values do not modify the
2689 # Reset this so later displayed values do not modify the
2690 # ExecutionResult
2690 # ExecutionResult
2691 self.displayhook.exec_result = None
2691 self.displayhook.exec_result = None
2692
2692
2693 self.events.trigger('post_execute')
2693 self.events.trigger('post_execute')
2694 if not silent:
2694 if not silent:
2695 self.events.trigger('post_run_cell')
2695 self.events.trigger('post_run_cell')
2696
2696
2697 if store_history:
2697 if store_history:
2698 # Write output to the database. Does nothing unless
2698 # Write output to the database. Does nothing unless
2699 # history output logging is enabled.
2699 # history output logging is enabled.
2700 self.history_manager.store_output(self.execution_count)
2700 self.history_manager.store_output(self.execution_count)
2701 # Each cell is a *single* input, regardless of how many lines it has
2701 # Each cell is a *single* input, regardless of how many lines it has
2702 self.execution_count += 1
2702 self.execution_count += 1
2703
2703
2704 return result
2704 return result
2705
2705
2706 def transform_ast(self, node):
2706 def transform_ast(self, node):
2707 """Apply the AST transformations from self.ast_transformers
2707 """Apply the AST transformations from self.ast_transformers
2708
2708
2709 Parameters
2709 Parameters
2710 ----------
2710 ----------
2711 node : ast.Node
2711 node : ast.Node
2712 The root node to be transformed. Typically called with the ast.Module
2712 The root node to be transformed. Typically called with the ast.Module
2713 produced by parsing user input.
2713 produced by parsing user input.
2714
2714
2715 Returns
2715 Returns
2716 -------
2716 -------
2717 An ast.Node corresponding to the node it was called with. Note that it
2717 An ast.Node corresponding to the node it was called with. Note that it
2718 may also modify the passed object, so don't rely on references to the
2718 may also modify the passed object, so don't rely on references to the
2719 original AST.
2719 original AST.
2720 """
2720 """
2721 for transformer in self.ast_transformers:
2721 for transformer in self.ast_transformers:
2722 try:
2722 try:
2723 node = transformer.visit(node)
2723 node = transformer.visit(node)
2724 except InputRejected:
2724 except InputRejected:
2725 # User-supplied AST transformers can reject an input by raising
2725 # User-supplied AST transformers can reject an input by raising
2726 # an InputRejected. Short-circuit in this case so that we
2726 # an InputRejected. Short-circuit in this case so that we
2727 # don't unregister the transform.
2727 # don't unregister the transform.
2728 raise
2728 raise
2729 except Exception:
2729 except Exception:
2730 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2730 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2731 self.ast_transformers.remove(transformer)
2731 self.ast_transformers.remove(transformer)
2732
2732
2733 if self.ast_transformers:
2733 if self.ast_transformers:
2734 ast.fix_missing_locations(node)
2734 ast.fix_missing_locations(node)
2735 return node
2735 return node
2736
2736
2737
2737
2738 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2738 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2739 compiler=compile, result=None):
2739 compiler=compile, result=None):
2740 """Run a sequence of AST nodes. The execution mode depends on the
2740 """Run a sequence of AST nodes. The execution mode depends on the
2741 interactivity parameter.
2741 interactivity parameter.
2742
2742
2743 Parameters
2743 Parameters
2744 ----------
2744 ----------
2745 nodelist : list
2745 nodelist : list
2746 A sequence of AST nodes to run.
2746 A sequence of AST nodes to run.
2747 cell_name : str
2747 cell_name : str
2748 Will be passed to the compiler as the filename of the cell. Typically
2748 Will be passed to the compiler as the filename of the cell. Typically
2749 the value returned by ip.compile.cache(cell).
2749 the value returned by ip.compile.cache(cell).
2750 interactivity : str
2750 interactivity : str
2751 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2751 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2752 run interactively (displaying output from expressions). 'last_expr'
2752 run interactively (displaying output from expressions). 'last_expr'
2753 will run the last node interactively only if it is an expression (i.e.
2753 will run the last node interactively only if it is an expression (i.e.
2754 expressions in loops or other blocks are not displayed. Other values
2754 expressions in loops or other blocks are not displayed. Other values
2755 for this parameter will raise a ValueError.
2755 for this parameter will raise a ValueError.
2756 compiler : callable
2756 compiler : callable
2757 A function with the same interface as the built-in compile(), to turn
2757 A function with the same interface as the built-in compile(), to turn
2758 the AST nodes into code objects. Default is the built-in compile().
2758 the AST nodes into code objects. Default is the built-in compile().
2759 result : ExecutionResult, optional
2759 result : ExecutionResult, optional
2760 An object to store exceptions that occur during execution.
2760 An object to store exceptions that occur during execution.
2761
2761
2762 Returns
2762 Returns
2763 -------
2763 -------
2764 True if an exception occurred while running code, False if it finished
2764 True if an exception occurred while running code, False if it finished
2765 running.
2765 running.
2766 """
2766 """
2767 if not nodelist:
2767 if not nodelist:
2768 return
2768 return
2769
2769
2770 if interactivity == 'last_expr':
2770 if interactivity == 'last_expr':
2771 if isinstance(nodelist[-1], ast.Expr):
2771 if isinstance(nodelist[-1], ast.Expr):
2772 interactivity = "last"
2772 interactivity = "last"
2773 else:
2773 else:
2774 interactivity = "none"
2774 interactivity = "none"
2775
2775
2776 if interactivity == 'none':
2776 if interactivity == 'none':
2777 to_run_exec, to_run_interactive = nodelist, []
2777 to_run_exec, to_run_interactive = nodelist, []
2778 elif interactivity == 'last':
2778 elif interactivity == 'last':
2779 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2779 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2780 elif interactivity == 'all':
2780 elif interactivity == 'all':
2781 to_run_exec, to_run_interactive = [], nodelist
2781 to_run_exec, to_run_interactive = [], nodelist
2782 else:
2782 else:
2783 raise ValueError("Interactivity was %r" % interactivity)
2783 raise ValueError("Interactivity was %r" % interactivity)
2784
2784
2785 try:
2785 try:
2786 for i, node in enumerate(to_run_exec):
2786 for i, node in enumerate(to_run_exec):
2787 mod = ast.Module([node])
2787 mod = ast.Module([node])
2788 code = compiler(mod, cell_name, "exec")
2788 code = compiler(mod, cell_name, "exec")
2789 if self.run_code(code, result):
2789 if self.run_code(code, result):
2790 return True
2790 return True
2791
2791
2792 for i, node in enumerate(to_run_interactive):
2792 for i, node in enumerate(to_run_interactive):
2793 mod = ast.Interactive([node])
2793 mod = ast.Interactive([node])
2794 code = compiler(mod, cell_name, "single")
2794 code = compiler(mod, cell_name, "single")
2795 if self.run_code(code, result):
2795 if self.run_code(code, result):
2796 return True
2796 return True
2797
2797
2798 # Flush softspace
2798 # Flush softspace
2799 if softspace(sys.stdout, 0):
2799 if softspace(sys.stdout, 0):
2800 print()
2800 print()
2801
2801
2802 except:
2802 except:
2803 # It's possible to have exceptions raised here, typically by
2803 # It's possible to have exceptions raised here, typically by
2804 # compilation of odd code (such as a naked 'return' outside a
2804 # compilation of odd code (such as a naked 'return' outside a
2805 # function) that did parse but isn't valid. Typically the exception
2805 # function) that did parse but isn't valid. Typically the exception
2806 # is a SyntaxError, but it's safest just to catch anything and show
2806 # is a SyntaxError, but it's safest just to catch anything and show
2807 # the user a traceback.
2807 # the user a traceback.
2808
2808
2809 # We do only one try/except outside the loop to minimize the impact
2809 # We do only one try/except outside the loop to minimize the impact
2810 # on runtime, and also because if any node in the node list is
2810 # on runtime, and also because if any node in the node list is
2811 # broken, we should stop execution completely.
2811 # broken, we should stop execution completely.
2812 if result:
2812 if result:
2813 result.error_before_exec = sys.exc_info()[1]
2813 result.error_before_exec = sys.exc_info()[1]
2814 self.showtraceback()
2814 self.showtraceback()
2815 return True
2815 return True
2816
2816
2817 return False
2817 return False
2818
2818
2819 def run_code(self, code_obj, result=None):
2819 def run_code(self, code_obj, result=None):
2820 """Execute a code object.
2820 """Execute a code object.
2821
2821
2822 When an exception occurs, self.showtraceback() is called to display a
2822 When an exception occurs, self.showtraceback() is called to display a
2823 traceback.
2823 traceback.
2824
2824
2825 Parameters
2825 Parameters
2826 ----------
2826 ----------
2827 code_obj : code object
2827 code_obj : code object
2828 A compiled code object, to be executed
2828 A compiled code object, to be executed
2829 result : ExecutionResult, optional
2829 result : ExecutionResult, optional
2830 An object to store exceptions that occur during execution.
2830 An object to store exceptions that occur during execution.
2831
2831
2832 Returns
2832 Returns
2833 -------
2833 -------
2834 False : successful execution.
2834 False : successful execution.
2835 True : an error occurred.
2835 True : an error occurred.
2836 """
2836 """
2837 # Set our own excepthook in case the user code tries to call it
2837 # Set our own excepthook in case the user code tries to call it
2838 # directly, so that the IPython crash handler doesn't get triggered
2838 # directly, so that the IPython crash handler doesn't get triggered
2839 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2839 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2840
2840
2841 # we save the original sys.excepthook in the instance, in case config
2841 # we save the original sys.excepthook in the instance, in case config
2842 # code (such as magics) needs access to it.
2842 # code (such as magics) needs access to it.
2843 self.sys_excepthook = old_excepthook
2843 self.sys_excepthook = old_excepthook
2844 outflag = 1 # happens in more places, so it's easier as default
2844 outflag = 1 # happens in more places, so it's easier as default
2845 try:
2845 try:
2846 try:
2846 try:
2847 self.hooks.pre_run_code_hook()
2847 self.hooks.pre_run_code_hook()
2848 #rprint('Running code', repr(code_obj)) # dbg
2848 #rprint('Running code', repr(code_obj)) # dbg
2849 exec(code_obj, self.user_global_ns, self.user_ns)
2849 exec(code_obj, self.user_global_ns, self.user_ns)
2850 finally:
2850 finally:
2851 # Reset our crash handler in place
2851 # Reset our crash handler in place
2852 sys.excepthook = old_excepthook
2852 sys.excepthook = old_excepthook
2853 except SystemExit as e:
2853 except SystemExit as e:
2854 if result is not None:
2854 if result is not None:
2855 result.error_in_exec = e
2855 result.error_in_exec = e
2856 self.showtraceback(exception_only=True)
2856 self.showtraceback(exception_only=True)
2857 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
2857 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
2858 except self.custom_exceptions:
2858 except self.custom_exceptions:
2859 etype, value, tb = sys.exc_info()
2859 etype, value, tb = sys.exc_info()
2860 if result is not None:
2860 if result is not None:
2861 result.error_in_exec = value
2861 result.error_in_exec = value
2862 self.CustomTB(etype, value, tb)
2862 self.CustomTB(etype, value, tb)
2863 except:
2863 except:
2864 if result is not None:
2864 if result is not None:
2865 result.error_in_exec = sys.exc_info()[1]
2865 result.error_in_exec = sys.exc_info()[1]
2866 self.showtraceback()
2866 self.showtraceback()
2867 else:
2867 else:
2868 outflag = 0
2868 outflag = 0
2869 return outflag
2869 return outflag
2870
2870
2871 # For backwards compatibility
2871 # For backwards compatibility
2872 runcode = run_code
2872 runcode = run_code
2873
2873
2874 #-------------------------------------------------------------------------
2874 #-------------------------------------------------------------------------
2875 # Things related to GUI support and pylab
2875 # Things related to GUI support and pylab
2876 #-------------------------------------------------------------------------
2876 #-------------------------------------------------------------------------
2877
2877
2878 active_eventloop = None
2878 active_eventloop = None
2879
2879
2880 def enable_gui(self, gui=None):
2880 def enable_gui(self, gui=None):
2881 raise NotImplementedError('Implement enable_gui in a subclass')
2881 raise NotImplementedError('Implement enable_gui in a subclass')
2882
2882
2883 def enable_matplotlib(self, gui=None):
2883 def enable_matplotlib(self, gui=None):
2884 """Enable interactive matplotlib and inline figure support.
2884 """Enable interactive matplotlib and inline figure support.
2885
2885
2886 This takes the following steps:
2886 This takes the following steps:
2887
2887
2888 1. select the appropriate eventloop and matplotlib backend
2888 1. select the appropriate eventloop and matplotlib backend
2889 2. set up matplotlib for interactive use with that backend
2889 2. set up matplotlib for interactive use with that backend
2890 3. configure formatters for inline figure display
2890 3. configure formatters for inline figure display
2891 4. enable the selected gui eventloop
2891 4. enable the selected gui eventloop
2892
2892
2893 Parameters
2893 Parameters
2894 ----------
2894 ----------
2895 gui : optional, string
2895 gui : optional, string
2896 If given, dictates the choice of matplotlib GUI backend to use
2896 If given, dictates the choice of matplotlib GUI backend to use
2897 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2897 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2898 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2898 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2899 matplotlib (as dictated by the matplotlib build-time options plus the
2899 matplotlib (as dictated by the matplotlib build-time options plus the
2900 user's matplotlibrc configuration file). Note that not all backends
2900 user's matplotlibrc configuration file). Note that not all backends
2901 make sense in all contexts, for example a terminal ipython can't
2901 make sense in all contexts, for example a terminal ipython can't
2902 display figures inline.
2902 display figures inline.
2903 """
2903 """
2904 from IPython.core import pylabtools as pt
2904 from IPython.core import pylabtools as pt
2905 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2905 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2906
2906
2907 if gui != 'inline':
2907 if gui != 'inline':
2908 # If we have our first gui selection, store it
2908 # If we have our first gui selection, store it
2909 if self.pylab_gui_select is None:
2909 if self.pylab_gui_select is None:
2910 self.pylab_gui_select = gui
2910 self.pylab_gui_select = gui
2911 # Otherwise if they are different
2911 # Otherwise if they are different
2912 elif gui != self.pylab_gui_select:
2912 elif gui != self.pylab_gui_select:
2913 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2913 print ('Warning: Cannot change to a different GUI toolkit: %s.'
2914 ' Using %s instead.' % (gui, self.pylab_gui_select))
2914 ' Using %s instead.' % (gui, self.pylab_gui_select))
2915 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2915 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2916
2916
2917 pt.activate_matplotlib(backend)
2917 pt.activate_matplotlib(backend)
2918 pt.configure_inline_support(self, backend)
2918 pt.configure_inline_support(self, backend)
2919
2919
2920 # Now we must activate the gui pylab wants to use, and fix %run to take
2920 # Now we must activate the gui pylab wants to use, and fix %run to take
2921 # plot updates into account
2921 # plot updates into account
2922 self.enable_gui(gui)
2922 self.enable_gui(gui)
2923 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2923 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2924 pt.mpl_runner(self.safe_execfile)
2924 pt.mpl_runner(self.safe_execfile)
2925
2925
2926 return gui, backend
2926 return gui, backend
2927
2927
2928 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2928 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2929 """Activate pylab support at runtime.
2929 """Activate pylab support at runtime.
2930
2930
2931 This turns on support for matplotlib, preloads into the interactive
2931 This turns on support for matplotlib, preloads into the interactive
2932 namespace all of numpy and pylab, and configures IPython to correctly
2932 namespace all of numpy and pylab, and configures IPython to correctly
2933 interact with the GUI event loop. The GUI backend to be used can be
2933 interact with the GUI event loop. The GUI backend to be used can be
2934 optionally selected with the optional ``gui`` argument.
2934 optionally selected with the optional ``gui`` argument.
2935
2935
2936 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2936 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2937
2937
2938 Parameters
2938 Parameters
2939 ----------
2939 ----------
2940 gui : optional, string
2940 gui : optional, string
2941 If given, dictates the choice of matplotlib GUI backend to use
2941 If given, dictates the choice of matplotlib GUI backend to use
2942 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2942 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2943 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2943 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2944 matplotlib (as dictated by the matplotlib build-time options plus the
2944 matplotlib (as dictated by the matplotlib build-time options plus the
2945 user's matplotlibrc configuration file). Note that not all backends
2945 user's matplotlibrc configuration file). Note that not all backends
2946 make sense in all contexts, for example a terminal ipython can't
2946 make sense in all contexts, for example a terminal ipython can't
2947 display figures inline.
2947 display figures inline.
2948 import_all : optional, bool, default: True
2948 import_all : optional, bool, default: True
2949 Whether to do `from numpy import *` and `from pylab import *`
2949 Whether to do `from numpy import *` and `from pylab import *`
2950 in addition to module imports.
2950 in addition to module imports.
2951 welcome_message : deprecated
2951 welcome_message : deprecated
2952 This argument is ignored, no welcome message will be displayed.
2952 This argument is ignored, no welcome message will be displayed.
2953 """
2953 """
2954 from IPython.core.pylabtools import import_pylab
2954 from IPython.core.pylabtools import import_pylab
2955
2955
2956 gui, backend = self.enable_matplotlib(gui)
2956 gui, backend = self.enable_matplotlib(gui)
2957
2957
2958 # We want to prevent the loading of pylab to pollute the user's
2958 # We want to prevent the loading of pylab to pollute the user's
2959 # namespace as shown by the %who* magics, so we execute the activation
2959 # namespace as shown by the %who* magics, so we execute the activation
2960 # code in an empty namespace, and we update *both* user_ns and
2960 # code in an empty namespace, and we update *both* user_ns and
2961 # user_ns_hidden with this information.
2961 # user_ns_hidden with this information.
2962 ns = {}
2962 ns = {}
2963 import_pylab(ns, import_all)
2963 import_pylab(ns, import_all)
2964 # warn about clobbered names
2964 # warn about clobbered names
2965 ignored = {"__builtins__"}
2965 ignored = {"__builtins__"}
2966 both = set(ns).intersection(self.user_ns).difference(ignored)
2966 both = set(ns).intersection(self.user_ns).difference(ignored)
2967 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2967 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
2968 self.user_ns.update(ns)
2968 self.user_ns.update(ns)
2969 self.user_ns_hidden.update(ns)
2969 self.user_ns_hidden.update(ns)
2970 return gui, backend, clobbered
2970 return gui, backend, clobbered
2971
2971
2972 #-------------------------------------------------------------------------
2972 #-------------------------------------------------------------------------
2973 # Utilities
2973 # Utilities
2974 #-------------------------------------------------------------------------
2974 #-------------------------------------------------------------------------
2975
2975
2976 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2976 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2977 """Expand python variables in a string.
2977 """Expand python variables in a string.
2978
2978
2979 The depth argument indicates how many frames above the caller should
2979 The depth argument indicates how many frames above the caller should
2980 be walked to look for the local namespace where to expand variables.
2980 be walked to look for the local namespace where to expand variables.
2981
2981
2982 The global namespace for expansion is always the user's interactive
2982 The global namespace for expansion is always the user's interactive
2983 namespace.
2983 namespace.
2984 """
2984 """
2985 ns = self.user_ns.copy()
2985 ns = self.user_ns.copy()
2986 try:
2986 try:
2987 frame = sys._getframe(depth+1)
2987 frame = sys._getframe(depth+1)
2988 except ValueError:
2988 except ValueError:
2989 # This is thrown if there aren't that many frames on the stack,
2989 # This is thrown if there aren't that many frames on the stack,
2990 # e.g. if a script called run_line_magic() directly.
2990 # e.g. if a script called run_line_magic() directly.
2991 pass
2991 pass
2992 else:
2992 else:
2993 ns.update(frame.f_locals)
2993 ns.update(frame.f_locals)
2994
2994
2995 try:
2995 try:
2996 # We have to use .vformat() here, because 'self' is a valid and common
2996 # We have to use .vformat() here, because 'self' is a valid and common
2997 # name, and expanding **ns for .format() would make it collide with
2997 # name, and expanding **ns for .format() would make it collide with
2998 # the 'self' argument of the method.
2998 # the 'self' argument of the method.
2999 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
2999 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3000 except Exception:
3000 except Exception:
3001 # if formatter couldn't format, just let it go untransformed
3001 # if formatter couldn't format, just let it go untransformed
3002 pass
3002 pass
3003 return cmd
3003 return cmd
3004
3004
3005 def mktempfile(self, data=None, prefix='ipython_edit_'):
3005 def mktempfile(self, data=None, prefix='ipython_edit_'):
3006 """Make a new tempfile and return its filename.
3006 """Make a new tempfile and return its filename.
3007
3007
3008 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3008 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3009 but it registers the created filename internally so ipython cleans it up
3009 but it registers the created filename internally so ipython cleans it up
3010 at exit time.
3010 at exit time.
3011
3011
3012 Optional inputs:
3012 Optional inputs:
3013
3013
3014 - data(None): if data is given, it gets written out to the temp file
3014 - data(None): if data is given, it gets written out to the temp file
3015 immediately, and the file is closed again."""
3015 immediately, and the file is closed again."""
3016
3016
3017 dirname = tempfile.mkdtemp(prefix=prefix)
3017 dirname = tempfile.mkdtemp(prefix=prefix)
3018 self.tempdirs.append(dirname)
3018 self.tempdirs.append(dirname)
3019
3019
3020 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3020 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3021 os.close(handle) # On Windows, there can only be one open handle on a file
3021 os.close(handle) # On Windows, there can only be one open handle on a file
3022 self.tempfiles.append(filename)
3022 self.tempfiles.append(filename)
3023
3023
3024 if data:
3024 if data:
3025 tmp_file = open(filename,'w')
3025 tmp_file = open(filename,'w')
3026 tmp_file.write(data)
3026 tmp_file.write(data)
3027 tmp_file.close()
3027 tmp_file.close()
3028 return filename
3028 return filename
3029
3029
3030 @undoc
3030 @undoc
3031 def write(self,data):
3031 def write(self,data):
3032 """DEPRECATED: Write a string to the default output"""
3032 """DEPRECATED: Write a string to the default output"""
3033 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3033 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3034 DeprecationWarning, stacklevel=2)
3034 DeprecationWarning, stacklevel=2)
3035 sys.stdout.write(data)
3035 sys.stdout.write(data)
3036
3036
3037 @undoc
3037 @undoc
3038 def write_err(self,data):
3038 def write_err(self,data):
3039 """DEPRECATED: Write a string to the default error output"""
3039 """DEPRECATED: Write a string to the default error output"""
3040 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3040 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3041 DeprecationWarning, stacklevel=2)
3041 DeprecationWarning, stacklevel=2)
3042 sys.stderr.write(data)
3042 sys.stderr.write(data)
3043
3043
3044 def ask_yes_no(self, prompt, default=None, interrupt=None):
3044 def ask_yes_no(self, prompt, default=None, interrupt=None):
3045 if self.quiet:
3045 if self.quiet:
3046 return True
3046 return True
3047 return ask_yes_no(prompt,default,interrupt)
3047 return ask_yes_no(prompt,default,interrupt)
3048
3048
3049 def show_usage(self):
3049 def show_usage(self):
3050 """Show a usage message"""
3050 """Show a usage message"""
3051 page.page(IPython.core.usage.interactive_usage)
3051 page.page(IPython.core.usage.interactive_usage)
3052
3052
3053 def extract_input_lines(self, range_str, raw=False):
3053 def extract_input_lines(self, range_str, raw=False):
3054 """Return as a string a set of input history slices.
3054 """Return as a string a set of input history slices.
3055
3055
3056 Parameters
3056 Parameters
3057 ----------
3057 ----------
3058 range_str : string
3058 range_str : string
3059 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3059 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3060 since this function is for use by magic functions which get their
3060 since this function is for use by magic functions which get their
3061 arguments as strings. The number before the / is the session
3061 arguments as strings. The number before the / is the session
3062 number: ~n goes n back from the current session.
3062 number: ~n goes n back from the current session.
3063
3063
3064 raw : bool, optional
3064 raw : bool, optional
3065 By default, the processed input is used. If this is true, the raw
3065 By default, the processed input is used. If this is true, the raw
3066 input history is used instead.
3066 input history is used instead.
3067
3067
3068 Notes
3068 Notes
3069 -----
3069 -----
3070
3070
3071 Slices can be described with two notations:
3071 Slices can be described with two notations:
3072
3072
3073 * ``N:M`` -> standard python form, means including items N...(M-1).
3073 * ``N:M`` -> standard python form, means including items N...(M-1).
3074 * ``N-M`` -> include items N..M (closed endpoint).
3074 * ``N-M`` -> include items N..M (closed endpoint).
3075 """
3075 """
3076 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3076 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3077 return "\n".join(x for _, _, x in lines)
3077 return "\n".join(x for _, _, x in lines)
3078
3078
3079 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3079 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3080 """Get a code string from history, file, url, or a string or macro.
3080 """Get a code string from history, file, url, or a string or macro.
3081
3081
3082 This is mainly used by magic functions.
3082 This is mainly used by magic functions.
3083
3083
3084 Parameters
3084 Parameters
3085 ----------
3085 ----------
3086
3086
3087 target : str
3087 target : str
3088
3088
3089 A string specifying code to retrieve. This will be tried respectively
3089 A string specifying code to retrieve. This will be tried respectively
3090 as: ranges of input history (see %history for syntax), url,
3090 as: ranges of input history (see %history for syntax), url,
3091 corresponding .py file, filename, or an expression evaluating to a
3091 corresponding .py file, filename, or an expression evaluating to a
3092 string or Macro in the user namespace.
3092 string or Macro in the user namespace.
3093
3093
3094 raw : bool
3094 raw : bool
3095 If true (default), retrieve raw history. Has no effect on the other
3095 If true (default), retrieve raw history. Has no effect on the other
3096 retrieval mechanisms.
3096 retrieval mechanisms.
3097
3097
3098 py_only : bool (default False)
3098 py_only : bool (default False)
3099 Only try to fetch python code, do not try alternative methods to decode file
3099 Only try to fetch python code, do not try alternative methods to decode file
3100 if unicode fails.
3100 if unicode fails.
3101
3101
3102 Returns
3102 Returns
3103 -------
3103 -------
3104 A string of code.
3104 A string of code.
3105
3105
3106 ValueError is raised if nothing is found, and TypeError if it evaluates
3106 ValueError is raised if nothing is found, and TypeError if it evaluates
3107 to an object of another type. In each case, .args[0] is a printable
3107 to an object of another type. In each case, .args[0] is a printable
3108 message.
3108 message.
3109 """
3109 """
3110 code = self.extract_input_lines(target, raw=raw) # Grab history
3110 code = self.extract_input_lines(target, raw=raw) # Grab history
3111 if code:
3111 if code:
3112 return code
3112 return code
3113 try:
3113 try:
3114 if target.startswith(('http://', 'https://')):
3114 if target.startswith(('http://', 'https://')):
3115 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3115 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3116 except UnicodeDecodeError:
3116 except UnicodeDecodeError:
3117 if not py_only :
3117 if not py_only :
3118 # Deferred import
3118 # Deferred import
3119 from urllib.request import urlopen
3119 from urllib.request import urlopen
3120 response = urlopen(target)
3120 response = urlopen(target)
3121 return response.read().decode('latin1')
3121 return response.read().decode('latin1')
3122 raise ValueError(("'%s' seem to be unreadable.") % target)
3122 raise ValueError(("'%s' seem to be unreadable.") % target)
3123
3123
3124 potential_target = [target]
3124 potential_target = [target]
3125 try :
3125 try :
3126 potential_target.insert(0,get_py_filename(target))
3126 potential_target.insert(0,get_py_filename(target))
3127 except IOError:
3127 except IOError:
3128 pass
3128 pass
3129
3129
3130 for tgt in potential_target :
3130 for tgt in potential_target :
3131 if os.path.isfile(tgt): # Read file
3131 if os.path.isfile(tgt): # Read file
3132 try :
3132 try :
3133 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3133 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3134 except UnicodeDecodeError :
3134 except UnicodeDecodeError :
3135 if not py_only :
3135 if not py_only :
3136 with io_open(tgt,'r', encoding='latin1') as f :
3136 with io_open(tgt,'r', encoding='latin1') as f :
3137 return f.read()
3137 return f.read()
3138 raise ValueError(("'%s' seem to be unreadable.") % target)
3138 raise ValueError(("'%s' seem to be unreadable.") % target)
3139 elif os.path.isdir(os.path.expanduser(tgt)):
3139 elif os.path.isdir(os.path.expanduser(tgt)):
3140 raise ValueError("'%s' is a directory, not a regular file." % target)
3140 raise ValueError("'%s' is a directory, not a regular file." % target)
3141
3141
3142 if search_ns:
3142 if search_ns:
3143 # Inspect namespace to load object source
3143 # Inspect namespace to load object source
3144 object_info = self.object_inspect(target, detail_level=1)
3144 object_info = self.object_inspect(target, detail_level=1)
3145 if object_info['found'] and object_info['source']:
3145 if object_info['found'] and object_info['source']:
3146 return object_info['source']
3146 return object_info['source']
3147
3147
3148 try: # User namespace
3148 try: # User namespace
3149 codeobj = eval(target, self.user_ns)
3149 codeobj = eval(target, self.user_ns)
3150 except Exception:
3150 except Exception:
3151 raise ValueError(("'%s' was not found in history, as a file, url, "
3151 raise ValueError(("'%s' was not found in history, as a file, url, "
3152 "nor in the user namespace.") % target)
3152 "nor in the user namespace.") % target)
3153
3153
3154 if isinstance(codeobj, str):
3154 if isinstance(codeobj, str):
3155 return codeobj
3155 return codeobj
3156 elif isinstance(codeobj, Macro):
3156 elif isinstance(codeobj, Macro):
3157 return codeobj.value
3157 return codeobj.value
3158
3158
3159 raise TypeError("%s is neither a string nor a macro." % target,
3159 raise TypeError("%s is neither a string nor a macro." % target,
3160 codeobj)
3160 codeobj)
3161
3161
3162 #-------------------------------------------------------------------------
3162 #-------------------------------------------------------------------------
3163 # Things related to IPython exiting
3163 # Things related to IPython exiting
3164 #-------------------------------------------------------------------------
3164 #-------------------------------------------------------------------------
3165 def atexit_operations(self):
3165 def atexit_operations(self):
3166 """This will be executed at the time of exit.
3166 """This will be executed at the time of exit.
3167
3167
3168 Cleanup operations and saving of persistent data that is done
3168 Cleanup operations and saving of persistent data that is done
3169 unconditionally by IPython should be performed here.
3169 unconditionally by IPython should be performed here.
3170
3170
3171 For things that may depend on startup flags or platform specifics (such
3171 For things that may depend on startup flags or platform specifics (such
3172 as having readline or not), register a separate atexit function in the
3172 as having readline or not), register a separate atexit function in the
3173 code that has the appropriate information, rather than trying to
3173 code that has the appropriate information, rather than trying to
3174 clutter
3174 clutter
3175 """
3175 """
3176 # Close the history session (this stores the end time and line count)
3176 # Close the history session (this stores the end time and line count)
3177 # this must be *before* the tempfile cleanup, in case of temporary
3177 # this must be *before* the tempfile cleanup, in case of temporary
3178 # history db
3178 # history db
3179 self.history_manager.end_session()
3179 self.history_manager.end_session()
3180
3180
3181 # Cleanup all tempfiles and folders left around
3181 # Cleanup all tempfiles and folders left around
3182 for tfile in self.tempfiles:
3182 for tfile in self.tempfiles:
3183 try:
3183 try:
3184 os.unlink(tfile)
3184 os.unlink(tfile)
3185 except OSError:
3185 except OSError:
3186 pass
3186 pass
3187
3187
3188 for tdir in self.tempdirs:
3188 for tdir in self.tempdirs:
3189 try:
3189 try:
3190 os.rmdir(tdir)
3190 os.rmdir(tdir)
3191 except OSError:
3191 except OSError:
3192 pass
3192 pass
3193
3193
3194 # Clear all user namespaces to release all references cleanly.
3194 # Clear all user namespaces to release all references cleanly.
3195 self.reset(new_session=False)
3195 self.reset(new_session=False)
3196
3196
3197 # Run user hooks
3197 # Run user hooks
3198 self.hooks.shutdown_hook()
3198 self.hooks.shutdown_hook()
3199
3199
3200 def cleanup(self):
3200 def cleanup(self):
3201 self.restore_sys_module_state()
3201 self.restore_sys_module_state()
3202
3202
3203
3203
3204 # Overridden in terminal subclass to change prompts
3204 # Overridden in terminal subclass to change prompts
3205 def switch_doctest_mode(self, mode):
3205 def switch_doctest_mode(self, mode):
3206 pass
3206 pass
3207
3207
3208
3208
3209 class InteractiveShellABC(metaclass=abc.ABCMeta):
3209 class InteractiveShellABC(metaclass=abc.ABCMeta):
3210 """An abstract base class for InteractiveShell."""
3210 """An abstract base class for InteractiveShell."""
3211
3211
3212 InteractiveShellABC.register(InteractiveShell)
3212 InteractiveShellABC.register(InteractiveShell)
@@ -1,1374 +1,1373 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Implementation of execution-related magic functions."""
2 """Implementation of execution-related magic functions."""
3
3
4 # Copyright (c) IPython Development Team.
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
5 # Distributed under the terms of the Modified BSD License.
6
6
7
7
8 import ast
8 import ast
9 import bdb
9 import bdb
10 import builtins as builtin_mod
10 import gc
11 import gc
11 import itertools
12 import itertools
12 import os
13 import os
13 import sys
14 import sys
14 import time
15 import time
15 import timeit
16 import timeit
16 import math
17 import math
17 from pdb import Restart
18 from pdb import Restart
18
19
19 # cProfile was added in Python2.5
20 # cProfile was added in Python2.5
20 try:
21 try:
21 import cProfile as profile
22 import cProfile as profile
22 import pstats
23 import pstats
23 except ImportError:
24 except ImportError:
24 # profile isn't bundled by default in Debian for license reasons
25 # profile isn't bundled by default in Debian for license reasons
25 try:
26 try:
26 import profile, pstats
27 import profile, pstats
27 except ImportError:
28 except ImportError:
28 profile = pstats = None
29 profile = pstats = None
29
30
30 from IPython.core import oinspect
31 from IPython.core import oinspect
31 from IPython.core import magic_arguments
32 from IPython.core import magic_arguments
32 from IPython.core import page
33 from IPython.core import page
33 from IPython.core.error import UsageError
34 from IPython.core.error import UsageError
34 from IPython.core.macro import Macro
35 from IPython.core.macro import Macro
35 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
36 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
36 line_cell_magic, on_off, needs_local_scope)
37 line_cell_magic, on_off, needs_local_scope)
37 from IPython.testing.skipdoctest import skip_doctest
38 from IPython.testing.skipdoctest import skip_doctest
38 from IPython.utils import py3compat
39 from IPython.utils.py3compat import builtin_mod
40 from IPython.utils.contexts import preserve_keys
39 from IPython.utils.contexts import preserve_keys
41 from IPython.utils.capture import capture_output
40 from IPython.utils.capture import capture_output
42 from IPython.utils.ipstruct import Struct
41 from IPython.utils.ipstruct import Struct
43 from IPython.utils.module_paths import find_mod
42 from IPython.utils.module_paths import find_mod
44 from IPython.utils.path import get_py_filename, shellglob
43 from IPython.utils.path import get_py_filename, shellglob
45 from IPython.utils.timing import clock, clock2
44 from IPython.utils.timing import clock, clock2
46 from warnings import warn
45 from warnings import warn
47 from logging import error
46 from logging import error
48 from io import StringIO
47 from io import StringIO
49
48
50
49
51 #-----------------------------------------------------------------------------
50 #-----------------------------------------------------------------------------
52 # Magic implementation classes
51 # Magic implementation classes
53 #-----------------------------------------------------------------------------
52 #-----------------------------------------------------------------------------
54
53
55
54
56 class TimeitResult(object):
55 class TimeitResult(object):
57 """
56 """
58 Object returned by the timeit magic with info about the run.
57 Object returned by the timeit magic with info about the run.
59
58
60 Contains the following attributes :
59 Contains the following attributes :
61
60
62 loops: (int) number of loops done per measurement
61 loops: (int) number of loops done per measurement
63 repeat: (int) number of times the measurement has been repeated
62 repeat: (int) number of times the measurement has been repeated
64 best: (float) best execution time / number
63 best: (float) best execution time / number
65 all_runs: (list of float) execution time of each run (in s)
64 all_runs: (list of float) execution time of each run (in s)
66 compile_time: (float) time of statement compilation (s)
65 compile_time: (float) time of statement compilation (s)
67
66
68 """
67 """
69 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
68 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
70 self.loops = loops
69 self.loops = loops
71 self.repeat = repeat
70 self.repeat = repeat
72 self.best = best
71 self.best = best
73 self.worst = worst
72 self.worst = worst
74 self.all_runs = all_runs
73 self.all_runs = all_runs
75 self.compile_time = compile_time
74 self.compile_time = compile_time
76 self._precision = precision
75 self._precision = precision
77 self.timings = [ dt / self.loops for dt in all_runs]
76 self.timings = [ dt / self.loops for dt in all_runs]
78
77
79 @property
78 @property
80 def average(self):
79 def average(self):
81 return math.fsum(self.timings) / len(self.timings)
80 return math.fsum(self.timings) / len(self.timings)
82
81
83 @property
82 @property
84 def stdev(self):
83 def stdev(self):
85 mean = self.average
84 mean = self.average
86 return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5
85 return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5
87
86
88 def __str__(self):
87 def __str__(self):
89 return (u"%s loop%s, average of %d: %s +- %s per loop (using standard deviation)"
88 return (u"%s loop%s, average of %d: %s +- %s per loop (using standard deviation)"
90 % (self.loops,"" if self.loops == 1 else "s", self.repeat,
89 % (self.loops,"" if self.loops == 1 else "s", self.repeat,
91 _format_time(self.average, self._precision),
90 _format_time(self.average, self._precision),
92 _format_time(self.stdev, self._precision)))
91 _format_time(self.stdev, self._precision)))
93
92
94 def _repr_pretty_(self, p , cycle):
93 def _repr_pretty_(self, p , cycle):
95 unic = self.__str__()
94 unic = self.__str__()
96 p.text(u'<TimeitResult : '+unic+u'>')
95 p.text(u'<TimeitResult : '+unic+u'>')
97
96
98
97
99
98
100 class TimeitTemplateFiller(ast.NodeTransformer):
99 class TimeitTemplateFiller(ast.NodeTransformer):
101 """Fill in the AST template for timing execution.
100 """Fill in the AST template for timing execution.
102
101
103 This is quite closely tied to the template definition, which is in
102 This is quite closely tied to the template definition, which is in
104 :meth:`ExecutionMagics.timeit`.
103 :meth:`ExecutionMagics.timeit`.
105 """
104 """
106 def __init__(self, ast_setup, ast_stmt):
105 def __init__(self, ast_setup, ast_stmt):
107 self.ast_setup = ast_setup
106 self.ast_setup = ast_setup
108 self.ast_stmt = ast_stmt
107 self.ast_stmt = ast_stmt
109
108
110 def visit_FunctionDef(self, node):
109 def visit_FunctionDef(self, node):
111 "Fill in the setup statement"
110 "Fill in the setup statement"
112 self.generic_visit(node)
111 self.generic_visit(node)
113 if node.name == "inner":
112 if node.name == "inner":
114 node.body[:1] = self.ast_setup.body
113 node.body[:1] = self.ast_setup.body
115
114
116 return node
115 return node
117
116
118 def visit_For(self, node):
117 def visit_For(self, node):
119 "Fill in the statement to be timed"
118 "Fill in the statement to be timed"
120 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
119 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
121 node.body = self.ast_stmt.body
120 node.body = self.ast_stmt.body
122 return node
121 return node
123
122
124
123
125 class Timer(timeit.Timer):
124 class Timer(timeit.Timer):
126 """Timer class that explicitly uses self.inner
125 """Timer class that explicitly uses self.inner
127
126
128 which is an undocumented implementation detail of CPython,
127 which is an undocumented implementation detail of CPython,
129 not shared by PyPy.
128 not shared by PyPy.
130 """
129 """
131 # Timer.timeit copied from CPython 3.4.2
130 # Timer.timeit copied from CPython 3.4.2
132 def timeit(self, number=timeit.default_number):
131 def timeit(self, number=timeit.default_number):
133 """Time 'number' executions of the main statement.
132 """Time 'number' executions of the main statement.
134
133
135 To be precise, this executes the setup statement once, and
134 To be precise, this executes the setup statement once, and
136 then returns the time it takes to execute the main statement
135 then returns the time it takes to execute the main statement
137 a number of times, as a float measured in seconds. The
136 a number of times, as a float measured in seconds. The
138 argument is the number of times through the loop, defaulting
137 argument is the number of times through the loop, defaulting
139 to one million. The main statement, the setup statement and
138 to one million. The main statement, the setup statement and
140 the timer function to be used are passed to the constructor.
139 the timer function to be used are passed to the constructor.
141 """
140 """
142 it = itertools.repeat(None, number)
141 it = itertools.repeat(None, number)
143 gcold = gc.isenabled()
142 gcold = gc.isenabled()
144 gc.disable()
143 gc.disable()
145 try:
144 try:
146 timing = self.inner(it, self.timer)
145 timing = self.inner(it, self.timer)
147 finally:
146 finally:
148 if gcold:
147 if gcold:
149 gc.enable()
148 gc.enable()
150 return timing
149 return timing
151
150
152
151
153 @magics_class
152 @magics_class
154 class ExecutionMagics(Magics):
153 class ExecutionMagics(Magics):
155 """Magics related to code execution, debugging, profiling, etc.
154 """Magics related to code execution, debugging, profiling, etc.
156
155
157 """
156 """
158
157
159 def __init__(self, shell):
158 def __init__(self, shell):
160 super(ExecutionMagics, self).__init__(shell)
159 super(ExecutionMagics, self).__init__(shell)
161 if profile is None:
160 if profile is None:
162 self.prun = self.profile_missing_notice
161 self.prun = self.profile_missing_notice
163 # Default execution function used to actually run user code.
162 # Default execution function used to actually run user code.
164 self.default_runner = None
163 self.default_runner = None
165
164
166 def profile_missing_notice(self, *args, **kwargs):
165 def profile_missing_notice(self, *args, **kwargs):
167 error("""\
166 error("""\
168 The profile module could not be found. It has been removed from the standard
167 The profile module could not be found. It has been removed from the standard
169 python packages because of its non-free license. To use profiling, install the
168 python packages because of its non-free license. To use profiling, install the
170 python-profiler package from non-free.""")
169 python-profiler package from non-free.""")
171
170
172 @skip_doctest
171 @skip_doctest
173 @line_cell_magic
172 @line_cell_magic
174 def prun(self, parameter_s='', cell=None):
173 def prun(self, parameter_s='', cell=None):
175
174
176 """Run a statement through the python code profiler.
175 """Run a statement through the python code profiler.
177
176
178 Usage, in line mode:
177 Usage, in line mode:
179 %prun [options] statement
178 %prun [options] statement
180
179
181 Usage, in cell mode:
180 Usage, in cell mode:
182 %%prun [options] [statement]
181 %%prun [options] [statement]
183 code...
182 code...
184 code...
183 code...
185
184
186 In cell mode, the additional code lines are appended to the (possibly
185 In cell mode, the additional code lines are appended to the (possibly
187 empty) statement in the first line. Cell mode allows you to easily
186 empty) statement in the first line. Cell mode allows you to easily
188 profile multiline blocks without having to put them in a separate
187 profile multiline blocks without having to put them in a separate
189 function.
188 function.
190
189
191 The given statement (which doesn't require quote marks) is run via the
190 The given statement (which doesn't require quote marks) is run via the
192 python profiler in a manner similar to the profile.run() function.
191 python profiler in a manner similar to the profile.run() function.
193 Namespaces are internally managed to work correctly; profile.run
192 Namespaces are internally managed to work correctly; profile.run
194 cannot be used in IPython because it makes certain assumptions about
193 cannot be used in IPython because it makes certain assumptions about
195 namespaces which do not hold under IPython.
194 namespaces which do not hold under IPython.
196
195
197 Options:
196 Options:
198
197
199 -l <limit>
198 -l <limit>
200 you can place restrictions on what or how much of the
199 you can place restrictions on what or how much of the
201 profile gets printed. The limit value can be:
200 profile gets printed. The limit value can be:
202
201
203 * A string: only information for function names containing this string
202 * A string: only information for function names containing this string
204 is printed.
203 is printed.
205
204
206 * An integer: only these many lines are printed.
205 * An integer: only these many lines are printed.
207
206
208 * A float (between 0 and 1): this fraction of the report is printed
207 * A float (between 0 and 1): this fraction of the report is printed
209 (for example, use a limit of 0.4 to see the topmost 40% only).
208 (for example, use a limit of 0.4 to see the topmost 40% only).
210
209
211 You can combine several limits with repeated use of the option. For
210 You can combine several limits with repeated use of the option. For
212 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
211 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
213 information about class constructors.
212 information about class constructors.
214
213
215 -r
214 -r
216 return the pstats.Stats object generated by the profiling. This
215 return the pstats.Stats object generated by the profiling. This
217 object has all the information about the profile in it, and you can
216 object has all the information about the profile in it, and you can
218 later use it for further analysis or in other functions.
217 later use it for further analysis or in other functions.
219
218
220 -s <key>
219 -s <key>
221 sort profile by given key. You can provide more than one key
220 sort profile by given key. You can provide more than one key
222 by using the option several times: '-s key1 -s key2 -s key3...'. The
221 by using the option several times: '-s key1 -s key2 -s key3...'. The
223 default sorting key is 'time'.
222 default sorting key is 'time'.
224
223
225 The following is copied verbatim from the profile documentation
224 The following is copied verbatim from the profile documentation
226 referenced below:
225 referenced below:
227
226
228 When more than one key is provided, additional keys are used as
227 When more than one key is provided, additional keys are used as
229 secondary criteria when the there is equality in all keys selected
228 secondary criteria when the there is equality in all keys selected
230 before them.
229 before them.
231
230
232 Abbreviations can be used for any key names, as long as the
231 Abbreviations can be used for any key names, as long as the
233 abbreviation is unambiguous. The following are the keys currently
232 abbreviation is unambiguous. The following are the keys currently
234 defined:
233 defined:
235
234
236 ============ =====================
235 ============ =====================
237 Valid Arg Meaning
236 Valid Arg Meaning
238 ============ =====================
237 ============ =====================
239 "calls" call count
238 "calls" call count
240 "cumulative" cumulative time
239 "cumulative" cumulative time
241 "file" file name
240 "file" file name
242 "module" file name
241 "module" file name
243 "pcalls" primitive call count
242 "pcalls" primitive call count
244 "line" line number
243 "line" line number
245 "name" function name
244 "name" function name
246 "nfl" name/file/line
245 "nfl" name/file/line
247 "stdname" standard name
246 "stdname" standard name
248 "time" internal time
247 "time" internal time
249 ============ =====================
248 ============ =====================
250
249
251 Note that all sorts on statistics are in descending order (placing
250 Note that all sorts on statistics are in descending order (placing
252 most time consuming items first), where as name, file, and line number
251 most time consuming items first), where as name, file, and line number
253 searches are in ascending order (i.e., alphabetical). The subtle
252 searches are in ascending order (i.e., alphabetical). The subtle
254 distinction between "nfl" and "stdname" is that the standard name is a
253 distinction between "nfl" and "stdname" is that the standard name is a
255 sort of the name as printed, which means that the embedded line
254 sort of the name as printed, which means that the embedded line
256 numbers get compared in an odd way. For example, lines 3, 20, and 40
255 numbers get compared in an odd way. For example, lines 3, 20, and 40
257 would (if the file names were the same) appear in the string order
256 would (if the file names were the same) appear in the string order
258 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
257 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
259 line numbers. In fact, sort_stats("nfl") is the same as
258 line numbers. In fact, sort_stats("nfl") is the same as
260 sort_stats("name", "file", "line").
259 sort_stats("name", "file", "line").
261
260
262 -T <filename>
261 -T <filename>
263 save profile results as shown on screen to a text
262 save profile results as shown on screen to a text
264 file. The profile is still shown on screen.
263 file. The profile is still shown on screen.
265
264
266 -D <filename>
265 -D <filename>
267 save (via dump_stats) profile statistics to given
266 save (via dump_stats) profile statistics to given
268 filename. This data is in a format understood by the pstats module, and
267 filename. This data is in a format understood by the pstats module, and
269 is generated by a call to the dump_stats() method of profile
268 is generated by a call to the dump_stats() method of profile
270 objects. The profile is still shown on screen.
269 objects. The profile is still shown on screen.
271
270
272 -q
271 -q
273 suppress output to the pager. Best used with -T and/or -D above.
272 suppress output to the pager. Best used with -T and/or -D above.
274
273
275 If you want to run complete programs under the profiler's control, use
274 If you want to run complete programs under the profiler's control, use
276 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
275 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
277 contains profiler specific options as described here.
276 contains profiler specific options as described here.
278
277
279 You can read the complete documentation for the profile module with::
278 You can read the complete documentation for the profile module with::
280
279
281 In [1]: import profile; profile.help()
280 In [1]: import profile; profile.help()
282 """
281 """
283 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
282 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
284 list_all=True, posix=False)
283 list_all=True, posix=False)
285 if cell is not None:
284 if cell is not None:
286 arg_str += '\n' + cell
285 arg_str += '\n' + cell
287 arg_str = self.shell.input_splitter.transform_cell(arg_str)
286 arg_str = self.shell.input_splitter.transform_cell(arg_str)
288 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
287 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
289
288
290 def _run_with_profiler(self, code, opts, namespace):
289 def _run_with_profiler(self, code, opts, namespace):
291 """
290 """
292 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
291 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
293
292
294 Parameters
293 Parameters
295 ----------
294 ----------
296 code : str
295 code : str
297 Code to be executed.
296 Code to be executed.
298 opts : Struct
297 opts : Struct
299 Options parsed by `self.parse_options`.
298 Options parsed by `self.parse_options`.
300 namespace : dict
299 namespace : dict
301 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
300 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
302
301
303 """
302 """
304
303
305 # Fill default values for unspecified options:
304 # Fill default values for unspecified options:
306 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
305 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
307
306
308 prof = profile.Profile()
307 prof = profile.Profile()
309 try:
308 try:
310 prof = prof.runctx(code, namespace, namespace)
309 prof = prof.runctx(code, namespace, namespace)
311 sys_exit = ''
310 sys_exit = ''
312 except SystemExit:
311 except SystemExit:
313 sys_exit = """*** SystemExit exception caught in code being profiled."""
312 sys_exit = """*** SystemExit exception caught in code being profiled."""
314
313
315 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
314 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
316
315
317 lims = opts.l
316 lims = opts.l
318 if lims:
317 if lims:
319 lims = [] # rebuild lims with ints/floats/strings
318 lims = [] # rebuild lims with ints/floats/strings
320 for lim in opts.l:
319 for lim in opts.l:
321 try:
320 try:
322 lims.append(int(lim))
321 lims.append(int(lim))
323 except ValueError:
322 except ValueError:
324 try:
323 try:
325 lims.append(float(lim))
324 lims.append(float(lim))
326 except ValueError:
325 except ValueError:
327 lims.append(lim)
326 lims.append(lim)
328
327
329 # Trap output.
328 # Trap output.
330 stdout_trap = StringIO()
329 stdout_trap = StringIO()
331 stats_stream = stats.stream
330 stats_stream = stats.stream
332 try:
331 try:
333 stats.stream = stdout_trap
332 stats.stream = stdout_trap
334 stats.print_stats(*lims)
333 stats.print_stats(*lims)
335 finally:
334 finally:
336 stats.stream = stats_stream
335 stats.stream = stats_stream
337
336
338 output = stdout_trap.getvalue()
337 output = stdout_trap.getvalue()
339 output = output.rstrip()
338 output = output.rstrip()
340
339
341 if 'q' not in opts:
340 if 'q' not in opts:
342 page.page(output)
341 page.page(output)
343 print(sys_exit, end=' ')
342 print(sys_exit, end=' ')
344
343
345 dump_file = opts.D[0]
344 dump_file = opts.D[0]
346 text_file = opts.T[0]
345 text_file = opts.T[0]
347 if dump_file:
346 if dump_file:
348 prof.dump_stats(dump_file)
347 prof.dump_stats(dump_file)
349 print('\n*** Profile stats marshalled to file',\
348 print('\n*** Profile stats marshalled to file',\
350 repr(dump_file)+'.',sys_exit)
349 repr(dump_file)+'.',sys_exit)
351 if text_file:
350 if text_file:
352 pfile = open(text_file,'w')
351 pfile = open(text_file,'w')
353 pfile.write(output)
352 pfile.write(output)
354 pfile.close()
353 pfile.close()
355 print('\n*** Profile printout saved to text file',\
354 print('\n*** Profile printout saved to text file',\
356 repr(text_file)+'.',sys_exit)
355 repr(text_file)+'.',sys_exit)
357
356
358 if 'r' in opts:
357 if 'r' in opts:
359 return stats
358 return stats
360 else:
359 else:
361 return None
360 return None
362
361
363 @line_magic
362 @line_magic
364 def pdb(self, parameter_s=''):
363 def pdb(self, parameter_s=''):
365 """Control the automatic calling of the pdb interactive debugger.
364 """Control the automatic calling of the pdb interactive debugger.
366
365
367 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
366 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
368 argument it works as a toggle.
367 argument it works as a toggle.
369
368
370 When an exception is triggered, IPython can optionally call the
369 When an exception is triggered, IPython can optionally call the
371 interactive pdb debugger after the traceback printout. %pdb toggles
370 interactive pdb debugger after the traceback printout. %pdb toggles
372 this feature on and off.
371 this feature on and off.
373
372
374 The initial state of this feature is set in your configuration
373 The initial state of this feature is set in your configuration
375 file (the option is ``InteractiveShell.pdb``).
374 file (the option is ``InteractiveShell.pdb``).
376
375
377 If you want to just activate the debugger AFTER an exception has fired,
376 If you want to just activate the debugger AFTER an exception has fired,
378 without having to type '%pdb on' and rerunning your code, you can use
377 without having to type '%pdb on' and rerunning your code, you can use
379 the %debug magic."""
378 the %debug magic."""
380
379
381 par = parameter_s.strip().lower()
380 par = parameter_s.strip().lower()
382
381
383 if par:
382 if par:
384 try:
383 try:
385 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
384 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
386 except KeyError:
385 except KeyError:
387 print ('Incorrect argument. Use on/1, off/0, '
386 print ('Incorrect argument. Use on/1, off/0, '
388 'or nothing for a toggle.')
387 'or nothing for a toggle.')
389 return
388 return
390 else:
389 else:
391 # toggle
390 # toggle
392 new_pdb = not self.shell.call_pdb
391 new_pdb = not self.shell.call_pdb
393
392
394 # set on the shell
393 # set on the shell
395 self.shell.call_pdb = new_pdb
394 self.shell.call_pdb = new_pdb
396 print('Automatic pdb calling has been turned',on_off(new_pdb))
395 print('Automatic pdb calling has been turned',on_off(new_pdb))
397
396
398 @skip_doctest
397 @skip_doctest
399 @magic_arguments.magic_arguments()
398 @magic_arguments.magic_arguments()
400 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
399 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
401 help="""
400 help="""
402 Set break point at LINE in FILE.
401 Set break point at LINE in FILE.
403 """
402 """
404 )
403 )
405 @magic_arguments.argument('statement', nargs='*',
404 @magic_arguments.argument('statement', nargs='*',
406 help="""
405 help="""
407 Code to run in debugger.
406 Code to run in debugger.
408 You can omit this in cell magic mode.
407 You can omit this in cell magic mode.
409 """
408 """
410 )
409 )
411 @line_cell_magic
410 @line_cell_magic
412 def debug(self, line='', cell=None):
411 def debug(self, line='', cell=None):
413 """Activate the interactive debugger.
412 """Activate the interactive debugger.
414
413
415 This magic command support two ways of activating debugger.
414 This magic command support two ways of activating debugger.
416 One is to activate debugger before executing code. This way, you
415 One is to activate debugger before executing code. This way, you
417 can set a break point, to step through the code from the point.
416 can set a break point, to step through the code from the point.
418 You can use this mode by giving statements to execute and optionally
417 You can use this mode by giving statements to execute and optionally
419 a breakpoint.
418 a breakpoint.
420
419
421 The other one is to activate debugger in post-mortem mode. You can
420 The other one is to activate debugger in post-mortem mode. You can
422 activate this mode simply running %debug without any argument.
421 activate this mode simply running %debug without any argument.
423 If an exception has just occurred, this lets you inspect its stack
422 If an exception has just occurred, this lets you inspect its stack
424 frames interactively. Note that this will always work only on the last
423 frames interactively. Note that this will always work only on the last
425 traceback that occurred, so you must call this quickly after an
424 traceback that occurred, so you must call this quickly after an
426 exception that you wish to inspect has fired, because if another one
425 exception that you wish to inspect has fired, because if another one
427 occurs, it clobbers the previous one.
426 occurs, it clobbers the previous one.
428
427
429 If you want IPython to automatically do this on every exception, see
428 If you want IPython to automatically do this on every exception, see
430 the %pdb magic for more details.
429 the %pdb magic for more details.
431 """
430 """
432 args = magic_arguments.parse_argstring(self.debug, line)
431 args = magic_arguments.parse_argstring(self.debug, line)
433
432
434 if not (args.breakpoint or args.statement or cell):
433 if not (args.breakpoint or args.statement or cell):
435 self._debug_post_mortem()
434 self._debug_post_mortem()
436 else:
435 else:
437 code = "\n".join(args.statement)
436 code = "\n".join(args.statement)
438 if cell:
437 if cell:
439 code += "\n" + cell
438 code += "\n" + cell
440 self._debug_exec(code, args.breakpoint)
439 self._debug_exec(code, args.breakpoint)
441
440
442 def _debug_post_mortem(self):
441 def _debug_post_mortem(self):
443 self.shell.debugger(force=True)
442 self.shell.debugger(force=True)
444
443
445 def _debug_exec(self, code, breakpoint):
444 def _debug_exec(self, code, breakpoint):
446 if breakpoint:
445 if breakpoint:
447 (filename, bp_line) = breakpoint.rsplit(':', 1)
446 (filename, bp_line) = breakpoint.rsplit(':', 1)
448 bp_line = int(bp_line)
447 bp_line = int(bp_line)
449 else:
448 else:
450 (filename, bp_line) = (None, None)
449 (filename, bp_line) = (None, None)
451 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
450 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
452
451
453 @line_magic
452 @line_magic
454 def tb(self, s):
453 def tb(self, s):
455 """Print the last traceback with the currently active exception mode.
454 """Print the last traceback with the currently active exception mode.
456
455
457 See %xmode for changing exception reporting modes."""
456 See %xmode for changing exception reporting modes."""
458 self.shell.showtraceback()
457 self.shell.showtraceback()
459
458
460 @skip_doctest
459 @skip_doctest
461 @line_magic
460 @line_magic
462 def run(self, parameter_s='', runner=None,
461 def run(self, parameter_s='', runner=None,
463 file_finder=get_py_filename):
462 file_finder=get_py_filename):
464 """Run the named file inside IPython as a program.
463 """Run the named file inside IPython as a program.
465
464
466 Usage::
465 Usage::
467
466
468 %run [-n -i -e -G]
467 %run [-n -i -e -G]
469 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
468 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
470 ( -m mod | file ) [args]
469 ( -m mod | file ) [args]
471
470
472 Parameters after the filename are passed as command-line arguments to
471 Parameters after the filename are passed as command-line arguments to
473 the program (put in sys.argv). Then, control returns to IPython's
472 the program (put in sys.argv). Then, control returns to IPython's
474 prompt.
473 prompt.
475
474
476 This is similar to running at a system prompt ``python file args``,
475 This is similar to running at a system prompt ``python file args``,
477 but with the advantage of giving you IPython's tracebacks, and of
476 but with the advantage of giving you IPython's tracebacks, and of
478 loading all variables into your interactive namespace for further use
477 loading all variables into your interactive namespace for further use
479 (unless -p is used, see below).
478 (unless -p is used, see below).
480
479
481 The file is executed in a namespace initially consisting only of
480 The file is executed in a namespace initially consisting only of
482 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
481 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
483 sees its environment as if it were being run as a stand-alone program
482 sees its environment as if it were being run as a stand-alone program
484 (except for sharing global objects such as previously imported
483 (except for sharing global objects such as previously imported
485 modules). But after execution, the IPython interactive namespace gets
484 modules). But after execution, the IPython interactive namespace gets
486 updated with all variables defined in the program (except for __name__
485 updated with all variables defined in the program (except for __name__
487 and sys.argv). This allows for very convenient loading of code for
486 and sys.argv). This allows for very convenient loading of code for
488 interactive work, while giving each program a 'clean sheet' to run in.
487 interactive work, while giving each program a 'clean sheet' to run in.
489
488
490 Arguments are expanded using shell-like glob match. Patterns
489 Arguments are expanded using shell-like glob match. Patterns
491 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
490 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
492 tilde '~' will be expanded into user's home directory. Unlike
491 tilde '~' will be expanded into user's home directory. Unlike
493 real shells, quotation does not suppress expansions. Use
492 real shells, quotation does not suppress expansions. Use
494 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
493 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
495 To completely disable these expansions, you can use -G flag.
494 To completely disable these expansions, you can use -G flag.
496
495
497 Options:
496 Options:
498
497
499 -n
498 -n
500 __name__ is NOT set to '__main__', but to the running file's name
499 __name__ is NOT set to '__main__', but to the running file's name
501 without extension (as python does under import). This allows running
500 without extension (as python does under import). This allows running
502 scripts and reloading the definitions in them without calling code
501 scripts and reloading the definitions in them without calling code
503 protected by an ``if __name__ == "__main__"`` clause.
502 protected by an ``if __name__ == "__main__"`` clause.
504
503
505 -i
504 -i
506 run the file in IPython's namespace instead of an empty one. This
505 run the file in IPython's namespace instead of an empty one. This
507 is useful if you are experimenting with code written in a text editor
506 is useful if you are experimenting with code written in a text editor
508 which depends on variables defined interactively.
507 which depends on variables defined interactively.
509
508
510 -e
509 -e
511 ignore sys.exit() calls or SystemExit exceptions in the script
510 ignore sys.exit() calls or SystemExit exceptions in the script
512 being run. This is particularly useful if IPython is being used to
511 being run. This is particularly useful if IPython is being used to
513 run unittests, which always exit with a sys.exit() call. In such
512 run unittests, which always exit with a sys.exit() call. In such
514 cases you are interested in the output of the test results, not in
513 cases you are interested in the output of the test results, not in
515 seeing a traceback of the unittest module.
514 seeing a traceback of the unittest module.
516
515
517 -t
516 -t
518 print timing information at the end of the run. IPython will give
517 print timing information at the end of the run. IPython will give
519 you an estimated CPU time consumption for your script, which under
518 you an estimated CPU time consumption for your script, which under
520 Unix uses the resource module to avoid the wraparound problems of
519 Unix uses the resource module to avoid the wraparound problems of
521 time.clock(). Under Unix, an estimate of time spent on system tasks
520 time.clock(). Under Unix, an estimate of time spent on system tasks
522 is also given (for Windows platforms this is reported as 0.0).
521 is also given (for Windows platforms this is reported as 0.0).
523
522
524 If -t is given, an additional ``-N<N>`` option can be given, where <N>
523 If -t is given, an additional ``-N<N>`` option can be given, where <N>
525 must be an integer indicating how many times you want the script to
524 must be an integer indicating how many times you want the script to
526 run. The final timing report will include total and per run results.
525 run. The final timing report will include total and per run results.
527
526
528 For example (testing the script uniq_stable.py)::
527 For example (testing the script uniq_stable.py)::
529
528
530 In [1]: run -t uniq_stable
529 In [1]: run -t uniq_stable
531
530
532 IPython CPU timings (estimated):
531 IPython CPU timings (estimated):
533 User : 0.19597 s.
532 User : 0.19597 s.
534 System: 0.0 s.
533 System: 0.0 s.
535
534
536 In [2]: run -t -N5 uniq_stable
535 In [2]: run -t -N5 uniq_stable
537
536
538 IPython CPU timings (estimated):
537 IPython CPU timings (estimated):
539 Total runs performed: 5
538 Total runs performed: 5
540 Times : Total Per run
539 Times : Total Per run
541 User : 0.910862 s, 0.1821724 s.
540 User : 0.910862 s, 0.1821724 s.
542 System: 0.0 s, 0.0 s.
541 System: 0.0 s, 0.0 s.
543
542
544 -d
543 -d
545 run your program under the control of pdb, the Python debugger.
544 run your program under the control of pdb, the Python debugger.
546 This allows you to execute your program step by step, watch variables,
545 This allows you to execute your program step by step, watch variables,
547 etc. Internally, what IPython does is similar to calling::
546 etc. Internally, what IPython does is similar to calling::
548
547
549 pdb.run('execfile("YOURFILENAME")')
548 pdb.run('execfile("YOURFILENAME")')
550
549
551 with a breakpoint set on line 1 of your file. You can change the line
550 with a breakpoint set on line 1 of your file. You can change the line
552 number for this automatic breakpoint to be <N> by using the -bN option
551 number for this automatic breakpoint to be <N> by using the -bN option
553 (where N must be an integer). For example::
552 (where N must be an integer). For example::
554
553
555 %run -d -b40 myscript
554 %run -d -b40 myscript
556
555
557 will set the first breakpoint at line 40 in myscript.py. Note that
556 will set the first breakpoint at line 40 in myscript.py. Note that
558 the first breakpoint must be set on a line which actually does
557 the first breakpoint must be set on a line which actually does
559 something (not a comment or docstring) for it to stop execution.
558 something (not a comment or docstring) for it to stop execution.
560
559
561 Or you can specify a breakpoint in a different file::
560 Or you can specify a breakpoint in a different file::
562
561
563 %run -d -b myotherfile.py:20 myscript
562 %run -d -b myotherfile.py:20 myscript
564
563
565 When the pdb debugger starts, you will see a (Pdb) prompt. You must
564 When the pdb debugger starts, you will see a (Pdb) prompt. You must
566 first enter 'c' (without quotes) to start execution up to the first
565 first enter 'c' (without quotes) to start execution up to the first
567 breakpoint.
566 breakpoint.
568
567
569 Entering 'help' gives information about the use of the debugger. You
568 Entering 'help' gives information about the use of the debugger. You
570 can easily see pdb's full documentation with "import pdb;pdb.help()"
569 can easily see pdb's full documentation with "import pdb;pdb.help()"
571 at a prompt.
570 at a prompt.
572
571
573 -p
572 -p
574 run program under the control of the Python profiler module (which
573 run program under the control of the Python profiler module (which
575 prints a detailed report of execution times, function calls, etc).
574 prints a detailed report of execution times, function calls, etc).
576
575
577 You can pass other options after -p which affect the behavior of the
576 You can pass other options after -p which affect the behavior of the
578 profiler itself. See the docs for %prun for details.
577 profiler itself. See the docs for %prun for details.
579
578
580 In this mode, the program's variables do NOT propagate back to the
579 In this mode, the program's variables do NOT propagate back to the
581 IPython interactive namespace (because they remain in the namespace
580 IPython interactive namespace (because they remain in the namespace
582 where the profiler executes them).
581 where the profiler executes them).
583
582
584 Internally this triggers a call to %prun, see its documentation for
583 Internally this triggers a call to %prun, see its documentation for
585 details on the options available specifically for profiling.
584 details on the options available specifically for profiling.
586
585
587 There is one special usage for which the text above doesn't apply:
586 There is one special usage for which the text above doesn't apply:
588 if the filename ends with .ipy[nb], the file is run as ipython script,
587 if the filename ends with .ipy[nb], the file is run as ipython script,
589 just as if the commands were written on IPython prompt.
588 just as if the commands were written on IPython prompt.
590
589
591 -m
590 -m
592 specify module name to load instead of script path. Similar to
591 specify module name to load instead of script path. Similar to
593 the -m option for the python interpreter. Use this option last if you
592 the -m option for the python interpreter. Use this option last if you
594 want to combine with other %run options. Unlike the python interpreter
593 want to combine with other %run options. Unlike the python interpreter
595 only source modules are allowed no .pyc or .pyo files.
594 only source modules are allowed no .pyc or .pyo files.
596 For example::
595 For example::
597
596
598 %run -m example
597 %run -m example
599
598
600 will run the example module.
599 will run the example module.
601
600
602 -G
601 -G
603 disable shell-like glob expansion of arguments.
602 disable shell-like glob expansion of arguments.
604
603
605 """
604 """
606
605
607 # get arguments and set sys.argv for program to be run.
606 # get arguments and set sys.argv for program to be run.
608 opts, arg_lst = self.parse_options(parameter_s,
607 opts, arg_lst = self.parse_options(parameter_s,
609 'nidtN:b:pD:l:rs:T:em:G',
608 'nidtN:b:pD:l:rs:T:em:G',
610 mode='list', list_all=1)
609 mode='list', list_all=1)
611 if "m" in opts:
610 if "m" in opts:
612 modulename = opts["m"][0]
611 modulename = opts["m"][0]
613 modpath = find_mod(modulename)
612 modpath = find_mod(modulename)
614 if modpath is None:
613 if modpath is None:
615 warn('%r is not a valid modulename on sys.path'%modulename)
614 warn('%r is not a valid modulename on sys.path'%modulename)
616 return
615 return
617 arg_lst = [modpath] + arg_lst
616 arg_lst = [modpath] + arg_lst
618 try:
617 try:
619 filename = file_finder(arg_lst[0])
618 filename = file_finder(arg_lst[0])
620 except IndexError:
619 except IndexError:
621 warn('you must provide at least a filename.')
620 warn('you must provide at least a filename.')
622 print('\n%run:\n', oinspect.getdoc(self.run))
621 print('\n%run:\n', oinspect.getdoc(self.run))
623 return
622 return
624 except IOError as e:
623 except IOError as e:
625 try:
624 try:
626 msg = str(e)
625 msg = str(e)
627 except UnicodeError:
626 except UnicodeError:
628 msg = e.message
627 msg = e.message
629 error(msg)
628 error(msg)
630 return
629 return
631
630
632 if filename.lower().endswith(('.ipy', '.ipynb')):
631 if filename.lower().endswith(('.ipy', '.ipynb')):
633 with preserve_keys(self.shell.user_ns, '__file__'):
632 with preserve_keys(self.shell.user_ns, '__file__'):
634 self.shell.user_ns['__file__'] = filename
633 self.shell.user_ns['__file__'] = filename
635 self.shell.safe_execfile_ipy(filename)
634 self.shell.safe_execfile_ipy(filename)
636 return
635 return
637
636
638 # Control the response to exit() calls made by the script being run
637 # Control the response to exit() calls made by the script being run
639 exit_ignore = 'e' in opts
638 exit_ignore = 'e' in opts
640
639
641 # Make sure that the running script gets a proper sys.argv as if it
640 # Make sure that the running script gets a proper sys.argv as if it
642 # were run from a system shell.
641 # were run from a system shell.
643 save_argv = sys.argv # save it for later restoring
642 save_argv = sys.argv # save it for later restoring
644
643
645 if 'G' in opts:
644 if 'G' in opts:
646 args = arg_lst[1:]
645 args = arg_lst[1:]
647 else:
646 else:
648 # tilde and glob expansion
647 # tilde and glob expansion
649 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
648 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
650
649
651 sys.argv = [filename] + args # put in the proper filename
650 sys.argv = [filename] + args # put in the proper filename
652
651
653 if 'i' in opts:
652 if 'i' in opts:
654 # Run in user's interactive namespace
653 # Run in user's interactive namespace
655 prog_ns = self.shell.user_ns
654 prog_ns = self.shell.user_ns
656 __name__save = self.shell.user_ns['__name__']
655 __name__save = self.shell.user_ns['__name__']
657 prog_ns['__name__'] = '__main__'
656 prog_ns['__name__'] = '__main__'
658 main_mod = self.shell.user_module
657 main_mod = self.shell.user_module
659
658
660 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
659 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
661 # set the __file__ global in the script's namespace
660 # set the __file__ global in the script's namespace
662 # TK: Is this necessary in interactive mode?
661 # TK: Is this necessary in interactive mode?
663 prog_ns['__file__'] = filename
662 prog_ns['__file__'] = filename
664 else:
663 else:
665 # Run in a fresh, empty namespace
664 # Run in a fresh, empty namespace
666 if 'n' in opts:
665 if 'n' in opts:
667 name = os.path.splitext(os.path.basename(filename))[0]
666 name = os.path.splitext(os.path.basename(filename))[0]
668 else:
667 else:
669 name = '__main__'
668 name = '__main__'
670
669
671 # The shell MUST hold a reference to prog_ns so after %run
670 # The shell MUST hold a reference to prog_ns so after %run
672 # exits, the python deletion mechanism doesn't zero it out
671 # exits, the python deletion mechanism doesn't zero it out
673 # (leaving dangling references). See interactiveshell for details
672 # (leaving dangling references). See interactiveshell for details
674 main_mod = self.shell.new_main_mod(filename, name)
673 main_mod = self.shell.new_main_mod(filename, name)
675 prog_ns = main_mod.__dict__
674 prog_ns = main_mod.__dict__
676
675
677 # pickle fix. See interactiveshell for an explanation. But we need to
676 # pickle fix. See interactiveshell for an explanation. But we need to
678 # make sure that, if we overwrite __main__, we replace it at the end
677 # make sure that, if we overwrite __main__, we replace it at the end
679 main_mod_name = prog_ns['__name__']
678 main_mod_name = prog_ns['__name__']
680
679
681 if main_mod_name == '__main__':
680 if main_mod_name == '__main__':
682 restore_main = sys.modules['__main__']
681 restore_main = sys.modules['__main__']
683 else:
682 else:
684 restore_main = False
683 restore_main = False
685
684
686 # This needs to be undone at the end to prevent holding references to
685 # This needs to be undone at the end to prevent holding references to
687 # every single object ever created.
686 # every single object ever created.
688 sys.modules[main_mod_name] = main_mod
687 sys.modules[main_mod_name] = main_mod
689
688
690 if 'p' in opts or 'd' in opts:
689 if 'p' in opts or 'd' in opts:
691 if 'm' in opts:
690 if 'm' in opts:
692 code = 'run_module(modulename, prog_ns)'
691 code = 'run_module(modulename, prog_ns)'
693 code_ns = {
692 code_ns = {
694 'run_module': self.shell.safe_run_module,
693 'run_module': self.shell.safe_run_module,
695 'prog_ns': prog_ns,
694 'prog_ns': prog_ns,
696 'modulename': modulename,
695 'modulename': modulename,
697 }
696 }
698 else:
697 else:
699 if 'd' in opts:
698 if 'd' in opts:
700 # allow exceptions to raise in debug mode
699 # allow exceptions to raise in debug mode
701 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
700 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
702 else:
701 else:
703 code = 'execfile(filename, prog_ns)'
702 code = 'execfile(filename, prog_ns)'
704 code_ns = {
703 code_ns = {
705 'execfile': self.shell.safe_execfile,
704 'execfile': self.shell.safe_execfile,
706 'prog_ns': prog_ns,
705 'prog_ns': prog_ns,
707 'filename': get_py_filename(filename),
706 'filename': get_py_filename(filename),
708 }
707 }
709
708
710 try:
709 try:
711 stats = None
710 stats = None
712 if 'p' in opts:
711 if 'p' in opts:
713 stats = self._run_with_profiler(code, opts, code_ns)
712 stats = self._run_with_profiler(code, opts, code_ns)
714 else:
713 else:
715 if 'd' in opts:
714 if 'd' in opts:
716 bp_file, bp_line = parse_breakpoint(
715 bp_file, bp_line = parse_breakpoint(
717 opts.get('b', ['1'])[0], filename)
716 opts.get('b', ['1'])[0], filename)
718 self._run_with_debugger(
717 self._run_with_debugger(
719 code, code_ns, filename, bp_line, bp_file)
718 code, code_ns, filename, bp_line, bp_file)
720 else:
719 else:
721 if 'm' in opts:
720 if 'm' in opts:
722 def run():
721 def run():
723 self.shell.safe_run_module(modulename, prog_ns)
722 self.shell.safe_run_module(modulename, prog_ns)
724 else:
723 else:
725 if runner is None:
724 if runner is None:
726 runner = self.default_runner
725 runner = self.default_runner
727 if runner is None:
726 if runner is None:
728 runner = self.shell.safe_execfile
727 runner = self.shell.safe_execfile
729
728
730 def run():
729 def run():
731 runner(filename, prog_ns, prog_ns,
730 runner(filename, prog_ns, prog_ns,
732 exit_ignore=exit_ignore)
731 exit_ignore=exit_ignore)
733
732
734 if 't' in opts:
733 if 't' in opts:
735 # timed execution
734 # timed execution
736 try:
735 try:
737 nruns = int(opts['N'][0])
736 nruns = int(opts['N'][0])
738 if nruns < 1:
737 if nruns < 1:
739 error('Number of runs must be >=1')
738 error('Number of runs must be >=1')
740 return
739 return
741 except (KeyError):
740 except (KeyError):
742 nruns = 1
741 nruns = 1
743 self._run_with_timing(run, nruns)
742 self._run_with_timing(run, nruns)
744 else:
743 else:
745 # regular execution
744 # regular execution
746 run()
745 run()
747
746
748 if 'i' in opts:
747 if 'i' in opts:
749 self.shell.user_ns['__name__'] = __name__save
748 self.shell.user_ns['__name__'] = __name__save
750 else:
749 else:
751 # update IPython interactive namespace
750 # update IPython interactive namespace
752
751
753 # Some forms of read errors on the file may mean the
752 # Some forms of read errors on the file may mean the
754 # __name__ key was never set; using pop we don't have to
753 # __name__ key was never set; using pop we don't have to
755 # worry about a possible KeyError.
754 # worry about a possible KeyError.
756 prog_ns.pop('__name__', None)
755 prog_ns.pop('__name__', None)
757
756
758 with preserve_keys(self.shell.user_ns, '__file__'):
757 with preserve_keys(self.shell.user_ns, '__file__'):
759 self.shell.user_ns.update(prog_ns)
758 self.shell.user_ns.update(prog_ns)
760 finally:
759 finally:
761 # It's a bit of a mystery why, but __builtins__ can change from
760 # It's a bit of a mystery why, but __builtins__ can change from
762 # being a module to becoming a dict missing some key data after
761 # being a module to becoming a dict missing some key data after
763 # %run. As best I can see, this is NOT something IPython is doing
762 # %run. As best I can see, this is NOT something IPython is doing
764 # at all, and similar problems have been reported before:
763 # at all, and similar problems have been reported before:
765 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
764 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
766 # Since this seems to be done by the interpreter itself, the best
765 # Since this seems to be done by the interpreter itself, the best
767 # we can do is to at least restore __builtins__ for the user on
766 # we can do is to at least restore __builtins__ for the user on
768 # exit.
767 # exit.
769 self.shell.user_ns['__builtins__'] = builtin_mod
768 self.shell.user_ns['__builtins__'] = builtin_mod
770
769
771 # Ensure key global structures are restored
770 # Ensure key global structures are restored
772 sys.argv = save_argv
771 sys.argv = save_argv
773 if restore_main:
772 if restore_main:
774 sys.modules['__main__'] = restore_main
773 sys.modules['__main__'] = restore_main
775 else:
774 else:
776 # Remove from sys.modules the reference to main_mod we'd
775 # Remove from sys.modules the reference to main_mod we'd
777 # added. Otherwise it will trap references to objects
776 # added. Otherwise it will trap references to objects
778 # contained therein.
777 # contained therein.
779 del sys.modules[main_mod_name]
778 del sys.modules[main_mod_name]
780
779
781 return stats
780 return stats
782
781
783 def _run_with_debugger(self, code, code_ns, filename=None,
782 def _run_with_debugger(self, code, code_ns, filename=None,
784 bp_line=None, bp_file=None):
783 bp_line=None, bp_file=None):
785 """
784 """
786 Run `code` in debugger with a break point.
785 Run `code` in debugger with a break point.
787
786
788 Parameters
787 Parameters
789 ----------
788 ----------
790 code : str
789 code : str
791 Code to execute.
790 Code to execute.
792 code_ns : dict
791 code_ns : dict
793 A namespace in which `code` is executed.
792 A namespace in which `code` is executed.
794 filename : str
793 filename : str
795 `code` is ran as if it is in `filename`.
794 `code` is ran as if it is in `filename`.
796 bp_line : int, optional
795 bp_line : int, optional
797 Line number of the break point.
796 Line number of the break point.
798 bp_file : str, optional
797 bp_file : str, optional
799 Path to the file in which break point is specified.
798 Path to the file in which break point is specified.
800 `filename` is used if not given.
799 `filename` is used if not given.
801
800
802 Raises
801 Raises
803 ------
802 ------
804 UsageError
803 UsageError
805 If the break point given by `bp_line` is not valid.
804 If the break point given by `bp_line` is not valid.
806
805
807 """
806 """
808 deb = self.shell.InteractiveTB.pdb
807 deb = self.shell.InteractiveTB.pdb
809 if not deb:
808 if not deb:
810 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
809 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
811 deb = self.shell.InteractiveTB.pdb
810 deb = self.shell.InteractiveTB.pdb
812
811
813 # deb.checkline() fails if deb.curframe exists but is None; it can
812 # deb.checkline() fails if deb.curframe exists but is None; it can
814 # handle it not existing. https://github.com/ipython/ipython/issues/10028
813 # handle it not existing. https://github.com/ipython/ipython/issues/10028
815 if hasattr(deb, 'curframe'):
814 if hasattr(deb, 'curframe'):
816 del deb.curframe
815 del deb.curframe
817
816
818 # reset Breakpoint state, which is moronically kept
817 # reset Breakpoint state, which is moronically kept
819 # in a class
818 # in a class
820 bdb.Breakpoint.next = 1
819 bdb.Breakpoint.next = 1
821 bdb.Breakpoint.bplist = {}
820 bdb.Breakpoint.bplist = {}
822 bdb.Breakpoint.bpbynumber = [None]
821 bdb.Breakpoint.bpbynumber = [None]
823 if bp_line is not None:
822 if bp_line is not None:
824 # Set an initial breakpoint to stop execution
823 # Set an initial breakpoint to stop execution
825 maxtries = 10
824 maxtries = 10
826 bp_file = bp_file or filename
825 bp_file = bp_file or filename
827 checkline = deb.checkline(bp_file, bp_line)
826 checkline = deb.checkline(bp_file, bp_line)
828 if not checkline:
827 if not checkline:
829 for bp in range(bp_line + 1, bp_line + maxtries + 1):
828 for bp in range(bp_line + 1, bp_line + maxtries + 1):
830 if deb.checkline(bp_file, bp):
829 if deb.checkline(bp_file, bp):
831 break
830 break
832 else:
831 else:
833 msg = ("\nI failed to find a valid line to set "
832 msg = ("\nI failed to find a valid line to set "
834 "a breakpoint\n"
833 "a breakpoint\n"
835 "after trying up to line: %s.\n"
834 "after trying up to line: %s.\n"
836 "Please set a valid breakpoint manually "
835 "Please set a valid breakpoint manually "
837 "with the -b option." % bp)
836 "with the -b option." % bp)
838 raise UsageError(msg)
837 raise UsageError(msg)
839 # if we find a good linenumber, set the breakpoint
838 # if we find a good linenumber, set the breakpoint
840 deb.do_break('%s:%s' % (bp_file, bp_line))
839 deb.do_break('%s:%s' % (bp_file, bp_line))
841
840
842 if filename:
841 if filename:
843 # Mimic Pdb._runscript(...)
842 # Mimic Pdb._runscript(...)
844 deb._wait_for_mainpyfile = True
843 deb._wait_for_mainpyfile = True
845 deb.mainpyfile = deb.canonic(filename)
844 deb.mainpyfile = deb.canonic(filename)
846
845
847 # Start file run
846 # Start file run
848 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
847 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
849 try:
848 try:
850 if filename:
849 if filename:
851 # save filename so it can be used by methods on the deb object
850 # save filename so it can be used by methods on the deb object
852 deb._exec_filename = filename
851 deb._exec_filename = filename
853 while True:
852 while True:
854 try:
853 try:
855 deb.run(code, code_ns)
854 deb.run(code, code_ns)
856 except Restart:
855 except Restart:
857 print("Restarting")
856 print("Restarting")
858 if filename:
857 if filename:
859 deb._wait_for_mainpyfile = True
858 deb._wait_for_mainpyfile = True
860 deb.mainpyfile = deb.canonic(filename)
859 deb.mainpyfile = deb.canonic(filename)
861 continue
860 continue
862 else:
861 else:
863 break
862 break
864
863
865
864
866 except:
865 except:
867 etype, value, tb = sys.exc_info()
866 etype, value, tb = sys.exc_info()
868 # Skip three frames in the traceback: the %run one,
867 # Skip three frames in the traceback: the %run one,
869 # one inside bdb.py, and the command-line typed by the
868 # one inside bdb.py, and the command-line typed by the
870 # user (run by exec in pdb itself).
869 # user (run by exec in pdb itself).
871 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
870 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
872
871
873 @staticmethod
872 @staticmethod
874 def _run_with_timing(run, nruns):
873 def _run_with_timing(run, nruns):
875 """
874 """
876 Run function `run` and print timing information.
875 Run function `run` and print timing information.
877
876
878 Parameters
877 Parameters
879 ----------
878 ----------
880 run : callable
879 run : callable
881 Any callable object which takes no argument.
880 Any callable object which takes no argument.
882 nruns : int
881 nruns : int
883 Number of times to execute `run`.
882 Number of times to execute `run`.
884
883
885 """
884 """
886 twall0 = time.time()
885 twall0 = time.time()
887 if nruns == 1:
886 if nruns == 1:
888 t0 = clock2()
887 t0 = clock2()
889 run()
888 run()
890 t1 = clock2()
889 t1 = clock2()
891 t_usr = t1[0] - t0[0]
890 t_usr = t1[0] - t0[0]
892 t_sys = t1[1] - t0[1]
891 t_sys = t1[1] - t0[1]
893 print("\nIPython CPU timings (estimated):")
892 print("\nIPython CPU timings (estimated):")
894 print(" User : %10.2f s." % t_usr)
893 print(" User : %10.2f s." % t_usr)
895 print(" System : %10.2f s." % t_sys)
894 print(" System : %10.2f s." % t_sys)
896 else:
895 else:
897 runs = range(nruns)
896 runs = range(nruns)
898 t0 = clock2()
897 t0 = clock2()
899 for nr in runs:
898 for nr in runs:
900 run()
899 run()
901 t1 = clock2()
900 t1 = clock2()
902 t_usr = t1[0] - t0[0]
901 t_usr = t1[0] - t0[0]
903 t_sys = t1[1] - t0[1]
902 t_sys = t1[1] - t0[1]
904 print("\nIPython CPU timings (estimated):")
903 print("\nIPython CPU timings (estimated):")
905 print("Total runs performed:", nruns)
904 print("Total runs performed:", nruns)
906 print(" Times : %10s %10s" % ('Total', 'Per run'))
905 print(" Times : %10s %10s" % ('Total', 'Per run'))
907 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
906 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
908 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
907 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
909 twall1 = time.time()
908 twall1 = time.time()
910 print("Wall time: %10.2f s." % (twall1 - twall0))
909 print("Wall time: %10.2f s." % (twall1 - twall0))
911
910
912 @skip_doctest
911 @skip_doctest
913 @line_cell_magic
912 @line_cell_magic
914 def timeit(self, line='', cell=None):
913 def timeit(self, line='', cell=None):
915 """Time execution of a Python statement or expression
914 """Time execution of a Python statement or expression
916
915
917 Usage, in line mode:
916 Usage, in line mode:
918 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
917 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
919 or in cell mode:
918 or in cell mode:
920 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
919 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
921 code
920 code
922 code...
921 code...
923
922
924 Time execution of a Python statement or expression using the timeit
923 Time execution of a Python statement or expression using the timeit
925 module. This function can be used both as a line and cell magic:
924 module. This function can be used both as a line and cell magic:
926
925
927 - In line mode you can time a single-line statement (though multiple
926 - In line mode you can time a single-line statement (though multiple
928 ones can be chained with using semicolons).
927 ones can be chained with using semicolons).
929
928
930 - In cell mode, the statement in the first line is used as setup code
929 - In cell mode, the statement in the first line is used as setup code
931 (executed but not timed) and the body of the cell is timed. The cell
930 (executed but not timed) and the body of the cell is timed. The cell
932 body has access to any variables created in the setup code.
931 body has access to any variables created in the setup code.
933
932
934 Options:
933 Options:
935 -n<N>: execute the given statement <N> times in a loop. If this value
934 -n<N>: execute the given statement <N> times in a loop. If this value
936 is not given, a fitting value is chosen.
935 is not given, a fitting value is chosen.
937
936
938 -r<R>: repeat the loop iteration <R> times and take the best result.
937 -r<R>: repeat the loop iteration <R> times and take the best result.
939 Default: 3
938 Default: 3
940
939
941 -t: use time.time to measure the time, which is the default on Unix.
940 -t: use time.time to measure the time, which is the default on Unix.
942 This function measures wall time.
941 This function measures wall time.
943
942
944 -c: use time.clock to measure the time, which is the default on
943 -c: use time.clock to measure the time, which is the default on
945 Windows and measures wall time. On Unix, resource.getrusage is used
944 Windows and measures wall time. On Unix, resource.getrusage is used
946 instead and returns the CPU user time.
945 instead and returns the CPU user time.
947
946
948 -p<P>: use a precision of <P> digits to display the timing result.
947 -p<P>: use a precision of <P> digits to display the timing result.
949 Default: 3
948 Default: 3
950
949
951 -q: Quiet, do not print result.
950 -q: Quiet, do not print result.
952
951
953 -o: return a TimeitResult that can be stored in a variable to inspect
952 -o: return a TimeitResult that can be stored in a variable to inspect
954 the result in more details.
953 the result in more details.
955
954
956
955
957 Examples
956 Examples
958 --------
957 --------
959 ::
958 ::
960
959
961 In [1]: %timeit pass
960 In [1]: %timeit pass
962 100000000 loops, average of 7: 5.48 ns +- 0.354 ns per loop (using standard deviation)
961 100000000 loops, average of 7: 5.48 ns +- 0.354 ns per loop (using standard deviation)
963
962
964 In [2]: u = None
963 In [2]: u = None
965
964
966 In [3]: %timeit u is None
965 In [3]: %timeit u is None
967 10000000 loops, average of 7: 22.7 ns +- 2.33 ns per loop (using standard deviation)
966 10000000 loops, average of 7: 22.7 ns +- 2.33 ns per loop (using standard deviation)
968
967
969 In [4]: %timeit -r 4 u == None
968 In [4]: %timeit -r 4 u == None
970 10000000 loops, average of 4: 27.5 ns +- 2.91 ns per loop (using standard deviation)
969 10000000 loops, average of 4: 27.5 ns +- 2.91 ns per loop (using standard deviation)
971
970
972 In [5]: import time
971 In [5]: import time
973
972
974 In [6]: %timeit -n1 time.sleep(2)
973 In [6]: %timeit -n1 time.sleep(2)
975 1 loop, average of 7: 2 s +- 4.71 Β΅s per loop (using standard deviation)
974 1 loop, average of 7: 2 s +- 4.71 Β΅s per loop (using standard deviation)
976
975
977
976
978 The times reported by %timeit will be slightly higher than those
977 The times reported by %timeit will be slightly higher than those
979 reported by the timeit.py script when variables are accessed. This is
978 reported by the timeit.py script when variables are accessed. This is
980 due to the fact that %timeit executes the statement in the namespace
979 due to the fact that %timeit executes the statement in the namespace
981 of the shell, compared with timeit.py, which uses a single setup
980 of the shell, compared with timeit.py, which uses a single setup
982 statement to import function or create variables. Generally, the bias
981 statement to import function or create variables. Generally, the bias
983 does not matter as long as results from timeit.py are not mixed with
982 does not matter as long as results from timeit.py are not mixed with
984 those from %timeit."""
983 those from %timeit."""
985
984
986 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
985 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
987 posix=False, strict=False)
986 posix=False, strict=False)
988 if stmt == "" and cell is None:
987 if stmt == "" and cell is None:
989 return
988 return
990
989
991 timefunc = timeit.default_timer
990 timefunc = timeit.default_timer
992 number = int(getattr(opts, "n", 0))
991 number = int(getattr(opts, "n", 0))
993 default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat
992 default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat
994 repeat = int(getattr(opts, "r", default_repeat))
993 repeat = int(getattr(opts, "r", default_repeat))
995 precision = int(getattr(opts, "p", 3))
994 precision = int(getattr(opts, "p", 3))
996 quiet = 'q' in opts
995 quiet = 'q' in opts
997 return_result = 'o' in opts
996 return_result = 'o' in opts
998 if hasattr(opts, "t"):
997 if hasattr(opts, "t"):
999 timefunc = time.time
998 timefunc = time.time
1000 if hasattr(opts, "c"):
999 if hasattr(opts, "c"):
1001 timefunc = clock
1000 timefunc = clock
1002
1001
1003 timer = Timer(timer=timefunc)
1002 timer = Timer(timer=timefunc)
1004 # this code has tight coupling to the inner workings of timeit.Timer,
1003 # this code has tight coupling to the inner workings of timeit.Timer,
1005 # but is there a better way to achieve that the code stmt has access
1004 # but is there a better way to achieve that the code stmt has access
1006 # to the shell namespace?
1005 # to the shell namespace?
1007 transform = self.shell.input_splitter.transform_cell
1006 transform = self.shell.input_splitter.transform_cell
1008
1007
1009 if cell is None:
1008 if cell is None:
1010 # called as line magic
1009 # called as line magic
1011 ast_setup = self.shell.compile.ast_parse("pass")
1010 ast_setup = self.shell.compile.ast_parse("pass")
1012 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1011 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1013 else:
1012 else:
1014 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1013 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1015 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1014 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1016
1015
1017 ast_setup = self.shell.transform_ast(ast_setup)
1016 ast_setup = self.shell.transform_ast(ast_setup)
1018 ast_stmt = self.shell.transform_ast(ast_stmt)
1017 ast_stmt = self.shell.transform_ast(ast_stmt)
1019
1018
1020 # This codestring is taken from timeit.template - we fill it in as an
1019 # This codestring is taken from timeit.template - we fill it in as an
1021 # AST, so that we can apply our AST transformations to the user code
1020 # AST, so that we can apply our AST transformations to the user code
1022 # without affecting the timing code.
1021 # without affecting the timing code.
1023 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1022 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1024 ' setup\n'
1023 ' setup\n'
1025 ' _t0 = _timer()\n'
1024 ' _t0 = _timer()\n'
1026 ' for _i in _it:\n'
1025 ' for _i in _it:\n'
1027 ' stmt\n'
1026 ' stmt\n'
1028 ' _t1 = _timer()\n'
1027 ' _t1 = _timer()\n'
1029 ' return _t1 - _t0\n')
1028 ' return _t1 - _t0\n')
1030
1029
1031 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1030 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1032 timeit_ast = ast.fix_missing_locations(timeit_ast)
1031 timeit_ast = ast.fix_missing_locations(timeit_ast)
1033
1032
1034 # Track compilation time so it can be reported if too long
1033 # Track compilation time so it can be reported if too long
1035 # Minimum time above which compilation time will be reported
1034 # Minimum time above which compilation time will be reported
1036 tc_min = 0.1
1035 tc_min = 0.1
1037
1036
1038 t0 = clock()
1037 t0 = clock()
1039 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1038 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1040 tc = clock()-t0
1039 tc = clock()-t0
1041
1040
1042 ns = {}
1041 ns = {}
1043 exec(code, self.shell.user_ns, ns)
1042 exec(code, self.shell.user_ns, ns)
1044 timer.inner = ns["inner"]
1043 timer.inner = ns["inner"]
1045
1044
1046 # This is used to check if there is a huge difference between the
1045 # This is used to check if there is a huge difference between the
1047 # best and worst timings.
1046 # best and worst timings.
1048 # Issue: https://github.com/ipython/ipython/issues/6471
1047 # Issue: https://github.com/ipython/ipython/issues/6471
1049 if number == 0:
1048 if number == 0:
1050 # determine number so that 0.2 <= total time < 2.0
1049 # determine number so that 0.2 <= total time < 2.0
1051 for index in range(0, 10):
1050 for index in range(0, 10):
1052 number = 10 ** index
1051 number = 10 ** index
1053 time_number = timer.timeit(number)
1052 time_number = timer.timeit(number)
1054 if time_number >= 0.2:
1053 if time_number >= 0.2:
1055 break
1054 break
1056
1055
1057 all_runs = timer.repeat(repeat, number)
1056 all_runs = timer.repeat(repeat, number)
1058 best = min(all_runs) / number
1057 best = min(all_runs) / number
1059 worst = max(all_runs) / number
1058 worst = max(all_runs) / number
1060 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1059 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1061
1060
1062 if not quiet :
1061 if not quiet :
1063 # Check best timing is greater than zero to avoid a
1062 # Check best timing is greater than zero to avoid a
1064 # ZeroDivisionError.
1063 # ZeroDivisionError.
1065 # In cases where the slowest timing is lesser than a micosecond
1064 # In cases where the slowest timing is lesser than a micosecond
1066 # we assume that it does not really matter if the fastest
1065 # we assume that it does not really matter if the fastest
1067 # timing is 4 times faster than the slowest timing or not.
1066 # timing is 4 times faster than the slowest timing or not.
1068 if worst > 4 * best and best > 0 and worst > 1e-6:
1067 if worst > 4 * best and best > 0 and worst > 1e-6:
1069 print("The slowest run took %0.2f times longer than the "
1068 print("The slowest run took %0.2f times longer than the "
1070 "fastest. This could mean that an intermediate result "
1069 "fastest. This could mean that an intermediate result "
1071 "is being cached." % (worst / best))
1070 "is being cached." % (worst / best))
1072
1071
1073 print( timeit_result )
1072 print( timeit_result )
1074
1073
1075 if tc > tc_min:
1074 if tc > tc_min:
1076 print("Compiler time: %.2f s" % tc)
1075 print("Compiler time: %.2f s" % tc)
1077 if return_result:
1076 if return_result:
1078 return timeit_result
1077 return timeit_result
1079
1078
1080 @skip_doctest
1079 @skip_doctest
1081 @needs_local_scope
1080 @needs_local_scope
1082 @line_cell_magic
1081 @line_cell_magic
1083 def time(self,line='', cell=None, local_ns=None):
1082 def time(self,line='', cell=None, local_ns=None):
1084 """Time execution of a Python statement or expression.
1083 """Time execution of a Python statement or expression.
1085
1084
1086 The CPU and wall clock times are printed, and the value of the
1085 The CPU and wall clock times are printed, and the value of the
1087 expression (if any) is returned. Note that under Win32, system time
1086 expression (if any) is returned. Note that under Win32, system time
1088 is always reported as 0, since it can not be measured.
1087 is always reported as 0, since it can not be measured.
1089
1088
1090 This function can be used both as a line and cell magic:
1089 This function can be used both as a line and cell magic:
1091
1090
1092 - In line mode you can time a single-line statement (though multiple
1091 - In line mode you can time a single-line statement (though multiple
1093 ones can be chained with using semicolons).
1092 ones can be chained with using semicolons).
1094
1093
1095 - In cell mode, you can time the cell body (a directly
1094 - In cell mode, you can time the cell body (a directly
1096 following statement raises an error).
1095 following statement raises an error).
1097
1096
1098 This function provides very basic timing functionality. Use the timeit
1097 This function provides very basic timing functionality. Use the timeit
1099 magic for more control over the measurement.
1098 magic for more control over the measurement.
1100
1099
1101 Examples
1100 Examples
1102 --------
1101 --------
1103 ::
1102 ::
1104
1103
1105 In [1]: %time 2**128
1104 In [1]: %time 2**128
1106 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1105 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1107 Wall time: 0.00
1106 Wall time: 0.00
1108 Out[1]: 340282366920938463463374607431768211456L
1107 Out[1]: 340282366920938463463374607431768211456L
1109
1108
1110 In [2]: n = 1000000
1109 In [2]: n = 1000000
1111
1110
1112 In [3]: %time sum(range(n))
1111 In [3]: %time sum(range(n))
1113 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1112 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1114 Wall time: 1.37
1113 Wall time: 1.37
1115 Out[3]: 499999500000L
1114 Out[3]: 499999500000L
1116
1115
1117 In [4]: %time print 'hello world'
1116 In [4]: %time print 'hello world'
1118 hello world
1117 hello world
1119 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1118 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1120 Wall time: 0.00
1119 Wall time: 0.00
1121
1120
1122 Note that the time needed by Python to compile the given expression
1121 Note that the time needed by Python to compile the given expression
1123 will be reported if it is more than 0.1s. In this example, the
1122 will be reported if it is more than 0.1s. In this example, the
1124 actual exponentiation is done by Python at compilation time, so while
1123 actual exponentiation is done by Python at compilation time, so while
1125 the expression can take a noticeable amount of time to compute, that
1124 the expression can take a noticeable amount of time to compute, that
1126 time is purely due to the compilation:
1125 time is purely due to the compilation:
1127
1126
1128 In [5]: %time 3**9999;
1127 In [5]: %time 3**9999;
1129 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1128 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1130 Wall time: 0.00 s
1129 Wall time: 0.00 s
1131
1130
1132 In [6]: %time 3**999999;
1131 In [6]: %time 3**999999;
1133 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1132 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1134 Wall time: 0.00 s
1133 Wall time: 0.00 s
1135 Compiler : 0.78 s
1134 Compiler : 0.78 s
1136 """
1135 """
1137
1136
1138 # fail immediately if the given expression can't be compiled
1137 # fail immediately if the given expression can't be compiled
1139
1138
1140 if line and cell:
1139 if line and cell:
1141 raise UsageError("Can't use statement directly after '%%time'!")
1140 raise UsageError("Can't use statement directly after '%%time'!")
1142
1141
1143 if cell:
1142 if cell:
1144 expr = self.shell.input_transformer_manager.transform_cell(cell)
1143 expr = self.shell.input_transformer_manager.transform_cell(cell)
1145 else:
1144 else:
1146 expr = self.shell.input_transformer_manager.transform_cell(line)
1145 expr = self.shell.input_transformer_manager.transform_cell(line)
1147
1146
1148 # Minimum time above which parse time will be reported
1147 # Minimum time above which parse time will be reported
1149 tp_min = 0.1
1148 tp_min = 0.1
1150
1149
1151 t0 = clock()
1150 t0 = clock()
1152 expr_ast = self.shell.compile.ast_parse(expr)
1151 expr_ast = self.shell.compile.ast_parse(expr)
1153 tp = clock()-t0
1152 tp = clock()-t0
1154
1153
1155 # Apply AST transformations
1154 # Apply AST transformations
1156 expr_ast = self.shell.transform_ast(expr_ast)
1155 expr_ast = self.shell.transform_ast(expr_ast)
1157
1156
1158 # Minimum time above which compilation time will be reported
1157 # Minimum time above which compilation time will be reported
1159 tc_min = 0.1
1158 tc_min = 0.1
1160
1159
1161 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1160 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1162 mode = 'eval'
1161 mode = 'eval'
1163 source = '<timed eval>'
1162 source = '<timed eval>'
1164 expr_ast = ast.Expression(expr_ast.body[0].value)
1163 expr_ast = ast.Expression(expr_ast.body[0].value)
1165 else:
1164 else:
1166 mode = 'exec'
1165 mode = 'exec'
1167 source = '<timed exec>'
1166 source = '<timed exec>'
1168 t0 = clock()
1167 t0 = clock()
1169 code = self.shell.compile(expr_ast, source, mode)
1168 code = self.shell.compile(expr_ast, source, mode)
1170 tc = clock()-t0
1169 tc = clock()-t0
1171
1170
1172 # skew measurement as little as possible
1171 # skew measurement as little as possible
1173 glob = self.shell.user_ns
1172 glob = self.shell.user_ns
1174 wtime = time.time
1173 wtime = time.time
1175 # time execution
1174 # time execution
1176 wall_st = wtime()
1175 wall_st = wtime()
1177 if mode=='eval':
1176 if mode=='eval':
1178 st = clock2()
1177 st = clock2()
1179 try:
1178 try:
1180 out = eval(code, glob, local_ns)
1179 out = eval(code, glob, local_ns)
1181 except:
1180 except:
1182 self.shell.showtraceback()
1181 self.shell.showtraceback()
1183 return
1182 return
1184 end = clock2()
1183 end = clock2()
1185 else:
1184 else:
1186 st = clock2()
1185 st = clock2()
1187 try:
1186 try:
1188 exec(code, glob, local_ns)
1187 exec(code, glob, local_ns)
1189 except:
1188 except:
1190 self.shell.showtraceback()
1189 self.shell.showtraceback()
1191 return
1190 return
1192 end = clock2()
1191 end = clock2()
1193 out = None
1192 out = None
1194 wall_end = wtime()
1193 wall_end = wtime()
1195 # Compute actual times and report
1194 # Compute actual times and report
1196 wall_time = wall_end-wall_st
1195 wall_time = wall_end-wall_st
1197 cpu_user = end[0]-st[0]
1196 cpu_user = end[0]-st[0]
1198 cpu_sys = end[1]-st[1]
1197 cpu_sys = end[1]-st[1]
1199 cpu_tot = cpu_user+cpu_sys
1198 cpu_tot = cpu_user+cpu_sys
1200 # On windows cpu_sys is always zero, so no new information to the next print
1199 # On windows cpu_sys is always zero, so no new information to the next print
1201 if sys.platform != 'win32':
1200 if sys.platform != 'win32':
1202 print("CPU times: user %s, sys: %s, total: %s" % \
1201 print("CPU times: user %s, sys: %s, total: %s" % \
1203 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1202 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1204 print("Wall time: %s" % _format_time(wall_time))
1203 print("Wall time: %s" % _format_time(wall_time))
1205 if tc > tc_min:
1204 if tc > tc_min:
1206 print("Compiler : %s" % _format_time(tc))
1205 print("Compiler : %s" % _format_time(tc))
1207 if tp > tp_min:
1206 if tp > tp_min:
1208 print("Parser : %s" % _format_time(tp))
1207 print("Parser : %s" % _format_time(tp))
1209 return out
1208 return out
1210
1209
1211 @skip_doctest
1210 @skip_doctest
1212 @line_magic
1211 @line_magic
1213 def macro(self, parameter_s=''):
1212 def macro(self, parameter_s=''):
1214 """Define a macro for future re-execution. It accepts ranges of history,
1213 """Define a macro for future re-execution. It accepts ranges of history,
1215 filenames or string objects.
1214 filenames or string objects.
1216
1215
1217 Usage:\\
1216 Usage:\\
1218 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1217 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1219
1218
1220 Options:
1219 Options:
1221
1220
1222 -r: use 'raw' input. By default, the 'processed' history is used,
1221 -r: use 'raw' input. By default, the 'processed' history is used,
1223 so that magics are loaded in their transformed version to valid
1222 so that magics are loaded in their transformed version to valid
1224 Python. If this option is given, the raw input as typed at the
1223 Python. If this option is given, the raw input as typed at the
1225 command line is used instead.
1224 command line is used instead.
1226
1225
1227 -q: quiet macro definition. By default, a tag line is printed
1226 -q: quiet macro definition. By default, a tag line is printed
1228 to indicate the macro has been created, and then the contents of
1227 to indicate the macro has been created, and then the contents of
1229 the macro are printed. If this option is given, then no printout
1228 the macro are printed. If this option is given, then no printout
1230 is produced once the macro is created.
1229 is produced once the macro is created.
1231
1230
1232 This will define a global variable called `name` which is a string
1231 This will define a global variable called `name` which is a string
1233 made of joining the slices and lines you specify (n1,n2,... numbers
1232 made of joining the slices and lines you specify (n1,n2,... numbers
1234 above) from your input history into a single string. This variable
1233 above) from your input history into a single string. This variable
1235 acts like an automatic function which re-executes those lines as if
1234 acts like an automatic function which re-executes those lines as if
1236 you had typed them. You just type 'name' at the prompt and the code
1235 you had typed them. You just type 'name' at the prompt and the code
1237 executes.
1236 executes.
1238
1237
1239 The syntax for indicating input ranges is described in %history.
1238 The syntax for indicating input ranges is described in %history.
1240
1239
1241 Note: as a 'hidden' feature, you can also use traditional python slice
1240 Note: as a 'hidden' feature, you can also use traditional python slice
1242 notation, where N:M means numbers N through M-1.
1241 notation, where N:M means numbers N through M-1.
1243
1242
1244 For example, if your history contains (print using %hist -n )::
1243 For example, if your history contains (print using %hist -n )::
1245
1244
1246 44: x=1
1245 44: x=1
1247 45: y=3
1246 45: y=3
1248 46: z=x+y
1247 46: z=x+y
1249 47: print x
1248 47: print x
1250 48: a=5
1249 48: a=5
1251 49: print 'x',x,'y',y
1250 49: print 'x',x,'y',y
1252
1251
1253 you can create a macro with lines 44 through 47 (included) and line 49
1252 you can create a macro with lines 44 through 47 (included) and line 49
1254 called my_macro with::
1253 called my_macro with::
1255
1254
1256 In [55]: %macro my_macro 44-47 49
1255 In [55]: %macro my_macro 44-47 49
1257
1256
1258 Now, typing `my_macro` (without quotes) will re-execute all this code
1257 Now, typing `my_macro` (without quotes) will re-execute all this code
1259 in one pass.
1258 in one pass.
1260
1259
1261 You don't need to give the line-numbers in order, and any given line
1260 You don't need to give the line-numbers in order, and any given line
1262 number can appear multiple times. You can assemble macros with any
1261 number can appear multiple times. You can assemble macros with any
1263 lines from your input history in any order.
1262 lines from your input history in any order.
1264
1263
1265 The macro is a simple object which holds its value in an attribute,
1264 The macro is a simple object which holds its value in an attribute,
1266 but IPython's display system checks for macros and executes them as
1265 but IPython's display system checks for macros and executes them as
1267 code instead of printing them when you type their name.
1266 code instead of printing them when you type their name.
1268
1267
1269 You can view a macro's contents by explicitly printing it with::
1268 You can view a macro's contents by explicitly printing it with::
1270
1269
1271 print macro_name
1270 print macro_name
1272
1271
1273 """
1272 """
1274 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1273 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1275 if not args: # List existing macros
1274 if not args: # List existing macros
1276 return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro))
1275 return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro))
1277 if len(args) == 1:
1276 if len(args) == 1:
1278 raise UsageError(
1277 raise UsageError(
1279 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1278 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1280 name, codefrom = args[0], " ".join(args[1:])
1279 name, codefrom = args[0], " ".join(args[1:])
1281
1280
1282 #print 'rng',ranges # dbg
1281 #print 'rng',ranges # dbg
1283 try:
1282 try:
1284 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1283 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1285 except (ValueError, TypeError) as e:
1284 except (ValueError, TypeError) as e:
1286 print(e.args[0])
1285 print(e.args[0])
1287 return
1286 return
1288 macro = Macro(lines)
1287 macro = Macro(lines)
1289 self.shell.define_macro(name, macro)
1288 self.shell.define_macro(name, macro)
1290 if not ( 'q' in opts) :
1289 if not ( 'q' in opts) :
1291 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1290 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1292 print('=== Macro contents: ===')
1291 print('=== Macro contents: ===')
1293 print(macro, end=' ')
1292 print(macro, end=' ')
1294
1293
1295 @magic_arguments.magic_arguments()
1294 @magic_arguments.magic_arguments()
1296 @magic_arguments.argument('output', type=str, default='', nargs='?',
1295 @magic_arguments.argument('output', type=str, default='', nargs='?',
1297 help="""The name of the variable in which to store output.
1296 help="""The name of the variable in which to store output.
1298 This is a utils.io.CapturedIO object with stdout/err attributes
1297 This is a utils.io.CapturedIO object with stdout/err attributes
1299 for the text of the captured output.
1298 for the text of the captured output.
1300
1299
1301 CapturedOutput also has a show() method for displaying the output,
1300 CapturedOutput also has a show() method for displaying the output,
1302 and __call__ as well, so you can use that to quickly display the
1301 and __call__ as well, so you can use that to quickly display the
1303 output.
1302 output.
1304
1303
1305 If unspecified, captured output is discarded.
1304 If unspecified, captured output is discarded.
1306 """
1305 """
1307 )
1306 )
1308 @magic_arguments.argument('--no-stderr', action="store_true",
1307 @magic_arguments.argument('--no-stderr', action="store_true",
1309 help="""Don't capture stderr."""
1308 help="""Don't capture stderr."""
1310 )
1309 )
1311 @magic_arguments.argument('--no-stdout', action="store_true",
1310 @magic_arguments.argument('--no-stdout', action="store_true",
1312 help="""Don't capture stdout."""
1311 help="""Don't capture stdout."""
1313 )
1312 )
1314 @magic_arguments.argument('--no-display', action="store_true",
1313 @magic_arguments.argument('--no-display', action="store_true",
1315 help="""Don't capture IPython's rich display."""
1314 help="""Don't capture IPython's rich display."""
1316 )
1315 )
1317 @cell_magic
1316 @cell_magic
1318 def capture(self, line, cell):
1317 def capture(self, line, cell):
1319 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1318 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1320 args = magic_arguments.parse_argstring(self.capture, line)
1319 args = magic_arguments.parse_argstring(self.capture, line)
1321 out = not args.no_stdout
1320 out = not args.no_stdout
1322 err = not args.no_stderr
1321 err = not args.no_stderr
1323 disp = not args.no_display
1322 disp = not args.no_display
1324 with capture_output(out, err, disp) as io:
1323 with capture_output(out, err, disp) as io:
1325 self.shell.run_cell(cell)
1324 self.shell.run_cell(cell)
1326 if args.output:
1325 if args.output:
1327 self.shell.user_ns[args.output] = io
1326 self.shell.user_ns[args.output] = io
1328
1327
1329 def parse_breakpoint(text, current_file):
1328 def parse_breakpoint(text, current_file):
1330 '''Returns (file, line) for file:line and (current_file, line) for line'''
1329 '''Returns (file, line) for file:line and (current_file, line) for line'''
1331 colon = text.find(':')
1330 colon = text.find(':')
1332 if colon == -1:
1331 if colon == -1:
1333 return current_file, int(text)
1332 return current_file, int(text)
1334 else:
1333 else:
1335 return text[:colon], int(text[colon+1:])
1334 return text[:colon], int(text[colon+1:])
1336
1335
1337 def _format_time(timespan, precision=3):
1336 def _format_time(timespan, precision=3):
1338 """Formats the timespan in a human readable form"""
1337 """Formats the timespan in a human readable form"""
1339
1338
1340 if timespan >= 60.0:
1339 if timespan >= 60.0:
1341 # we have more than a minute, format that in a human readable form
1340 # we have more than a minute, format that in a human readable form
1342 # Idea from http://snipplr.com/view/5713/
1341 # Idea from http://snipplr.com/view/5713/
1343 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1342 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1344 time = []
1343 time = []
1345 leftover = timespan
1344 leftover = timespan
1346 for suffix, length in parts:
1345 for suffix, length in parts:
1347 value = int(leftover / length)
1346 value = int(leftover / length)
1348 if value > 0:
1347 if value > 0:
1349 leftover = leftover % length
1348 leftover = leftover % length
1350 time.append(u'%s%s' % (str(value), suffix))
1349 time.append(u'%s%s' % (str(value), suffix))
1351 if leftover < 1:
1350 if leftover < 1:
1352 break
1351 break
1353 return " ".join(time)
1352 return " ".join(time)
1354
1353
1355
1354
1356 # Unfortunately the unicode 'micro' symbol can cause problems in
1355 # Unfortunately the unicode 'micro' symbol can cause problems in
1357 # certain terminals.
1356 # certain terminals.
1358 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1357 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1359 # Try to prevent crashes by being more secure than it needs to
1358 # Try to prevent crashes by being more secure than it needs to
1360 # E.g. eclipse is able to print a Β΅, but has no sys.stdout.encoding set.
1359 # E.g. eclipse is able to print a Β΅, but has no sys.stdout.encoding set.
1361 units = [u"s", u"ms",u'us',"ns"] # the save value
1360 units = [u"s", u"ms",u'us',"ns"] # the save value
1362 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1361 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1363 try:
1362 try:
1364 u'\xb5'.encode(sys.stdout.encoding)
1363 u'\xb5'.encode(sys.stdout.encoding)
1365 units = [u"s", u"ms",u'\xb5s',"ns"]
1364 units = [u"s", u"ms",u'\xb5s',"ns"]
1366 except:
1365 except:
1367 pass
1366 pass
1368 scaling = [1, 1e3, 1e6, 1e9]
1367 scaling = [1, 1e3, 1e6, 1e9]
1369
1368
1370 if timespan > 0.0:
1369 if timespan > 0.0:
1371 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1370 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1372 else:
1371 else:
1373 order = 3
1372 order = 3
1374 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
1373 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
@@ -1,343 +1,339 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Provides a reload() function that acts recursively.
3 Provides a reload() function that acts recursively.
4
4
5 Python's normal :func:`python:reload` function only reloads the module that it's
5 Python's normal :func:`python:reload` function only reloads the module that it's
6 passed. The :func:`reload` function in this module also reloads everything
6 passed. The :func:`reload` function in this module also reloads everything
7 imported from that module, which is useful when you're changing files deep
7 imported from that module, which is useful when you're changing files deep
8 inside a package.
8 inside a package.
9
9
10 To use this as your default reload function, type this for Python 2::
10 To use this as your default reload function, type this for Python 2::
11
11
12 import __builtin__
12 import __builtin__
13 from IPython.lib import deepreload
13 from IPython.lib import deepreload
14 __builtin__.reload = deepreload.reload
14 __builtin__.reload = deepreload.reload
15
15
16 Or this for Python 3::
16 Or this for Python 3::
17
17
18 import builtins
18 import builtins
19 from IPython.lib import deepreload
19 from IPython.lib import deepreload
20 builtins.reload = deepreload.reload
20 builtins.reload = deepreload.reload
21
21
22 A reference to the original :func:`python:reload` is stored in this module as
22 A reference to the original :func:`python:reload` is stored in this module as
23 :data:`original_reload`, so you can restore it later.
23 :data:`original_reload`, so you can restore it later.
24
24
25 This code is almost entirely based on knee.py, which is a Python
25 This code is almost entirely based on knee.py, which is a Python
26 re-implementation of hierarchical module import.
26 re-implementation of hierarchical module import.
27 """
27 """
28 #*****************************************************************************
28 #*****************************************************************************
29 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
29 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
30 #
30 #
31 # Distributed under the terms of the BSD License. The full license is in
31 # Distributed under the terms of the BSD License. The full license is in
32 # the file COPYING, distributed as part of this software.
32 # the file COPYING, distributed as part of this software.
33 #*****************************************************************************
33 #*****************************************************************************
34
34
35 import builtins as builtin_mod
35 from contextlib import contextmanager
36 from contextlib import contextmanager
36 import imp
37 import imp
37 import sys
38 import sys
38
39
39 from types import ModuleType
40 from types import ModuleType
40 from warnings import warn
41 from warnings import warn
41
42
42 from IPython.utils.py3compat import builtin_mod, builtin_mod_name
43
44 original_import = builtin_mod.__import__
43 original_import = builtin_mod.__import__
45
44
46 @contextmanager
45 @contextmanager
47 def replace_import_hook(new_import):
46 def replace_import_hook(new_import):
48 saved_import = builtin_mod.__import__
47 saved_import = builtin_mod.__import__
49 builtin_mod.__import__ = new_import
48 builtin_mod.__import__ = new_import
50 try:
49 try:
51 yield
50 yield
52 finally:
51 finally:
53 builtin_mod.__import__ = saved_import
52 builtin_mod.__import__ = saved_import
54
53
55 def get_parent(globals, level):
54 def get_parent(globals, level):
56 """
55 """
57 parent, name = get_parent(globals, level)
56 parent, name = get_parent(globals, level)
58
57
59 Return the package that an import is being performed in. If globals comes
58 Return the package that an import is being performed in. If globals comes
60 from the module foo.bar.bat (not itself a package), this returns the
59 from the module foo.bar.bat (not itself a package), this returns the
61 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
60 sys.modules entry for foo.bar. If globals is from a package's __init__.py,
62 the package's entry in sys.modules is returned.
61 the package's entry in sys.modules is returned.
63
62
64 If globals doesn't come from a package or a module in a package, or a
63 If globals doesn't come from a package or a module in a package, or a
65 corresponding entry is not found in sys.modules, None is returned.
64 corresponding entry is not found in sys.modules, None is returned.
66 """
65 """
67 orig_level = level
66 orig_level = level
68
67
69 if not level or not isinstance(globals, dict):
68 if not level or not isinstance(globals, dict):
70 return None, ''
69 return None, ''
71
70
72 pkgname = globals.get('__package__', None)
71 pkgname = globals.get('__package__', None)
73
72
74 if pkgname is not None:
73 if pkgname is not None:
75 # __package__ is set, so use it
74 # __package__ is set, so use it
76 if not hasattr(pkgname, 'rindex'):
75 if not hasattr(pkgname, 'rindex'):
77 raise ValueError('__package__ set to non-string')
76 raise ValueError('__package__ set to non-string')
78 if len(pkgname) == 0:
77 if len(pkgname) == 0:
79 if level > 0:
78 if level > 0:
80 raise ValueError('Attempted relative import in non-package')
79 raise ValueError('Attempted relative import in non-package')
81 return None, ''
80 return None, ''
82 name = pkgname
81 name = pkgname
83 else:
82 else:
84 # __package__ not set, so figure it out and set it
83 # __package__ not set, so figure it out and set it
85 if '__name__' not in globals:
84 if '__name__' not in globals:
86 return None, ''
85 return None, ''
87 modname = globals['__name__']
86 modname = globals['__name__']
88
87
89 if '__path__' in globals:
88 if '__path__' in globals:
90 # __path__ is set, so modname is already the package name
89 # __path__ is set, so modname is already the package name
91 globals['__package__'] = name = modname
90 globals['__package__'] = name = modname
92 else:
91 else:
93 # Normal module, so work out the package name if any
92 # Normal module, so work out the package name if any
94 lastdot = modname.rfind('.')
93 lastdot = modname.rfind('.')
95 if lastdot < 0 < level:
94 if lastdot < 0 < level:
96 raise ValueError("Attempted relative import in non-package")
95 raise ValueError("Attempted relative import in non-package")
97 if lastdot < 0:
96 if lastdot < 0:
98 globals['__package__'] = None
97 globals['__package__'] = None
99 return None, ''
98 return None, ''
100 globals['__package__'] = name = modname[:lastdot]
99 globals['__package__'] = name = modname[:lastdot]
101
100
102 dot = len(name)
101 dot = len(name)
103 for x in range(level, 1, -1):
102 for x in range(level, 1, -1):
104 try:
103 try:
105 dot = name.rindex('.', 0, dot)
104 dot = name.rindex('.', 0, dot)
106 except ValueError:
105 except ValueError:
107 raise ValueError("attempted relative import beyond top-level "
106 raise ValueError("attempted relative import beyond top-level "
108 "package")
107 "package")
109 name = name[:dot]
108 name = name[:dot]
110
109
111 try:
110 try:
112 parent = sys.modules[name]
111 parent = sys.modules[name]
113 except:
112 except:
114 if orig_level < 1:
113 if orig_level < 1:
115 warn("Parent module '%.200s' not found while handling absolute "
114 warn("Parent module '%.200s' not found while handling absolute "
116 "import" % name)
115 "import" % name)
117 parent = None
116 parent = None
118 else:
117 else:
119 raise SystemError("Parent module '%.200s' not loaded, cannot "
118 raise SystemError("Parent module '%.200s' not loaded, cannot "
120 "perform relative import" % name)
119 "perform relative import" % name)
121
120
122 # We expect, but can't guarantee, if parent != None, that:
121 # We expect, but can't guarantee, if parent != None, that:
123 # - parent.__name__ == name
122 # - parent.__name__ == name
124 # - parent.__dict__ is globals
123 # - parent.__dict__ is globals
125 # If this is violated... Who cares?
124 # If this is violated... Who cares?
126 return parent, name
125 return parent, name
127
126
128 def load_next(mod, altmod, name, buf):
127 def load_next(mod, altmod, name, buf):
129 """
128 """
130 mod, name, buf = load_next(mod, altmod, name, buf)
129 mod, name, buf = load_next(mod, altmod, name, buf)
131
130
132 altmod is either None or same as mod
131 altmod is either None or same as mod
133 """
132 """
134
133
135 if len(name) == 0:
134 if len(name) == 0:
136 # completely empty module name should only happen in
135 # completely empty module name should only happen in
137 # 'from . import' (or '__import__("")')
136 # 'from . import' (or '__import__("")')
138 return mod, None, buf
137 return mod, None, buf
139
138
140 dot = name.find('.')
139 dot = name.find('.')
141 if dot == 0:
140 if dot == 0:
142 raise ValueError('Empty module name')
141 raise ValueError('Empty module name')
143
142
144 if dot < 0:
143 if dot < 0:
145 subname = name
144 subname = name
146 next = None
145 next = None
147 else:
146 else:
148 subname = name[:dot]
147 subname = name[:dot]
149 next = name[dot+1:]
148 next = name[dot+1:]
150
149
151 if buf != '':
150 if buf != '':
152 buf += '.'
151 buf += '.'
153 buf += subname
152 buf += subname
154
153
155 result = import_submodule(mod, subname, buf)
154 result = import_submodule(mod, subname, buf)
156 if result is None and mod != altmod:
155 if result is None and mod != altmod:
157 result = import_submodule(altmod, subname, subname)
156 result = import_submodule(altmod, subname, subname)
158 if result is not None:
157 if result is not None:
159 buf = subname
158 buf = subname
160
159
161 if result is None:
160 if result is None:
162 raise ImportError("No module named %.200s" % name)
161 raise ImportError("No module named %.200s" % name)
163
162
164 return result, next, buf
163 return result, next, buf
165
164
166 # Need to keep track of what we've already reloaded to prevent cyclic evil
165 # Need to keep track of what we've already reloaded to prevent cyclic evil
167 found_now = {}
166 found_now = {}
168
167
169 def import_submodule(mod, subname, fullname):
168 def import_submodule(mod, subname, fullname):
170 """m = import_submodule(mod, subname, fullname)"""
169 """m = import_submodule(mod, subname, fullname)"""
171 # Require:
170 # Require:
172 # if mod == None: subname == fullname
171 # if mod == None: subname == fullname
173 # else: mod.__name__ + "." + subname == fullname
172 # else: mod.__name__ + "." + subname == fullname
174
173
175 global found_now
174 global found_now
176 if fullname in found_now and fullname in sys.modules:
175 if fullname in found_now and fullname in sys.modules:
177 m = sys.modules[fullname]
176 m = sys.modules[fullname]
178 else:
177 else:
179 print('Reloading', fullname)
178 print('Reloading', fullname)
180 found_now[fullname] = 1
179 found_now[fullname] = 1
181 oldm = sys.modules.get(fullname, None)
180 oldm = sys.modules.get(fullname, None)
182
181
183 if mod is None:
182 if mod is None:
184 path = None
183 path = None
185 elif hasattr(mod, '__path__'):
184 elif hasattr(mod, '__path__'):
186 path = mod.__path__
185 path = mod.__path__
187 else:
186 else:
188 return None
187 return None
189
188
190 try:
189 try:
191 # This appears to be necessary on Python 3, because imp.find_module()
190 # This appears to be necessary on Python 3, because imp.find_module()
192 # tries to import standard libraries (like io) itself, and we don't
191 # tries to import standard libraries (like io) itself, and we don't
193 # want them to be processed by our deep_import_hook.
192 # want them to be processed by our deep_import_hook.
194 with replace_import_hook(original_import):
193 with replace_import_hook(original_import):
195 fp, filename, stuff = imp.find_module(subname, path)
194 fp, filename, stuff = imp.find_module(subname, path)
196 except ImportError:
195 except ImportError:
197 return None
196 return None
198
197
199 try:
198 try:
200 m = imp.load_module(fullname, fp, filename, stuff)
199 m = imp.load_module(fullname, fp, filename, stuff)
201 except:
200 except:
202 # load_module probably removed name from modules because of
201 # load_module probably removed name from modules because of
203 # the error. Put back the original module object.
202 # the error. Put back the original module object.
204 if oldm:
203 if oldm:
205 sys.modules[fullname] = oldm
204 sys.modules[fullname] = oldm
206 raise
205 raise
207 finally:
206 finally:
208 if fp: fp.close()
207 if fp: fp.close()
209
208
210 add_submodule(mod, m, fullname, subname)
209 add_submodule(mod, m, fullname, subname)
211
210
212 return m
211 return m
213
212
214 def add_submodule(mod, submod, fullname, subname):
213 def add_submodule(mod, submod, fullname, subname):
215 """mod.{subname} = submod"""
214 """mod.{subname} = submod"""
216 if mod is None:
215 if mod is None:
217 return #Nothing to do here.
216 return #Nothing to do here.
218
217
219 if submod is None:
218 if submod is None:
220 submod = sys.modules[fullname]
219 submod = sys.modules[fullname]
221
220
222 setattr(mod, subname, submod)
221 setattr(mod, subname, submod)
223
222
224 return
223 return
225
224
226 def ensure_fromlist(mod, fromlist, buf, recursive):
225 def ensure_fromlist(mod, fromlist, buf, recursive):
227 """Handle 'from module import a, b, c' imports."""
226 """Handle 'from module import a, b, c' imports."""
228 if not hasattr(mod, '__path__'):
227 if not hasattr(mod, '__path__'):
229 return
228 return
230 for item in fromlist:
229 for item in fromlist:
231 if not hasattr(item, 'rindex'):
230 if not hasattr(item, 'rindex'):
232 raise TypeError("Item in ``from list'' not a string")
231 raise TypeError("Item in ``from list'' not a string")
233 if item == '*':
232 if item == '*':
234 if recursive:
233 if recursive:
235 continue # avoid endless recursion
234 continue # avoid endless recursion
236 try:
235 try:
237 all = mod.__all__
236 all = mod.__all__
238 except AttributeError:
237 except AttributeError:
239 pass
238 pass
240 else:
239 else:
241 ret = ensure_fromlist(mod, all, buf, 1)
240 ret = ensure_fromlist(mod, all, buf, 1)
242 if not ret:
241 if not ret:
243 return 0
242 return 0
244 elif not hasattr(mod, item):
243 elif not hasattr(mod, item):
245 import_submodule(mod, item, buf + '.' + item)
244 import_submodule(mod, item, buf + '.' + item)
246
245
247 def deep_import_hook(name, globals=None, locals=None, fromlist=None, level=-1):
246 def deep_import_hook(name, globals=None, locals=None, fromlist=None, level=-1):
248 """Replacement for __import__()"""
247 """Replacement for __import__()"""
249 parent, buf = get_parent(globals, level)
248 parent, buf = get_parent(globals, level)
250
249
251 head, name, buf = load_next(parent, None if level < 0 else parent, name, buf)
250 head, name, buf = load_next(parent, None if level < 0 else parent, name, buf)
252
251
253 tail = head
252 tail = head
254 while name:
253 while name:
255 tail, name, buf = load_next(tail, tail, name, buf)
254 tail, name, buf = load_next(tail, tail, name, buf)
256
255
257 # If tail is None, both get_parent and load_next found
256 # If tail is None, both get_parent and load_next found
258 # an empty module name: someone called __import__("") or
257 # an empty module name: someone called __import__("") or
259 # doctored faulty bytecode
258 # doctored faulty bytecode
260 if tail is None:
259 if tail is None:
261 raise ValueError('Empty module name')
260 raise ValueError('Empty module name')
262
261
263 if not fromlist:
262 if not fromlist:
264 return head
263 return head
265
264
266 ensure_fromlist(tail, fromlist, buf, 0)
265 ensure_fromlist(tail, fromlist, buf, 0)
267 return tail
266 return tail
268
267
269 modules_reloading = {}
268 modules_reloading = {}
270
269
271 def deep_reload_hook(m):
270 def deep_reload_hook(m):
272 """Replacement for reload()."""
271 """Replacement for reload()."""
273 if not isinstance(m, ModuleType):
272 if not isinstance(m, ModuleType):
274 raise TypeError("reload() argument must be module")
273 raise TypeError("reload() argument must be module")
275
274
276 name = m.__name__
275 name = m.__name__
277
276
278 if name not in sys.modules:
277 if name not in sys.modules:
279 raise ImportError("reload(): module %.200s not in sys.modules" % name)
278 raise ImportError("reload(): module %.200s not in sys.modules" % name)
280
279
281 global modules_reloading
280 global modules_reloading
282 try:
281 try:
283 return modules_reloading[name]
282 return modules_reloading[name]
284 except:
283 except:
285 modules_reloading[name] = m
284 modules_reloading[name] = m
286
285
287 dot = name.rfind('.')
286 dot = name.rfind('.')
288 if dot < 0:
287 if dot < 0:
289 subname = name
288 subname = name
290 path = None
289 path = None
291 else:
290 else:
292 try:
291 try:
293 parent = sys.modules[name[:dot]]
292 parent = sys.modules[name[:dot]]
294 except KeyError:
293 except KeyError:
295 modules_reloading.clear()
294 modules_reloading.clear()
296 raise ImportError("reload(): parent %.200s not in sys.modules" % name[:dot])
295 raise ImportError("reload(): parent %.200s not in sys.modules" % name[:dot])
297 subname = name[dot+1:]
296 subname = name[dot+1:]
298 path = getattr(parent, "__path__", None)
297 path = getattr(parent, "__path__", None)
299
298
300 try:
299 try:
301 # This appears to be necessary on Python 3, because imp.find_module()
300 # This appears to be necessary on Python 3, because imp.find_module()
302 # tries to import standard libraries (like io) itself, and we don't
301 # tries to import standard libraries (like io) itself, and we don't
303 # want them to be processed by our deep_import_hook.
302 # want them to be processed by our deep_import_hook.
304 with replace_import_hook(original_import):
303 with replace_import_hook(original_import):
305 fp, filename, stuff = imp.find_module(subname, path)
304 fp, filename, stuff = imp.find_module(subname, path)
306 finally:
305 finally:
307 modules_reloading.clear()
306 modules_reloading.clear()
308
307
309 try:
308 try:
310 newm = imp.load_module(name, fp, filename, stuff)
309 newm = imp.load_module(name, fp, filename, stuff)
311 except:
310 except:
312 # load_module probably removed name from modules because of
311 # load_module probably removed name from modules because of
313 # the error. Put back the original module object.
312 # the error. Put back the original module object.
314 sys.modules[name] = m
313 sys.modules[name] = m
315 raise
314 raise
316 finally:
315 finally:
317 if fp: fp.close()
316 if fp: fp.close()
318
317
319 modules_reloading.clear()
318 modules_reloading.clear()
320 return newm
319 return newm
321
320
322 # Save the original hooks
321 # Save the original hooks
323 try:
322 original_reload = imp.reload # Python 3
324 original_reload = builtin_mod.reload
325 except AttributeError:
326 original_reload = imp.reload # Python 3
327
323
328 # Replacement for reload()
324 # Replacement for reload()
329 def reload(module, exclude=('sys', 'os.path', builtin_mod_name, '__main__',
325 def reload(module, exclude=('sys', 'os.path', 'builtins', '__main__',
330 'numpy', 'numpy._globals')):
326 'numpy', 'numpy._globals')):
331 """Recursively reload all modules used in the given module. Optionally
327 """Recursively reload all modules used in the given module. Optionally
332 takes a list of modules to exclude from reloading. The default exclude
328 takes a list of modules to exclude from reloading. The default exclude
333 list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
329 list contains sys, __main__, and __builtin__, to prevent, e.g., resetting
334 display, exception, and io hooks.
330 display, exception, and io hooks.
335 """
331 """
336 global found_now
332 global found_now
337 for i in exclude:
333 for i in exclude:
338 found_now[i] = 1
334 found_now[i] = 1
339 try:
335 try:
340 with replace_import_hook(deep_import_hook):
336 with replace_import_hook(deep_import_hook):
341 return deep_reload_hook(module)
337 return deep_reload_hook(module)
342 finally:
338 finally:
343 found_now = {}
339 found_now = {}
@@ -1,136 +1,136 b''
1 """Global IPython app to support test running.
1 """Global IPython app to support test running.
2
2
3 We must start our own ipython object and heavily muck with it so that all the
3 We must start our own ipython object and heavily muck with it so that all the
4 modifications IPython makes to system behavior don't send the doctest machinery
4 modifications IPython makes to system behavior don't send the doctest machinery
5 into a fit. This code should be considered a gross hack, but it gets the job
5 into a fit. This code should be considered a gross hack, but it gets the job
6 done.
6 done.
7 """
7 """
8
8
9 # Copyright (c) IPython Development Team.
9 # Copyright (c) IPython Development Team.
10 # Distributed under the terms of the Modified BSD License.
10 # Distributed under the terms of the Modified BSD License.
11
11
12 import builtins as builtin_mod
12 import sys
13 import sys
13 import warnings
14 import warnings
14
15
15 from . import tools
16 from . import tools
16
17
17 from IPython.core import page
18 from IPython.core import page
18 from IPython.utils import io
19 from IPython.utils import io
19 from IPython.utils import py3compat
20 from IPython.utils import py3compat
20 from IPython.utils.py3compat import builtin_mod
21 from IPython.terminal.interactiveshell import TerminalInteractiveShell
21 from IPython.terminal.interactiveshell import TerminalInteractiveShell
22
22
23
23
24 class StreamProxy(io.IOStream):
24 class StreamProxy(io.IOStream):
25 """Proxy for sys.stdout/err. This will request the stream *at call time*
25 """Proxy for sys.stdout/err. This will request the stream *at call time*
26 allowing for nose's Capture plugin's redirection of sys.stdout/err.
26 allowing for nose's Capture plugin's redirection of sys.stdout/err.
27
27
28 Parameters
28 Parameters
29 ----------
29 ----------
30 name : str
30 name : str
31 The name of the stream. This will be requested anew at every call
31 The name of the stream. This will be requested anew at every call
32 """
32 """
33
33
34 def __init__(self, name):
34 def __init__(self, name):
35 warnings.warn("StreamProxy is deprecated and unused as of IPython 5", DeprecationWarning,
35 warnings.warn("StreamProxy is deprecated and unused as of IPython 5", DeprecationWarning,
36 stacklevel=2,
36 stacklevel=2,
37 )
37 )
38 self.name=name
38 self.name=name
39
39
40 @property
40 @property
41 def stream(self):
41 def stream(self):
42 return getattr(sys, self.name)
42 return getattr(sys, self.name)
43
43
44 def flush(self):
44 def flush(self):
45 self.stream.flush()
45 self.stream.flush()
46
46
47
47
48 def get_ipython():
48 def get_ipython():
49 # This will get replaced by the real thing once we start IPython below
49 # This will get replaced by the real thing once we start IPython below
50 return start_ipython()
50 return start_ipython()
51
51
52
52
53 # A couple of methods to override those in the running IPython to interact
53 # A couple of methods to override those in the running IPython to interact
54 # better with doctest (doctest captures on raw stdout, so we need to direct
54 # better with doctest (doctest captures on raw stdout, so we need to direct
55 # various types of output there otherwise it will miss them).
55 # various types of output there otherwise it will miss them).
56
56
57 def xsys(self, cmd):
57 def xsys(self, cmd):
58 """Replace the default system call with a capturing one for doctest.
58 """Replace the default system call with a capturing one for doctest.
59 """
59 """
60 # We use getoutput, but we need to strip it because pexpect captures
60 # We use getoutput, but we need to strip it because pexpect captures
61 # the trailing newline differently from commands.getoutput
61 # the trailing newline differently from commands.getoutput
62 print(self.getoutput(cmd, split=False, depth=1).rstrip(), end='', file=sys.stdout)
62 print(self.getoutput(cmd, split=False, depth=1).rstrip(), end='', file=sys.stdout)
63 sys.stdout.flush()
63 sys.stdout.flush()
64
64
65
65
66 def _showtraceback(self, etype, evalue, stb):
66 def _showtraceback(self, etype, evalue, stb):
67 """Print the traceback purely on stdout for doctest to capture it.
67 """Print the traceback purely on stdout for doctest to capture it.
68 """
68 """
69 print(self.InteractiveTB.stb2text(stb), file=sys.stdout)
69 print(self.InteractiveTB.stb2text(stb), file=sys.stdout)
70
70
71
71
72 def start_ipython():
72 def start_ipython():
73 """Start a global IPython shell, which we need for IPython-specific syntax.
73 """Start a global IPython shell, which we need for IPython-specific syntax.
74 """
74 """
75 global get_ipython
75 global get_ipython
76
76
77 # This function should only ever run once!
77 # This function should only ever run once!
78 if hasattr(start_ipython, 'already_called'):
78 if hasattr(start_ipython, 'already_called'):
79 return
79 return
80 start_ipython.already_called = True
80 start_ipython.already_called = True
81
81
82 # Store certain global objects that IPython modifies
82 # Store certain global objects that IPython modifies
83 _displayhook = sys.displayhook
83 _displayhook = sys.displayhook
84 _excepthook = sys.excepthook
84 _excepthook = sys.excepthook
85 _main = sys.modules.get('__main__')
85 _main = sys.modules.get('__main__')
86
86
87 # Create custom argv and namespaces for our IPython to be test-friendly
87 # Create custom argv and namespaces for our IPython to be test-friendly
88 config = tools.default_config()
88 config = tools.default_config()
89 config.TerminalInteractiveShell.simple_prompt = True
89 config.TerminalInteractiveShell.simple_prompt = True
90
90
91 # Create and initialize our test-friendly IPython instance.
91 # Create and initialize our test-friendly IPython instance.
92 shell = TerminalInteractiveShell.instance(config=config,
92 shell = TerminalInteractiveShell.instance(config=config,
93 )
93 )
94
94
95 # A few more tweaks needed for playing nicely with doctests...
95 # A few more tweaks needed for playing nicely with doctests...
96
96
97 # remove history file
97 # remove history file
98 shell.tempfiles.append(config.HistoryManager.hist_file)
98 shell.tempfiles.append(config.HistoryManager.hist_file)
99
99
100 # These traps are normally only active for interactive use, set them
100 # These traps are normally only active for interactive use, set them
101 # permanently since we'll be mocking interactive sessions.
101 # permanently since we'll be mocking interactive sessions.
102 shell.builtin_trap.activate()
102 shell.builtin_trap.activate()
103
103
104 # Modify the IPython system call with one that uses getoutput, so that we
104 # Modify the IPython system call with one that uses getoutput, so that we
105 # can capture subcommands and print them to Python's stdout, otherwise the
105 # can capture subcommands and print them to Python's stdout, otherwise the
106 # doctest machinery would miss them.
106 # doctest machinery would miss them.
107 shell.system = py3compat.MethodType(xsys, shell)
107 shell.system = py3compat.MethodType(xsys, shell)
108
108
109 shell._showtraceback = py3compat.MethodType(_showtraceback, shell)
109 shell._showtraceback = py3compat.MethodType(_showtraceback, shell)
110
110
111 # IPython is ready, now clean up some global state...
111 # IPython is ready, now clean up some global state...
112
112
113 # Deactivate the various python system hooks added by ipython for
113 # Deactivate the various python system hooks added by ipython for
114 # interactive convenience so we don't confuse the doctest system
114 # interactive convenience so we don't confuse the doctest system
115 sys.modules['__main__'] = _main
115 sys.modules['__main__'] = _main
116 sys.displayhook = _displayhook
116 sys.displayhook = _displayhook
117 sys.excepthook = _excepthook
117 sys.excepthook = _excepthook
118
118
119 # So that ipython magics and aliases can be doctested (they work by making
119 # So that ipython magics and aliases can be doctested (they work by making
120 # a call into a global _ip object). Also make the top-level get_ipython
120 # a call into a global _ip object). Also make the top-level get_ipython
121 # now return this without recursively calling here again.
121 # now return this without recursively calling here again.
122 _ip = shell
122 _ip = shell
123 get_ipython = _ip.get_ipython
123 get_ipython = _ip.get_ipython
124 builtin_mod._ip = _ip
124 builtin_mod._ip = _ip
125 builtin_mod.get_ipython = get_ipython
125 builtin_mod.get_ipython = get_ipython
126
126
127 # Override paging, so we don't require user interaction during the tests.
127 # Override paging, so we don't require user interaction during the tests.
128 def nopage(strng, start=0, screen_lines=0, pager_cmd=None):
128 def nopage(strng, start=0, screen_lines=0, pager_cmd=None):
129 if isinstance(strng, dict):
129 if isinstance(strng, dict):
130 strng = strng.get('text/plain', '')
130 strng = strng.get('text/plain', '')
131 print(strng)
131 print(strng)
132
132
133 page.orig_page = page.pager_page
133 page.orig_page = page.pager_page
134 page.pager_page = nopage
134 page.pager_page = nopage
135
135
136 return _ip
136 return _ip
@@ -1,766 +1,764 b''
1 """Nose Plugin that supports IPython doctests.
1 """Nose Plugin that supports IPython doctests.
2
2
3 Limitations:
3 Limitations:
4
4
5 - When generating examples for use as doctests, make sure that you have
5 - When generating examples for use as doctests, make sure that you have
6 pretty-printing OFF. This can be done either by setting the
6 pretty-printing OFF. This can be done either by setting the
7 ``PlainTextFormatter.pprint`` option in your configuration file to False, or
7 ``PlainTextFormatter.pprint`` option in your configuration file to False, or
8 by interactively disabling it with %Pprint. This is required so that IPython
8 by interactively disabling it with %Pprint. This is required so that IPython
9 output matches that of normal Python, which is used by doctest for internal
9 output matches that of normal Python, which is used by doctest for internal
10 execution.
10 execution.
11
11
12 - Do not rely on specific prompt numbers for results (such as using
12 - Do not rely on specific prompt numbers for results (such as using
13 '_34==True', for example). For IPython tests run via an external process the
13 '_34==True', for example). For IPython tests run via an external process the
14 prompt numbers may be different, and IPython tests run as normal python code
14 prompt numbers may be different, and IPython tests run as normal python code
15 won't even have these special _NN variables set at all.
15 won't even have these special _NN variables set at all.
16 """
16 """
17
17
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19 # Module imports
19 # Module imports
20
20
21 # From the standard library
21 # From the standard library
22 import builtins as builtin_mod
22 import doctest
23 import doctest
23 import inspect
24 import inspect
24 import logging
25 import logging
25 import os
26 import os
26 import re
27 import re
27 import sys
28 import sys
28 from importlib import import_module
29 from importlib import import_module
29 from io import StringIO
30 from io import StringIO
30
31
31 from testpath import modified_env
32 from testpath import modified_env
32
33
33 from inspect import getmodule
34 from inspect import getmodule
34
35
35 # We are overriding the default doctest runner, so we need to import a few
36 # We are overriding the default doctest runner, so we need to import a few
36 # things from doctest directly
37 # things from doctest directly
37 from doctest import (REPORTING_FLAGS, REPORT_ONLY_FIRST_FAILURE,
38 from doctest import (REPORTING_FLAGS, REPORT_ONLY_FIRST_FAILURE,
38 _unittest_reportflags, DocTestRunner,
39 _unittest_reportflags, DocTestRunner,
39 _extract_future_flags, pdb, _OutputRedirectingPdb,
40 _extract_future_flags, pdb, _OutputRedirectingPdb,
40 _exception_traceback,
41 _exception_traceback,
41 linecache)
42 linecache)
42
43
43 # Third-party modules
44 # Third-party modules
44
45
45 from nose.plugins import doctests, Plugin
46 from nose.plugins import doctests, Plugin
46 from nose.util import anyp, tolist
47 from nose.util import anyp, tolist
47
48
48 # Our own imports
49 from IPython.utils.py3compat import builtin_mod
50
51 #-----------------------------------------------------------------------------
49 #-----------------------------------------------------------------------------
52 # Module globals and other constants
50 # Module globals and other constants
53 #-----------------------------------------------------------------------------
51 #-----------------------------------------------------------------------------
54
52
55 log = logging.getLogger(__name__)
53 log = logging.getLogger(__name__)
56
54
57
55
58 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
59 # Classes and functions
57 # Classes and functions
60 #-----------------------------------------------------------------------------
58 #-----------------------------------------------------------------------------
61
59
62 def is_extension_module(filename):
60 def is_extension_module(filename):
63 """Return whether the given filename is an extension module.
61 """Return whether the given filename is an extension module.
64
62
65 This simply checks that the extension is either .so or .pyd.
63 This simply checks that the extension is either .so or .pyd.
66 """
64 """
67 return os.path.splitext(filename)[1].lower() in ('.so','.pyd')
65 return os.path.splitext(filename)[1].lower() in ('.so','.pyd')
68
66
69
67
70 class DocTestSkip(object):
68 class DocTestSkip(object):
71 """Object wrapper for doctests to be skipped."""
69 """Object wrapper for doctests to be skipped."""
72
70
73 ds_skip = """Doctest to skip.
71 ds_skip = """Doctest to skip.
74 >>> 1 #doctest: +SKIP
72 >>> 1 #doctest: +SKIP
75 """
73 """
76
74
77 def __init__(self,obj):
75 def __init__(self,obj):
78 self.obj = obj
76 self.obj = obj
79
77
80 def __getattribute__(self,key):
78 def __getattribute__(self,key):
81 if key == '__doc__':
79 if key == '__doc__':
82 return DocTestSkip.ds_skip
80 return DocTestSkip.ds_skip
83 else:
81 else:
84 return getattr(object.__getattribute__(self,'obj'),key)
82 return getattr(object.__getattribute__(self,'obj'),key)
85
83
86 # Modified version of the one in the stdlib, that fixes a python bug (doctests
84 # Modified version of the one in the stdlib, that fixes a python bug (doctests
87 # not found in extension modules, http://bugs.python.org/issue3158)
85 # not found in extension modules, http://bugs.python.org/issue3158)
88 class DocTestFinder(doctest.DocTestFinder):
86 class DocTestFinder(doctest.DocTestFinder):
89
87
90 def _from_module(self, module, object):
88 def _from_module(self, module, object):
91 """
89 """
92 Return true if the given object is defined in the given
90 Return true if the given object is defined in the given
93 module.
91 module.
94 """
92 """
95 if module is None:
93 if module is None:
96 return True
94 return True
97 elif inspect.isfunction(object):
95 elif inspect.isfunction(object):
98 return module.__dict__ is object.__globals__
96 return module.__dict__ is object.__globals__
99 elif inspect.isbuiltin(object):
97 elif inspect.isbuiltin(object):
100 return module.__name__ == object.__module__
98 return module.__name__ == object.__module__
101 elif inspect.isclass(object):
99 elif inspect.isclass(object):
102 return module.__name__ == object.__module__
100 return module.__name__ == object.__module__
103 elif inspect.ismethod(object):
101 elif inspect.ismethod(object):
104 # This one may be a bug in cython that fails to correctly set the
102 # This one may be a bug in cython that fails to correctly set the
105 # __module__ attribute of methods, but since the same error is easy
103 # __module__ attribute of methods, but since the same error is easy
106 # to make by extension code writers, having this safety in place
104 # to make by extension code writers, having this safety in place
107 # isn't such a bad idea
105 # isn't such a bad idea
108 return module.__name__ == object.__self__.__class__.__module__
106 return module.__name__ == object.__self__.__class__.__module__
109 elif inspect.getmodule(object) is not None:
107 elif inspect.getmodule(object) is not None:
110 return module is inspect.getmodule(object)
108 return module is inspect.getmodule(object)
111 elif hasattr(object, '__module__'):
109 elif hasattr(object, '__module__'):
112 return module.__name__ == object.__module__
110 return module.__name__ == object.__module__
113 elif isinstance(object, property):
111 elif isinstance(object, property):
114 return True # [XX] no way not be sure.
112 return True # [XX] no way not be sure.
115 elif inspect.ismethoddescriptor(object):
113 elif inspect.ismethoddescriptor(object):
116 # Unbound PyQt signals reach this point in Python 3.4b3, and we want
114 # Unbound PyQt signals reach this point in Python 3.4b3, and we want
117 # to avoid throwing an error. See also http://bugs.python.org/issue3158
115 # to avoid throwing an error. See also http://bugs.python.org/issue3158
118 return False
116 return False
119 else:
117 else:
120 raise ValueError("object must be a class or function, got %r" % object)
118 raise ValueError("object must be a class or function, got %r" % object)
121
119
122 def _find(self, tests, obj, name, module, source_lines, globs, seen):
120 def _find(self, tests, obj, name, module, source_lines, globs, seen):
123 """
121 """
124 Find tests for the given object and any contained objects, and
122 Find tests for the given object and any contained objects, and
125 add them to `tests`.
123 add them to `tests`.
126 """
124 """
127 print('_find for:', obj, name, module) # dbg
125 print('_find for:', obj, name, module) # dbg
128 if hasattr(obj,"skip_doctest"):
126 if hasattr(obj,"skip_doctest"):
129 #print 'SKIPPING DOCTEST FOR:',obj # dbg
127 #print 'SKIPPING DOCTEST FOR:',obj # dbg
130 obj = DocTestSkip(obj)
128 obj = DocTestSkip(obj)
131
129
132 doctest.DocTestFinder._find(self,tests, obj, name, module,
130 doctest.DocTestFinder._find(self,tests, obj, name, module,
133 source_lines, globs, seen)
131 source_lines, globs, seen)
134
132
135 # Below we re-run pieces of the above method with manual modifications,
133 # Below we re-run pieces of the above method with manual modifications,
136 # because the original code is buggy and fails to correctly identify
134 # because the original code is buggy and fails to correctly identify
137 # doctests in extension modules.
135 # doctests in extension modules.
138
136
139 # Local shorthands
137 # Local shorthands
140 from inspect import isroutine, isclass
138 from inspect import isroutine, isclass
141
139
142 # Look for tests in a module's contained objects.
140 # Look for tests in a module's contained objects.
143 if inspect.ismodule(obj) and self._recurse:
141 if inspect.ismodule(obj) and self._recurse:
144 for valname, val in obj.__dict__.items():
142 for valname, val in obj.__dict__.items():
145 valname1 = '%s.%s' % (name, valname)
143 valname1 = '%s.%s' % (name, valname)
146 if ( (isroutine(val) or isclass(val))
144 if ( (isroutine(val) or isclass(val))
147 and self._from_module(module, val) ):
145 and self._from_module(module, val) ):
148
146
149 self._find(tests, val, valname1, module, source_lines,
147 self._find(tests, val, valname1, module, source_lines,
150 globs, seen)
148 globs, seen)
151
149
152 # Look for tests in a class's contained objects.
150 # Look for tests in a class's contained objects.
153 if inspect.isclass(obj) and self._recurse:
151 if inspect.isclass(obj) and self._recurse:
154 #print 'RECURSE into class:',obj # dbg
152 #print 'RECURSE into class:',obj # dbg
155 for valname, val in obj.__dict__.items():
153 for valname, val in obj.__dict__.items():
156 # Special handling for staticmethod/classmethod.
154 # Special handling for staticmethod/classmethod.
157 if isinstance(val, staticmethod):
155 if isinstance(val, staticmethod):
158 val = getattr(obj, valname)
156 val = getattr(obj, valname)
159 if isinstance(val, classmethod):
157 if isinstance(val, classmethod):
160 val = getattr(obj, valname).__func__
158 val = getattr(obj, valname).__func__
161
159
162 # Recurse to methods, properties, and nested classes.
160 # Recurse to methods, properties, and nested classes.
163 if ((inspect.isfunction(val) or inspect.isclass(val) or
161 if ((inspect.isfunction(val) or inspect.isclass(val) or
164 inspect.ismethod(val) or
162 inspect.ismethod(val) or
165 isinstance(val, property)) and
163 isinstance(val, property)) and
166 self._from_module(module, val)):
164 self._from_module(module, val)):
167 valname = '%s.%s' % (name, valname)
165 valname = '%s.%s' % (name, valname)
168 self._find(tests, val, valname, module, source_lines,
166 self._find(tests, val, valname, module, source_lines,
169 globs, seen)
167 globs, seen)
170
168
171
169
172 class IPDoctestOutputChecker(doctest.OutputChecker):
170 class IPDoctestOutputChecker(doctest.OutputChecker):
173 """Second-chance checker with support for random tests.
171 """Second-chance checker with support for random tests.
174
172
175 If the default comparison doesn't pass, this checker looks in the expected
173 If the default comparison doesn't pass, this checker looks in the expected
176 output string for flags that tell us to ignore the output.
174 output string for flags that tell us to ignore the output.
177 """
175 """
178
176
179 random_re = re.compile(r'#\s*random\s+')
177 random_re = re.compile(r'#\s*random\s+')
180
178
181 def check_output(self, want, got, optionflags):
179 def check_output(self, want, got, optionflags):
182 """Check output, accepting special markers embedded in the output.
180 """Check output, accepting special markers embedded in the output.
183
181
184 If the output didn't pass the default validation but the special string
182 If the output didn't pass the default validation but the special string
185 '#random' is included, we accept it."""
183 '#random' is included, we accept it."""
186
184
187 # Let the original tester verify first, in case people have valid tests
185 # Let the original tester verify first, in case people have valid tests
188 # that happen to have a comment saying '#random' embedded in.
186 # that happen to have a comment saying '#random' embedded in.
189 ret = doctest.OutputChecker.check_output(self, want, got,
187 ret = doctest.OutputChecker.check_output(self, want, got,
190 optionflags)
188 optionflags)
191 if not ret and self.random_re.search(want):
189 if not ret and self.random_re.search(want):
192 #print >> sys.stderr, 'RANDOM OK:',want # dbg
190 #print >> sys.stderr, 'RANDOM OK:',want # dbg
193 return True
191 return True
194
192
195 return ret
193 return ret
196
194
197
195
198 class DocTestCase(doctests.DocTestCase):
196 class DocTestCase(doctests.DocTestCase):
199 """Proxy for DocTestCase: provides an address() method that
197 """Proxy for DocTestCase: provides an address() method that
200 returns the correct address for the doctest case. Otherwise
198 returns the correct address for the doctest case. Otherwise
201 acts as a proxy to the test case. To provide hints for address(),
199 acts as a proxy to the test case. To provide hints for address(),
202 an obj may also be passed -- this will be used as the test object
200 an obj may also be passed -- this will be used as the test object
203 for purposes of determining the test address, if it is provided.
201 for purposes of determining the test address, if it is provided.
204 """
202 """
205
203
206 # Note: this method was taken from numpy's nosetester module.
204 # Note: this method was taken from numpy's nosetester module.
207
205
208 # Subclass nose.plugins.doctests.DocTestCase to work around a bug in
206 # Subclass nose.plugins.doctests.DocTestCase to work around a bug in
209 # its constructor that blocks non-default arguments from being passed
207 # its constructor that blocks non-default arguments from being passed
210 # down into doctest.DocTestCase
208 # down into doctest.DocTestCase
211
209
212 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
210 def __init__(self, test, optionflags=0, setUp=None, tearDown=None,
213 checker=None, obj=None, result_var='_'):
211 checker=None, obj=None, result_var='_'):
214 self._result_var = result_var
212 self._result_var = result_var
215 doctests.DocTestCase.__init__(self, test,
213 doctests.DocTestCase.__init__(self, test,
216 optionflags=optionflags,
214 optionflags=optionflags,
217 setUp=setUp, tearDown=tearDown,
215 setUp=setUp, tearDown=tearDown,
218 checker=checker)
216 checker=checker)
219 # Now we must actually copy the original constructor from the stdlib
217 # Now we must actually copy the original constructor from the stdlib
220 # doctest class, because we can't call it directly and a bug in nose
218 # doctest class, because we can't call it directly and a bug in nose
221 # means it never gets passed the right arguments.
219 # means it never gets passed the right arguments.
222
220
223 self._dt_optionflags = optionflags
221 self._dt_optionflags = optionflags
224 self._dt_checker = checker
222 self._dt_checker = checker
225 self._dt_test = test
223 self._dt_test = test
226 self._dt_test_globs_ori = test.globs
224 self._dt_test_globs_ori = test.globs
227 self._dt_setUp = setUp
225 self._dt_setUp = setUp
228 self._dt_tearDown = tearDown
226 self._dt_tearDown = tearDown
229
227
230 # XXX - store this runner once in the object!
228 # XXX - store this runner once in the object!
231 runner = IPDocTestRunner(optionflags=optionflags,
229 runner = IPDocTestRunner(optionflags=optionflags,
232 checker=checker, verbose=False)
230 checker=checker, verbose=False)
233 self._dt_runner = runner
231 self._dt_runner = runner
234
232
235
233
236 # Each doctest should remember the directory it was loaded from, so
234 # Each doctest should remember the directory it was loaded from, so
237 # things like %run work without too many contortions
235 # things like %run work without too many contortions
238 self._ori_dir = os.path.dirname(test.filename)
236 self._ori_dir = os.path.dirname(test.filename)
239
237
240 # Modified runTest from the default stdlib
238 # Modified runTest from the default stdlib
241 def runTest(self):
239 def runTest(self):
242 test = self._dt_test
240 test = self._dt_test
243 runner = self._dt_runner
241 runner = self._dt_runner
244
242
245 old = sys.stdout
243 old = sys.stdout
246 new = StringIO()
244 new = StringIO()
247 optionflags = self._dt_optionflags
245 optionflags = self._dt_optionflags
248
246
249 if not (optionflags & REPORTING_FLAGS):
247 if not (optionflags & REPORTING_FLAGS):
250 # The option flags don't include any reporting flags,
248 # The option flags don't include any reporting flags,
251 # so add the default reporting flags
249 # so add the default reporting flags
252 optionflags |= _unittest_reportflags
250 optionflags |= _unittest_reportflags
253
251
254 try:
252 try:
255 # Save our current directory and switch out to the one where the
253 # Save our current directory and switch out to the one where the
256 # test was originally created, in case another doctest did a
254 # test was originally created, in case another doctest did a
257 # directory change. We'll restore this in the finally clause.
255 # directory change. We'll restore this in the finally clause.
258 curdir = os.getcwd()
256 curdir = os.getcwd()
259 #print 'runTest in dir:', self._ori_dir # dbg
257 #print 'runTest in dir:', self._ori_dir # dbg
260 os.chdir(self._ori_dir)
258 os.chdir(self._ori_dir)
261
259
262 runner.DIVIDER = "-"*70
260 runner.DIVIDER = "-"*70
263 failures, tries = runner.run(test,out=new.write,
261 failures, tries = runner.run(test,out=new.write,
264 clear_globs=False)
262 clear_globs=False)
265 finally:
263 finally:
266 sys.stdout = old
264 sys.stdout = old
267 os.chdir(curdir)
265 os.chdir(curdir)
268
266
269 if failures:
267 if failures:
270 raise self.failureException(self.format_failure(new.getvalue()))
268 raise self.failureException(self.format_failure(new.getvalue()))
271
269
272 def setUp(self):
270 def setUp(self):
273 """Modified test setup that syncs with ipython namespace"""
271 """Modified test setup that syncs with ipython namespace"""
274 #print "setUp test", self._dt_test.examples # dbg
272 #print "setUp test", self._dt_test.examples # dbg
275 if isinstance(self._dt_test.examples[0], IPExample):
273 if isinstance(self._dt_test.examples[0], IPExample):
276 # for IPython examples *only*, we swap the globals with the ipython
274 # for IPython examples *only*, we swap the globals with the ipython
277 # namespace, after updating it with the globals (which doctest
275 # namespace, after updating it with the globals (which doctest
278 # fills with the necessary info from the module being tested).
276 # fills with the necessary info from the module being tested).
279 self.user_ns_orig = {}
277 self.user_ns_orig = {}
280 self.user_ns_orig.update(_ip.user_ns)
278 self.user_ns_orig.update(_ip.user_ns)
281 _ip.user_ns.update(self._dt_test.globs)
279 _ip.user_ns.update(self._dt_test.globs)
282 # We must remove the _ key in the namespace, so that Python's
280 # We must remove the _ key in the namespace, so that Python's
283 # doctest code sets it naturally
281 # doctest code sets it naturally
284 _ip.user_ns.pop('_', None)
282 _ip.user_ns.pop('_', None)
285 _ip.user_ns['__builtins__'] = builtin_mod
283 _ip.user_ns['__builtins__'] = builtin_mod
286 self._dt_test.globs = _ip.user_ns
284 self._dt_test.globs = _ip.user_ns
287
285
288 super(DocTestCase, self).setUp()
286 super(DocTestCase, self).setUp()
289
287
290 def tearDown(self):
288 def tearDown(self):
291
289
292 # Undo the test.globs reassignment we made, so that the parent class
290 # Undo the test.globs reassignment we made, so that the parent class
293 # teardown doesn't destroy the ipython namespace
291 # teardown doesn't destroy the ipython namespace
294 if isinstance(self._dt_test.examples[0], IPExample):
292 if isinstance(self._dt_test.examples[0], IPExample):
295 self._dt_test.globs = self._dt_test_globs_ori
293 self._dt_test.globs = self._dt_test_globs_ori
296 _ip.user_ns.clear()
294 _ip.user_ns.clear()
297 _ip.user_ns.update(self.user_ns_orig)
295 _ip.user_ns.update(self.user_ns_orig)
298
296
299 # XXX - fperez: I am not sure if this is truly a bug in nose 0.11, but
297 # XXX - fperez: I am not sure if this is truly a bug in nose 0.11, but
300 # it does look like one to me: its tearDown method tries to run
298 # it does look like one to me: its tearDown method tries to run
301 #
299 #
302 # delattr(builtin_mod, self._result_var)
300 # delattr(builtin_mod, self._result_var)
303 #
301 #
304 # without checking that the attribute really is there; it implicitly
302 # without checking that the attribute really is there; it implicitly
305 # assumes it should have been set via displayhook. But if the
303 # assumes it should have been set via displayhook. But if the
306 # displayhook was never called, this doesn't necessarily happen. I
304 # displayhook was never called, this doesn't necessarily happen. I
307 # haven't been able to find a little self-contained example outside of
305 # haven't been able to find a little self-contained example outside of
308 # ipython that would show the problem so I can report it to the nose
306 # ipython that would show the problem so I can report it to the nose
309 # team, but it does happen a lot in our code.
307 # team, but it does happen a lot in our code.
310 #
308 #
311 # So here, we just protect as narrowly as possible by trapping an
309 # So here, we just protect as narrowly as possible by trapping an
312 # attribute error whose message would be the name of self._result_var,
310 # attribute error whose message would be the name of self._result_var,
313 # and letting any other error propagate.
311 # and letting any other error propagate.
314 try:
312 try:
315 super(DocTestCase, self).tearDown()
313 super(DocTestCase, self).tearDown()
316 except AttributeError as exc:
314 except AttributeError as exc:
317 if exc.args[0] != self._result_var:
315 if exc.args[0] != self._result_var:
318 raise
316 raise
319
317
320
318
321 # A simple subclassing of the original with a different class name, so we can
319 # A simple subclassing of the original with a different class name, so we can
322 # distinguish and treat differently IPython examples from pure python ones.
320 # distinguish and treat differently IPython examples from pure python ones.
323 class IPExample(doctest.Example): pass
321 class IPExample(doctest.Example): pass
324
322
325
323
326 class IPExternalExample(doctest.Example):
324 class IPExternalExample(doctest.Example):
327 """Doctest examples to be run in an external process."""
325 """Doctest examples to be run in an external process."""
328
326
329 def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
327 def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
330 options=None):
328 options=None):
331 # Parent constructor
329 # Parent constructor
332 doctest.Example.__init__(self,source,want,exc_msg,lineno,indent,options)
330 doctest.Example.__init__(self,source,want,exc_msg,lineno,indent,options)
333
331
334 # An EXTRA newline is needed to prevent pexpect hangs
332 # An EXTRA newline is needed to prevent pexpect hangs
335 self.source += '\n'
333 self.source += '\n'
336
334
337
335
338 class IPDocTestParser(doctest.DocTestParser):
336 class IPDocTestParser(doctest.DocTestParser):
339 """
337 """
340 A class used to parse strings containing doctest examples.
338 A class used to parse strings containing doctest examples.
341
339
342 Note: This is a version modified to properly recognize IPython input and
340 Note: This is a version modified to properly recognize IPython input and
343 convert any IPython examples into valid Python ones.
341 convert any IPython examples into valid Python ones.
344 """
342 """
345 # This regular expression is used to find doctest examples in a
343 # This regular expression is used to find doctest examples in a
346 # string. It defines three groups: `source` is the source code
344 # string. It defines three groups: `source` is the source code
347 # (including leading indentation and prompts); `indent` is the
345 # (including leading indentation and prompts); `indent` is the
348 # indentation of the first (PS1) line of the source code; and
346 # indentation of the first (PS1) line of the source code; and
349 # `want` is the expected output (including leading indentation).
347 # `want` is the expected output (including leading indentation).
350
348
351 # Classic Python prompts or default IPython ones
349 # Classic Python prompts or default IPython ones
352 _PS1_PY = r'>>>'
350 _PS1_PY = r'>>>'
353 _PS2_PY = r'\.\.\.'
351 _PS2_PY = r'\.\.\.'
354
352
355 _PS1_IP = r'In\ \[\d+\]:'
353 _PS1_IP = r'In\ \[\d+\]:'
356 _PS2_IP = r'\ \ \ \.\.\.+:'
354 _PS2_IP = r'\ \ \ \.\.\.+:'
357
355
358 _RE_TPL = r'''
356 _RE_TPL = r'''
359 # Source consists of a PS1 line followed by zero or more PS2 lines.
357 # Source consists of a PS1 line followed by zero or more PS2 lines.
360 (?P<source>
358 (?P<source>
361 (?:^(?P<indent> [ ]*) (?P<ps1> %s) .*) # PS1 line
359 (?:^(?P<indent> [ ]*) (?P<ps1> %s) .*) # PS1 line
362 (?:\n [ ]* (?P<ps2> %s) .*)*) # PS2 lines
360 (?:\n [ ]* (?P<ps2> %s) .*)*) # PS2 lines
363 \n? # a newline
361 \n? # a newline
364 # Want consists of any non-blank lines that do not start with PS1.
362 # Want consists of any non-blank lines that do not start with PS1.
365 (?P<want> (?:(?![ ]*$) # Not a blank line
363 (?P<want> (?:(?![ ]*$) # Not a blank line
366 (?![ ]*%s) # Not a line starting with PS1
364 (?![ ]*%s) # Not a line starting with PS1
367 (?![ ]*%s) # Not a line starting with PS2
365 (?![ ]*%s) # Not a line starting with PS2
368 .*$\n? # But any other line
366 .*$\n? # But any other line
369 )*)
367 )*)
370 '''
368 '''
371
369
372 _EXAMPLE_RE_PY = re.compile( _RE_TPL % (_PS1_PY,_PS2_PY,_PS1_PY,_PS2_PY),
370 _EXAMPLE_RE_PY = re.compile( _RE_TPL % (_PS1_PY,_PS2_PY,_PS1_PY,_PS2_PY),
373 re.MULTILINE | re.VERBOSE)
371 re.MULTILINE | re.VERBOSE)
374
372
375 _EXAMPLE_RE_IP = re.compile( _RE_TPL % (_PS1_IP,_PS2_IP,_PS1_IP,_PS2_IP),
373 _EXAMPLE_RE_IP = re.compile( _RE_TPL % (_PS1_IP,_PS2_IP,_PS1_IP,_PS2_IP),
376 re.MULTILINE | re.VERBOSE)
374 re.MULTILINE | re.VERBOSE)
377
375
378 # Mark a test as being fully random. In this case, we simply append the
376 # Mark a test as being fully random. In this case, we simply append the
379 # random marker ('#random') to each individual example's output. This way
377 # random marker ('#random') to each individual example's output. This way
380 # we don't need to modify any other code.
378 # we don't need to modify any other code.
381 _RANDOM_TEST = re.compile(r'#\s*all-random\s+')
379 _RANDOM_TEST = re.compile(r'#\s*all-random\s+')
382
380
383 # Mark tests to be executed in an external process - currently unsupported.
381 # Mark tests to be executed in an external process - currently unsupported.
384 _EXTERNAL_IP = re.compile(r'#\s*ipdoctest:\s*EXTERNAL')
382 _EXTERNAL_IP = re.compile(r'#\s*ipdoctest:\s*EXTERNAL')
385
383
386 def ip2py(self,source):
384 def ip2py(self,source):
387 """Convert input IPython source into valid Python."""
385 """Convert input IPython source into valid Python."""
388 block = _ip.input_transformer_manager.transform_cell(source)
386 block = _ip.input_transformer_manager.transform_cell(source)
389 if len(block.splitlines()) == 1:
387 if len(block.splitlines()) == 1:
390 return _ip.prefilter(block)
388 return _ip.prefilter(block)
391 else:
389 else:
392 return block
390 return block
393
391
394 def parse(self, string, name='<string>'):
392 def parse(self, string, name='<string>'):
395 """
393 """
396 Divide the given string into examples and intervening text,
394 Divide the given string into examples and intervening text,
397 and return them as a list of alternating Examples and strings.
395 and return them as a list of alternating Examples and strings.
398 Line numbers for the Examples are 0-based. The optional
396 Line numbers for the Examples are 0-based. The optional
399 argument `name` is a name identifying this string, and is only
397 argument `name` is a name identifying this string, and is only
400 used for error messages.
398 used for error messages.
401 """
399 """
402
400
403 #print 'Parse string:\n',string # dbg
401 #print 'Parse string:\n',string # dbg
404
402
405 string = string.expandtabs()
403 string = string.expandtabs()
406 # If all lines begin with the same indentation, then strip it.
404 # If all lines begin with the same indentation, then strip it.
407 min_indent = self._min_indent(string)
405 min_indent = self._min_indent(string)
408 if min_indent > 0:
406 if min_indent > 0:
409 string = '\n'.join([l[min_indent:] for l in string.split('\n')])
407 string = '\n'.join([l[min_indent:] for l in string.split('\n')])
410
408
411 output = []
409 output = []
412 charno, lineno = 0, 0
410 charno, lineno = 0, 0
413
411
414 # We make 'all random' tests by adding the '# random' mark to every
412 # We make 'all random' tests by adding the '# random' mark to every
415 # block of output in the test.
413 # block of output in the test.
416 if self._RANDOM_TEST.search(string):
414 if self._RANDOM_TEST.search(string):
417 random_marker = '\n# random'
415 random_marker = '\n# random'
418 else:
416 else:
419 random_marker = ''
417 random_marker = ''
420
418
421 # Whether to convert the input from ipython to python syntax
419 # Whether to convert the input from ipython to python syntax
422 ip2py = False
420 ip2py = False
423 # Find all doctest examples in the string. First, try them as Python
421 # Find all doctest examples in the string. First, try them as Python
424 # examples, then as IPython ones
422 # examples, then as IPython ones
425 terms = list(self._EXAMPLE_RE_PY.finditer(string))
423 terms = list(self._EXAMPLE_RE_PY.finditer(string))
426 if terms:
424 if terms:
427 # Normal Python example
425 # Normal Python example
428 #print '-'*70 # dbg
426 #print '-'*70 # dbg
429 #print 'PyExample, Source:\n',string # dbg
427 #print 'PyExample, Source:\n',string # dbg
430 #print '-'*70 # dbg
428 #print '-'*70 # dbg
431 Example = doctest.Example
429 Example = doctest.Example
432 else:
430 else:
433 # It's an ipython example. Note that IPExamples are run
431 # It's an ipython example. Note that IPExamples are run
434 # in-process, so their syntax must be turned into valid python.
432 # in-process, so their syntax must be turned into valid python.
435 # IPExternalExamples are run out-of-process (via pexpect) so they
433 # IPExternalExamples are run out-of-process (via pexpect) so they
436 # don't need any filtering (a real ipython will be executing them).
434 # don't need any filtering (a real ipython will be executing them).
437 terms = list(self._EXAMPLE_RE_IP.finditer(string))
435 terms = list(self._EXAMPLE_RE_IP.finditer(string))
438 if self._EXTERNAL_IP.search(string):
436 if self._EXTERNAL_IP.search(string):
439 #print '-'*70 # dbg
437 #print '-'*70 # dbg
440 #print 'IPExternalExample, Source:\n',string # dbg
438 #print 'IPExternalExample, Source:\n',string # dbg
441 #print '-'*70 # dbg
439 #print '-'*70 # dbg
442 Example = IPExternalExample
440 Example = IPExternalExample
443 else:
441 else:
444 #print '-'*70 # dbg
442 #print '-'*70 # dbg
445 #print 'IPExample, Source:\n',string # dbg
443 #print 'IPExample, Source:\n',string # dbg
446 #print '-'*70 # dbg
444 #print '-'*70 # dbg
447 Example = IPExample
445 Example = IPExample
448 ip2py = True
446 ip2py = True
449
447
450 for m in terms:
448 for m in terms:
451 # Add the pre-example text to `output`.
449 # Add the pre-example text to `output`.
452 output.append(string[charno:m.start()])
450 output.append(string[charno:m.start()])
453 # Update lineno (lines before this example)
451 # Update lineno (lines before this example)
454 lineno += string.count('\n', charno, m.start())
452 lineno += string.count('\n', charno, m.start())
455 # Extract info from the regexp match.
453 # Extract info from the regexp match.
456 (source, options, want, exc_msg) = \
454 (source, options, want, exc_msg) = \
457 self._parse_example(m, name, lineno,ip2py)
455 self._parse_example(m, name, lineno,ip2py)
458
456
459 # Append the random-output marker (it defaults to empty in most
457 # Append the random-output marker (it defaults to empty in most
460 # cases, it's only non-empty for 'all-random' tests):
458 # cases, it's only non-empty for 'all-random' tests):
461 want += random_marker
459 want += random_marker
462
460
463 if Example is IPExternalExample:
461 if Example is IPExternalExample:
464 options[doctest.NORMALIZE_WHITESPACE] = True
462 options[doctest.NORMALIZE_WHITESPACE] = True
465 want += '\n'
463 want += '\n'
466
464
467 # Create an Example, and add it to the list.
465 # Create an Example, and add it to the list.
468 if not self._IS_BLANK_OR_COMMENT(source):
466 if not self._IS_BLANK_OR_COMMENT(source):
469 output.append(Example(source, want, exc_msg,
467 output.append(Example(source, want, exc_msg,
470 lineno=lineno,
468 lineno=lineno,
471 indent=min_indent+len(m.group('indent')),
469 indent=min_indent+len(m.group('indent')),
472 options=options))
470 options=options))
473 # Update lineno (lines inside this example)
471 # Update lineno (lines inside this example)
474 lineno += string.count('\n', m.start(), m.end())
472 lineno += string.count('\n', m.start(), m.end())
475 # Update charno.
473 # Update charno.
476 charno = m.end()
474 charno = m.end()
477 # Add any remaining post-example text to `output`.
475 # Add any remaining post-example text to `output`.
478 output.append(string[charno:])
476 output.append(string[charno:])
479 return output
477 return output
480
478
481 def _parse_example(self, m, name, lineno,ip2py=False):
479 def _parse_example(self, m, name, lineno,ip2py=False):
482 """
480 """
483 Given a regular expression match from `_EXAMPLE_RE` (`m`),
481 Given a regular expression match from `_EXAMPLE_RE` (`m`),
484 return a pair `(source, want)`, where `source` is the matched
482 return a pair `(source, want)`, where `source` is the matched
485 example's source code (with prompts and indentation stripped);
483 example's source code (with prompts and indentation stripped);
486 and `want` is the example's expected output (with indentation
484 and `want` is the example's expected output (with indentation
487 stripped).
485 stripped).
488
486
489 `name` is the string's name, and `lineno` is the line number
487 `name` is the string's name, and `lineno` is the line number
490 where the example starts; both are used for error messages.
488 where the example starts; both are used for error messages.
491
489
492 Optional:
490 Optional:
493 `ip2py`: if true, filter the input via IPython to convert the syntax
491 `ip2py`: if true, filter the input via IPython to convert the syntax
494 into valid python.
492 into valid python.
495 """
493 """
496
494
497 # Get the example's indentation level.
495 # Get the example's indentation level.
498 indent = len(m.group('indent'))
496 indent = len(m.group('indent'))
499
497
500 # Divide source into lines; check that they're properly
498 # Divide source into lines; check that they're properly
501 # indented; and then strip their indentation & prompts.
499 # indented; and then strip their indentation & prompts.
502 source_lines = m.group('source').split('\n')
500 source_lines = m.group('source').split('\n')
503
501
504 # We're using variable-length input prompts
502 # We're using variable-length input prompts
505 ps1 = m.group('ps1')
503 ps1 = m.group('ps1')
506 ps2 = m.group('ps2')
504 ps2 = m.group('ps2')
507 ps1_len = len(ps1)
505 ps1_len = len(ps1)
508
506
509 self._check_prompt_blank(source_lines, indent, name, lineno,ps1_len)
507 self._check_prompt_blank(source_lines, indent, name, lineno,ps1_len)
510 if ps2:
508 if ps2:
511 self._check_prefix(source_lines[1:], ' '*indent + ps2, name, lineno)
509 self._check_prefix(source_lines[1:], ' '*indent + ps2, name, lineno)
512
510
513 source = '\n'.join([sl[indent+ps1_len+1:] for sl in source_lines])
511 source = '\n'.join([sl[indent+ps1_len+1:] for sl in source_lines])
514
512
515 if ip2py:
513 if ip2py:
516 # Convert source input from IPython into valid Python syntax
514 # Convert source input from IPython into valid Python syntax
517 source = self.ip2py(source)
515 source = self.ip2py(source)
518
516
519 # Divide want into lines; check that it's properly indented; and
517 # Divide want into lines; check that it's properly indented; and
520 # then strip the indentation. Spaces before the last newline should
518 # then strip the indentation. Spaces before the last newline should
521 # be preserved, so plain rstrip() isn't good enough.
519 # be preserved, so plain rstrip() isn't good enough.
522 want = m.group('want')
520 want = m.group('want')
523 want_lines = want.split('\n')
521 want_lines = want.split('\n')
524 if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
522 if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):
525 del want_lines[-1] # forget final newline & spaces after it
523 del want_lines[-1] # forget final newline & spaces after it
526 self._check_prefix(want_lines, ' '*indent, name,
524 self._check_prefix(want_lines, ' '*indent, name,
527 lineno + len(source_lines))
525 lineno + len(source_lines))
528
526
529 # Remove ipython output prompt that might be present in the first line
527 # Remove ipython output prompt that might be present in the first line
530 want_lines[0] = re.sub(r'Out\[\d+\]: \s*?\n?','',want_lines[0])
528 want_lines[0] = re.sub(r'Out\[\d+\]: \s*?\n?','',want_lines[0])
531
529
532 want = '\n'.join([wl[indent:] for wl in want_lines])
530 want = '\n'.join([wl[indent:] for wl in want_lines])
533
531
534 # If `want` contains a traceback message, then extract it.
532 # If `want` contains a traceback message, then extract it.
535 m = self._EXCEPTION_RE.match(want)
533 m = self._EXCEPTION_RE.match(want)
536 if m:
534 if m:
537 exc_msg = m.group('msg')
535 exc_msg = m.group('msg')
538 else:
536 else:
539 exc_msg = None
537 exc_msg = None
540
538
541 # Extract options from the source.
539 # Extract options from the source.
542 options = self._find_options(source, name, lineno)
540 options = self._find_options(source, name, lineno)
543
541
544 return source, options, want, exc_msg
542 return source, options, want, exc_msg
545
543
546 def _check_prompt_blank(self, lines, indent, name, lineno, ps1_len):
544 def _check_prompt_blank(self, lines, indent, name, lineno, ps1_len):
547 """
545 """
548 Given the lines of a source string (including prompts and
546 Given the lines of a source string (including prompts and
549 leading indentation), check to make sure that every prompt is
547 leading indentation), check to make sure that every prompt is
550 followed by a space character. If any line is not followed by
548 followed by a space character. If any line is not followed by
551 a space character, then raise ValueError.
549 a space character, then raise ValueError.
552
550
553 Note: IPython-modified version which takes the input prompt length as a
551 Note: IPython-modified version which takes the input prompt length as a
554 parameter, so that prompts of variable length can be dealt with.
552 parameter, so that prompts of variable length can be dealt with.
555 """
553 """
556 space_idx = indent+ps1_len
554 space_idx = indent+ps1_len
557 min_len = space_idx+1
555 min_len = space_idx+1
558 for i, line in enumerate(lines):
556 for i, line in enumerate(lines):
559 if len(line) >= min_len and line[space_idx] != ' ':
557 if len(line) >= min_len and line[space_idx] != ' ':
560 raise ValueError('line %r of the docstring for %s '
558 raise ValueError('line %r of the docstring for %s '
561 'lacks blank after %s: %r' %
559 'lacks blank after %s: %r' %
562 (lineno+i+1, name,
560 (lineno+i+1, name,
563 line[indent:space_idx], line))
561 line[indent:space_idx], line))
564
562
565
563
566 SKIP = doctest.register_optionflag('SKIP')
564 SKIP = doctest.register_optionflag('SKIP')
567
565
568
566
569 class IPDocTestRunner(doctest.DocTestRunner,object):
567 class IPDocTestRunner(doctest.DocTestRunner,object):
570 """Test runner that synchronizes the IPython namespace with test globals.
568 """Test runner that synchronizes the IPython namespace with test globals.
571 """
569 """
572
570
573 def run(self, test, compileflags=None, out=None, clear_globs=True):
571 def run(self, test, compileflags=None, out=None, clear_globs=True):
574
572
575 # Hack: ipython needs access to the execution context of the example,
573 # Hack: ipython needs access to the execution context of the example,
576 # so that it can propagate user variables loaded by %run into
574 # so that it can propagate user variables loaded by %run into
577 # test.globs. We put them here into our modified %run as a function
575 # test.globs. We put them here into our modified %run as a function
578 # attribute. Our new %run will then only make the namespace update
576 # attribute. Our new %run will then only make the namespace update
579 # when called (rather than unconconditionally updating test.globs here
577 # when called (rather than unconconditionally updating test.globs here
580 # for all examples, most of which won't be calling %run anyway).
578 # for all examples, most of which won't be calling %run anyway).
581 #_ip._ipdoctest_test_globs = test.globs
579 #_ip._ipdoctest_test_globs = test.globs
582 #_ip._ipdoctest_test_filename = test.filename
580 #_ip._ipdoctest_test_filename = test.filename
583
581
584 test.globs.update(_ip.user_ns)
582 test.globs.update(_ip.user_ns)
585
583
586 # Override terminal size to standardise traceback format
584 # Override terminal size to standardise traceback format
587 with modified_env({'COLUMNS': '80', 'LINES': '24'}):
585 with modified_env({'COLUMNS': '80', 'LINES': '24'}):
588 return super(IPDocTestRunner,self).run(test,
586 return super(IPDocTestRunner,self).run(test,
589 compileflags,out,clear_globs)
587 compileflags,out,clear_globs)
590
588
591
589
592 class DocFileCase(doctest.DocFileCase):
590 class DocFileCase(doctest.DocFileCase):
593 """Overrides to provide filename
591 """Overrides to provide filename
594 """
592 """
595 def address(self):
593 def address(self):
596 return (self._dt_test.filename, None, None)
594 return (self._dt_test.filename, None, None)
597
595
598
596
599 class ExtensionDoctest(doctests.Doctest):
597 class ExtensionDoctest(doctests.Doctest):
600 """Nose Plugin that supports doctests in extension modules.
598 """Nose Plugin that supports doctests in extension modules.
601 """
599 """
602 name = 'extdoctest' # call nosetests with --with-extdoctest
600 name = 'extdoctest' # call nosetests with --with-extdoctest
603 enabled = True
601 enabled = True
604
602
605 def options(self, parser, env=os.environ):
603 def options(self, parser, env=os.environ):
606 Plugin.options(self, parser, env)
604 Plugin.options(self, parser, env)
607 parser.add_option('--doctest-tests', action='store_true',
605 parser.add_option('--doctest-tests', action='store_true',
608 dest='doctest_tests',
606 dest='doctest_tests',
609 default=env.get('NOSE_DOCTEST_TESTS',True),
607 default=env.get('NOSE_DOCTEST_TESTS',True),
610 help="Also look for doctests in test modules. "
608 help="Also look for doctests in test modules. "
611 "Note that classes, methods and functions should "
609 "Note that classes, methods and functions should "
612 "have either doctests or non-doctest tests, "
610 "have either doctests or non-doctest tests, "
613 "not both. [NOSE_DOCTEST_TESTS]")
611 "not both. [NOSE_DOCTEST_TESTS]")
614 parser.add_option('--doctest-extension', action="append",
612 parser.add_option('--doctest-extension', action="append",
615 dest="doctestExtension",
613 dest="doctestExtension",
616 help="Also look for doctests in files with "
614 help="Also look for doctests in files with "
617 "this extension [NOSE_DOCTEST_EXTENSION]")
615 "this extension [NOSE_DOCTEST_EXTENSION]")
618 # Set the default as a list, if given in env; otherwise
616 # Set the default as a list, if given in env; otherwise
619 # an additional value set on the command line will cause
617 # an additional value set on the command line will cause
620 # an error.
618 # an error.
621 env_setting = env.get('NOSE_DOCTEST_EXTENSION')
619 env_setting = env.get('NOSE_DOCTEST_EXTENSION')
622 if env_setting is not None:
620 if env_setting is not None:
623 parser.set_defaults(doctestExtension=tolist(env_setting))
621 parser.set_defaults(doctestExtension=tolist(env_setting))
624
622
625
623
626 def configure(self, options, config):
624 def configure(self, options, config):
627 Plugin.configure(self, options, config)
625 Plugin.configure(self, options, config)
628 # Pull standard doctest plugin out of config; we will do doctesting
626 # Pull standard doctest plugin out of config; we will do doctesting
629 config.plugins.plugins = [p for p in config.plugins.plugins
627 config.plugins.plugins = [p for p in config.plugins.plugins
630 if p.name != 'doctest']
628 if p.name != 'doctest']
631 self.doctest_tests = options.doctest_tests
629 self.doctest_tests = options.doctest_tests
632 self.extension = tolist(options.doctestExtension)
630 self.extension = tolist(options.doctestExtension)
633
631
634 self.parser = doctest.DocTestParser()
632 self.parser = doctest.DocTestParser()
635 self.finder = DocTestFinder()
633 self.finder = DocTestFinder()
636 self.checker = IPDoctestOutputChecker()
634 self.checker = IPDoctestOutputChecker()
637 self.globs = None
635 self.globs = None
638 self.extraglobs = None
636 self.extraglobs = None
639
637
640
638
641 def loadTestsFromExtensionModule(self,filename):
639 def loadTestsFromExtensionModule(self,filename):
642 bpath,mod = os.path.split(filename)
640 bpath,mod = os.path.split(filename)
643 modname = os.path.splitext(mod)[0]
641 modname = os.path.splitext(mod)[0]
644 try:
642 try:
645 sys.path.append(bpath)
643 sys.path.append(bpath)
646 module = import_module(modname)
644 module = import_module(modname)
647 tests = list(self.loadTestsFromModule(module))
645 tests = list(self.loadTestsFromModule(module))
648 finally:
646 finally:
649 sys.path.pop()
647 sys.path.pop()
650 return tests
648 return tests
651
649
652 # NOTE: the method below is almost a copy of the original one in nose, with
650 # NOTE: the method below is almost a copy of the original one in nose, with
653 # a few modifications to control output checking.
651 # a few modifications to control output checking.
654
652
655 def loadTestsFromModule(self, module):
653 def loadTestsFromModule(self, module):
656 #print '*** ipdoctest - lTM',module # dbg
654 #print '*** ipdoctest - lTM',module # dbg
657
655
658 if not self.matches(module.__name__):
656 if not self.matches(module.__name__):
659 log.debug("Doctest doesn't want module %s", module)
657 log.debug("Doctest doesn't want module %s", module)
660 return
658 return
661
659
662 tests = self.finder.find(module,globs=self.globs,
660 tests = self.finder.find(module,globs=self.globs,
663 extraglobs=self.extraglobs)
661 extraglobs=self.extraglobs)
664 if not tests:
662 if not tests:
665 return
663 return
666
664
667 # always use whitespace and ellipsis options
665 # always use whitespace and ellipsis options
668 optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
666 optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
669
667
670 tests.sort()
668 tests.sort()
671 module_file = module.__file__
669 module_file = module.__file__
672 if module_file[-4:] in ('.pyc', '.pyo'):
670 if module_file[-4:] in ('.pyc', '.pyo'):
673 module_file = module_file[:-1]
671 module_file = module_file[:-1]
674 for test in tests:
672 for test in tests:
675 if not test.examples:
673 if not test.examples:
676 continue
674 continue
677 if not test.filename:
675 if not test.filename:
678 test.filename = module_file
676 test.filename = module_file
679
677
680 yield DocTestCase(test,
678 yield DocTestCase(test,
681 optionflags=optionflags,
679 optionflags=optionflags,
682 checker=self.checker)
680 checker=self.checker)
683
681
684
682
685 def loadTestsFromFile(self, filename):
683 def loadTestsFromFile(self, filename):
686 #print "ipdoctest - from file", filename # dbg
684 #print "ipdoctest - from file", filename # dbg
687 if is_extension_module(filename):
685 if is_extension_module(filename):
688 for t in self.loadTestsFromExtensionModule(filename):
686 for t in self.loadTestsFromExtensionModule(filename):
689 yield t
687 yield t
690 else:
688 else:
691 if self.extension and anyp(filename.endswith, self.extension):
689 if self.extension and anyp(filename.endswith, self.extension):
692 name = os.path.basename(filename)
690 name = os.path.basename(filename)
693 dh = open(filename)
691 dh = open(filename)
694 try:
692 try:
695 doc = dh.read()
693 doc = dh.read()
696 finally:
694 finally:
697 dh.close()
695 dh.close()
698 test = self.parser.get_doctest(
696 test = self.parser.get_doctest(
699 doc, globs={'__file__': filename}, name=name,
697 doc, globs={'__file__': filename}, name=name,
700 filename=filename, lineno=0)
698 filename=filename, lineno=0)
701 if test.examples:
699 if test.examples:
702 #print 'FileCase:',test.examples # dbg
700 #print 'FileCase:',test.examples # dbg
703 yield DocFileCase(test)
701 yield DocFileCase(test)
704 else:
702 else:
705 yield False # no tests to load
703 yield False # no tests to load
706
704
707
705
708 class IPythonDoctest(ExtensionDoctest):
706 class IPythonDoctest(ExtensionDoctest):
709 """Nose Plugin that supports doctests in extension modules.
707 """Nose Plugin that supports doctests in extension modules.
710 """
708 """
711 name = 'ipdoctest' # call nosetests with --with-ipdoctest
709 name = 'ipdoctest' # call nosetests with --with-ipdoctest
712 enabled = True
710 enabled = True
713
711
714 def makeTest(self, obj, parent):
712 def makeTest(self, obj, parent):
715 """Look for doctests in the given object, which will be a
713 """Look for doctests in the given object, which will be a
716 function, method or class.
714 function, method or class.
717 """
715 """
718 #print 'Plugin analyzing:', obj, parent # dbg
716 #print 'Plugin analyzing:', obj, parent # dbg
719 # always use whitespace and ellipsis options
717 # always use whitespace and ellipsis options
720 optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
718 optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
721
719
722 doctests = self.finder.find(obj, module=getmodule(parent))
720 doctests = self.finder.find(obj, module=getmodule(parent))
723 if doctests:
721 if doctests:
724 for test in doctests:
722 for test in doctests:
725 if len(test.examples) == 0:
723 if len(test.examples) == 0:
726 continue
724 continue
727
725
728 yield DocTestCase(test, obj=obj,
726 yield DocTestCase(test, obj=obj,
729 optionflags=optionflags,
727 optionflags=optionflags,
730 checker=self.checker)
728 checker=self.checker)
731
729
732 def options(self, parser, env=os.environ):
730 def options(self, parser, env=os.environ):
733 #print "Options for nose plugin:", self.name # dbg
731 #print "Options for nose plugin:", self.name # dbg
734 Plugin.options(self, parser, env)
732 Plugin.options(self, parser, env)
735 parser.add_option('--ipdoctest-tests', action='store_true',
733 parser.add_option('--ipdoctest-tests', action='store_true',
736 dest='ipdoctest_tests',
734 dest='ipdoctest_tests',
737 default=env.get('NOSE_IPDOCTEST_TESTS',True),
735 default=env.get('NOSE_IPDOCTEST_TESTS',True),
738 help="Also look for doctests in test modules. "
736 help="Also look for doctests in test modules. "
739 "Note that classes, methods and functions should "
737 "Note that classes, methods and functions should "
740 "have either doctests or non-doctest tests, "
738 "have either doctests or non-doctest tests, "
741 "not both. [NOSE_IPDOCTEST_TESTS]")
739 "not both. [NOSE_IPDOCTEST_TESTS]")
742 parser.add_option('--ipdoctest-extension', action="append",
740 parser.add_option('--ipdoctest-extension', action="append",
743 dest="ipdoctest_extension",
741 dest="ipdoctest_extension",
744 help="Also look for doctests in files with "
742 help="Also look for doctests in files with "
745 "this extension [NOSE_IPDOCTEST_EXTENSION]")
743 "this extension [NOSE_IPDOCTEST_EXTENSION]")
746 # Set the default as a list, if given in env; otherwise
744 # Set the default as a list, if given in env; otherwise
747 # an additional value set on the command line will cause
745 # an additional value set on the command line will cause
748 # an error.
746 # an error.
749 env_setting = env.get('NOSE_IPDOCTEST_EXTENSION')
747 env_setting = env.get('NOSE_IPDOCTEST_EXTENSION')
750 if env_setting is not None:
748 if env_setting is not None:
751 parser.set_defaults(ipdoctest_extension=tolist(env_setting))
749 parser.set_defaults(ipdoctest_extension=tolist(env_setting))
752
750
753 def configure(self, options, config):
751 def configure(self, options, config):
754 #print "Configuring nose plugin:", self.name # dbg
752 #print "Configuring nose plugin:", self.name # dbg
755 Plugin.configure(self, options, config)
753 Plugin.configure(self, options, config)
756 # Pull standard doctest plugin out of config; we will do doctesting
754 # Pull standard doctest plugin out of config; we will do doctesting
757 config.plugins.plugins = [p for p in config.plugins.plugins
755 config.plugins.plugins = [p for p in config.plugins.plugins
758 if p.name != 'doctest']
756 if p.name != 'doctest']
759 self.doctest_tests = options.ipdoctest_tests
757 self.doctest_tests = options.ipdoctest_tests
760 self.extension = tolist(options.ipdoctest_extension)
758 self.extension = tolist(options.ipdoctest_extension)
761
759
762 self.parser = IPDocTestParser()
760 self.parser = IPDocTestParser()
763 self.finder = DocTestFinder(parser=self.parser)
761 self.finder = DocTestFinder(parser=self.parser)
764 self.checker = IPDoctestOutputChecker()
762 self.checker = IPDoctestOutputChecker()
765 self.globs = None
763 self.globs = None
766 self.extraglobs = None
764 self.extraglobs = None
General Comments 0
You need to be logged in to leave comments. Login now