##// END OF EJS Templates
Remove uses of compatibility builtin_mod and builtin_mod_name
Thomas Kluyver -
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -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 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -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:
324 original_reload = builtin_mod.reload
325 except AttributeError:
326 original_reload = imp.reload # Python 3
322 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