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:` |
|
|
3 | ||
|
4 | Authors: | |
|
5 | ||
|
6 | * Brian Granger | |
|
7 | * Fernando Perez | |
|
2 | A context manager for managing things injected into :mod:`builtins`. | |
|
8 | 3 | """ |
|
9 | #----------------------------------------------------------------------------- | |
|
10 | # Copyright (C) 2010-2011 The IPython Development Team. | |
|
11 | # | |
|
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 | #----------------------------------------------------------------------------- | |
|
4 | # Copyright (c) IPython Development Team. | |
|
5 | # Distributed under the terms of the Modified BSD License. | |
|
6 | import builtins as builtin_mod | |
|
20 | 7 | |
|
21 | 8 | from traitlets.config.configurable import Configurable |
|
22 | 9 | |
|
23 | from IPython.utils.py3compat import builtin_mod | |
|
24 | 10 | from traitlets import Instance |
|
25 | 11 | |
|
26 | #----------------------------------------------------------------------------- | |
|
27 | # Classes and functions | |
|
28 | #----------------------------------------------------------------------------- | |
|
29 | 12 | |
|
30 | 13 | class __BuiltinUndefined(object): pass |
|
31 | 14 | BuiltinUndefined = __BuiltinUndefined() |
|
32 | 15 | |
|
33 | 16 | class __HideBuiltin(object): pass |
|
34 | 17 | HideBuiltin = __HideBuiltin() |
|
35 | 18 | |
|
36 | 19 | |
|
37 | 20 | class BuiltinTrap(Configurable): |
|
38 | 21 | |
|
39 | 22 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', |
|
40 | 23 | allow_none=True) |
|
41 | 24 | |
|
42 | 25 | def __init__(self, shell=None): |
|
43 | 26 | super(BuiltinTrap, self).__init__(shell=shell, config=None) |
|
44 | 27 | self._orig_builtins = {} |
|
45 | 28 | # We define this to track if a single BuiltinTrap is nested. |
|
46 | 29 | # Only turn off the trap when the outermost call to __exit__ is made. |
|
47 | 30 | self._nested_level = 0 |
|
48 | 31 | self.shell = shell |
|
49 | 32 | # builtins we always add - if set to HideBuiltin, they will just |
|
50 | 33 | # be removed instead of being replaced by something else |
|
51 | 34 | self.auto_builtins = {'exit': HideBuiltin, |
|
52 | 35 | 'quit': HideBuiltin, |
|
53 | 36 | 'get_ipython': self.shell.get_ipython, |
|
54 | 37 | } |
|
55 | 38 | |
|
56 | 39 | def __enter__(self): |
|
57 | 40 | if self._nested_level == 0: |
|
58 | 41 | self.activate() |
|
59 | 42 | self._nested_level += 1 |
|
60 | 43 | # I return self, so callers can use add_builtin in a with clause. |
|
61 | 44 | return self |
|
62 | 45 | |
|
63 | 46 | def __exit__(self, type, value, traceback): |
|
64 | 47 | if self._nested_level == 1: |
|
65 | 48 | self.deactivate() |
|
66 | 49 | self._nested_level -= 1 |
|
67 | 50 | # Returning False will cause exceptions to propagate |
|
68 | 51 | return False |
|
69 | 52 | |
|
70 | 53 | def add_builtin(self, key, value): |
|
71 | 54 | """Add a builtin and save the original.""" |
|
72 | 55 | bdict = builtin_mod.__dict__ |
|
73 | 56 | orig = bdict.get(key, BuiltinUndefined) |
|
74 | 57 | if value is HideBuiltin: |
|
75 | 58 | if orig is not BuiltinUndefined: #same as 'key in bdict' |
|
76 | 59 | self._orig_builtins[key] = orig |
|
77 | 60 | del bdict[key] |
|
78 | 61 | else: |
|
79 | 62 | self._orig_builtins[key] = orig |
|
80 | 63 | bdict[key] = value |
|
81 | 64 | |
|
82 | 65 | def remove_builtin(self, key, orig): |
|
83 | 66 | """Remove an added builtin and re-set the original.""" |
|
84 | 67 | if orig is BuiltinUndefined: |
|
85 | 68 | del builtin_mod.__dict__[key] |
|
86 | 69 | else: |
|
87 | 70 | builtin_mod.__dict__[key] = orig |
|
88 | 71 | |
|
89 | 72 | def activate(self): |
|
90 | 73 | """Store ipython references in the __builtin__ namespace.""" |
|
91 | 74 | |
|
92 | 75 | add_builtin = self.add_builtin |
|
93 | 76 | for name, func in self.auto_builtins.items(): |
|
94 | 77 | add_builtin(name, func) |
|
95 | 78 | |
|
96 | 79 | def deactivate(self): |
|
97 | 80 | """Remove any builtins which might have been added by add_builtins, or |
|
98 | 81 | restore overwritten ones to their previous values.""" |
|
99 | 82 | remove_builtin = self.remove_builtin |
|
100 | 83 | for key, val in self._orig_builtins.items(): |
|
101 | 84 | remove_builtin(key, val) |
|
102 | 85 | self._orig_builtins.clear() |
|
103 | 86 | self._builtins_added = False |
@@ -1,1227 +1,1228 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """Word completion for IPython. |
|
3 | 3 | |
|
4 | 4 | This module started as fork of the rlcompleter module in the Python standard |
|
5 | 5 | library. The original enhancements made to rlcompleter have been sent |
|
6 | 6 | upstream and were accepted as of Python 2.3, |
|
7 | 7 | |
|
8 | 8 | """ |
|
9 | 9 | |
|
10 | 10 | # Copyright (c) IPython Development Team. |
|
11 | 11 | # Distributed under the terms of the Modified BSD License. |
|
12 | 12 | # |
|
13 | 13 | # Some of this code originated from rlcompleter in the Python standard library |
|
14 | 14 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
15 | 15 | |
|
16 | 16 | |
|
17 | 17 | import __main__ |
|
18 | import builtins as builtin_mod | |
|
18 | 19 | import glob |
|
19 | 20 | import inspect |
|
20 | 21 | import itertools |
|
21 | 22 | import keyword |
|
22 | 23 | import os |
|
23 | 24 | import re |
|
24 | 25 | import sys |
|
25 | 26 | import unicodedata |
|
26 | 27 | import string |
|
27 | 28 | import warnings |
|
28 | 29 | from importlib import import_module |
|
29 | 30 | |
|
30 | 31 | from traitlets.config.configurable import Configurable |
|
31 | 32 | from IPython.core.error import TryNext |
|
32 | 33 | from IPython.core.inputsplitter import ESC_MAGIC |
|
33 | 34 | from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol |
|
34 | 35 | from IPython.utils import generics |
|
35 | 36 | from IPython.utils.decorators import undoc |
|
36 | 37 | from IPython.utils.dir2 import dir2, get_real_method |
|
37 | 38 | from IPython.utils.process import arg_split |
|
38 |
from IPython.utils.py3compat import |
|
|
39 | from IPython.utils.py3compat import cast_unicode_py2 | |
|
39 | 40 | from traitlets import Bool, Enum, observe |
|
40 | 41 | |
|
41 | 42 | from functools import wraps |
|
42 | 43 | |
|
43 | 44 | #----------------------------------------------------------------------------- |
|
44 | 45 | # Globals |
|
45 | 46 | #----------------------------------------------------------------------------- |
|
46 | 47 | |
|
47 | 48 | # Public API |
|
48 | 49 | __all__ = ['Completer','IPCompleter'] |
|
49 | 50 | |
|
50 | 51 | if sys.platform == 'win32': |
|
51 | 52 | PROTECTABLES = ' ' |
|
52 | 53 | else: |
|
53 | 54 | PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&' |
|
54 | 55 | |
|
55 | 56 | |
|
56 | 57 | #----------------------------------------------------------------------------- |
|
57 | 58 | # Work around BUG decorators. |
|
58 | 59 | #----------------------------------------------------------------------------- |
|
59 | 60 | |
|
60 | 61 | def _strip_single_trailing_space(complete): |
|
61 | 62 | """ |
|
62 | 63 | This is a workaround for a weird IPython/Prompt_toolkit behavior, |
|
63 | 64 | that can be removed once we rely on a slightly more recent prompt_toolkit |
|
64 | 65 | version (likely > 1.0.3). So this can likely be removed in IPython 6.0 |
|
65 | 66 | |
|
66 | 67 | cf https://github.com/ipython/ipython/issues/9658 |
|
67 | 68 | and https://github.com/jonathanslenders/python-prompt-toolkit/pull/328 |
|
68 | 69 | |
|
69 | 70 | The bug is due to the fact that in PTK the completer will reinvoke itself |
|
70 | 71 | after trying to completer to the longuest common prefix of all the |
|
71 | 72 | completions, unless only one completion is available. |
|
72 | 73 | |
|
73 | 74 | This logic is faulty if the completion ends with space, which can happen in |
|
74 | 75 | case like:: |
|
75 | 76 | |
|
76 | 77 | from foo import im<ta> |
|
77 | 78 | |
|
78 | 79 | which only matching completion is `import `. Note the leading space at the |
|
79 | 80 | end. So leaving a space at the end is a reasonable request, but for now |
|
80 | 81 | we'll strip it. |
|
81 | 82 | """ |
|
82 | 83 | |
|
83 | 84 | @wraps(complete) |
|
84 | 85 | def comp(*args, **kwargs): |
|
85 | 86 | text, matches = complete(*args, **kwargs) |
|
86 | 87 | if len(matches) == 1: |
|
87 | 88 | return text, [matches[0].rstrip()] |
|
88 | 89 | return text, matches |
|
89 | 90 | |
|
90 | 91 | return comp |
|
91 | 92 | |
|
92 | 93 | |
|
93 | 94 | |
|
94 | 95 | #----------------------------------------------------------------------------- |
|
95 | 96 | # Main functions and classes |
|
96 | 97 | #----------------------------------------------------------------------------- |
|
97 | 98 | |
|
98 | 99 | def has_open_quotes(s): |
|
99 | 100 | """Return whether a string has open quotes. |
|
100 | 101 | |
|
101 | 102 | This simply counts whether the number of quote characters of either type in |
|
102 | 103 | the string is odd. |
|
103 | 104 | |
|
104 | 105 | Returns |
|
105 | 106 | ------- |
|
106 | 107 | If there is an open quote, the quote character is returned. Else, return |
|
107 | 108 | False. |
|
108 | 109 | """ |
|
109 | 110 | # We check " first, then ', so complex cases with nested quotes will get |
|
110 | 111 | # the " to take precedence. |
|
111 | 112 | if s.count('"') % 2: |
|
112 | 113 | return '"' |
|
113 | 114 | elif s.count("'") % 2: |
|
114 | 115 | return "'" |
|
115 | 116 | else: |
|
116 | 117 | return False |
|
117 | 118 | |
|
118 | 119 | |
|
119 | 120 | def protect_filename(s): |
|
120 | 121 | """Escape a string to protect certain characters.""" |
|
121 | 122 | if set(s) & set(PROTECTABLES): |
|
122 | 123 | if sys.platform == "win32": |
|
123 | 124 | return '"' + s + '"' |
|
124 | 125 | else: |
|
125 | 126 | return "".join(("\\" + c if c in PROTECTABLES else c) for c in s) |
|
126 | 127 | else: |
|
127 | 128 | return s |
|
128 | 129 | |
|
129 | 130 | |
|
130 | 131 | def expand_user(path): |
|
131 | 132 | """Expand '~'-style usernames in strings. |
|
132 | 133 | |
|
133 | 134 | This is similar to :func:`os.path.expanduser`, but it computes and returns |
|
134 | 135 | extra information that will be useful if the input was being used in |
|
135 | 136 | computing completions, and you wish to return the completions with the |
|
136 | 137 | original '~' instead of its expanded value. |
|
137 | 138 | |
|
138 | 139 | Parameters |
|
139 | 140 | ---------- |
|
140 | 141 | path : str |
|
141 | 142 | String to be expanded. If no ~ is present, the output is the same as the |
|
142 | 143 | input. |
|
143 | 144 | |
|
144 | 145 | Returns |
|
145 | 146 | ------- |
|
146 | 147 | newpath : str |
|
147 | 148 | Result of ~ expansion in the input path. |
|
148 | 149 | tilde_expand : bool |
|
149 | 150 | Whether any expansion was performed or not. |
|
150 | 151 | tilde_val : str |
|
151 | 152 | The value that ~ was replaced with. |
|
152 | 153 | """ |
|
153 | 154 | # Default values |
|
154 | 155 | tilde_expand = False |
|
155 | 156 | tilde_val = '' |
|
156 | 157 | newpath = path |
|
157 | 158 | |
|
158 | 159 | if path.startswith('~'): |
|
159 | 160 | tilde_expand = True |
|
160 | 161 | rest = len(path)-1 |
|
161 | 162 | newpath = os.path.expanduser(path) |
|
162 | 163 | if rest: |
|
163 | 164 | tilde_val = newpath[:-rest] |
|
164 | 165 | else: |
|
165 | 166 | tilde_val = newpath |
|
166 | 167 | |
|
167 | 168 | return newpath, tilde_expand, tilde_val |
|
168 | 169 | |
|
169 | 170 | |
|
170 | 171 | def compress_user(path, tilde_expand, tilde_val): |
|
171 | 172 | """Does the opposite of expand_user, with its outputs. |
|
172 | 173 | """ |
|
173 | 174 | if tilde_expand: |
|
174 | 175 | return path.replace(tilde_val, '~') |
|
175 | 176 | else: |
|
176 | 177 | return path |
|
177 | 178 | |
|
178 | 179 | |
|
179 | 180 | def completions_sorting_key(word): |
|
180 | 181 | """key for sorting completions |
|
181 | 182 | |
|
182 | 183 | This does several things: |
|
183 | 184 | |
|
184 | 185 | - Lowercase all completions, so they are sorted alphabetically with |
|
185 | 186 | upper and lower case words mingled |
|
186 | 187 | - Demote any completions starting with underscores to the end |
|
187 | 188 | - Insert any %magic and %%cellmagic completions in the alphabetical order |
|
188 | 189 | by their name |
|
189 | 190 | """ |
|
190 | 191 | # Case insensitive sort |
|
191 | 192 | word = word.lower() |
|
192 | 193 | |
|
193 | 194 | prio1, prio2 = 0, 0 |
|
194 | 195 | |
|
195 | 196 | if word.startswith('__'): |
|
196 | 197 | prio1 = 2 |
|
197 | 198 | elif word.startswith('_'): |
|
198 | 199 | prio1 = 1 |
|
199 | 200 | |
|
200 | 201 | if word.endswith('='): |
|
201 | 202 | prio1 = -1 |
|
202 | 203 | |
|
203 | 204 | if word.startswith('%%'): |
|
204 | 205 | # If there's another % in there, this is something else, so leave it alone |
|
205 | 206 | if not "%" in word[2:]: |
|
206 | 207 | word = word[2:] |
|
207 | 208 | prio2 = 2 |
|
208 | 209 | elif word.startswith('%'): |
|
209 | 210 | if not "%" in word[1:]: |
|
210 | 211 | word = word[1:] |
|
211 | 212 | prio2 = 1 |
|
212 | 213 | |
|
213 | 214 | return prio1, word, prio2 |
|
214 | 215 | |
|
215 | 216 | |
|
216 | 217 | @undoc |
|
217 | 218 | class Bunch(object): pass |
|
218 | 219 | |
|
219 | 220 | |
|
220 | 221 | if sys.platform == 'win32': |
|
221 | 222 | DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?' |
|
222 | 223 | else: |
|
223 | 224 | DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?' |
|
224 | 225 | |
|
225 | 226 | GREEDY_DELIMS = ' =\r\n' |
|
226 | 227 | |
|
227 | 228 | |
|
228 | 229 | class CompletionSplitter(object): |
|
229 | 230 | """An object to split an input line in a manner similar to readline. |
|
230 | 231 | |
|
231 | 232 | By having our own implementation, we can expose readline-like completion in |
|
232 | 233 | a uniform manner to all frontends. This object only needs to be given the |
|
233 | 234 | line of text to be split and the cursor position on said line, and it |
|
234 | 235 | returns the 'word' to be completed on at the cursor after splitting the |
|
235 | 236 | entire line. |
|
236 | 237 | |
|
237 | 238 | What characters are used as splitting delimiters can be controlled by |
|
238 | 239 | setting the `delims` attribute (this is a property that internally |
|
239 | 240 | automatically builds the necessary regular expression)""" |
|
240 | 241 | |
|
241 | 242 | # Private interface |
|
242 | 243 | |
|
243 | 244 | # A string of delimiter characters. The default value makes sense for |
|
244 | 245 | # IPython's most typical usage patterns. |
|
245 | 246 | _delims = DELIMS |
|
246 | 247 | |
|
247 | 248 | # The expression (a normal string) to be compiled into a regular expression |
|
248 | 249 | # for actual splitting. We store it as an attribute mostly for ease of |
|
249 | 250 | # debugging, since this type of code can be so tricky to debug. |
|
250 | 251 | _delim_expr = None |
|
251 | 252 | |
|
252 | 253 | # The regular expression that does the actual splitting |
|
253 | 254 | _delim_re = None |
|
254 | 255 | |
|
255 | 256 | def __init__(self, delims=None): |
|
256 | 257 | delims = CompletionSplitter._delims if delims is None else delims |
|
257 | 258 | self.delims = delims |
|
258 | 259 | |
|
259 | 260 | @property |
|
260 | 261 | def delims(self): |
|
261 | 262 | """Return the string of delimiter characters.""" |
|
262 | 263 | return self._delims |
|
263 | 264 | |
|
264 | 265 | @delims.setter |
|
265 | 266 | def delims(self, delims): |
|
266 | 267 | """Set the delimiters for line splitting.""" |
|
267 | 268 | expr = '[' + ''.join('\\'+ c for c in delims) + ']' |
|
268 | 269 | self._delim_re = re.compile(expr) |
|
269 | 270 | self._delims = delims |
|
270 | 271 | self._delim_expr = expr |
|
271 | 272 | |
|
272 | 273 | def split_line(self, line, cursor_pos=None): |
|
273 | 274 | """Split a line of text with a cursor at the given position. |
|
274 | 275 | """ |
|
275 | 276 | l = line if cursor_pos is None else line[:cursor_pos] |
|
276 | 277 | return self._delim_re.split(l)[-1] |
|
277 | 278 | |
|
278 | 279 | |
|
279 | 280 | class Completer(Configurable): |
|
280 | 281 | |
|
281 | 282 | greedy = Bool(False, |
|
282 | 283 | help="""Activate greedy completion |
|
283 | 284 | PENDING DEPRECTION. this is now mostly taken care of with Jedi. |
|
284 | 285 | |
|
285 | 286 | This will enable completion on elements of lists, results of function calls, etc., |
|
286 | 287 | but can be unsafe because the code is actually evaluated on TAB. |
|
287 | 288 | """ |
|
288 | 289 | ).tag(config=True) |
|
289 | 290 | |
|
290 | 291 | |
|
291 | 292 | def __init__(self, namespace=None, global_namespace=None, **kwargs): |
|
292 | 293 | """Create a new completer for the command line. |
|
293 | 294 | |
|
294 | 295 | Completer(namespace=ns, global_namespace=ns2) -> completer instance. |
|
295 | 296 | |
|
296 | 297 | If unspecified, the default namespace where completions are performed |
|
297 | 298 | is __main__ (technically, __main__.__dict__). Namespaces should be |
|
298 | 299 | given as dictionaries. |
|
299 | 300 | |
|
300 | 301 | An optional second namespace can be given. This allows the completer |
|
301 | 302 | to handle cases where both the local and global scopes need to be |
|
302 | 303 | distinguished. |
|
303 | 304 | |
|
304 | 305 | Completer instances should be used as the completion mechanism of |
|
305 | 306 | readline via the set_completer() call: |
|
306 | 307 | |
|
307 | 308 | readline.set_completer(Completer(my_namespace).complete) |
|
308 | 309 | """ |
|
309 | 310 | |
|
310 | 311 | # Don't bind to namespace quite yet, but flag whether the user wants a |
|
311 | 312 | # specific namespace or to use __main__.__dict__. This will allow us |
|
312 | 313 | # to bind to __main__.__dict__ at completion time, not now. |
|
313 | 314 | if namespace is None: |
|
314 | 315 | self.use_main_ns = 1 |
|
315 | 316 | else: |
|
316 | 317 | self.use_main_ns = 0 |
|
317 | 318 | self.namespace = namespace |
|
318 | 319 | |
|
319 | 320 | # The global namespace, if given, can be bound directly |
|
320 | 321 | if global_namespace is None: |
|
321 | 322 | self.global_namespace = {} |
|
322 | 323 | else: |
|
323 | 324 | self.global_namespace = global_namespace |
|
324 | 325 | |
|
325 | 326 | super(Completer, self).__init__(**kwargs) |
|
326 | 327 | |
|
327 | 328 | def complete(self, text, state): |
|
328 | 329 | """Return the next possible completion for 'text'. |
|
329 | 330 | |
|
330 | 331 | This is called successively with state == 0, 1, 2, ... until it |
|
331 | 332 | returns None. The completion should begin with 'text'. |
|
332 | 333 | |
|
333 | 334 | """ |
|
334 | 335 | if self.use_main_ns: |
|
335 | 336 | self.namespace = __main__.__dict__ |
|
336 | 337 | |
|
337 | 338 | if state == 0: |
|
338 | 339 | if "." in text: |
|
339 | 340 | self.matches = self.attr_matches(text) |
|
340 | 341 | else: |
|
341 | 342 | self.matches = self.global_matches(text) |
|
342 | 343 | try: |
|
343 | 344 | return self.matches[state] |
|
344 | 345 | except IndexError: |
|
345 | 346 | return None |
|
346 | 347 | |
|
347 | 348 | def global_matches(self, text): |
|
348 | 349 | """Compute matches when text is a simple name. |
|
349 | 350 | |
|
350 | 351 | Return a list of all keywords, built-in functions and names currently |
|
351 | 352 | defined in self.namespace or self.global_namespace that match. |
|
352 | 353 | |
|
353 | 354 | """ |
|
354 | 355 | matches = [] |
|
355 | 356 | match_append = matches.append |
|
356 | 357 | n = len(text) |
|
357 | 358 | for lst in [keyword.kwlist, |
|
358 | 359 | builtin_mod.__dict__.keys(), |
|
359 | 360 | self.namespace.keys(), |
|
360 | 361 | self.global_namespace.keys()]: |
|
361 | 362 | for word in lst: |
|
362 | 363 | if word[:n] == text and word != "__builtins__": |
|
363 | 364 | match_append(word) |
|
364 | 365 | return [cast_unicode_py2(m) for m in matches] |
|
365 | 366 | |
|
366 | 367 | def attr_matches(self, text): |
|
367 | 368 | """Compute matches when text contains a dot. |
|
368 | 369 | |
|
369 | 370 | Assuming the text is of the form NAME.NAME....[NAME], and is |
|
370 | 371 | evaluatable in self.namespace or self.global_namespace, it will be |
|
371 | 372 | evaluated and its attributes (as revealed by dir()) are used as |
|
372 | 373 | possible completions. (For class instances, class members are are |
|
373 | 374 | also considered.) |
|
374 | 375 | |
|
375 | 376 | WARNING: this can still invoke arbitrary C code, if an object |
|
376 | 377 | with a __getattr__ hook is evaluated. |
|
377 | 378 | |
|
378 | 379 | """ |
|
379 | 380 | |
|
380 | 381 | # Another option, seems to work great. Catches things like ''.<tab> |
|
381 | 382 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) |
|
382 | 383 | |
|
383 | 384 | if m: |
|
384 | 385 | expr, attr = m.group(1, 3) |
|
385 | 386 | elif self.greedy: |
|
386 | 387 | m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer) |
|
387 | 388 | if not m2: |
|
388 | 389 | return [] |
|
389 | 390 | expr, attr = m2.group(1,2) |
|
390 | 391 | else: |
|
391 | 392 | return [] |
|
392 | 393 | |
|
393 | 394 | try: |
|
394 | 395 | obj = eval(expr, self.namespace) |
|
395 | 396 | except: |
|
396 | 397 | try: |
|
397 | 398 | obj = eval(expr, self.global_namespace) |
|
398 | 399 | except: |
|
399 | 400 | return [] |
|
400 | 401 | |
|
401 | 402 | if self.limit_to__all__ and hasattr(obj, '__all__'): |
|
402 | 403 | words = get__all__entries(obj) |
|
403 | 404 | else: |
|
404 | 405 | words = dir2(obj) |
|
405 | 406 | |
|
406 | 407 | try: |
|
407 | 408 | words = generics.complete_object(obj, words) |
|
408 | 409 | except TryNext: |
|
409 | 410 | pass |
|
410 | 411 | except Exception: |
|
411 | 412 | # Silence errors from completion function |
|
412 | 413 | #raise # dbg |
|
413 | 414 | pass |
|
414 | 415 | # Build match list to return |
|
415 | 416 | n = len(attr) |
|
416 | 417 | return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ] |
|
417 | 418 | |
|
418 | 419 | |
|
419 | 420 | def get__all__entries(obj): |
|
420 | 421 | """returns the strings in the __all__ attribute""" |
|
421 | 422 | try: |
|
422 | 423 | words = getattr(obj, '__all__') |
|
423 | 424 | except: |
|
424 | 425 | return [] |
|
425 | 426 | |
|
426 | 427 | return [cast_unicode_py2(w) for w in words if isinstance(w, str)] |
|
427 | 428 | |
|
428 | 429 | |
|
429 | 430 | def match_dict_keys(keys, prefix, delims): |
|
430 | 431 | """Used by dict_key_matches, matching the prefix to a list of keys""" |
|
431 | 432 | if not prefix: |
|
432 | 433 | return None, 0, [repr(k) for k in keys |
|
433 | 434 | if isinstance(k, (str, bytes))] |
|
434 | 435 | quote_match = re.search('["\']', prefix) |
|
435 | 436 | quote = quote_match.group() |
|
436 | 437 | try: |
|
437 | 438 | prefix_str = eval(prefix + quote, {}) |
|
438 | 439 | except Exception: |
|
439 | 440 | return None, 0, [] |
|
440 | 441 | |
|
441 | 442 | pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$' |
|
442 | 443 | token_match = re.search(pattern, prefix, re.UNICODE) |
|
443 | 444 | token_start = token_match.start() |
|
444 | 445 | token_prefix = token_match.group() |
|
445 | 446 | |
|
446 | 447 | # TODO: support bytes in Py3k |
|
447 | 448 | matched = [] |
|
448 | 449 | for key in keys: |
|
449 | 450 | try: |
|
450 | 451 | if not key.startswith(prefix_str): |
|
451 | 452 | continue |
|
452 | 453 | except (AttributeError, TypeError, UnicodeError): |
|
453 | 454 | # Python 3+ TypeError on b'a'.startswith('a') or vice-versa |
|
454 | 455 | continue |
|
455 | 456 | |
|
456 | 457 | # reformat remainder of key to begin with prefix |
|
457 | 458 | rem = key[len(prefix_str):] |
|
458 | 459 | # force repr wrapped in ' |
|
459 | 460 | rem_repr = repr(rem + '"') |
|
460 | 461 | if rem_repr.startswith('u') and prefix[0] not in 'uU': |
|
461 | 462 | # Found key is unicode, but prefix is Py2 string. |
|
462 | 463 | # Therefore attempt to interpret key as string. |
|
463 | 464 | try: |
|
464 | 465 | rem_repr = repr(rem.encode('ascii') + '"') |
|
465 | 466 | except UnicodeEncodeError: |
|
466 | 467 | continue |
|
467 | 468 | |
|
468 | 469 | rem_repr = rem_repr[1 + rem_repr.index("'"):-2] |
|
469 | 470 | if quote == '"': |
|
470 | 471 | # The entered prefix is quoted with ", |
|
471 | 472 | # but the match is quoted with '. |
|
472 | 473 | # A contained " hence needs escaping for comparison: |
|
473 | 474 | rem_repr = rem_repr.replace('"', '\\"') |
|
474 | 475 | |
|
475 | 476 | # then reinsert prefix from start of token |
|
476 | 477 | matched.append('%s%s' % (token_prefix, rem_repr)) |
|
477 | 478 | return quote, token_start, matched |
|
478 | 479 | |
|
479 | 480 | |
|
480 | 481 | def _safe_isinstance(obj, module, class_name): |
|
481 | 482 | """Checks if obj is an instance of module.class_name if loaded |
|
482 | 483 | """ |
|
483 | 484 | return (module in sys.modules and |
|
484 | 485 | isinstance(obj, getattr(import_module(module), class_name))) |
|
485 | 486 | |
|
486 | 487 | |
|
487 | 488 | def back_unicode_name_matches(text): |
|
488 | 489 | u"""Match unicode characters back to unicode name |
|
489 | 490 | |
|
490 | 491 | This does β -> \\snowman |
|
491 | 492 | |
|
492 | 493 | Note that snowman is not a valid python3 combining character but will be expanded. |
|
493 | 494 | Though it will not recombine back to the snowman character by the completion machinery. |
|
494 | 495 | |
|
495 | 496 | This will not either back-complete standard sequences like \\n, \\b ... |
|
496 | 497 | |
|
497 | 498 | Used on Python 3 only. |
|
498 | 499 | """ |
|
499 | 500 | if len(text)<2: |
|
500 | 501 | return u'', () |
|
501 | 502 | maybe_slash = text[-2] |
|
502 | 503 | if maybe_slash != '\\': |
|
503 | 504 | return u'', () |
|
504 | 505 | |
|
505 | 506 | char = text[-1] |
|
506 | 507 | # no expand on quote for completion in strings. |
|
507 | 508 | # nor backcomplete standard ascii keys |
|
508 | 509 | if char in string.ascii_letters or char in ['"',"'"]: |
|
509 | 510 | return u'', () |
|
510 | 511 | try : |
|
511 | 512 | unic = unicodedata.name(char) |
|
512 | 513 | return '\\'+char,['\\'+unic] |
|
513 | 514 | except KeyError: |
|
514 | 515 | pass |
|
515 | 516 | return u'', () |
|
516 | 517 | |
|
517 | 518 | def back_latex_name_matches(text): |
|
518 | 519 | u"""Match latex characters back to unicode name |
|
519 | 520 | |
|
520 | 521 | This does ->\\sqrt |
|
521 | 522 | |
|
522 | 523 | Used on Python 3 only. |
|
523 | 524 | """ |
|
524 | 525 | if len(text)<2: |
|
525 | 526 | return u'', () |
|
526 | 527 | maybe_slash = text[-2] |
|
527 | 528 | if maybe_slash != '\\': |
|
528 | 529 | return u'', () |
|
529 | 530 | |
|
530 | 531 | |
|
531 | 532 | char = text[-1] |
|
532 | 533 | # no expand on quote for completion in strings. |
|
533 | 534 | # nor backcomplete standard ascii keys |
|
534 | 535 | if char in string.ascii_letters or char in ['"',"'"]: |
|
535 | 536 | return u'', () |
|
536 | 537 | try : |
|
537 | 538 | latex = reverse_latex_symbol[char] |
|
538 | 539 | # '\\' replace the \ as well |
|
539 | 540 | return '\\'+char,[latex] |
|
540 | 541 | except KeyError: |
|
541 | 542 | pass |
|
542 | 543 | return u'', () |
|
543 | 544 | |
|
544 | 545 | |
|
545 | 546 | class IPCompleter(Completer): |
|
546 | 547 | """Extension of the completer class with IPython-specific features""" |
|
547 | 548 | |
|
548 | 549 | @observe('greedy') |
|
549 | 550 | def _greedy_changed(self, change): |
|
550 | 551 | """update the splitter and readline delims when greedy is changed""" |
|
551 | 552 | if change['new']: |
|
552 | 553 | self.splitter.delims = GREEDY_DELIMS |
|
553 | 554 | else: |
|
554 | 555 | self.splitter.delims = DELIMS |
|
555 | 556 | |
|
556 | 557 | merge_completions = Bool(True, |
|
557 | 558 | help="""Whether to merge completion results into a single list |
|
558 | 559 | |
|
559 | 560 | If False, only the completion results from the first non-empty |
|
560 | 561 | completer will be returned. |
|
561 | 562 | """ |
|
562 | 563 | ).tag(config=True) |
|
563 | 564 | omit__names = Enum((0,1,2), default_value=2, |
|
564 | 565 | help="""Instruct the completer to omit private method names |
|
565 | 566 | |
|
566 | 567 | Specifically, when completing on ``object.<tab>``. |
|
567 | 568 | |
|
568 | 569 | When 2 [default]: all names that start with '_' will be excluded. |
|
569 | 570 | |
|
570 | 571 | When 1: all 'magic' names (``__foo__``) will be excluded. |
|
571 | 572 | |
|
572 | 573 | When 0: nothing will be excluded. |
|
573 | 574 | """ |
|
574 | 575 | ).tag(config=True) |
|
575 | 576 | limit_to__all__ = Bool(False, |
|
576 | 577 | help=""" |
|
577 | 578 | DEPRECATED as of version 5.0. |
|
578 | 579 | |
|
579 | 580 | Instruct the completer to use __all__ for the completion |
|
580 | 581 | |
|
581 | 582 | Specifically, when completing on ``object.<tab>``. |
|
582 | 583 | |
|
583 | 584 | When True: only those names in obj.__all__ will be included. |
|
584 | 585 | |
|
585 | 586 | When False [default]: the __all__ attribute is ignored |
|
586 | 587 | """, |
|
587 | 588 | ).tag(config=True) |
|
588 | 589 | |
|
589 | 590 | def __init__(self, shell=None, namespace=None, global_namespace=None, |
|
590 | 591 | use_readline=False, config=None, **kwargs): |
|
591 | 592 | """IPCompleter() -> completer |
|
592 | 593 | |
|
593 | 594 | Return a completer object suitable for use by the readline library |
|
594 | 595 | via readline.set_completer(). |
|
595 | 596 | |
|
596 | 597 | Inputs: |
|
597 | 598 | |
|
598 | 599 | - shell: a pointer to the ipython shell itself. This is needed |
|
599 | 600 | because this completer knows about magic functions, and those can |
|
600 | 601 | only be accessed via the ipython instance. |
|
601 | 602 | |
|
602 | 603 | - namespace: an optional dict where completions are performed. |
|
603 | 604 | |
|
604 | 605 | - global_namespace: secondary optional dict for completions, to |
|
605 | 606 | handle cases (such as IPython embedded inside functions) where |
|
606 | 607 | both Python scopes are visible. |
|
607 | 608 | |
|
608 | 609 | use_readline : bool, optional |
|
609 | 610 | DEPRECATED, ignored. |
|
610 | 611 | """ |
|
611 | 612 | |
|
612 | 613 | self.magic_escape = ESC_MAGIC |
|
613 | 614 | self.splitter = CompletionSplitter() |
|
614 | 615 | |
|
615 | 616 | if use_readline: |
|
616 | 617 | warnings.warn('The use_readline parameter is deprecated and ignored since IPython 6.0.', |
|
617 | 618 | DeprecationWarning, stacklevel=2) |
|
618 | 619 | |
|
619 | 620 | # _greedy_changed() depends on splitter and readline being defined: |
|
620 | 621 | Completer.__init__(self, namespace=namespace, global_namespace=global_namespace, |
|
621 | 622 | config=config, **kwargs) |
|
622 | 623 | |
|
623 | 624 | # List where completion matches will be stored |
|
624 | 625 | self.matches = [] |
|
625 | 626 | self.shell = shell |
|
626 | 627 | # Regexp to split filenames with spaces in them |
|
627 | 628 | self.space_name_re = re.compile(r'([^\\] )') |
|
628 | 629 | # Hold a local ref. to glob.glob for speed |
|
629 | 630 | self.glob = glob.glob |
|
630 | 631 | |
|
631 | 632 | # Determine if we are running on 'dumb' terminals, like (X)Emacs |
|
632 | 633 | # buffers, to avoid completion problems. |
|
633 | 634 | term = os.environ.get('TERM','xterm') |
|
634 | 635 | self.dumb_terminal = term in ['dumb','emacs'] |
|
635 | 636 | |
|
636 | 637 | # Special handling of backslashes needed in win32 platforms |
|
637 | 638 | if sys.platform == "win32": |
|
638 | 639 | self.clean_glob = self._clean_glob_win32 |
|
639 | 640 | else: |
|
640 | 641 | self.clean_glob = self._clean_glob |
|
641 | 642 | |
|
642 | 643 | #regexp to parse docstring for function signature |
|
643 | 644 | self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') |
|
644 | 645 | self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') |
|
645 | 646 | #use this if positional argument name is also needed |
|
646 | 647 | #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)') |
|
647 | 648 | |
|
648 | 649 | # All active matcher routines for completion |
|
649 | 650 | self.matchers = [ |
|
650 | 651 | self.python_matches, |
|
651 | 652 | self.file_matches, |
|
652 | 653 | self.magic_matches, |
|
653 | 654 | self.python_func_kw_matches, |
|
654 | 655 | self.dict_key_matches, |
|
655 | 656 | ] |
|
656 | 657 | |
|
657 | 658 | # This is set externally by InteractiveShell |
|
658 | 659 | self.custom_completers = None |
|
659 | 660 | |
|
660 | 661 | def all_completions(self, text): |
|
661 | 662 | """ |
|
662 | 663 | Wrapper around the complete method for the benefit of emacs. |
|
663 | 664 | """ |
|
664 | 665 | return self.complete(text)[1] |
|
665 | 666 | |
|
666 | 667 | def _clean_glob(self, text): |
|
667 | 668 | return self.glob("%s*" % text) |
|
668 | 669 | |
|
669 | 670 | def _clean_glob_win32(self,text): |
|
670 | 671 | return [f.replace("\\","/") |
|
671 | 672 | for f in self.glob("%s*" % text)] |
|
672 | 673 | |
|
673 | 674 | def file_matches(self, text): |
|
674 | 675 | """Match filenames, expanding ~USER type strings. |
|
675 | 676 | |
|
676 | 677 | Most of the seemingly convoluted logic in this completer is an |
|
677 | 678 | attempt to handle filenames with spaces in them. And yet it's not |
|
678 | 679 | quite perfect, because Python's readline doesn't expose all of the |
|
679 | 680 | GNU readline details needed for this to be done correctly. |
|
680 | 681 | |
|
681 | 682 | For a filename with a space in it, the printed completions will be |
|
682 | 683 | only the parts after what's already been typed (instead of the |
|
683 | 684 | full completions, as is normally done). I don't think with the |
|
684 | 685 | current (as of Python 2.3) Python readline it's possible to do |
|
685 | 686 | better.""" |
|
686 | 687 | |
|
687 | 688 | # chars that require escaping with backslash - i.e. chars |
|
688 | 689 | # that readline treats incorrectly as delimiters, but we |
|
689 | 690 | # don't want to treat as delimiters in filename matching |
|
690 | 691 | # when escaped with backslash |
|
691 | 692 | if text.startswith('!'): |
|
692 | 693 | text = text[1:] |
|
693 | 694 | text_prefix = u'!' |
|
694 | 695 | else: |
|
695 | 696 | text_prefix = u'' |
|
696 | 697 | |
|
697 | 698 | text_until_cursor = self.text_until_cursor |
|
698 | 699 | # track strings with open quotes |
|
699 | 700 | open_quotes = has_open_quotes(text_until_cursor) |
|
700 | 701 | |
|
701 | 702 | if '(' in text_until_cursor or '[' in text_until_cursor: |
|
702 | 703 | lsplit = text |
|
703 | 704 | else: |
|
704 | 705 | try: |
|
705 | 706 | # arg_split ~ shlex.split, but with unicode bugs fixed by us |
|
706 | 707 | lsplit = arg_split(text_until_cursor)[-1] |
|
707 | 708 | except ValueError: |
|
708 | 709 | # typically an unmatched ", or backslash without escaped char. |
|
709 | 710 | if open_quotes: |
|
710 | 711 | lsplit = text_until_cursor.split(open_quotes)[-1] |
|
711 | 712 | else: |
|
712 | 713 | return [] |
|
713 | 714 | except IndexError: |
|
714 | 715 | # tab pressed on empty line |
|
715 | 716 | lsplit = "" |
|
716 | 717 | |
|
717 | 718 | if not open_quotes and lsplit != protect_filename(lsplit): |
|
718 | 719 | # if protectables are found, do matching on the whole escaped name |
|
719 | 720 | has_protectables = True |
|
720 | 721 | text0,text = text,lsplit |
|
721 | 722 | else: |
|
722 | 723 | has_protectables = False |
|
723 | 724 | text = os.path.expanduser(text) |
|
724 | 725 | |
|
725 | 726 | if text == "": |
|
726 | 727 | return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")] |
|
727 | 728 | |
|
728 | 729 | # Compute the matches from the filesystem |
|
729 | 730 | if sys.platform == 'win32': |
|
730 | 731 | m0 = self.clean_glob(text) |
|
731 | 732 | else: |
|
732 | 733 | m0 = self.clean_glob(text.replace('\\', '')) |
|
733 | 734 | |
|
734 | 735 | if has_protectables: |
|
735 | 736 | # If we had protectables, we need to revert our changes to the |
|
736 | 737 | # beginning of filename so that we don't double-write the part |
|
737 | 738 | # of the filename we have so far |
|
738 | 739 | len_lsplit = len(lsplit) |
|
739 | 740 | matches = [text_prefix + text0 + |
|
740 | 741 | protect_filename(f[len_lsplit:]) for f in m0] |
|
741 | 742 | else: |
|
742 | 743 | if open_quotes: |
|
743 | 744 | # if we have a string with an open quote, we don't need to |
|
744 | 745 | # protect the names at all (and we _shouldn't_, as it |
|
745 | 746 | # would cause bugs when the filesystem call is made). |
|
746 | 747 | matches = m0 |
|
747 | 748 | else: |
|
748 | 749 | matches = [text_prefix + |
|
749 | 750 | protect_filename(f) for f in m0] |
|
750 | 751 | |
|
751 | 752 | # Mark directories in input list by appending '/' to their names. |
|
752 | 753 | return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches] |
|
753 | 754 | |
|
754 | 755 | def magic_matches(self, text): |
|
755 | 756 | """Match magics""" |
|
756 | 757 | # Get all shell magics now rather than statically, so magics loaded at |
|
757 | 758 | # runtime show up too. |
|
758 | 759 | lsm = self.shell.magics_manager.lsmagic() |
|
759 | 760 | line_magics = lsm['line'] |
|
760 | 761 | cell_magics = lsm['cell'] |
|
761 | 762 | pre = self.magic_escape |
|
762 | 763 | pre2 = pre+pre |
|
763 | 764 | |
|
764 | 765 | # Completion logic: |
|
765 | 766 | # - user gives %%: only do cell magics |
|
766 | 767 | # - user gives %: do both line and cell magics |
|
767 | 768 | # - no prefix: do both |
|
768 | 769 | # In other words, line magics are skipped if the user gives %% explicitly |
|
769 | 770 | bare_text = text.lstrip(pre) |
|
770 | 771 | comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)] |
|
771 | 772 | if not text.startswith(pre2): |
|
772 | 773 | comp += [ pre+m for m in line_magics if m.startswith(bare_text)] |
|
773 | 774 | return [cast_unicode_py2(c) for c in comp] |
|
774 | 775 | |
|
775 | 776 | |
|
776 | 777 | def python_matches(self, text): |
|
777 | 778 | """Match attributes or global python names""" |
|
778 | 779 | if "." in text: |
|
779 | 780 | try: |
|
780 | 781 | matches = self.attr_matches(text) |
|
781 | 782 | if text.endswith('.') and self.omit__names: |
|
782 | 783 | if self.omit__names == 1: |
|
783 | 784 | # true if txt is _not_ a __ name, false otherwise: |
|
784 | 785 | no__name = (lambda txt: |
|
785 | 786 | re.match(r'.*\.__.*?__',txt) is None) |
|
786 | 787 | else: |
|
787 | 788 | # true if txt is _not_ a _ name, false otherwise: |
|
788 | 789 | no__name = (lambda txt: |
|
789 | 790 | re.match(r'\._.*?',txt[txt.rindex('.'):]) is None) |
|
790 | 791 | matches = filter(no__name, matches) |
|
791 | 792 | except NameError: |
|
792 | 793 | # catches <undefined attributes>.<tab> |
|
793 | 794 | matches = [] |
|
794 | 795 | else: |
|
795 | 796 | matches = self.global_matches(text) |
|
796 | 797 | return matches |
|
797 | 798 | |
|
798 | 799 | def _default_arguments_from_docstring(self, doc): |
|
799 | 800 | """Parse the first line of docstring for call signature. |
|
800 | 801 | |
|
801 | 802 | Docstring should be of the form 'min(iterable[, key=func])\n'. |
|
802 | 803 | It can also parse cython docstring of the form |
|
803 | 804 | 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'. |
|
804 | 805 | """ |
|
805 | 806 | if doc is None: |
|
806 | 807 | return [] |
|
807 | 808 | |
|
808 | 809 | #care only the firstline |
|
809 | 810 | line = doc.lstrip().splitlines()[0] |
|
810 | 811 | |
|
811 | 812 | #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') |
|
812 | 813 | #'min(iterable[, key=func])\n' -> 'iterable[, key=func]' |
|
813 | 814 | sig = self.docstring_sig_re.search(line) |
|
814 | 815 | if sig is None: |
|
815 | 816 | return [] |
|
816 | 817 | # iterable[, key=func]' -> ['iterable[' ,' key=func]'] |
|
817 | 818 | sig = sig.groups()[0].split(',') |
|
818 | 819 | ret = [] |
|
819 | 820 | for s in sig: |
|
820 | 821 | #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') |
|
821 | 822 | ret += self.docstring_kwd_re.findall(s) |
|
822 | 823 | return ret |
|
823 | 824 | |
|
824 | 825 | def _default_arguments(self, obj): |
|
825 | 826 | """Return the list of default arguments of obj if it is callable, |
|
826 | 827 | or empty list otherwise.""" |
|
827 | 828 | call_obj = obj |
|
828 | 829 | ret = [] |
|
829 | 830 | if inspect.isbuiltin(obj): |
|
830 | 831 | pass |
|
831 | 832 | elif not (inspect.isfunction(obj) or inspect.ismethod(obj)): |
|
832 | 833 | if inspect.isclass(obj): |
|
833 | 834 | #for cython embededsignature=True the constructor docstring |
|
834 | 835 | #belongs to the object itself not __init__ |
|
835 | 836 | ret += self._default_arguments_from_docstring( |
|
836 | 837 | getattr(obj, '__doc__', '')) |
|
837 | 838 | # for classes, check for __init__,__new__ |
|
838 | 839 | call_obj = (getattr(obj, '__init__', None) or |
|
839 | 840 | getattr(obj, '__new__', None)) |
|
840 | 841 | # for all others, check if they are __call__able |
|
841 | 842 | elif hasattr(obj, '__call__'): |
|
842 | 843 | call_obj = obj.__call__ |
|
843 | 844 | ret += self._default_arguments_from_docstring( |
|
844 | 845 | getattr(call_obj, '__doc__', '')) |
|
845 | 846 | |
|
846 | 847 | _keeps = (inspect.Parameter.KEYWORD_ONLY, |
|
847 | 848 | inspect.Parameter.POSITIONAL_OR_KEYWORD) |
|
848 | 849 | |
|
849 | 850 | try: |
|
850 | 851 | sig = inspect.signature(call_obj) |
|
851 | 852 | ret.extend(k for k, v in sig.parameters.items() if |
|
852 | 853 | v.kind in _keeps) |
|
853 | 854 | except ValueError: |
|
854 | 855 | pass |
|
855 | 856 | |
|
856 | 857 | return list(set(ret)) |
|
857 | 858 | |
|
858 | 859 | def python_func_kw_matches(self,text): |
|
859 | 860 | """Match named parameters (kwargs) of the last open function""" |
|
860 | 861 | |
|
861 | 862 | if "." in text: # a parameter cannot be dotted |
|
862 | 863 | return [] |
|
863 | 864 | try: regexp = self.__funcParamsRegex |
|
864 | 865 | except AttributeError: |
|
865 | 866 | regexp = self.__funcParamsRegex = re.compile(r''' |
|
866 | 867 | '.*?(?<!\\)' | # single quoted strings or |
|
867 | 868 | ".*?(?<!\\)" | # double quoted strings or |
|
868 | 869 | \w+ | # identifier |
|
869 | 870 | \S # other characters |
|
870 | 871 | ''', re.VERBOSE | re.DOTALL) |
|
871 | 872 | # 1. find the nearest identifier that comes before an unclosed |
|
872 | 873 | # parenthesis before the cursor |
|
873 | 874 | # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo" |
|
874 | 875 | tokens = regexp.findall(self.text_until_cursor) |
|
875 | 876 | iterTokens = reversed(tokens); openPar = 0 |
|
876 | 877 | |
|
877 | 878 | for token in iterTokens: |
|
878 | 879 | if token == ')': |
|
879 | 880 | openPar -= 1 |
|
880 | 881 | elif token == '(': |
|
881 | 882 | openPar += 1 |
|
882 | 883 | if openPar > 0: |
|
883 | 884 | # found the last unclosed parenthesis |
|
884 | 885 | break |
|
885 | 886 | else: |
|
886 | 887 | return [] |
|
887 | 888 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) |
|
888 | 889 | ids = [] |
|
889 | 890 | isId = re.compile(r'\w+$').match |
|
890 | 891 | |
|
891 | 892 | while True: |
|
892 | 893 | try: |
|
893 | 894 | ids.append(next(iterTokens)) |
|
894 | 895 | if not isId(ids[-1]): |
|
895 | 896 | ids.pop(); break |
|
896 | 897 | if not next(iterTokens) == '.': |
|
897 | 898 | break |
|
898 | 899 | except StopIteration: |
|
899 | 900 | break |
|
900 | 901 | |
|
901 | 902 | # Find all named arguments already assigned to, as to avoid suggesting |
|
902 | 903 | # them again |
|
903 | 904 | usedNamedArgs = set() |
|
904 | 905 | par_level = -1 |
|
905 | 906 | for token, next_token in zip(tokens, tokens[1:]): |
|
906 | 907 | if token == '(': |
|
907 | 908 | par_level += 1 |
|
908 | 909 | elif token == ')': |
|
909 | 910 | par_level -= 1 |
|
910 | 911 | |
|
911 | 912 | if par_level != 0: |
|
912 | 913 | continue |
|
913 | 914 | |
|
914 | 915 | if next_token != '=': |
|
915 | 916 | continue |
|
916 | 917 | |
|
917 | 918 | usedNamedArgs.add(token) |
|
918 | 919 | |
|
919 | 920 | # lookup the candidate callable matches either using global_matches |
|
920 | 921 | # or attr_matches for dotted names |
|
921 | 922 | if len(ids) == 1: |
|
922 | 923 | callableMatches = self.global_matches(ids[0]) |
|
923 | 924 | else: |
|
924 | 925 | callableMatches = self.attr_matches('.'.join(ids[::-1])) |
|
925 | 926 | argMatches = [] |
|
926 | 927 | for callableMatch in callableMatches: |
|
927 | 928 | try: |
|
928 | 929 | namedArgs = self._default_arguments(eval(callableMatch, |
|
929 | 930 | self.namespace)) |
|
930 | 931 | except: |
|
931 | 932 | continue |
|
932 | 933 | |
|
933 | 934 | # Remove used named arguments from the list, no need to show twice |
|
934 | 935 | for namedArg in set(namedArgs) - usedNamedArgs: |
|
935 | 936 | if namedArg.startswith(text): |
|
936 | 937 | argMatches.append(u"%s=" %namedArg) |
|
937 | 938 | return argMatches |
|
938 | 939 | |
|
939 | 940 | def dict_key_matches(self, text): |
|
940 | 941 | "Match string keys in a dictionary, after e.g. 'foo[' " |
|
941 | 942 | def get_keys(obj): |
|
942 | 943 | # Objects can define their own completions by defining an |
|
943 | 944 | # _ipy_key_completions_() method. |
|
944 | 945 | method = get_real_method(obj, '_ipython_key_completions_') |
|
945 | 946 | if method is not None: |
|
946 | 947 | return method() |
|
947 | 948 | |
|
948 | 949 | # Special case some common in-memory dict-like types |
|
949 | 950 | if isinstance(obj, dict) or\ |
|
950 | 951 | _safe_isinstance(obj, 'pandas', 'DataFrame'): |
|
951 | 952 | try: |
|
952 | 953 | return list(obj.keys()) |
|
953 | 954 | except Exception: |
|
954 | 955 | return [] |
|
955 | 956 | elif _safe_isinstance(obj, 'numpy', 'ndarray') or\ |
|
956 | 957 | _safe_isinstance(obj, 'numpy', 'void'): |
|
957 | 958 | return obj.dtype.names or [] |
|
958 | 959 | return [] |
|
959 | 960 | |
|
960 | 961 | try: |
|
961 | 962 | regexps = self.__dict_key_regexps |
|
962 | 963 | except AttributeError: |
|
963 | 964 | dict_key_re_fmt = r'''(?x) |
|
964 | 965 | ( # match dict-referring expression wrt greedy setting |
|
965 | 966 | %s |
|
966 | 967 | ) |
|
967 | 968 | \[ # open bracket |
|
968 | 969 | \s* # and optional whitespace |
|
969 | 970 | ([uUbB]? # string prefix (r not handled) |
|
970 | 971 | (?: # unclosed string |
|
971 | 972 | '(?:[^']|(?<!\\)\\')* |
|
972 | 973 | | |
|
973 | 974 | "(?:[^"]|(?<!\\)\\")* |
|
974 | 975 | ) |
|
975 | 976 | )? |
|
976 | 977 | $ |
|
977 | 978 | ''' |
|
978 | 979 | regexps = self.__dict_key_regexps = { |
|
979 | 980 | False: re.compile(dict_key_re_fmt % ''' |
|
980 | 981 | # identifiers separated by . |
|
981 | 982 | (?!\d)\w+ |
|
982 | 983 | (?:\.(?!\d)\w+)* |
|
983 | 984 | '''), |
|
984 | 985 | True: re.compile(dict_key_re_fmt % ''' |
|
985 | 986 | .+ |
|
986 | 987 | ''') |
|
987 | 988 | } |
|
988 | 989 | |
|
989 | 990 | match = regexps[self.greedy].search(self.text_until_cursor) |
|
990 | 991 | if match is None: |
|
991 | 992 | return [] |
|
992 | 993 | |
|
993 | 994 | expr, prefix = match.groups() |
|
994 | 995 | try: |
|
995 | 996 | obj = eval(expr, self.namespace) |
|
996 | 997 | except Exception: |
|
997 | 998 | try: |
|
998 | 999 | obj = eval(expr, self.global_namespace) |
|
999 | 1000 | except Exception: |
|
1000 | 1001 | return [] |
|
1001 | 1002 | |
|
1002 | 1003 | keys = get_keys(obj) |
|
1003 | 1004 | if not keys: |
|
1004 | 1005 | return keys |
|
1005 | 1006 | closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims) |
|
1006 | 1007 | if not matches: |
|
1007 | 1008 | return matches |
|
1008 | 1009 | |
|
1009 | 1010 | # get the cursor position of |
|
1010 | 1011 | # - the text being completed |
|
1011 | 1012 | # - the start of the key text |
|
1012 | 1013 | # - the start of the completion |
|
1013 | 1014 | text_start = len(self.text_until_cursor) - len(text) |
|
1014 | 1015 | if prefix: |
|
1015 | 1016 | key_start = match.start(2) |
|
1016 | 1017 | completion_start = key_start + token_offset |
|
1017 | 1018 | else: |
|
1018 | 1019 | key_start = completion_start = match.end() |
|
1019 | 1020 | |
|
1020 | 1021 | # grab the leading prefix, to make sure all completions start with `text` |
|
1021 | 1022 | if text_start > key_start: |
|
1022 | 1023 | leading = '' |
|
1023 | 1024 | else: |
|
1024 | 1025 | leading = text[text_start:completion_start] |
|
1025 | 1026 | |
|
1026 | 1027 | # the index of the `[` character |
|
1027 | 1028 | bracket_idx = match.end(1) |
|
1028 | 1029 | |
|
1029 | 1030 | # append closing quote and bracket as appropriate |
|
1030 | 1031 | # this is *not* appropriate if the opening quote or bracket is outside |
|
1031 | 1032 | # the text given to this method |
|
1032 | 1033 | suf = '' |
|
1033 | 1034 | continuation = self.line_buffer[len(self.text_until_cursor):] |
|
1034 | 1035 | if key_start > text_start and closing_quote: |
|
1035 | 1036 | # quotes were opened inside text, maybe close them |
|
1036 | 1037 | if continuation.startswith(closing_quote): |
|
1037 | 1038 | continuation = continuation[len(closing_quote):] |
|
1038 | 1039 | else: |
|
1039 | 1040 | suf += closing_quote |
|
1040 | 1041 | if bracket_idx > text_start: |
|
1041 | 1042 | # brackets were opened inside text, maybe close them |
|
1042 | 1043 | if not continuation.startswith(']'): |
|
1043 | 1044 | suf += ']' |
|
1044 | 1045 | |
|
1045 | 1046 | return [leading + k + suf for k in matches] |
|
1046 | 1047 | |
|
1047 | 1048 | def unicode_name_matches(self, text): |
|
1048 | 1049 | u"""Match Latex-like syntax for unicode characters base |
|
1049 | 1050 | on the name of the character. |
|
1050 | 1051 | |
|
1051 | 1052 | This does \\GREEK SMALL LETTER ETA -> Ξ· |
|
1052 | 1053 | |
|
1053 | 1054 | Works only on valid python 3 identifier, or on combining characters that |
|
1054 | 1055 | will combine to form a valid identifier. |
|
1055 | 1056 | |
|
1056 | 1057 | Used on Python 3 only. |
|
1057 | 1058 | """ |
|
1058 | 1059 | slashpos = text.rfind('\\') |
|
1059 | 1060 | if slashpos > -1: |
|
1060 | 1061 | s = text[slashpos+1:] |
|
1061 | 1062 | try : |
|
1062 | 1063 | unic = unicodedata.lookup(s) |
|
1063 | 1064 | # allow combining chars |
|
1064 | 1065 | if ('a'+unic).isidentifier(): |
|
1065 | 1066 | return '\\'+s,[unic] |
|
1066 | 1067 | except KeyError: |
|
1067 | 1068 | pass |
|
1068 | 1069 | return u'', [] |
|
1069 | 1070 | |
|
1070 | 1071 | |
|
1071 | 1072 | |
|
1072 | 1073 | |
|
1073 | 1074 | def latex_matches(self, text): |
|
1074 | 1075 | u"""Match Latex syntax for unicode characters. |
|
1075 | 1076 | |
|
1076 | 1077 | This does both \\alp -> \\alpha and \\alpha -> Ξ± |
|
1077 | 1078 | |
|
1078 | 1079 | Used on Python 3 only. |
|
1079 | 1080 | """ |
|
1080 | 1081 | slashpos = text.rfind('\\') |
|
1081 | 1082 | if slashpos > -1: |
|
1082 | 1083 | s = text[slashpos:] |
|
1083 | 1084 | if s in latex_symbols: |
|
1084 | 1085 | # Try to complete a full latex symbol to unicode |
|
1085 | 1086 | # \\alpha -> Ξ± |
|
1086 | 1087 | return s, [latex_symbols[s]] |
|
1087 | 1088 | else: |
|
1088 | 1089 | # If a user has partially typed a latex symbol, give them |
|
1089 | 1090 | # a full list of options \al -> [\aleph, \alpha] |
|
1090 | 1091 | matches = [k for k in latex_symbols if k.startswith(s)] |
|
1091 | 1092 | return s, matches |
|
1092 | 1093 | return u'', [] |
|
1093 | 1094 | |
|
1094 | 1095 | def dispatch_custom_completer(self, text): |
|
1095 | 1096 | if not self.custom_completers: |
|
1096 | 1097 | return |
|
1097 | 1098 | |
|
1098 | 1099 | line = self.line_buffer |
|
1099 | 1100 | if not line.strip(): |
|
1100 | 1101 | return None |
|
1101 | 1102 | |
|
1102 | 1103 | # Create a little structure to pass all the relevant information about |
|
1103 | 1104 | # the current completion to any custom completer. |
|
1104 | 1105 | event = Bunch() |
|
1105 | 1106 | event.line = line |
|
1106 | 1107 | event.symbol = text |
|
1107 | 1108 | cmd = line.split(None,1)[0] |
|
1108 | 1109 | event.command = cmd |
|
1109 | 1110 | event.text_until_cursor = self.text_until_cursor |
|
1110 | 1111 | |
|
1111 | 1112 | # for foo etc, try also to find completer for %foo |
|
1112 | 1113 | if not cmd.startswith(self.magic_escape): |
|
1113 | 1114 | try_magic = self.custom_completers.s_matches( |
|
1114 | 1115 | self.magic_escape + cmd) |
|
1115 | 1116 | else: |
|
1116 | 1117 | try_magic = [] |
|
1117 | 1118 | |
|
1118 | 1119 | for c in itertools.chain(self.custom_completers.s_matches(cmd), |
|
1119 | 1120 | try_magic, |
|
1120 | 1121 | self.custom_completers.flat_matches(self.text_until_cursor)): |
|
1121 | 1122 | try: |
|
1122 | 1123 | res = c(event) |
|
1123 | 1124 | if res: |
|
1124 | 1125 | # first, try case sensitive match |
|
1125 | 1126 | withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)] |
|
1126 | 1127 | if withcase: |
|
1127 | 1128 | return withcase |
|
1128 | 1129 | # if none, then case insensitive ones are ok too |
|
1129 | 1130 | text_low = text.lower() |
|
1130 | 1131 | return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)] |
|
1131 | 1132 | except TryNext: |
|
1132 | 1133 | pass |
|
1133 | 1134 | |
|
1134 | 1135 | return None |
|
1135 | 1136 | |
|
1136 | 1137 | @_strip_single_trailing_space |
|
1137 | 1138 | def complete(self, text=None, line_buffer=None, cursor_pos=None): |
|
1138 | 1139 | """Find completions for the given text and line context. |
|
1139 | 1140 | |
|
1140 | 1141 | Note that both the text and the line_buffer are optional, but at least |
|
1141 | 1142 | one of them must be given. |
|
1142 | 1143 | |
|
1143 | 1144 | Parameters |
|
1144 | 1145 | ---------- |
|
1145 | 1146 | text : string, optional |
|
1146 | 1147 | Text to perform the completion on. If not given, the line buffer |
|
1147 | 1148 | is split using the instance's CompletionSplitter object. |
|
1148 | 1149 | |
|
1149 | 1150 | line_buffer : string, optional |
|
1150 | 1151 | If not given, the completer attempts to obtain the current line |
|
1151 | 1152 | buffer via readline. This keyword allows clients which are |
|
1152 | 1153 | requesting for text completions in non-readline contexts to inform |
|
1153 | 1154 | the completer of the entire text. |
|
1154 | 1155 | |
|
1155 | 1156 | cursor_pos : int, optional |
|
1156 | 1157 | Index of the cursor in the full line buffer. Should be provided by |
|
1157 | 1158 | remote frontends where kernel has no access to frontend state. |
|
1158 | 1159 | |
|
1159 | 1160 | Returns |
|
1160 | 1161 | ------- |
|
1161 | 1162 | text : str |
|
1162 | 1163 | Text that was actually used in the completion. |
|
1163 | 1164 | |
|
1164 | 1165 | matches : list |
|
1165 | 1166 | A list of completion matches. |
|
1166 | 1167 | """ |
|
1167 | 1168 | # if the cursor position isn't given, the only sane assumption we can |
|
1168 | 1169 | # make is that it's at the end of the line (the common case) |
|
1169 | 1170 | if cursor_pos is None: |
|
1170 | 1171 | cursor_pos = len(line_buffer) if text is None else len(text) |
|
1171 | 1172 | |
|
1172 | 1173 | if self.use_main_ns: |
|
1173 | 1174 | self.namespace = __main__.__dict__ |
|
1174 | 1175 | |
|
1175 | 1176 | base_text = text if not line_buffer else line_buffer[:cursor_pos] |
|
1176 | 1177 | latex_text, latex_matches = self.latex_matches(base_text) |
|
1177 | 1178 | if latex_matches: |
|
1178 | 1179 | return latex_text, latex_matches |
|
1179 | 1180 | name_text = '' |
|
1180 | 1181 | name_matches = [] |
|
1181 | 1182 | for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches): |
|
1182 | 1183 | name_text, name_matches = meth(base_text) |
|
1183 | 1184 | if name_text: |
|
1184 | 1185 | return name_text, name_matches |
|
1185 | 1186 | |
|
1186 | 1187 | # if text is either None or an empty string, rely on the line buffer |
|
1187 | 1188 | if not text: |
|
1188 | 1189 | text = self.splitter.split_line(line_buffer, cursor_pos) |
|
1189 | 1190 | |
|
1190 | 1191 | # If no line buffer is given, assume the input text is all there was |
|
1191 | 1192 | if line_buffer is None: |
|
1192 | 1193 | line_buffer = text |
|
1193 | 1194 | |
|
1194 | 1195 | self.line_buffer = line_buffer |
|
1195 | 1196 | self.text_until_cursor = self.line_buffer[:cursor_pos] |
|
1196 | 1197 | |
|
1197 | 1198 | # Start with a clean slate of completions |
|
1198 | 1199 | self.matches[:] = [] |
|
1199 | 1200 | custom_res = self.dispatch_custom_completer(text) |
|
1200 | 1201 | if custom_res is not None: |
|
1201 | 1202 | # did custom completers produce something? |
|
1202 | 1203 | self.matches = custom_res |
|
1203 | 1204 | else: |
|
1204 | 1205 | # Extend the list of completions with the results of each |
|
1205 | 1206 | # matcher, so we return results to the user from all |
|
1206 | 1207 | # namespaces. |
|
1207 | 1208 | if self.merge_completions: |
|
1208 | 1209 | self.matches = [] |
|
1209 | 1210 | for matcher in self.matchers: |
|
1210 | 1211 | try: |
|
1211 | 1212 | self.matches.extend(matcher(text)) |
|
1212 | 1213 | except: |
|
1213 | 1214 | # Show the ugly traceback if the matcher causes an |
|
1214 | 1215 | # exception, but do NOT crash the kernel! |
|
1215 | 1216 | sys.excepthook(*sys.exc_info()) |
|
1216 | 1217 | else: |
|
1217 | 1218 | for matcher in self.matchers: |
|
1218 | 1219 | self.matches = matcher(text) |
|
1219 | 1220 | if self.matches: |
|
1220 | 1221 | break |
|
1221 | 1222 | # FIXME: we should extend our api to return a dict with completions for |
|
1222 | 1223 | # different types of objects. The rlcomplete() method could then |
|
1223 | 1224 | # simply collapse the dict into a list for readline, but we'd have |
|
1224 | 1225 | # richer completion semantics in other evironments. |
|
1225 | 1226 | self.matches = sorted(set(self.matches), key=completions_sorting_key) |
|
1226 | 1227 | |
|
1227 | 1228 | return text, self.matches |
@@ -1,321 +1,321 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Displayhook for IPython. |
|
3 | 3 | |
|
4 | 4 | This defines a callable class that IPython uses for `sys.displayhook`. |
|
5 | 5 | """ |
|
6 | 6 | |
|
7 | 7 | # Copyright (c) IPython Development Team. |
|
8 | 8 | # Distributed under the terms of the Modified BSD License. |
|
9 | 9 | |
|
10 | ||
|
10 | import builtins as builtin_mod | |
|
11 | 11 | import sys |
|
12 | 12 | import io as _io |
|
13 | 13 | import tokenize |
|
14 | 14 | |
|
15 | 15 | from traitlets.config.configurable import Configurable |
|
16 |
from IPython.utils.py3compat import |
|
|
16 | from IPython.utils.py3compat import cast_unicode_py2 | |
|
17 | 17 | from traitlets import Instance, Float |
|
18 | 18 | from warnings import warn |
|
19 | 19 | |
|
20 | 20 | # TODO: Move the various attributes (cache_size, [others now moved]). Some |
|
21 | 21 | # of these are also attributes of InteractiveShell. They should be on ONE object |
|
22 | 22 | # only and the other objects should ask that one object for their values. |
|
23 | 23 | |
|
24 | 24 | class DisplayHook(Configurable): |
|
25 | 25 | """The custom IPython displayhook to replace sys.displayhook. |
|
26 | 26 | |
|
27 | 27 | This class does many things, but the basic idea is that it is a callable |
|
28 | 28 | that gets called anytime user code returns a value. |
|
29 | 29 | """ |
|
30 | 30 | |
|
31 | 31 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', |
|
32 | 32 | allow_none=True) |
|
33 | 33 | exec_result = Instance('IPython.core.interactiveshell.ExecutionResult', |
|
34 | 34 | allow_none=True) |
|
35 | 35 | cull_fraction = Float(0.2) |
|
36 | 36 | |
|
37 | 37 | def __init__(self, shell=None, cache_size=1000, **kwargs): |
|
38 | 38 | super(DisplayHook, self).__init__(shell=shell, **kwargs) |
|
39 | 39 | cache_size_min = 3 |
|
40 | 40 | if cache_size <= 0: |
|
41 | 41 | self.do_full_cache = 0 |
|
42 | 42 | cache_size = 0 |
|
43 | 43 | elif cache_size < cache_size_min: |
|
44 | 44 | self.do_full_cache = 0 |
|
45 | 45 | cache_size = 0 |
|
46 | 46 | warn('caching was disabled (min value for cache size is %s).' % |
|
47 | 47 | cache_size_min,stacklevel=3) |
|
48 | 48 | else: |
|
49 | 49 | self.do_full_cache = 1 |
|
50 | 50 | |
|
51 | 51 | self.cache_size = cache_size |
|
52 | 52 | |
|
53 | 53 | # we need a reference to the user-level namespace |
|
54 | 54 | self.shell = shell |
|
55 | 55 | |
|
56 | 56 | self._,self.__,self.___ = '','','' |
|
57 | 57 | |
|
58 | 58 | # these are deliberately global: |
|
59 | 59 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} |
|
60 | 60 | self.shell.user_ns.update(to_user_ns) |
|
61 | 61 | |
|
62 | 62 | @property |
|
63 | 63 | def prompt_count(self): |
|
64 | 64 | return self.shell.execution_count |
|
65 | 65 | |
|
66 | 66 | #------------------------------------------------------------------------- |
|
67 | 67 | # Methods used in __call__. Override these methods to modify the behavior |
|
68 | 68 | # of the displayhook. |
|
69 | 69 | #------------------------------------------------------------------------- |
|
70 | 70 | |
|
71 | 71 | def check_for_underscore(self): |
|
72 | 72 | """Check if the user has set the '_' variable by hand.""" |
|
73 | 73 | # If something injected a '_' variable in __builtin__, delete |
|
74 | 74 | # ipython's automatic one so we don't clobber that. gettext() in |
|
75 | 75 | # particular uses _, so we need to stay away from it. |
|
76 | 76 | if '_' in builtin_mod.__dict__: |
|
77 | 77 | try: |
|
78 | 78 | user_value = self.shell.user_ns['_'] |
|
79 | 79 | if user_value is not self._: |
|
80 | 80 | return |
|
81 | 81 | del self.shell.user_ns['_'] |
|
82 | 82 | except KeyError: |
|
83 | 83 | pass |
|
84 | 84 | |
|
85 | 85 | def quiet(self): |
|
86 | 86 | """Should we silence the display hook because of ';'?""" |
|
87 | 87 | # do not print output if input ends in ';' |
|
88 | 88 | |
|
89 | 89 | try: |
|
90 | 90 | cell = cast_unicode_py2(self.shell.history_manager.input_hist_parsed[-1]) |
|
91 | 91 | except IndexError: |
|
92 | 92 | # some uses of ipshellembed may fail here |
|
93 | 93 | return False |
|
94 | 94 | |
|
95 | 95 | sio = _io.StringIO(cell) |
|
96 | 96 | tokens = list(tokenize.generate_tokens(sio.readline)) |
|
97 | 97 | |
|
98 | 98 | for token in reversed(tokens): |
|
99 | 99 | if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT): |
|
100 | 100 | continue |
|
101 | 101 | if (token[0] == tokenize.OP) and (token[1] == ';'): |
|
102 | 102 | return True |
|
103 | 103 | else: |
|
104 | 104 | return False |
|
105 | 105 | |
|
106 | 106 | def start_displayhook(self): |
|
107 | 107 | """Start the displayhook, initializing resources.""" |
|
108 | 108 | pass |
|
109 | 109 | |
|
110 | 110 | def write_output_prompt(self): |
|
111 | 111 | """Write the output prompt. |
|
112 | 112 | |
|
113 | 113 | The default implementation simply writes the prompt to |
|
114 | 114 | ``sys.stdout``. |
|
115 | 115 | """ |
|
116 | 116 | # Use write, not print which adds an extra space. |
|
117 | 117 | sys.stdout.write(self.shell.separate_out) |
|
118 | 118 | outprompt = 'Out[{}]: '.format(self.shell.execution_count) |
|
119 | 119 | if self.do_full_cache: |
|
120 | 120 | sys.stdout.write(outprompt) |
|
121 | 121 | |
|
122 | 122 | def compute_format_data(self, result): |
|
123 | 123 | """Compute format data of the object to be displayed. |
|
124 | 124 | |
|
125 | 125 | The format data is a generalization of the :func:`repr` of an object. |
|
126 | 126 | In the default implementation the format data is a :class:`dict` of |
|
127 | 127 | key value pair where the keys are valid MIME types and the values |
|
128 | 128 | are JSON'able data structure containing the raw data for that MIME |
|
129 | 129 | type. It is up to frontends to determine pick a MIME to to use and |
|
130 | 130 | display that data in an appropriate manner. |
|
131 | 131 | |
|
132 | 132 | This method only computes the format data for the object and should |
|
133 | 133 | NOT actually print or write that to a stream. |
|
134 | 134 | |
|
135 | 135 | Parameters |
|
136 | 136 | ---------- |
|
137 | 137 | result : object |
|
138 | 138 | The Python object passed to the display hook, whose format will be |
|
139 | 139 | computed. |
|
140 | 140 | |
|
141 | 141 | Returns |
|
142 | 142 | ------- |
|
143 | 143 | (format_dict, md_dict) : dict |
|
144 | 144 | format_dict is a :class:`dict` whose keys are valid MIME types and values are |
|
145 | 145 | JSON'able raw data for that MIME type. It is recommended that |
|
146 | 146 | all return values of this should always include the "text/plain" |
|
147 | 147 | MIME type representation of the object. |
|
148 | 148 | md_dict is a :class:`dict` with the same MIME type keys |
|
149 | 149 | of metadata associated with each output. |
|
150 | 150 | |
|
151 | 151 | """ |
|
152 | 152 | return self.shell.display_formatter.format(result) |
|
153 | 153 | |
|
154 | 154 | # This can be set to True by the write_output_prompt method in a subclass |
|
155 | 155 | prompt_end_newline = False |
|
156 | 156 | |
|
157 | 157 | def write_format_data(self, format_dict, md_dict=None): |
|
158 | 158 | """Write the format data dict to the frontend. |
|
159 | 159 | |
|
160 | 160 | This default version of this method simply writes the plain text |
|
161 | 161 | representation of the object to ``sys.stdout``. Subclasses should |
|
162 | 162 | override this method to send the entire `format_dict` to the |
|
163 | 163 | frontends. |
|
164 | 164 | |
|
165 | 165 | Parameters |
|
166 | 166 | ---------- |
|
167 | 167 | format_dict : dict |
|
168 | 168 | The format dict for the object passed to `sys.displayhook`. |
|
169 | 169 | md_dict : dict (optional) |
|
170 | 170 | The metadata dict to be associated with the display data. |
|
171 | 171 | """ |
|
172 | 172 | if 'text/plain' not in format_dict: |
|
173 | 173 | # nothing to do |
|
174 | 174 | return |
|
175 | 175 | # We want to print because we want to always make sure we have a |
|
176 | 176 | # newline, even if all the prompt separators are ''. This is the |
|
177 | 177 | # standard IPython behavior. |
|
178 | 178 | result_repr = format_dict['text/plain'] |
|
179 | 179 | if '\n' in result_repr: |
|
180 | 180 | # So that multi-line strings line up with the left column of |
|
181 | 181 | # the screen, instead of having the output prompt mess up |
|
182 | 182 | # their first line. |
|
183 | 183 | # We use the prompt template instead of the expanded prompt |
|
184 | 184 | # because the expansion may add ANSI escapes that will interfere |
|
185 | 185 | # with our ability to determine whether or not we should add |
|
186 | 186 | # a newline. |
|
187 | 187 | if not self.prompt_end_newline: |
|
188 | 188 | # But avoid extraneous empty lines. |
|
189 | 189 | result_repr = '\n' + result_repr |
|
190 | 190 | |
|
191 | 191 | print(result_repr) |
|
192 | 192 | |
|
193 | 193 | def update_user_ns(self, result): |
|
194 | 194 | """Update user_ns with various things like _, __, _1, etc.""" |
|
195 | 195 | |
|
196 | 196 | # Avoid recursive reference when displaying _oh/Out |
|
197 | 197 | if result is not self.shell.user_ns['_oh']: |
|
198 | 198 | if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: |
|
199 | 199 | self.cull_cache() |
|
200 | 200 | |
|
201 | 201 | # Don't overwrite '_' and friends if '_' is in __builtin__ |
|
202 | 202 | # (otherwise we cause buggy behavior for things like gettext). and |
|
203 | 203 | # do not overwrite _, __ or ___ if one of these has been assigned |
|
204 | 204 | # by the user. |
|
205 | 205 | update_unders = True |
|
206 | 206 | for unders in ['_'*i for i in range(1,4)]: |
|
207 | 207 | if not unders in self.shell.user_ns: |
|
208 | 208 | continue |
|
209 | 209 | if getattr(self, unders) is not self.shell.user_ns.get(unders): |
|
210 | 210 | update_unders = False |
|
211 | 211 | |
|
212 | 212 | self.___ = self.__ |
|
213 | 213 | self.__ = self._ |
|
214 | 214 | self._ = result |
|
215 | 215 | |
|
216 | 216 | if ('_' not in builtin_mod.__dict__) and (update_unders): |
|
217 | 217 | self.shell.push({'_':self._, |
|
218 | 218 | '__':self.__, |
|
219 | 219 | '___':self.___}, interactive=False) |
|
220 | 220 | |
|
221 | 221 | # hackish access to top-level namespace to create _1,_2... dynamically |
|
222 | 222 | to_main = {} |
|
223 | 223 | if self.do_full_cache: |
|
224 | 224 | new_result = '_%s' % self.prompt_count |
|
225 | 225 | to_main[new_result] = result |
|
226 | 226 | self.shell.push(to_main, interactive=False) |
|
227 | 227 | self.shell.user_ns['_oh'][self.prompt_count] = result |
|
228 | 228 | |
|
229 | 229 | def fill_exec_result(self, result): |
|
230 | 230 | if self.exec_result is not None: |
|
231 | 231 | self.exec_result.result = result |
|
232 | 232 | |
|
233 | 233 | def log_output(self, format_dict): |
|
234 | 234 | """Log the output.""" |
|
235 | 235 | if 'text/plain' not in format_dict: |
|
236 | 236 | # nothing to do |
|
237 | 237 | return |
|
238 | 238 | if self.shell.logger.log_output: |
|
239 | 239 | self.shell.logger.log_write(format_dict['text/plain'], 'output') |
|
240 | 240 | self.shell.history_manager.output_hist_reprs[self.prompt_count] = \ |
|
241 | 241 | format_dict['text/plain'] |
|
242 | 242 | |
|
243 | 243 | def finish_displayhook(self): |
|
244 | 244 | """Finish up all displayhook activities.""" |
|
245 | 245 | sys.stdout.write(self.shell.separate_out2) |
|
246 | 246 | sys.stdout.flush() |
|
247 | 247 | |
|
248 | 248 | def __call__(self, result=None): |
|
249 | 249 | """Printing with history cache management. |
|
250 | 250 | |
|
251 | 251 | This is invoked everytime the interpreter needs to print, and is |
|
252 | 252 | activated by setting the variable sys.displayhook to it. |
|
253 | 253 | """ |
|
254 | 254 | self.check_for_underscore() |
|
255 | 255 | if result is not None and not self.quiet(): |
|
256 | 256 | self.start_displayhook() |
|
257 | 257 | self.write_output_prompt() |
|
258 | 258 | format_dict, md_dict = self.compute_format_data(result) |
|
259 | 259 | self.update_user_ns(result) |
|
260 | 260 | self.fill_exec_result(result) |
|
261 | 261 | if format_dict: |
|
262 | 262 | self.write_format_data(format_dict, md_dict) |
|
263 | 263 | self.log_output(format_dict) |
|
264 | 264 | self.finish_displayhook() |
|
265 | 265 | |
|
266 | 266 | def cull_cache(self): |
|
267 | 267 | """Output cache is full, cull the oldest entries""" |
|
268 | 268 | oh = self.shell.user_ns.get('_oh', {}) |
|
269 | 269 | sz = len(oh) |
|
270 | 270 | cull_count = max(int(sz * self.cull_fraction), 2) |
|
271 | 271 | warn('Output cache limit (currently {sz} entries) hit.\n' |
|
272 | 272 | 'Flushing oldest {cull_count} entries.'.format(sz=sz, cull_count=cull_count)) |
|
273 | 273 | |
|
274 | 274 | for i, n in enumerate(sorted(oh)): |
|
275 | 275 | if i >= cull_count: |
|
276 | 276 | break |
|
277 | 277 | self.shell.user_ns.pop('_%i' % n, None) |
|
278 | 278 | oh.pop(n, None) |
|
279 | 279 | |
|
280 | 280 | |
|
281 | 281 | def flush(self): |
|
282 | 282 | if not self.do_full_cache: |
|
283 | 283 | raise ValueError("You shouldn't have reached the cache flush " |
|
284 | 284 | "if full caching is not enabled!") |
|
285 | 285 | # delete auto-generated vars from global namespace |
|
286 | 286 | |
|
287 | 287 | for n in range(1,self.prompt_count + 1): |
|
288 | 288 | key = '_'+repr(n) |
|
289 | 289 | try: |
|
290 | 290 | del self.shell.user_ns[key] |
|
291 | 291 | except: pass |
|
292 | 292 | # In some embedded circumstances, the user_ns doesn't have the |
|
293 | 293 | # '_oh' key set up. |
|
294 | 294 | oh = self.shell.user_ns.get('_oh', None) |
|
295 | 295 | if oh is not None: |
|
296 | 296 | oh.clear() |
|
297 | 297 | |
|
298 | 298 | # Release our own references to objects: |
|
299 | 299 | self._, self.__, self.___ = '', '', '' |
|
300 | 300 | |
|
301 | 301 | if '_' not in builtin_mod.__dict__: |
|
302 | 302 | self.shell.user_ns.update({'_':None,'__':None, '___':None}) |
|
303 | 303 | import gc |
|
304 | 304 | # TODO: Is this really needed? |
|
305 | 305 | # IronPython blocks here forever |
|
306 | 306 | if sys.platform != "cli": |
|
307 | 307 | gc.collect() |
|
308 | 308 | |
|
309 | 309 | |
|
310 | 310 | class CapturingDisplayHook(object): |
|
311 | 311 | def __init__(self, shell, outputs=None): |
|
312 | 312 | self.shell = shell |
|
313 | 313 | if outputs is None: |
|
314 | 314 | outputs = [] |
|
315 | 315 | self.outputs = outputs |
|
316 | 316 | |
|
317 | 317 | def __call__(self, result=None): |
|
318 | 318 | if result is None: |
|
319 | 319 | return |
|
320 | 320 | format_dict, md_dict = self.shell.display_formatter.format(result) |
|
321 | 321 | self.outputs.append((format_dict, md_dict)) |
|
1 | 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 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Implementation of execution-related magic functions.""" |
|
3 | 3 | |
|
4 | 4 | # Copyright (c) IPython Development Team. |
|
5 | 5 | # Distributed under the terms of the Modified BSD License. |
|
6 | 6 | |
|
7 | 7 | |
|
8 | 8 | import ast |
|
9 | 9 | import bdb |
|
10 | import builtins as builtin_mod | |
|
10 | 11 | import gc |
|
11 | 12 | import itertools |
|
12 | 13 | import os |
|
13 | 14 | import sys |
|
14 | 15 | import time |
|
15 | 16 | import timeit |
|
16 | 17 | import math |
|
17 | 18 | from pdb import Restart |
|
18 | 19 | |
|
19 | 20 | # cProfile was added in Python2.5 |
|
20 | 21 | try: |
|
21 | 22 | import cProfile as profile |
|
22 | 23 | import pstats |
|
23 | 24 | except ImportError: |
|
24 | 25 | # profile isn't bundled by default in Debian for license reasons |
|
25 | 26 | try: |
|
26 | 27 | import profile, pstats |
|
27 | 28 | except ImportError: |
|
28 | 29 | profile = pstats = None |
|
29 | 30 | |
|
30 | 31 | from IPython.core import oinspect |
|
31 | 32 | from IPython.core import magic_arguments |
|
32 | 33 | from IPython.core import page |
|
33 | 34 | from IPython.core.error import UsageError |
|
34 | 35 | from IPython.core.macro import Macro |
|
35 | 36 | from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic, |
|
36 | 37 | line_cell_magic, on_off, needs_local_scope) |
|
37 | 38 | from IPython.testing.skipdoctest import skip_doctest |
|
38 | from IPython.utils import py3compat | |
|
39 | from IPython.utils.py3compat import builtin_mod | |
|
40 | 39 | from IPython.utils.contexts import preserve_keys |
|
41 | 40 | from IPython.utils.capture import capture_output |
|
42 | 41 | from IPython.utils.ipstruct import Struct |
|
43 | 42 | from IPython.utils.module_paths import find_mod |
|
44 | 43 | from IPython.utils.path import get_py_filename, shellglob |
|
45 | 44 | from IPython.utils.timing import clock, clock2 |
|
46 | 45 | from warnings import warn |
|
47 | 46 | from logging import error |
|
48 | 47 | from io import StringIO |
|
49 | 48 | |
|
50 | 49 | |
|
51 | 50 | #----------------------------------------------------------------------------- |
|
52 | 51 | # Magic implementation classes |
|
53 | 52 | #----------------------------------------------------------------------------- |
|
54 | 53 | |
|
55 | 54 | |
|
56 | 55 | class TimeitResult(object): |
|
57 | 56 | """ |
|
58 | 57 | Object returned by the timeit magic with info about the run. |
|
59 | 58 | |
|
60 | 59 | Contains the following attributes : |
|
61 | 60 | |
|
62 | 61 | loops: (int) number of loops done per measurement |
|
63 | 62 | repeat: (int) number of times the measurement has been repeated |
|
64 | 63 | best: (float) best execution time / number |
|
65 | 64 | all_runs: (list of float) execution time of each run (in s) |
|
66 | 65 | compile_time: (float) time of statement compilation (s) |
|
67 | 66 | |
|
68 | 67 | """ |
|
69 | 68 | def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision): |
|
70 | 69 | self.loops = loops |
|
71 | 70 | self.repeat = repeat |
|
72 | 71 | self.best = best |
|
73 | 72 | self.worst = worst |
|
74 | 73 | self.all_runs = all_runs |
|
75 | 74 | self.compile_time = compile_time |
|
76 | 75 | self._precision = precision |
|
77 | 76 | self.timings = [ dt / self.loops for dt in all_runs] |
|
78 | 77 | |
|
79 | 78 | @property |
|
80 | 79 | def average(self): |
|
81 | 80 | return math.fsum(self.timings) / len(self.timings) |
|
82 | 81 | |
|
83 | 82 | @property |
|
84 | 83 | def stdev(self): |
|
85 | 84 | mean = self.average |
|
86 | 85 | return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5 |
|
87 | 86 | |
|
88 | 87 | def __str__(self): |
|
89 | 88 | return (u"%s loop%s, average of %d: %s +- %s per loop (using standard deviation)" |
|
90 | 89 | % (self.loops,"" if self.loops == 1 else "s", self.repeat, |
|
91 | 90 | _format_time(self.average, self._precision), |
|
92 | 91 | _format_time(self.stdev, self._precision))) |
|
93 | 92 | |
|
94 | 93 | def _repr_pretty_(self, p , cycle): |
|
95 | 94 | unic = self.__str__() |
|
96 | 95 | p.text(u'<TimeitResult : '+unic+u'>') |
|
97 | 96 | |
|
98 | 97 | |
|
99 | 98 | |
|
100 | 99 | class TimeitTemplateFiller(ast.NodeTransformer): |
|
101 | 100 | """Fill in the AST template for timing execution. |
|
102 | 101 | |
|
103 | 102 | This is quite closely tied to the template definition, which is in |
|
104 | 103 | :meth:`ExecutionMagics.timeit`. |
|
105 | 104 | """ |
|
106 | 105 | def __init__(self, ast_setup, ast_stmt): |
|
107 | 106 | self.ast_setup = ast_setup |
|
108 | 107 | self.ast_stmt = ast_stmt |
|
109 | 108 | |
|
110 | 109 | def visit_FunctionDef(self, node): |
|
111 | 110 | "Fill in the setup statement" |
|
112 | 111 | self.generic_visit(node) |
|
113 | 112 | if node.name == "inner": |
|
114 | 113 | node.body[:1] = self.ast_setup.body |
|
115 | 114 | |
|
116 | 115 | return node |
|
117 | 116 | |
|
118 | 117 | def visit_For(self, node): |
|
119 | 118 | "Fill in the statement to be timed" |
|
120 | 119 | if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt': |
|
121 | 120 | node.body = self.ast_stmt.body |
|
122 | 121 | return node |
|
123 | 122 | |
|
124 | 123 | |
|
125 | 124 | class Timer(timeit.Timer): |
|
126 | 125 | """Timer class that explicitly uses self.inner |
|
127 | 126 | |
|
128 | 127 | which is an undocumented implementation detail of CPython, |
|
129 | 128 | not shared by PyPy. |
|
130 | 129 | """ |
|
131 | 130 | # Timer.timeit copied from CPython 3.4.2 |
|
132 | 131 | def timeit(self, number=timeit.default_number): |
|
133 | 132 | """Time 'number' executions of the main statement. |
|
134 | 133 | |
|
135 | 134 | To be precise, this executes the setup statement once, and |
|
136 | 135 | then returns the time it takes to execute the main statement |
|
137 | 136 | a number of times, as a float measured in seconds. The |
|
138 | 137 | argument is the number of times through the loop, defaulting |
|
139 | 138 | to one million. The main statement, the setup statement and |
|
140 | 139 | the timer function to be used are passed to the constructor. |
|
141 | 140 | """ |
|
142 | 141 | it = itertools.repeat(None, number) |
|
143 | 142 | gcold = gc.isenabled() |
|
144 | 143 | gc.disable() |
|
145 | 144 | try: |
|
146 | 145 | timing = self.inner(it, self.timer) |
|
147 | 146 | finally: |
|
148 | 147 | if gcold: |
|
149 | 148 | gc.enable() |
|
150 | 149 | return timing |
|
151 | 150 | |
|
152 | 151 | |
|
153 | 152 | @magics_class |
|
154 | 153 | class ExecutionMagics(Magics): |
|
155 | 154 | """Magics related to code execution, debugging, profiling, etc. |
|
156 | 155 | |
|
157 | 156 | """ |
|
158 | 157 | |
|
159 | 158 | def __init__(self, shell): |
|
160 | 159 | super(ExecutionMagics, self).__init__(shell) |
|
161 | 160 | if profile is None: |
|
162 | 161 | self.prun = self.profile_missing_notice |
|
163 | 162 | # Default execution function used to actually run user code. |
|
164 | 163 | self.default_runner = None |
|
165 | 164 | |
|
166 | 165 | def profile_missing_notice(self, *args, **kwargs): |
|
167 | 166 | error("""\ |
|
168 | 167 | The profile module could not be found. It has been removed from the standard |
|
169 | 168 | python packages because of its non-free license. To use profiling, install the |
|
170 | 169 | python-profiler package from non-free.""") |
|
171 | 170 | |
|
172 | 171 | @skip_doctest |
|
173 | 172 | @line_cell_magic |
|
174 | 173 | def prun(self, parameter_s='', cell=None): |
|
175 | 174 | |
|
176 | 175 | """Run a statement through the python code profiler. |
|
177 | 176 | |
|
178 | 177 | Usage, in line mode: |
|
179 | 178 | %prun [options] statement |
|
180 | 179 | |
|
181 | 180 | Usage, in cell mode: |
|
182 | 181 | %%prun [options] [statement] |
|
183 | 182 | code... |
|
184 | 183 | code... |
|
185 | 184 | |
|
186 | 185 | In cell mode, the additional code lines are appended to the (possibly |
|
187 | 186 | empty) statement in the first line. Cell mode allows you to easily |
|
188 | 187 | profile multiline blocks without having to put them in a separate |
|
189 | 188 | function. |
|
190 | 189 | |
|
191 | 190 | The given statement (which doesn't require quote marks) is run via the |
|
192 | 191 | python profiler in a manner similar to the profile.run() function. |
|
193 | 192 | Namespaces are internally managed to work correctly; profile.run |
|
194 | 193 | cannot be used in IPython because it makes certain assumptions about |
|
195 | 194 | namespaces which do not hold under IPython. |
|
196 | 195 | |
|
197 | 196 | Options: |
|
198 | 197 | |
|
199 | 198 | -l <limit> |
|
200 | 199 | you can place restrictions on what or how much of the |
|
201 | 200 | profile gets printed. The limit value can be: |
|
202 | 201 | |
|
203 | 202 | * A string: only information for function names containing this string |
|
204 | 203 | is printed. |
|
205 | 204 | |
|
206 | 205 | * An integer: only these many lines are printed. |
|
207 | 206 | |
|
208 | 207 | * A float (between 0 and 1): this fraction of the report is printed |
|
209 | 208 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
210 | 209 | |
|
211 | 210 | You can combine several limits with repeated use of the option. For |
|
212 | 211 | example, ``-l __init__ -l 5`` will print only the topmost 5 lines of |
|
213 | 212 | information about class constructors. |
|
214 | 213 | |
|
215 | 214 | -r |
|
216 | 215 | return the pstats.Stats object generated by the profiling. This |
|
217 | 216 | object has all the information about the profile in it, and you can |
|
218 | 217 | later use it for further analysis or in other functions. |
|
219 | 218 | |
|
220 | 219 | -s <key> |
|
221 | 220 | sort profile by given key. You can provide more than one key |
|
222 | 221 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
223 | 222 | default sorting key is 'time'. |
|
224 | 223 | |
|
225 | 224 | The following is copied verbatim from the profile documentation |
|
226 | 225 | referenced below: |
|
227 | 226 | |
|
228 | 227 | When more than one key is provided, additional keys are used as |
|
229 | 228 | secondary criteria when the there is equality in all keys selected |
|
230 | 229 | before them. |
|
231 | 230 | |
|
232 | 231 | Abbreviations can be used for any key names, as long as the |
|
233 | 232 | abbreviation is unambiguous. The following are the keys currently |
|
234 | 233 | defined: |
|
235 | 234 | |
|
236 | 235 | ============ ===================== |
|
237 | 236 | Valid Arg Meaning |
|
238 | 237 | ============ ===================== |
|
239 | 238 | "calls" call count |
|
240 | 239 | "cumulative" cumulative time |
|
241 | 240 | "file" file name |
|
242 | 241 | "module" file name |
|
243 | 242 | "pcalls" primitive call count |
|
244 | 243 | "line" line number |
|
245 | 244 | "name" function name |
|
246 | 245 | "nfl" name/file/line |
|
247 | 246 | "stdname" standard name |
|
248 | 247 | "time" internal time |
|
249 | 248 | ============ ===================== |
|
250 | 249 | |
|
251 | 250 | Note that all sorts on statistics are in descending order (placing |
|
252 | 251 | most time consuming items first), where as name, file, and line number |
|
253 | 252 | searches are in ascending order (i.e., alphabetical). The subtle |
|
254 | 253 | distinction between "nfl" and "stdname" is that the standard name is a |
|
255 | 254 | sort of the name as printed, which means that the embedded line |
|
256 | 255 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
257 | 256 | would (if the file names were the same) appear in the string order |
|
258 | 257 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
259 | 258 | line numbers. In fact, sort_stats("nfl") is the same as |
|
260 | 259 | sort_stats("name", "file", "line"). |
|
261 | 260 | |
|
262 | 261 | -T <filename> |
|
263 | 262 | save profile results as shown on screen to a text |
|
264 | 263 | file. The profile is still shown on screen. |
|
265 | 264 | |
|
266 | 265 | -D <filename> |
|
267 | 266 | save (via dump_stats) profile statistics to given |
|
268 | 267 | filename. This data is in a format understood by the pstats module, and |
|
269 | 268 | is generated by a call to the dump_stats() method of profile |
|
270 | 269 | objects. The profile is still shown on screen. |
|
271 | 270 | |
|
272 | 271 | -q |
|
273 | 272 | suppress output to the pager. Best used with -T and/or -D above. |
|
274 | 273 | |
|
275 | 274 | If you want to run complete programs under the profiler's control, use |
|
276 | 275 | ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts |
|
277 | 276 | contains profiler specific options as described here. |
|
278 | 277 | |
|
279 | 278 | You can read the complete documentation for the profile module with:: |
|
280 | 279 | |
|
281 | 280 | In [1]: import profile; profile.help() |
|
282 | 281 | """ |
|
283 | 282 | opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q', |
|
284 | 283 | list_all=True, posix=False) |
|
285 | 284 | if cell is not None: |
|
286 | 285 | arg_str += '\n' + cell |
|
287 | 286 | arg_str = self.shell.input_splitter.transform_cell(arg_str) |
|
288 | 287 | return self._run_with_profiler(arg_str, opts, self.shell.user_ns) |
|
289 | 288 | |
|
290 | 289 | def _run_with_profiler(self, code, opts, namespace): |
|
291 | 290 | """ |
|
292 | 291 | Run `code` with profiler. Used by ``%prun`` and ``%run -p``. |
|
293 | 292 | |
|
294 | 293 | Parameters |
|
295 | 294 | ---------- |
|
296 | 295 | code : str |
|
297 | 296 | Code to be executed. |
|
298 | 297 | opts : Struct |
|
299 | 298 | Options parsed by `self.parse_options`. |
|
300 | 299 | namespace : dict |
|
301 | 300 | A dictionary for Python namespace (e.g., `self.shell.user_ns`). |
|
302 | 301 | |
|
303 | 302 | """ |
|
304 | 303 | |
|
305 | 304 | # Fill default values for unspecified options: |
|
306 | 305 | opts.merge(Struct(D=[''], l=[], s=['time'], T=[''])) |
|
307 | 306 | |
|
308 | 307 | prof = profile.Profile() |
|
309 | 308 | try: |
|
310 | 309 | prof = prof.runctx(code, namespace, namespace) |
|
311 | 310 | sys_exit = '' |
|
312 | 311 | except SystemExit: |
|
313 | 312 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
314 | 313 | |
|
315 | 314 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
316 | 315 | |
|
317 | 316 | lims = opts.l |
|
318 | 317 | if lims: |
|
319 | 318 | lims = [] # rebuild lims with ints/floats/strings |
|
320 | 319 | for lim in opts.l: |
|
321 | 320 | try: |
|
322 | 321 | lims.append(int(lim)) |
|
323 | 322 | except ValueError: |
|
324 | 323 | try: |
|
325 | 324 | lims.append(float(lim)) |
|
326 | 325 | except ValueError: |
|
327 | 326 | lims.append(lim) |
|
328 | 327 | |
|
329 | 328 | # Trap output. |
|
330 | 329 | stdout_trap = StringIO() |
|
331 | 330 | stats_stream = stats.stream |
|
332 | 331 | try: |
|
333 | 332 | stats.stream = stdout_trap |
|
334 | 333 | stats.print_stats(*lims) |
|
335 | 334 | finally: |
|
336 | 335 | stats.stream = stats_stream |
|
337 | 336 | |
|
338 | 337 | output = stdout_trap.getvalue() |
|
339 | 338 | output = output.rstrip() |
|
340 | 339 | |
|
341 | 340 | if 'q' not in opts: |
|
342 | 341 | page.page(output) |
|
343 | 342 | print(sys_exit, end=' ') |
|
344 | 343 | |
|
345 | 344 | dump_file = opts.D[0] |
|
346 | 345 | text_file = opts.T[0] |
|
347 | 346 | if dump_file: |
|
348 | 347 | prof.dump_stats(dump_file) |
|
349 | 348 | print('\n*** Profile stats marshalled to file',\ |
|
350 | 349 | repr(dump_file)+'.',sys_exit) |
|
351 | 350 | if text_file: |
|
352 | 351 | pfile = open(text_file,'w') |
|
353 | 352 | pfile.write(output) |
|
354 | 353 | pfile.close() |
|
355 | 354 | print('\n*** Profile printout saved to text file',\ |
|
356 | 355 | repr(text_file)+'.',sys_exit) |
|
357 | 356 | |
|
358 | 357 | if 'r' in opts: |
|
359 | 358 | return stats |
|
360 | 359 | else: |
|
361 | 360 | return None |
|
362 | 361 | |
|
363 | 362 | @line_magic |
|
364 | 363 | def pdb(self, parameter_s=''): |
|
365 | 364 | """Control the automatic calling of the pdb interactive debugger. |
|
366 | 365 | |
|
367 | 366 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
368 | 367 | argument it works as a toggle. |
|
369 | 368 | |
|
370 | 369 | When an exception is triggered, IPython can optionally call the |
|
371 | 370 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
372 | 371 | this feature on and off. |
|
373 | 372 | |
|
374 | 373 | The initial state of this feature is set in your configuration |
|
375 | 374 | file (the option is ``InteractiveShell.pdb``). |
|
376 | 375 | |
|
377 | 376 | If you want to just activate the debugger AFTER an exception has fired, |
|
378 | 377 | without having to type '%pdb on' and rerunning your code, you can use |
|
379 | 378 | the %debug magic.""" |
|
380 | 379 | |
|
381 | 380 | par = parameter_s.strip().lower() |
|
382 | 381 | |
|
383 | 382 | if par: |
|
384 | 383 | try: |
|
385 | 384 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
386 | 385 | except KeyError: |
|
387 | 386 | print ('Incorrect argument. Use on/1, off/0, ' |
|
388 | 387 | 'or nothing for a toggle.') |
|
389 | 388 | return |
|
390 | 389 | else: |
|
391 | 390 | # toggle |
|
392 | 391 | new_pdb = not self.shell.call_pdb |
|
393 | 392 | |
|
394 | 393 | # set on the shell |
|
395 | 394 | self.shell.call_pdb = new_pdb |
|
396 | 395 | print('Automatic pdb calling has been turned',on_off(new_pdb)) |
|
397 | 396 | |
|
398 | 397 | @skip_doctest |
|
399 | 398 | @magic_arguments.magic_arguments() |
|
400 | 399 | @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE', |
|
401 | 400 | help=""" |
|
402 | 401 | Set break point at LINE in FILE. |
|
403 | 402 | """ |
|
404 | 403 | ) |
|
405 | 404 | @magic_arguments.argument('statement', nargs='*', |
|
406 | 405 | help=""" |
|
407 | 406 | Code to run in debugger. |
|
408 | 407 | You can omit this in cell magic mode. |
|
409 | 408 | """ |
|
410 | 409 | ) |
|
411 | 410 | @line_cell_magic |
|
412 | 411 | def debug(self, line='', cell=None): |
|
413 | 412 | """Activate the interactive debugger. |
|
414 | 413 | |
|
415 | 414 | This magic command support two ways of activating debugger. |
|
416 | 415 | One is to activate debugger before executing code. This way, you |
|
417 | 416 | can set a break point, to step through the code from the point. |
|
418 | 417 | You can use this mode by giving statements to execute and optionally |
|
419 | 418 | a breakpoint. |
|
420 | 419 | |
|
421 | 420 | The other one is to activate debugger in post-mortem mode. You can |
|
422 | 421 | activate this mode simply running %debug without any argument. |
|
423 | 422 | If an exception has just occurred, this lets you inspect its stack |
|
424 | 423 | frames interactively. Note that this will always work only on the last |
|
425 | 424 | traceback that occurred, so you must call this quickly after an |
|
426 | 425 | exception that you wish to inspect has fired, because if another one |
|
427 | 426 | occurs, it clobbers the previous one. |
|
428 | 427 | |
|
429 | 428 | If you want IPython to automatically do this on every exception, see |
|
430 | 429 | the %pdb magic for more details. |
|
431 | 430 | """ |
|
432 | 431 | args = magic_arguments.parse_argstring(self.debug, line) |
|
433 | 432 | |
|
434 | 433 | if not (args.breakpoint or args.statement or cell): |
|
435 | 434 | self._debug_post_mortem() |
|
436 | 435 | else: |
|
437 | 436 | code = "\n".join(args.statement) |
|
438 | 437 | if cell: |
|
439 | 438 | code += "\n" + cell |
|
440 | 439 | self._debug_exec(code, args.breakpoint) |
|
441 | 440 | |
|
442 | 441 | def _debug_post_mortem(self): |
|
443 | 442 | self.shell.debugger(force=True) |
|
444 | 443 | |
|
445 | 444 | def _debug_exec(self, code, breakpoint): |
|
446 | 445 | if breakpoint: |
|
447 | 446 | (filename, bp_line) = breakpoint.rsplit(':', 1) |
|
448 | 447 | bp_line = int(bp_line) |
|
449 | 448 | else: |
|
450 | 449 | (filename, bp_line) = (None, None) |
|
451 | 450 | self._run_with_debugger(code, self.shell.user_ns, filename, bp_line) |
|
452 | 451 | |
|
453 | 452 | @line_magic |
|
454 | 453 | def tb(self, s): |
|
455 | 454 | """Print the last traceback with the currently active exception mode. |
|
456 | 455 | |
|
457 | 456 | See %xmode for changing exception reporting modes.""" |
|
458 | 457 | self.shell.showtraceback() |
|
459 | 458 | |
|
460 | 459 | @skip_doctest |
|
461 | 460 | @line_magic |
|
462 | 461 | def run(self, parameter_s='', runner=None, |
|
463 | 462 | file_finder=get_py_filename): |
|
464 | 463 | """Run the named file inside IPython as a program. |
|
465 | 464 | |
|
466 | 465 | Usage:: |
|
467 | 466 | |
|
468 | 467 | %run [-n -i -e -G] |
|
469 | 468 | [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )] |
|
470 | 469 | ( -m mod | file ) [args] |
|
471 | 470 | |
|
472 | 471 | Parameters after the filename are passed as command-line arguments to |
|
473 | 472 | the program (put in sys.argv). Then, control returns to IPython's |
|
474 | 473 | prompt. |
|
475 | 474 | |
|
476 | 475 | This is similar to running at a system prompt ``python file args``, |
|
477 | 476 | but with the advantage of giving you IPython's tracebacks, and of |
|
478 | 477 | loading all variables into your interactive namespace for further use |
|
479 | 478 | (unless -p is used, see below). |
|
480 | 479 | |
|
481 | 480 | The file is executed in a namespace initially consisting only of |
|
482 | 481 | ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus |
|
483 | 482 | sees its environment as if it were being run as a stand-alone program |
|
484 | 483 | (except for sharing global objects such as previously imported |
|
485 | 484 | modules). But after execution, the IPython interactive namespace gets |
|
486 | 485 | updated with all variables defined in the program (except for __name__ |
|
487 | 486 | and sys.argv). This allows for very convenient loading of code for |
|
488 | 487 | interactive work, while giving each program a 'clean sheet' to run in. |
|
489 | 488 | |
|
490 | 489 | Arguments are expanded using shell-like glob match. Patterns |
|
491 | 490 | '*', '?', '[seq]' and '[!seq]' can be used. Additionally, |
|
492 | 491 | tilde '~' will be expanded into user's home directory. Unlike |
|
493 | 492 | real shells, quotation does not suppress expansions. Use |
|
494 | 493 | *two* back slashes (e.g. ``\\\\*``) to suppress expansions. |
|
495 | 494 | To completely disable these expansions, you can use -G flag. |
|
496 | 495 | |
|
497 | 496 | Options: |
|
498 | 497 | |
|
499 | 498 | -n |
|
500 | 499 | __name__ is NOT set to '__main__', but to the running file's name |
|
501 | 500 | without extension (as python does under import). This allows running |
|
502 | 501 | scripts and reloading the definitions in them without calling code |
|
503 | 502 | protected by an ``if __name__ == "__main__"`` clause. |
|
504 | 503 | |
|
505 | 504 | -i |
|
506 | 505 | run the file in IPython's namespace instead of an empty one. This |
|
507 | 506 | is useful if you are experimenting with code written in a text editor |
|
508 | 507 | which depends on variables defined interactively. |
|
509 | 508 | |
|
510 | 509 | -e |
|
511 | 510 | ignore sys.exit() calls or SystemExit exceptions in the script |
|
512 | 511 | being run. This is particularly useful if IPython is being used to |
|
513 | 512 | run unittests, which always exit with a sys.exit() call. In such |
|
514 | 513 | cases you are interested in the output of the test results, not in |
|
515 | 514 | seeing a traceback of the unittest module. |
|
516 | 515 | |
|
517 | 516 | -t |
|
518 | 517 | print timing information at the end of the run. IPython will give |
|
519 | 518 | you an estimated CPU time consumption for your script, which under |
|
520 | 519 | Unix uses the resource module to avoid the wraparound problems of |
|
521 | 520 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
522 | 521 | is also given (for Windows platforms this is reported as 0.0). |
|
523 | 522 | |
|
524 | 523 | If -t is given, an additional ``-N<N>`` option can be given, where <N> |
|
525 | 524 | must be an integer indicating how many times you want the script to |
|
526 | 525 | run. The final timing report will include total and per run results. |
|
527 | 526 | |
|
528 | 527 | For example (testing the script uniq_stable.py):: |
|
529 | 528 | |
|
530 | 529 | In [1]: run -t uniq_stable |
|
531 | 530 | |
|
532 | 531 | IPython CPU timings (estimated): |
|
533 | 532 | User : 0.19597 s. |
|
534 | 533 | System: 0.0 s. |
|
535 | 534 | |
|
536 | 535 | In [2]: run -t -N5 uniq_stable |
|
537 | 536 | |
|
538 | 537 | IPython CPU timings (estimated): |
|
539 | 538 | Total runs performed: 5 |
|
540 | 539 | Times : Total Per run |
|
541 | 540 | User : 0.910862 s, 0.1821724 s. |
|
542 | 541 | System: 0.0 s, 0.0 s. |
|
543 | 542 | |
|
544 | 543 | -d |
|
545 | 544 | run your program under the control of pdb, the Python debugger. |
|
546 | 545 | This allows you to execute your program step by step, watch variables, |
|
547 | 546 | etc. Internally, what IPython does is similar to calling:: |
|
548 | 547 | |
|
549 | 548 | pdb.run('execfile("YOURFILENAME")') |
|
550 | 549 | |
|
551 | 550 | with a breakpoint set on line 1 of your file. You can change the line |
|
552 | 551 | number for this automatic breakpoint to be <N> by using the -bN option |
|
553 | 552 | (where N must be an integer). For example:: |
|
554 | 553 | |
|
555 | 554 | %run -d -b40 myscript |
|
556 | 555 | |
|
557 | 556 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
558 | 557 | the first breakpoint must be set on a line which actually does |
|
559 | 558 | something (not a comment or docstring) for it to stop execution. |
|
560 | 559 | |
|
561 | 560 | Or you can specify a breakpoint in a different file:: |
|
562 | 561 | |
|
563 | 562 | %run -d -b myotherfile.py:20 myscript |
|
564 | 563 | |
|
565 | 564 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
566 | 565 | first enter 'c' (without quotes) to start execution up to the first |
|
567 | 566 | breakpoint. |
|
568 | 567 | |
|
569 | 568 | Entering 'help' gives information about the use of the debugger. You |
|
570 | 569 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
571 | 570 | at a prompt. |
|
572 | 571 | |
|
573 | 572 | -p |
|
574 | 573 | run program under the control of the Python profiler module (which |
|
575 | 574 | prints a detailed report of execution times, function calls, etc). |
|
576 | 575 | |
|
577 | 576 | You can pass other options after -p which affect the behavior of the |
|
578 | 577 | profiler itself. See the docs for %prun for details. |
|
579 | 578 | |
|
580 | 579 | In this mode, the program's variables do NOT propagate back to the |
|
581 | 580 | IPython interactive namespace (because they remain in the namespace |
|
582 | 581 | where the profiler executes them). |
|
583 | 582 | |
|
584 | 583 | Internally this triggers a call to %prun, see its documentation for |
|
585 | 584 | details on the options available specifically for profiling. |
|
586 | 585 | |
|
587 | 586 | There is one special usage for which the text above doesn't apply: |
|
588 | 587 | if the filename ends with .ipy[nb], the file is run as ipython script, |
|
589 | 588 | just as if the commands were written on IPython prompt. |
|
590 | 589 | |
|
591 | 590 | -m |
|
592 | 591 | specify module name to load instead of script path. Similar to |
|
593 | 592 | the -m option for the python interpreter. Use this option last if you |
|
594 | 593 | want to combine with other %run options. Unlike the python interpreter |
|
595 | 594 | only source modules are allowed no .pyc or .pyo files. |
|
596 | 595 | For example:: |
|
597 | 596 | |
|
598 | 597 | %run -m example |
|
599 | 598 | |
|
600 | 599 | will run the example module. |
|
601 | 600 | |
|
602 | 601 | -G |
|
603 | 602 | disable shell-like glob expansion of arguments. |
|
604 | 603 | |
|
605 | 604 | """ |
|
606 | 605 | |
|
607 | 606 | # get arguments and set sys.argv for program to be run. |
|
608 | 607 | opts, arg_lst = self.parse_options(parameter_s, |
|
609 | 608 | 'nidtN:b:pD:l:rs:T:em:G', |
|
610 | 609 | mode='list', list_all=1) |
|
611 | 610 | if "m" in opts: |
|
612 | 611 | modulename = opts["m"][0] |
|
613 | 612 | modpath = find_mod(modulename) |
|
614 | 613 | if modpath is None: |
|
615 | 614 | warn('%r is not a valid modulename on sys.path'%modulename) |
|
616 | 615 | return |
|
617 | 616 | arg_lst = [modpath] + arg_lst |
|
618 | 617 | try: |
|
619 | 618 | filename = file_finder(arg_lst[0]) |
|
620 | 619 | except IndexError: |
|
621 | 620 | warn('you must provide at least a filename.') |
|
622 | 621 | print('\n%run:\n', oinspect.getdoc(self.run)) |
|
623 | 622 | return |
|
624 | 623 | except IOError as e: |
|
625 | 624 | try: |
|
626 | 625 | msg = str(e) |
|
627 | 626 | except UnicodeError: |
|
628 | 627 | msg = e.message |
|
629 | 628 | error(msg) |
|
630 | 629 | return |
|
631 | 630 | |
|
632 | 631 | if filename.lower().endswith(('.ipy', '.ipynb')): |
|
633 | 632 | with preserve_keys(self.shell.user_ns, '__file__'): |
|
634 | 633 | self.shell.user_ns['__file__'] = filename |
|
635 | 634 | self.shell.safe_execfile_ipy(filename) |
|
636 | 635 | return |
|
637 | 636 | |
|
638 | 637 | # Control the response to exit() calls made by the script being run |
|
639 | 638 | exit_ignore = 'e' in opts |
|
640 | 639 | |
|
641 | 640 | # Make sure that the running script gets a proper sys.argv as if it |
|
642 | 641 | # were run from a system shell. |
|
643 | 642 | save_argv = sys.argv # save it for later restoring |
|
644 | 643 | |
|
645 | 644 | if 'G' in opts: |
|
646 | 645 | args = arg_lst[1:] |
|
647 | 646 | else: |
|
648 | 647 | # tilde and glob expansion |
|
649 | 648 | args = shellglob(map(os.path.expanduser, arg_lst[1:])) |
|
650 | 649 | |
|
651 | 650 | sys.argv = [filename] + args # put in the proper filename |
|
652 | 651 | |
|
653 | 652 | if 'i' in opts: |
|
654 | 653 | # Run in user's interactive namespace |
|
655 | 654 | prog_ns = self.shell.user_ns |
|
656 | 655 | __name__save = self.shell.user_ns['__name__'] |
|
657 | 656 | prog_ns['__name__'] = '__main__' |
|
658 | 657 | main_mod = self.shell.user_module |
|
659 | 658 | |
|
660 | 659 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
661 | 660 | # set the __file__ global in the script's namespace |
|
662 | 661 | # TK: Is this necessary in interactive mode? |
|
663 | 662 | prog_ns['__file__'] = filename |
|
664 | 663 | else: |
|
665 | 664 | # Run in a fresh, empty namespace |
|
666 | 665 | if 'n' in opts: |
|
667 | 666 | name = os.path.splitext(os.path.basename(filename))[0] |
|
668 | 667 | else: |
|
669 | 668 | name = '__main__' |
|
670 | 669 | |
|
671 | 670 | # The shell MUST hold a reference to prog_ns so after %run |
|
672 | 671 | # exits, the python deletion mechanism doesn't zero it out |
|
673 | 672 | # (leaving dangling references). See interactiveshell for details |
|
674 | 673 | main_mod = self.shell.new_main_mod(filename, name) |
|
675 | 674 | prog_ns = main_mod.__dict__ |
|
676 | 675 | |
|
677 | 676 | # pickle fix. See interactiveshell for an explanation. But we need to |
|
678 | 677 | # make sure that, if we overwrite __main__, we replace it at the end |
|
679 | 678 | main_mod_name = prog_ns['__name__'] |
|
680 | 679 | |
|
681 | 680 | if main_mod_name == '__main__': |
|
682 | 681 | restore_main = sys.modules['__main__'] |
|
683 | 682 | else: |
|
684 | 683 | restore_main = False |
|
685 | 684 | |
|
686 | 685 | # This needs to be undone at the end to prevent holding references to |
|
687 | 686 | # every single object ever created. |
|
688 | 687 | sys.modules[main_mod_name] = main_mod |
|
689 | 688 | |
|
690 | 689 | if 'p' in opts or 'd' in opts: |
|
691 | 690 | if 'm' in opts: |
|
692 | 691 | code = 'run_module(modulename, prog_ns)' |
|
693 | 692 | code_ns = { |
|
694 | 693 | 'run_module': self.shell.safe_run_module, |
|
695 | 694 | 'prog_ns': prog_ns, |
|
696 | 695 | 'modulename': modulename, |
|
697 | 696 | } |
|
698 | 697 | else: |
|
699 | 698 | if 'd' in opts: |
|
700 | 699 | # allow exceptions to raise in debug mode |
|
701 | 700 | code = 'execfile(filename, prog_ns, raise_exceptions=True)' |
|
702 | 701 | else: |
|
703 | 702 | code = 'execfile(filename, prog_ns)' |
|
704 | 703 | code_ns = { |
|
705 | 704 | 'execfile': self.shell.safe_execfile, |
|
706 | 705 | 'prog_ns': prog_ns, |
|
707 | 706 | 'filename': get_py_filename(filename), |
|
708 | 707 | } |
|
709 | 708 | |
|
710 | 709 | try: |
|
711 | 710 | stats = None |
|
712 | 711 | if 'p' in opts: |
|
713 | 712 | stats = self._run_with_profiler(code, opts, code_ns) |
|
714 | 713 | else: |
|
715 | 714 | if 'd' in opts: |
|
716 | 715 | bp_file, bp_line = parse_breakpoint( |
|
717 | 716 | opts.get('b', ['1'])[0], filename) |
|
718 | 717 | self._run_with_debugger( |
|
719 | 718 | code, code_ns, filename, bp_line, bp_file) |
|
720 | 719 | else: |
|
721 | 720 | if 'm' in opts: |
|
722 | 721 | def run(): |
|
723 | 722 | self.shell.safe_run_module(modulename, prog_ns) |
|
724 | 723 | else: |
|
725 | 724 | if runner is None: |
|
726 | 725 | runner = self.default_runner |
|
727 | 726 | if runner is None: |
|
728 | 727 | runner = self.shell.safe_execfile |
|
729 | 728 | |
|
730 | 729 | def run(): |
|
731 | 730 | runner(filename, prog_ns, prog_ns, |
|
732 | 731 | exit_ignore=exit_ignore) |
|
733 | 732 | |
|
734 | 733 | if 't' in opts: |
|
735 | 734 | # timed execution |
|
736 | 735 | try: |
|
737 | 736 | nruns = int(opts['N'][0]) |
|
738 | 737 | if nruns < 1: |
|
739 | 738 | error('Number of runs must be >=1') |
|
740 | 739 | return |
|
741 | 740 | except (KeyError): |
|
742 | 741 | nruns = 1 |
|
743 | 742 | self._run_with_timing(run, nruns) |
|
744 | 743 | else: |
|
745 | 744 | # regular execution |
|
746 | 745 | run() |
|
747 | 746 | |
|
748 | 747 | if 'i' in opts: |
|
749 | 748 | self.shell.user_ns['__name__'] = __name__save |
|
750 | 749 | else: |
|
751 | 750 | # update IPython interactive namespace |
|
752 | 751 | |
|
753 | 752 | # Some forms of read errors on the file may mean the |
|
754 | 753 | # __name__ key was never set; using pop we don't have to |
|
755 | 754 | # worry about a possible KeyError. |
|
756 | 755 | prog_ns.pop('__name__', None) |
|
757 | 756 | |
|
758 | 757 | with preserve_keys(self.shell.user_ns, '__file__'): |
|
759 | 758 | self.shell.user_ns.update(prog_ns) |
|
760 | 759 | finally: |
|
761 | 760 | # It's a bit of a mystery why, but __builtins__ can change from |
|
762 | 761 | # being a module to becoming a dict missing some key data after |
|
763 | 762 | # %run. As best I can see, this is NOT something IPython is doing |
|
764 | 763 | # at all, and similar problems have been reported before: |
|
765 | 764 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
766 | 765 | # Since this seems to be done by the interpreter itself, the best |
|
767 | 766 | # we can do is to at least restore __builtins__ for the user on |
|
768 | 767 | # exit. |
|
769 | 768 | self.shell.user_ns['__builtins__'] = builtin_mod |
|
770 | 769 | |
|
771 | 770 | # Ensure key global structures are restored |
|
772 | 771 | sys.argv = save_argv |
|
773 | 772 | if restore_main: |
|
774 | 773 | sys.modules['__main__'] = restore_main |
|
775 | 774 | else: |
|
776 | 775 | # Remove from sys.modules the reference to main_mod we'd |
|
777 | 776 | # added. Otherwise it will trap references to objects |
|
778 | 777 | # contained therein. |
|
779 | 778 | del sys.modules[main_mod_name] |
|
780 | 779 | |
|
781 | 780 | return stats |
|
782 | 781 | |
|
783 | 782 | def _run_with_debugger(self, code, code_ns, filename=None, |
|
784 | 783 | bp_line=None, bp_file=None): |
|
785 | 784 | """ |
|
786 | 785 | Run `code` in debugger with a break point. |
|
787 | 786 | |
|
788 | 787 | Parameters |
|
789 | 788 | ---------- |
|
790 | 789 | code : str |
|
791 | 790 | Code to execute. |
|
792 | 791 | code_ns : dict |
|
793 | 792 | A namespace in which `code` is executed. |
|
794 | 793 | filename : str |
|
795 | 794 | `code` is ran as if it is in `filename`. |
|
796 | 795 | bp_line : int, optional |
|
797 | 796 | Line number of the break point. |
|
798 | 797 | bp_file : str, optional |
|
799 | 798 | Path to the file in which break point is specified. |
|
800 | 799 | `filename` is used if not given. |
|
801 | 800 | |
|
802 | 801 | Raises |
|
803 | 802 | ------ |
|
804 | 803 | UsageError |
|
805 | 804 | If the break point given by `bp_line` is not valid. |
|
806 | 805 | |
|
807 | 806 | """ |
|
808 | 807 | deb = self.shell.InteractiveTB.pdb |
|
809 | 808 | if not deb: |
|
810 | 809 | self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls() |
|
811 | 810 | deb = self.shell.InteractiveTB.pdb |
|
812 | 811 | |
|
813 | 812 | # deb.checkline() fails if deb.curframe exists but is None; it can |
|
814 | 813 | # handle it not existing. https://github.com/ipython/ipython/issues/10028 |
|
815 | 814 | if hasattr(deb, 'curframe'): |
|
816 | 815 | del deb.curframe |
|
817 | 816 | |
|
818 | 817 | # reset Breakpoint state, which is moronically kept |
|
819 | 818 | # in a class |
|
820 | 819 | bdb.Breakpoint.next = 1 |
|
821 | 820 | bdb.Breakpoint.bplist = {} |
|
822 | 821 | bdb.Breakpoint.bpbynumber = [None] |
|
823 | 822 | if bp_line is not None: |
|
824 | 823 | # Set an initial breakpoint to stop execution |
|
825 | 824 | maxtries = 10 |
|
826 | 825 | bp_file = bp_file or filename |
|
827 | 826 | checkline = deb.checkline(bp_file, bp_line) |
|
828 | 827 | if not checkline: |
|
829 | 828 | for bp in range(bp_line + 1, bp_line + maxtries + 1): |
|
830 | 829 | if deb.checkline(bp_file, bp): |
|
831 | 830 | break |
|
832 | 831 | else: |
|
833 | 832 | msg = ("\nI failed to find a valid line to set " |
|
834 | 833 | "a breakpoint\n" |
|
835 | 834 | "after trying up to line: %s.\n" |
|
836 | 835 | "Please set a valid breakpoint manually " |
|
837 | 836 | "with the -b option." % bp) |
|
838 | 837 | raise UsageError(msg) |
|
839 | 838 | # if we find a good linenumber, set the breakpoint |
|
840 | 839 | deb.do_break('%s:%s' % (bp_file, bp_line)) |
|
841 | 840 | |
|
842 | 841 | if filename: |
|
843 | 842 | # Mimic Pdb._runscript(...) |
|
844 | 843 | deb._wait_for_mainpyfile = True |
|
845 | 844 | deb.mainpyfile = deb.canonic(filename) |
|
846 | 845 | |
|
847 | 846 | # Start file run |
|
848 | 847 | print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt) |
|
849 | 848 | try: |
|
850 | 849 | if filename: |
|
851 | 850 | # save filename so it can be used by methods on the deb object |
|
852 | 851 | deb._exec_filename = filename |
|
853 | 852 | while True: |
|
854 | 853 | try: |
|
855 | 854 | deb.run(code, code_ns) |
|
856 | 855 | except Restart: |
|
857 | 856 | print("Restarting") |
|
858 | 857 | if filename: |
|
859 | 858 | deb._wait_for_mainpyfile = True |
|
860 | 859 | deb.mainpyfile = deb.canonic(filename) |
|
861 | 860 | continue |
|
862 | 861 | else: |
|
863 | 862 | break |
|
864 | 863 | |
|
865 | 864 | |
|
866 | 865 | except: |
|
867 | 866 | etype, value, tb = sys.exc_info() |
|
868 | 867 | # Skip three frames in the traceback: the %run one, |
|
869 | 868 | # one inside bdb.py, and the command-line typed by the |
|
870 | 869 | # user (run by exec in pdb itself). |
|
871 | 870 | self.shell.InteractiveTB(etype, value, tb, tb_offset=3) |
|
872 | 871 | |
|
873 | 872 | @staticmethod |
|
874 | 873 | def _run_with_timing(run, nruns): |
|
875 | 874 | """ |
|
876 | 875 | Run function `run` and print timing information. |
|
877 | 876 | |
|
878 | 877 | Parameters |
|
879 | 878 | ---------- |
|
880 | 879 | run : callable |
|
881 | 880 | Any callable object which takes no argument. |
|
882 | 881 | nruns : int |
|
883 | 882 | Number of times to execute `run`. |
|
884 | 883 | |
|
885 | 884 | """ |
|
886 | 885 | twall0 = time.time() |
|
887 | 886 | if nruns == 1: |
|
888 | 887 | t0 = clock2() |
|
889 | 888 | run() |
|
890 | 889 | t1 = clock2() |
|
891 | 890 | t_usr = t1[0] - t0[0] |
|
892 | 891 | t_sys = t1[1] - t0[1] |
|
893 | 892 | print("\nIPython CPU timings (estimated):") |
|
894 | 893 | print(" User : %10.2f s." % t_usr) |
|
895 | 894 | print(" System : %10.2f s." % t_sys) |
|
896 | 895 | else: |
|
897 | 896 | runs = range(nruns) |
|
898 | 897 | t0 = clock2() |
|
899 | 898 | for nr in runs: |
|
900 | 899 | run() |
|
901 | 900 | t1 = clock2() |
|
902 | 901 | t_usr = t1[0] - t0[0] |
|
903 | 902 | t_sys = t1[1] - t0[1] |
|
904 | 903 | print("\nIPython CPU timings (estimated):") |
|
905 | 904 | print("Total runs performed:", nruns) |
|
906 | 905 | print(" Times : %10s %10s" % ('Total', 'Per run')) |
|
907 | 906 | print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)) |
|
908 | 907 | print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)) |
|
909 | 908 | twall1 = time.time() |
|
910 | 909 | print("Wall time: %10.2f s." % (twall1 - twall0)) |
|
911 | 910 | |
|
912 | 911 | @skip_doctest |
|
913 | 912 | @line_cell_magic |
|
914 | 913 | def timeit(self, line='', cell=None): |
|
915 | 914 | """Time execution of a Python statement or expression |
|
916 | 915 | |
|
917 | 916 | Usage, in line mode: |
|
918 | 917 | %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement |
|
919 | 918 | or in cell mode: |
|
920 | 919 | %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code |
|
921 | 920 | code |
|
922 | 921 | code... |
|
923 | 922 | |
|
924 | 923 | Time execution of a Python statement or expression using the timeit |
|
925 | 924 | module. This function can be used both as a line and cell magic: |
|
926 | 925 | |
|
927 | 926 | - In line mode you can time a single-line statement (though multiple |
|
928 | 927 | ones can be chained with using semicolons). |
|
929 | 928 | |
|
930 | 929 | - In cell mode, the statement in the first line is used as setup code |
|
931 | 930 | (executed but not timed) and the body of the cell is timed. The cell |
|
932 | 931 | body has access to any variables created in the setup code. |
|
933 | 932 | |
|
934 | 933 | Options: |
|
935 | 934 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
936 | 935 | is not given, a fitting value is chosen. |
|
937 | 936 | |
|
938 | 937 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
939 | 938 | Default: 3 |
|
940 | 939 | |
|
941 | 940 | -t: use time.time to measure the time, which is the default on Unix. |
|
942 | 941 | This function measures wall time. |
|
943 | 942 | |
|
944 | 943 | -c: use time.clock to measure the time, which is the default on |
|
945 | 944 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
946 | 945 | instead and returns the CPU user time. |
|
947 | 946 | |
|
948 | 947 | -p<P>: use a precision of <P> digits to display the timing result. |
|
949 | 948 | Default: 3 |
|
950 | 949 | |
|
951 | 950 | -q: Quiet, do not print result. |
|
952 | 951 | |
|
953 | 952 | -o: return a TimeitResult that can be stored in a variable to inspect |
|
954 | 953 | the result in more details. |
|
955 | 954 | |
|
956 | 955 | |
|
957 | 956 | Examples |
|
958 | 957 | -------- |
|
959 | 958 | :: |
|
960 | 959 | |
|
961 | 960 | In [1]: %timeit pass |
|
962 | 961 | 100000000 loops, average of 7: 5.48 ns +- 0.354 ns per loop (using standard deviation) |
|
963 | 962 | |
|
964 | 963 | In [2]: u = None |
|
965 | 964 | |
|
966 | 965 | In [3]: %timeit u is None |
|
967 | 966 | 10000000 loops, average of 7: 22.7 ns +- 2.33 ns per loop (using standard deviation) |
|
968 | 967 | |
|
969 | 968 | In [4]: %timeit -r 4 u == None |
|
970 | 969 | 10000000 loops, average of 4: 27.5 ns +- 2.91 ns per loop (using standard deviation) |
|
971 | 970 | |
|
972 | 971 | In [5]: import time |
|
973 | 972 | |
|
974 | 973 | In [6]: %timeit -n1 time.sleep(2) |
|
975 | 974 | 1 loop, average of 7: 2 s +- 4.71 Β΅s per loop (using standard deviation) |
|
976 | 975 | |
|
977 | 976 | |
|
978 | 977 | The times reported by %timeit will be slightly higher than those |
|
979 | 978 | reported by the timeit.py script when variables are accessed. This is |
|
980 | 979 | due to the fact that %timeit executes the statement in the namespace |
|
981 | 980 | of the shell, compared with timeit.py, which uses a single setup |
|
982 | 981 | statement to import function or create variables. Generally, the bias |
|
983 | 982 | does not matter as long as results from timeit.py are not mixed with |
|
984 | 983 | those from %timeit.""" |
|
985 | 984 | |
|
986 | 985 | opts, stmt = self.parse_options(line,'n:r:tcp:qo', |
|
987 | 986 | posix=False, strict=False) |
|
988 | 987 | if stmt == "" and cell is None: |
|
989 | 988 | return |
|
990 | 989 | |
|
991 | 990 | timefunc = timeit.default_timer |
|
992 | 991 | number = int(getattr(opts, "n", 0)) |
|
993 | 992 | default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat |
|
994 | 993 | repeat = int(getattr(opts, "r", default_repeat)) |
|
995 | 994 | precision = int(getattr(opts, "p", 3)) |
|
996 | 995 | quiet = 'q' in opts |
|
997 | 996 | return_result = 'o' in opts |
|
998 | 997 | if hasattr(opts, "t"): |
|
999 | 998 | timefunc = time.time |
|
1000 | 999 | if hasattr(opts, "c"): |
|
1001 | 1000 | timefunc = clock |
|
1002 | 1001 | |
|
1003 | 1002 | timer = Timer(timer=timefunc) |
|
1004 | 1003 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1005 | 1004 | # but is there a better way to achieve that the code stmt has access |
|
1006 | 1005 | # to the shell namespace? |
|
1007 | 1006 | transform = self.shell.input_splitter.transform_cell |
|
1008 | 1007 | |
|
1009 | 1008 | if cell is None: |
|
1010 | 1009 | # called as line magic |
|
1011 | 1010 | ast_setup = self.shell.compile.ast_parse("pass") |
|
1012 | 1011 | ast_stmt = self.shell.compile.ast_parse(transform(stmt)) |
|
1013 | 1012 | else: |
|
1014 | 1013 | ast_setup = self.shell.compile.ast_parse(transform(stmt)) |
|
1015 | 1014 | ast_stmt = self.shell.compile.ast_parse(transform(cell)) |
|
1016 | 1015 | |
|
1017 | 1016 | ast_setup = self.shell.transform_ast(ast_setup) |
|
1018 | 1017 | ast_stmt = self.shell.transform_ast(ast_stmt) |
|
1019 | 1018 | |
|
1020 | 1019 | # This codestring is taken from timeit.template - we fill it in as an |
|
1021 | 1020 | # AST, so that we can apply our AST transformations to the user code |
|
1022 | 1021 | # without affecting the timing code. |
|
1023 | 1022 | timeit_ast_template = ast.parse('def inner(_it, _timer):\n' |
|
1024 | 1023 | ' setup\n' |
|
1025 | 1024 | ' _t0 = _timer()\n' |
|
1026 | 1025 | ' for _i in _it:\n' |
|
1027 | 1026 | ' stmt\n' |
|
1028 | 1027 | ' _t1 = _timer()\n' |
|
1029 | 1028 | ' return _t1 - _t0\n') |
|
1030 | 1029 | |
|
1031 | 1030 | timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template) |
|
1032 | 1031 | timeit_ast = ast.fix_missing_locations(timeit_ast) |
|
1033 | 1032 | |
|
1034 | 1033 | # Track compilation time so it can be reported if too long |
|
1035 | 1034 | # Minimum time above which compilation time will be reported |
|
1036 | 1035 | tc_min = 0.1 |
|
1037 | 1036 | |
|
1038 | 1037 | t0 = clock() |
|
1039 | 1038 | code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec") |
|
1040 | 1039 | tc = clock()-t0 |
|
1041 | 1040 | |
|
1042 | 1041 | ns = {} |
|
1043 | 1042 | exec(code, self.shell.user_ns, ns) |
|
1044 | 1043 | timer.inner = ns["inner"] |
|
1045 | 1044 | |
|
1046 | 1045 | # This is used to check if there is a huge difference between the |
|
1047 | 1046 | # best and worst timings. |
|
1048 | 1047 | # Issue: https://github.com/ipython/ipython/issues/6471 |
|
1049 | 1048 | if number == 0: |
|
1050 | 1049 | # determine number so that 0.2 <= total time < 2.0 |
|
1051 | 1050 | for index in range(0, 10): |
|
1052 | 1051 | number = 10 ** index |
|
1053 | 1052 | time_number = timer.timeit(number) |
|
1054 | 1053 | if time_number >= 0.2: |
|
1055 | 1054 | break |
|
1056 | 1055 | |
|
1057 | 1056 | all_runs = timer.repeat(repeat, number) |
|
1058 | 1057 | best = min(all_runs) / number |
|
1059 | 1058 | worst = max(all_runs) / number |
|
1060 | 1059 | timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision) |
|
1061 | 1060 | |
|
1062 | 1061 | if not quiet : |
|
1063 | 1062 | # Check best timing is greater than zero to avoid a |
|
1064 | 1063 | # ZeroDivisionError. |
|
1065 | 1064 | # In cases where the slowest timing is lesser than a micosecond |
|
1066 | 1065 | # we assume that it does not really matter if the fastest |
|
1067 | 1066 | # timing is 4 times faster than the slowest timing or not. |
|
1068 | 1067 | if worst > 4 * best and best > 0 and worst > 1e-6: |
|
1069 | 1068 | print("The slowest run took %0.2f times longer than the " |
|
1070 | 1069 | "fastest. This could mean that an intermediate result " |
|
1071 | 1070 | "is being cached." % (worst / best)) |
|
1072 | 1071 | |
|
1073 | 1072 | print( timeit_result ) |
|
1074 | 1073 | |
|
1075 | 1074 | if tc > tc_min: |
|
1076 | 1075 | print("Compiler time: %.2f s" % tc) |
|
1077 | 1076 | if return_result: |
|
1078 | 1077 | return timeit_result |
|
1079 | 1078 | |
|
1080 | 1079 | @skip_doctest |
|
1081 | 1080 | @needs_local_scope |
|
1082 | 1081 | @line_cell_magic |
|
1083 | 1082 | def time(self,line='', cell=None, local_ns=None): |
|
1084 | 1083 | """Time execution of a Python statement or expression. |
|
1085 | 1084 | |
|
1086 | 1085 | The CPU and wall clock times are printed, and the value of the |
|
1087 | 1086 | expression (if any) is returned. Note that under Win32, system time |
|
1088 | 1087 | is always reported as 0, since it can not be measured. |
|
1089 | 1088 | |
|
1090 | 1089 | This function can be used both as a line and cell magic: |
|
1091 | 1090 | |
|
1092 | 1091 | - In line mode you can time a single-line statement (though multiple |
|
1093 | 1092 | ones can be chained with using semicolons). |
|
1094 | 1093 | |
|
1095 | 1094 | - In cell mode, you can time the cell body (a directly |
|
1096 | 1095 | following statement raises an error). |
|
1097 | 1096 | |
|
1098 | 1097 | This function provides very basic timing functionality. Use the timeit |
|
1099 | 1098 | magic for more control over the measurement. |
|
1100 | 1099 | |
|
1101 | 1100 | Examples |
|
1102 | 1101 | -------- |
|
1103 | 1102 | :: |
|
1104 | 1103 | |
|
1105 | 1104 | In [1]: %time 2**128 |
|
1106 | 1105 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1107 | 1106 | Wall time: 0.00 |
|
1108 | 1107 | Out[1]: 340282366920938463463374607431768211456L |
|
1109 | 1108 | |
|
1110 | 1109 | In [2]: n = 1000000 |
|
1111 | 1110 | |
|
1112 | 1111 | In [3]: %time sum(range(n)) |
|
1113 | 1112 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1114 | 1113 | Wall time: 1.37 |
|
1115 | 1114 | Out[3]: 499999500000L |
|
1116 | 1115 | |
|
1117 | 1116 | In [4]: %time print 'hello world' |
|
1118 | 1117 | hello world |
|
1119 | 1118 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1120 | 1119 | Wall time: 0.00 |
|
1121 | 1120 | |
|
1122 | 1121 | Note that the time needed by Python to compile the given expression |
|
1123 | 1122 | will be reported if it is more than 0.1s. In this example, the |
|
1124 | 1123 | actual exponentiation is done by Python at compilation time, so while |
|
1125 | 1124 | the expression can take a noticeable amount of time to compute, that |
|
1126 | 1125 | time is purely due to the compilation: |
|
1127 | 1126 | |
|
1128 | 1127 | In [5]: %time 3**9999; |
|
1129 | 1128 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1130 | 1129 | Wall time: 0.00 s |
|
1131 | 1130 | |
|
1132 | 1131 | In [6]: %time 3**999999; |
|
1133 | 1132 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1134 | 1133 | Wall time: 0.00 s |
|
1135 | 1134 | Compiler : 0.78 s |
|
1136 | 1135 | """ |
|
1137 | 1136 | |
|
1138 | 1137 | # fail immediately if the given expression can't be compiled |
|
1139 | 1138 | |
|
1140 | 1139 | if line and cell: |
|
1141 | 1140 | raise UsageError("Can't use statement directly after '%%time'!") |
|
1142 | 1141 | |
|
1143 | 1142 | if cell: |
|
1144 | 1143 | expr = self.shell.input_transformer_manager.transform_cell(cell) |
|
1145 | 1144 | else: |
|
1146 | 1145 | expr = self.shell.input_transformer_manager.transform_cell(line) |
|
1147 | 1146 | |
|
1148 | 1147 | # Minimum time above which parse time will be reported |
|
1149 | 1148 | tp_min = 0.1 |
|
1150 | 1149 | |
|
1151 | 1150 | t0 = clock() |
|
1152 | 1151 | expr_ast = self.shell.compile.ast_parse(expr) |
|
1153 | 1152 | tp = clock()-t0 |
|
1154 | 1153 | |
|
1155 | 1154 | # Apply AST transformations |
|
1156 | 1155 | expr_ast = self.shell.transform_ast(expr_ast) |
|
1157 | 1156 | |
|
1158 | 1157 | # Minimum time above which compilation time will be reported |
|
1159 | 1158 | tc_min = 0.1 |
|
1160 | 1159 | |
|
1161 | 1160 | if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr): |
|
1162 | 1161 | mode = 'eval' |
|
1163 | 1162 | source = '<timed eval>' |
|
1164 | 1163 | expr_ast = ast.Expression(expr_ast.body[0].value) |
|
1165 | 1164 | else: |
|
1166 | 1165 | mode = 'exec' |
|
1167 | 1166 | source = '<timed exec>' |
|
1168 | 1167 | t0 = clock() |
|
1169 | 1168 | code = self.shell.compile(expr_ast, source, mode) |
|
1170 | 1169 | tc = clock()-t0 |
|
1171 | 1170 | |
|
1172 | 1171 | # skew measurement as little as possible |
|
1173 | 1172 | glob = self.shell.user_ns |
|
1174 | 1173 | wtime = time.time |
|
1175 | 1174 | # time execution |
|
1176 | 1175 | wall_st = wtime() |
|
1177 | 1176 | if mode=='eval': |
|
1178 | 1177 | st = clock2() |
|
1179 | 1178 | try: |
|
1180 | 1179 | out = eval(code, glob, local_ns) |
|
1181 | 1180 | except: |
|
1182 | 1181 | self.shell.showtraceback() |
|
1183 | 1182 | return |
|
1184 | 1183 | end = clock2() |
|
1185 | 1184 | else: |
|
1186 | 1185 | st = clock2() |
|
1187 | 1186 | try: |
|
1188 | 1187 | exec(code, glob, local_ns) |
|
1189 | 1188 | except: |
|
1190 | 1189 | self.shell.showtraceback() |
|
1191 | 1190 | return |
|
1192 | 1191 | end = clock2() |
|
1193 | 1192 | out = None |
|
1194 | 1193 | wall_end = wtime() |
|
1195 | 1194 | # Compute actual times and report |
|
1196 | 1195 | wall_time = wall_end-wall_st |
|
1197 | 1196 | cpu_user = end[0]-st[0] |
|
1198 | 1197 | cpu_sys = end[1]-st[1] |
|
1199 | 1198 | cpu_tot = cpu_user+cpu_sys |
|
1200 | 1199 | # On windows cpu_sys is always zero, so no new information to the next print |
|
1201 | 1200 | if sys.platform != 'win32': |
|
1202 | 1201 | print("CPU times: user %s, sys: %s, total: %s" % \ |
|
1203 | 1202 | (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot))) |
|
1204 | 1203 | print("Wall time: %s" % _format_time(wall_time)) |
|
1205 | 1204 | if tc > tc_min: |
|
1206 | 1205 | print("Compiler : %s" % _format_time(tc)) |
|
1207 | 1206 | if tp > tp_min: |
|
1208 | 1207 | print("Parser : %s" % _format_time(tp)) |
|
1209 | 1208 | return out |
|
1210 | 1209 | |
|
1211 | 1210 | @skip_doctest |
|
1212 | 1211 | @line_magic |
|
1213 | 1212 | def macro(self, parameter_s=''): |
|
1214 | 1213 | """Define a macro for future re-execution. It accepts ranges of history, |
|
1215 | 1214 | filenames or string objects. |
|
1216 | 1215 | |
|
1217 | 1216 | Usage:\\ |
|
1218 | 1217 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1219 | 1218 | |
|
1220 | 1219 | Options: |
|
1221 | 1220 | |
|
1222 | 1221 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1223 | 1222 | so that magics are loaded in their transformed version to valid |
|
1224 | 1223 | Python. If this option is given, the raw input as typed at the |
|
1225 | 1224 | command line is used instead. |
|
1226 | 1225 | |
|
1227 | 1226 | -q: quiet macro definition. By default, a tag line is printed |
|
1228 | 1227 | to indicate the macro has been created, and then the contents of |
|
1229 | 1228 | the macro are printed. If this option is given, then no printout |
|
1230 | 1229 | is produced once the macro is created. |
|
1231 | 1230 | |
|
1232 | 1231 | This will define a global variable called `name` which is a string |
|
1233 | 1232 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1234 | 1233 | above) from your input history into a single string. This variable |
|
1235 | 1234 | acts like an automatic function which re-executes those lines as if |
|
1236 | 1235 | you had typed them. You just type 'name' at the prompt and the code |
|
1237 | 1236 | executes. |
|
1238 | 1237 | |
|
1239 | 1238 | The syntax for indicating input ranges is described in %history. |
|
1240 | 1239 | |
|
1241 | 1240 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1242 | 1241 | notation, where N:M means numbers N through M-1. |
|
1243 | 1242 | |
|
1244 | 1243 | For example, if your history contains (print using %hist -n ):: |
|
1245 | 1244 | |
|
1246 | 1245 | 44: x=1 |
|
1247 | 1246 | 45: y=3 |
|
1248 | 1247 | 46: z=x+y |
|
1249 | 1248 | 47: print x |
|
1250 | 1249 | 48: a=5 |
|
1251 | 1250 | 49: print 'x',x,'y',y |
|
1252 | 1251 | |
|
1253 | 1252 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1254 | 1253 | called my_macro with:: |
|
1255 | 1254 | |
|
1256 | 1255 | In [55]: %macro my_macro 44-47 49 |
|
1257 | 1256 | |
|
1258 | 1257 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1259 | 1258 | in one pass. |
|
1260 | 1259 | |
|
1261 | 1260 | You don't need to give the line-numbers in order, and any given line |
|
1262 | 1261 | number can appear multiple times. You can assemble macros with any |
|
1263 | 1262 | lines from your input history in any order. |
|
1264 | 1263 | |
|
1265 | 1264 | The macro is a simple object which holds its value in an attribute, |
|
1266 | 1265 | but IPython's display system checks for macros and executes them as |
|
1267 | 1266 | code instead of printing them when you type their name. |
|
1268 | 1267 | |
|
1269 | 1268 | You can view a macro's contents by explicitly printing it with:: |
|
1270 | 1269 | |
|
1271 | 1270 | print macro_name |
|
1272 | 1271 | |
|
1273 | 1272 | """ |
|
1274 | 1273 | opts,args = self.parse_options(parameter_s,'rq',mode='list') |
|
1275 | 1274 | if not args: # List existing macros |
|
1276 | 1275 | return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)) |
|
1277 | 1276 | if len(args) == 1: |
|
1278 | 1277 | raise UsageError( |
|
1279 | 1278 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
1280 | 1279 | name, codefrom = args[0], " ".join(args[1:]) |
|
1281 | 1280 | |
|
1282 | 1281 | #print 'rng',ranges # dbg |
|
1283 | 1282 | try: |
|
1284 | 1283 | lines = self.shell.find_user_code(codefrom, 'r' in opts) |
|
1285 | 1284 | except (ValueError, TypeError) as e: |
|
1286 | 1285 | print(e.args[0]) |
|
1287 | 1286 | return |
|
1288 | 1287 | macro = Macro(lines) |
|
1289 | 1288 | self.shell.define_macro(name, macro) |
|
1290 | 1289 | if not ( 'q' in opts) : |
|
1291 | 1290 | print('Macro `%s` created. To execute, type its name (without quotes).' % name) |
|
1292 | 1291 | print('=== Macro contents: ===') |
|
1293 | 1292 | print(macro, end=' ') |
|
1294 | 1293 | |
|
1295 | 1294 | @magic_arguments.magic_arguments() |
|
1296 | 1295 | @magic_arguments.argument('output', type=str, default='', nargs='?', |
|
1297 | 1296 | help="""The name of the variable in which to store output. |
|
1298 | 1297 | This is a utils.io.CapturedIO object with stdout/err attributes |
|
1299 | 1298 | for the text of the captured output. |
|
1300 | 1299 | |
|
1301 | 1300 | CapturedOutput also has a show() method for displaying the output, |
|
1302 | 1301 | and __call__ as well, so you can use that to quickly display the |
|
1303 | 1302 | output. |
|
1304 | 1303 | |
|
1305 | 1304 | If unspecified, captured output is discarded. |
|
1306 | 1305 | """ |
|
1307 | 1306 | ) |
|
1308 | 1307 | @magic_arguments.argument('--no-stderr', action="store_true", |
|
1309 | 1308 | help="""Don't capture stderr.""" |
|
1310 | 1309 | ) |
|
1311 | 1310 | @magic_arguments.argument('--no-stdout', action="store_true", |
|
1312 | 1311 | help="""Don't capture stdout.""" |
|
1313 | 1312 | ) |
|
1314 | 1313 | @magic_arguments.argument('--no-display', action="store_true", |
|
1315 | 1314 | help="""Don't capture IPython's rich display.""" |
|
1316 | 1315 | ) |
|
1317 | 1316 | @cell_magic |
|
1318 | 1317 | def capture(self, line, cell): |
|
1319 | 1318 | """run the cell, capturing stdout, stderr, and IPython's rich display() calls.""" |
|
1320 | 1319 | args = magic_arguments.parse_argstring(self.capture, line) |
|
1321 | 1320 | out = not args.no_stdout |
|
1322 | 1321 | err = not args.no_stderr |
|
1323 | 1322 | disp = not args.no_display |
|
1324 | 1323 | with capture_output(out, err, disp) as io: |
|
1325 | 1324 | self.shell.run_cell(cell) |
|
1326 | 1325 | if args.output: |
|
1327 | 1326 | self.shell.user_ns[args.output] = io |
|
1328 | 1327 | |
|
1329 | 1328 | def parse_breakpoint(text, current_file): |
|
1330 | 1329 | '''Returns (file, line) for file:line and (current_file, line) for line''' |
|
1331 | 1330 | colon = text.find(':') |
|
1332 | 1331 | if colon == -1: |
|
1333 | 1332 | return current_file, int(text) |
|
1334 | 1333 | else: |
|
1335 | 1334 | return text[:colon], int(text[colon+1:]) |
|
1336 | 1335 | |
|
1337 | 1336 | def _format_time(timespan, precision=3): |
|
1338 | 1337 | """Formats the timespan in a human readable form""" |
|
1339 | 1338 | |
|
1340 | 1339 | if timespan >= 60.0: |
|
1341 | 1340 | # we have more than a minute, format that in a human readable form |
|
1342 | 1341 | # Idea from http://snipplr.com/view/5713/ |
|
1343 | 1342 | parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)] |
|
1344 | 1343 | time = [] |
|
1345 | 1344 | leftover = timespan |
|
1346 | 1345 | for suffix, length in parts: |
|
1347 | 1346 | value = int(leftover / length) |
|
1348 | 1347 | if value > 0: |
|
1349 | 1348 | leftover = leftover % length |
|
1350 | 1349 | time.append(u'%s%s' % (str(value), suffix)) |
|
1351 | 1350 | if leftover < 1: |
|
1352 | 1351 | break |
|
1353 | 1352 | return " ".join(time) |
|
1354 | 1353 | |
|
1355 | 1354 | |
|
1356 | 1355 | # Unfortunately the unicode 'micro' symbol can cause problems in |
|
1357 | 1356 | # certain terminals. |
|
1358 | 1357 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1359 | 1358 | # Try to prevent crashes by being more secure than it needs to |
|
1360 | 1359 | # E.g. eclipse is able to print a Β΅, but has no sys.stdout.encoding set. |
|
1361 | 1360 | units = [u"s", u"ms",u'us',"ns"] # the save value |
|
1362 | 1361 | if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding: |
|
1363 | 1362 | try: |
|
1364 | 1363 | u'\xb5'.encode(sys.stdout.encoding) |
|
1365 | 1364 | units = [u"s", u"ms",u'\xb5s',"ns"] |
|
1366 | 1365 | except: |
|
1367 | 1366 | pass |
|
1368 | 1367 | scaling = [1, 1e3, 1e6, 1e9] |
|
1369 | 1368 | |
|
1370 | 1369 | if timespan > 0.0: |
|
1371 | 1370 | order = min(-int(math.floor(math.log10(timespan)) // 3), 3) |
|
1372 | 1371 | else: |
|
1373 | 1372 | order = 3 |
|
1374 | 1373 | return u"%.*g %s" % (precision, timespan * scaling[order], units[order]) |
@@ -1,343 +1,339 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | Provides a reload() function that acts recursively. |
|
4 | 4 | |
|
5 | 5 | Python's normal :func:`python:reload` function only reloads the module that it's |
|
6 | 6 | passed. The :func:`reload` function in this module also reloads everything |
|
7 | 7 | imported from that module, which is useful when you're changing files deep |
|
8 | 8 | inside a package. |
|
9 | 9 | |
|
10 | 10 | To use this as your default reload function, type this for Python 2:: |
|
11 | 11 | |
|
12 | 12 | import __builtin__ |
|
13 | 13 | from IPython.lib import deepreload |
|
14 | 14 | __builtin__.reload = deepreload.reload |
|
15 | 15 | |
|
16 | 16 | Or this for Python 3:: |
|
17 | 17 | |
|
18 | 18 | import builtins |
|
19 | 19 | from IPython.lib import deepreload |
|
20 | 20 | builtins.reload = deepreload.reload |
|
21 | 21 | |
|
22 | 22 | A reference to the original :func:`python:reload` is stored in this module as |
|
23 | 23 | :data:`original_reload`, so you can restore it later. |
|
24 | 24 | |
|
25 | 25 | This code is almost entirely based on knee.py, which is a Python |
|
26 | 26 | re-implementation of hierarchical module import. |
|
27 | 27 | """ |
|
28 | 28 | #***************************************************************************** |
|
29 | 29 | # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu> |
|
30 | 30 | # |
|
31 | 31 | # Distributed under the terms of the BSD License. The full license is in |
|
32 | 32 | # the file COPYING, distributed as part of this software. |
|
33 | 33 | #***************************************************************************** |
|
34 | 34 | |
|
35 | import builtins as builtin_mod | |
|
35 | 36 | from contextlib import contextmanager |
|
36 | 37 | import imp |
|
37 | 38 | import sys |
|
38 | 39 | |
|
39 | 40 | from types import ModuleType |
|
40 | 41 | from warnings import warn |
|
41 | 42 | |
|
42 | from IPython.utils.py3compat import builtin_mod, builtin_mod_name | |
|
43 | ||
|
44 | 43 | original_import = builtin_mod.__import__ |
|
45 | 44 | |
|
46 | 45 | @contextmanager |
|
47 | 46 | def replace_import_hook(new_import): |
|
48 | 47 | saved_import = builtin_mod.__import__ |
|
49 | 48 | builtin_mod.__import__ = new_import |
|
50 | 49 | try: |
|
51 | 50 | yield |
|
52 | 51 | finally: |
|
53 | 52 | builtin_mod.__import__ = saved_import |
|
54 | 53 | |
|
55 | 54 | def get_parent(globals, level): |
|
56 | 55 | """ |
|
57 | 56 | parent, name = get_parent(globals, level) |
|
58 | 57 | |
|
59 | 58 | Return the package that an import is being performed in. If globals comes |
|
60 | 59 | from the module foo.bar.bat (not itself a package), this returns the |
|
61 | 60 | sys.modules entry for foo.bar. If globals is from a package's __init__.py, |
|
62 | 61 | the package's entry in sys.modules is returned. |
|
63 | 62 | |
|
64 | 63 | If globals doesn't come from a package or a module in a package, or a |
|
65 | 64 | corresponding entry is not found in sys.modules, None is returned. |
|
66 | 65 | """ |
|
67 | 66 | orig_level = level |
|
68 | 67 | |
|
69 | 68 | if not level or not isinstance(globals, dict): |
|
70 | 69 | return None, '' |
|
71 | 70 | |
|
72 | 71 | pkgname = globals.get('__package__', None) |
|
73 | 72 | |
|
74 | 73 | if pkgname is not None: |
|
75 | 74 | # __package__ is set, so use it |
|
76 | 75 | if not hasattr(pkgname, 'rindex'): |
|
77 | 76 | raise ValueError('__package__ set to non-string') |
|
78 | 77 | if len(pkgname) == 0: |
|
79 | 78 | if level > 0: |
|
80 | 79 | raise ValueError('Attempted relative import in non-package') |
|
81 | 80 | return None, '' |
|
82 | 81 | name = pkgname |
|
83 | 82 | else: |
|
84 | 83 | # __package__ not set, so figure it out and set it |
|
85 | 84 | if '__name__' not in globals: |
|
86 | 85 | return None, '' |
|
87 | 86 | modname = globals['__name__'] |
|
88 | 87 | |
|
89 | 88 | if '__path__' in globals: |
|
90 | 89 | # __path__ is set, so modname is already the package name |
|
91 | 90 | globals['__package__'] = name = modname |
|
92 | 91 | else: |
|
93 | 92 | # Normal module, so work out the package name if any |
|
94 | 93 | lastdot = modname.rfind('.') |
|
95 | 94 | if lastdot < 0 < level: |
|
96 | 95 | raise ValueError("Attempted relative import in non-package") |
|
97 | 96 | if lastdot < 0: |
|
98 | 97 | globals['__package__'] = None |
|
99 | 98 | return None, '' |
|
100 | 99 | globals['__package__'] = name = modname[:lastdot] |
|
101 | 100 | |
|
102 | 101 | dot = len(name) |
|
103 | 102 | for x in range(level, 1, -1): |
|
104 | 103 | try: |
|
105 | 104 | dot = name.rindex('.', 0, dot) |
|
106 | 105 | except ValueError: |
|
107 | 106 | raise ValueError("attempted relative import beyond top-level " |
|
108 | 107 | "package") |
|
109 | 108 | name = name[:dot] |
|
110 | 109 | |
|
111 | 110 | try: |
|
112 | 111 | parent = sys.modules[name] |
|
113 | 112 | except: |
|
114 | 113 | if orig_level < 1: |
|
115 | 114 | warn("Parent module '%.200s' not found while handling absolute " |
|
116 | 115 | "import" % name) |
|
117 | 116 | parent = None |
|
118 | 117 | else: |
|
119 | 118 | raise SystemError("Parent module '%.200s' not loaded, cannot " |
|
120 | 119 | "perform relative import" % name) |
|
121 | 120 | |
|
122 | 121 | # We expect, but can't guarantee, if parent != None, that: |
|
123 | 122 | # - parent.__name__ == name |
|
124 | 123 | # - parent.__dict__ is globals |
|
125 | 124 | # If this is violated... Who cares? |
|
126 | 125 | return parent, name |
|
127 | 126 | |
|
128 | 127 | def load_next(mod, altmod, name, buf): |
|
129 | 128 | """ |
|
130 | 129 | mod, name, buf = load_next(mod, altmod, name, buf) |
|
131 | 130 | |
|
132 | 131 | altmod is either None or same as mod |
|
133 | 132 | """ |
|
134 | 133 | |
|
135 | 134 | if len(name) == 0: |
|
136 | 135 | # completely empty module name should only happen in |
|
137 | 136 | # 'from . import' (or '__import__("")') |
|
138 | 137 | return mod, None, buf |
|
139 | 138 | |
|
140 | 139 | dot = name.find('.') |
|
141 | 140 | if dot == 0: |
|
142 | 141 | raise ValueError('Empty module name') |
|
143 | 142 | |
|
144 | 143 | if dot < 0: |
|
145 | 144 | subname = name |
|
146 | 145 | next = None |
|
147 | 146 | else: |
|
148 | 147 | subname = name[:dot] |
|
149 | 148 | next = name[dot+1:] |
|
150 | 149 | |
|
151 | 150 | if buf != '': |
|
152 | 151 | buf += '.' |
|
153 | 152 | buf += subname |
|
154 | 153 | |
|
155 | 154 | result = import_submodule(mod, subname, buf) |
|
156 | 155 | if result is None and mod != altmod: |
|
157 | 156 | result = import_submodule(altmod, subname, subname) |
|
158 | 157 | if result is not None: |
|
159 | 158 | buf = subname |
|
160 | 159 | |
|
161 | 160 | if result is None: |
|
162 | 161 | raise ImportError("No module named %.200s" % name) |
|
163 | 162 | |
|
164 | 163 | return result, next, buf |
|
165 | 164 | |
|
166 | 165 | # Need to keep track of what we've already reloaded to prevent cyclic evil |
|
167 | 166 | found_now = {} |
|
168 | 167 | |
|
169 | 168 | def import_submodule(mod, subname, fullname): |
|
170 | 169 | """m = import_submodule(mod, subname, fullname)""" |
|
171 | 170 | # Require: |
|
172 | 171 | # if mod == None: subname == fullname |
|
173 | 172 | # else: mod.__name__ + "." + subname == fullname |
|
174 | 173 | |
|
175 | 174 | global found_now |
|
176 | 175 | if fullname in found_now and fullname in sys.modules: |
|
177 | 176 | m = sys.modules[fullname] |
|
178 | 177 | else: |
|
179 | 178 | print('Reloading', fullname) |
|
180 | 179 | found_now[fullname] = 1 |
|
181 | 180 | oldm = sys.modules.get(fullname, None) |
|
182 | 181 | |
|
183 | 182 | if mod is None: |
|
184 | 183 | path = None |
|
185 | 184 | elif hasattr(mod, '__path__'): |
|
186 | 185 | path = mod.__path__ |
|
187 | 186 | else: |
|
188 | 187 | return None |
|
189 | 188 | |
|
190 | 189 | try: |
|
191 | 190 | # This appears to be necessary on Python 3, because imp.find_module() |
|
192 | 191 | # tries to import standard libraries (like io) itself, and we don't |
|
193 | 192 | # want them to be processed by our deep_import_hook. |
|
194 | 193 | with replace_import_hook(original_import): |
|
195 | 194 | fp, filename, stuff = imp.find_module(subname, path) |
|
196 | 195 | except ImportError: |
|
197 | 196 | return None |
|
198 | 197 | |
|
199 | 198 | try: |
|
200 | 199 | m = imp.load_module(fullname, fp, filename, stuff) |
|
201 | 200 | except: |
|
202 | 201 | # load_module probably removed name from modules because of |
|
203 | 202 | # the error. Put back the original module object. |
|
204 | 203 | if oldm: |
|
205 | 204 | sys.modules[fullname] = oldm |
|
206 | 205 | raise |
|
207 | 206 | finally: |
|
208 | 207 | if fp: fp.close() |
|
209 | 208 | |
|
210 | 209 | add_submodule(mod, m, fullname, subname) |
|
211 | 210 | |
|
212 | 211 | return m |
|
213 | 212 | |
|
214 | 213 | def add_submodule(mod, submod, fullname, subname): |
|
215 | 214 | """mod.{subname} = submod""" |
|
216 | 215 | if mod is None: |
|
217 | 216 | return #Nothing to do here. |
|
218 | 217 | |
|
219 | 218 | if submod is None: |
|
220 | 219 | submod = sys.modules[fullname] |
|
221 | 220 | |
|
222 | 221 | setattr(mod, subname, submod) |
|
223 | 222 | |
|
224 | 223 | return |
|
225 | 224 | |
|
226 | 225 | def ensure_fromlist(mod, fromlist, buf, recursive): |
|
227 | 226 | """Handle 'from module import a, b, c' imports.""" |
|
228 | 227 | if not hasattr(mod, '__path__'): |
|
229 | 228 | return |
|
230 | 229 | for item in fromlist: |
|
231 | 230 | if not hasattr(item, 'rindex'): |
|
232 | 231 | raise TypeError("Item in ``from list'' not a string") |
|
233 | 232 | if item == '*': |
|
234 | 233 | if recursive: |
|
235 | 234 | continue # avoid endless recursion |
|
236 | 235 | try: |
|
237 | 236 | all = mod.__all__ |
|
238 | 237 | except AttributeError: |
|
239 | 238 | pass |
|
240 | 239 | else: |
|
241 | 240 | ret = ensure_fromlist(mod, all, buf, 1) |
|
242 | 241 | if not ret: |
|
243 | 242 | return 0 |
|
244 | 243 | elif not hasattr(mod, item): |
|
245 | 244 | import_submodule(mod, item, buf + '.' + item) |
|
246 | 245 | |
|
247 | 246 | def deep_import_hook(name, globals=None, locals=None, fromlist=None, level=-1): |
|
248 | 247 | """Replacement for __import__()""" |
|
249 | 248 | parent, buf = get_parent(globals, level) |
|
250 | 249 | |
|
251 | 250 | head, name, buf = load_next(parent, None if level < 0 else parent, name, buf) |
|
252 | 251 | |
|
253 | 252 | tail = head |
|
254 | 253 | while name: |
|
255 | 254 | tail, name, buf = load_next(tail, tail, name, buf) |
|
256 | 255 | |
|
257 | 256 | # If tail is None, both get_parent and load_next found |
|
258 | 257 | # an empty module name: someone called __import__("") or |
|
259 | 258 | # doctored faulty bytecode |
|
260 | 259 | if tail is None: |
|
261 | 260 | raise ValueError('Empty module name') |
|
262 | 261 | |
|
263 | 262 | if not fromlist: |
|
264 | 263 | return head |
|
265 | 264 | |
|
266 | 265 | ensure_fromlist(tail, fromlist, buf, 0) |
|
267 | 266 | return tail |
|
268 | 267 | |
|
269 | 268 | modules_reloading = {} |
|
270 | 269 | |
|
271 | 270 | def deep_reload_hook(m): |
|
272 | 271 | """Replacement for reload().""" |
|
273 | 272 | if not isinstance(m, ModuleType): |
|
274 | 273 | raise TypeError("reload() argument must be module") |
|
275 | 274 | |
|
276 | 275 | name = m.__name__ |
|
277 | 276 | |
|
278 | 277 | if name not in sys.modules: |
|
279 | 278 | raise ImportError("reload(): module %.200s not in sys.modules" % name) |
|
280 | 279 | |
|
281 | 280 | global modules_reloading |
|
282 | 281 | try: |
|
283 | 282 | return modules_reloading[name] |
|
284 | 283 | except: |
|
285 | 284 | modules_reloading[name] = m |
|
286 | 285 | |
|
287 | 286 | dot = name.rfind('.') |
|
288 | 287 | if dot < 0: |
|
289 | 288 | subname = name |
|
290 | 289 | path = None |
|
291 | 290 | else: |
|
292 | 291 | try: |
|
293 | 292 | parent = sys.modules[name[:dot]] |
|
294 | 293 | except KeyError: |
|
295 | 294 | modules_reloading.clear() |
|
296 | 295 | raise ImportError("reload(): parent %.200s not in sys.modules" % name[:dot]) |
|
297 | 296 | subname = name[dot+1:] |
|
298 | 297 | path = getattr(parent, "__path__", None) |
|
299 | 298 | |
|
300 | 299 | try: |
|
301 | 300 | # This appears to be necessary on Python 3, because imp.find_module() |
|
302 | 301 | # tries to import standard libraries (like io) itself, and we don't |
|
303 | 302 | # want them to be processed by our deep_import_hook. |
|
304 | 303 | with replace_import_hook(original_import): |
|
305 | 304 | fp, filename, stuff = imp.find_module(subname, path) |
|
306 | 305 | finally: |
|
307 | 306 | modules_reloading.clear() |
|
308 | 307 | |
|
309 | 308 | try: |
|
310 | 309 | newm = imp.load_module(name, fp, filename, stuff) |
|
311 | 310 | except: |
|
312 | 311 | # load_module probably removed name from modules because of |
|
313 | 312 | # the error. Put back the original module object. |
|
314 | 313 | sys.modules[name] = m |
|
315 | 314 | raise |
|
316 | 315 | finally: |
|
317 | 316 | if fp: fp.close() |
|
318 | 317 | |
|
319 | 318 | modules_reloading.clear() |
|
320 | 319 | return newm |
|
321 | 320 | |
|
322 | 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 | 324 | # Replacement for reload() |
|
329 |
def reload(module, exclude=('sys', 'os.path', builtin |
|
|
325 | def reload(module, exclude=('sys', 'os.path', 'builtins', '__main__', | |
|
330 | 326 | 'numpy', 'numpy._globals')): |
|
331 | 327 | """Recursively reload all modules used in the given module. Optionally |
|
332 | 328 | takes a list of modules to exclude from reloading. The default exclude |
|
333 | 329 | list contains sys, __main__, and __builtin__, to prevent, e.g., resetting |
|
334 | 330 | display, exception, and io hooks. |
|
335 | 331 | """ |
|
336 | 332 | global found_now |
|
337 | 333 | for i in exclude: |
|
338 | 334 | found_now[i] = 1 |
|
339 | 335 | try: |
|
340 | 336 | with replace_import_hook(deep_import_hook): |
|
341 | 337 | return deep_reload_hook(module) |
|
342 | 338 | finally: |
|
343 | 339 | found_now = {} |
@@ -1,136 +1,136 b'' | |||
|
1 | 1 | """Global IPython app to support test running. |
|
2 | 2 | |
|
3 | 3 | We must start our own ipython object and heavily muck with it so that all the |
|
4 | 4 | modifications IPython makes to system behavior don't send the doctest machinery |
|
5 | 5 | into a fit. This code should be considered a gross hack, but it gets the job |
|
6 | 6 | done. |
|
7 | 7 | """ |
|
8 | 8 | |
|
9 | 9 | # Copyright (c) IPython Development Team. |
|
10 | 10 | # Distributed under the terms of the Modified BSD License. |
|
11 | 11 | |
|
12 | import builtins as builtin_mod | |
|
12 | 13 | import sys |
|
13 | 14 | import warnings |
|
14 | 15 | |
|
15 | 16 | from . import tools |
|
16 | 17 | |
|
17 | 18 | from IPython.core import page |
|
18 | 19 | from IPython.utils import io |
|
19 | 20 | from IPython.utils import py3compat |
|
20 | from IPython.utils.py3compat import builtin_mod | |
|
21 | 21 | from IPython.terminal.interactiveshell import TerminalInteractiveShell |
|
22 | 22 | |
|
23 | 23 | |
|
24 | 24 | class StreamProxy(io.IOStream): |
|
25 | 25 | """Proxy for sys.stdout/err. This will request the stream *at call time* |
|
26 | 26 | allowing for nose's Capture plugin's redirection of sys.stdout/err. |
|
27 | 27 | |
|
28 | 28 | Parameters |
|
29 | 29 | ---------- |
|
30 | 30 | name : str |
|
31 | 31 | The name of the stream. This will be requested anew at every call |
|
32 | 32 | """ |
|
33 | 33 | |
|
34 | 34 | def __init__(self, name): |
|
35 | 35 | warnings.warn("StreamProxy is deprecated and unused as of IPython 5", DeprecationWarning, |
|
36 | 36 | stacklevel=2, |
|
37 | 37 | ) |
|
38 | 38 | self.name=name |
|
39 | 39 | |
|
40 | 40 | @property |
|
41 | 41 | def stream(self): |
|
42 | 42 | return getattr(sys, self.name) |
|
43 | 43 | |
|
44 | 44 | def flush(self): |
|
45 | 45 | self.stream.flush() |
|
46 | 46 | |
|
47 | 47 | |
|
48 | 48 | def get_ipython(): |
|
49 | 49 | # This will get replaced by the real thing once we start IPython below |
|
50 | 50 | return start_ipython() |
|
51 | 51 | |
|
52 | 52 | |
|
53 | 53 | # A couple of methods to override those in the running IPython to interact |
|
54 | 54 | # better with doctest (doctest captures on raw stdout, so we need to direct |
|
55 | 55 | # various types of output there otherwise it will miss them). |
|
56 | 56 | |
|
57 | 57 | def xsys(self, cmd): |
|
58 | 58 | """Replace the default system call with a capturing one for doctest. |
|
59 | 59 | """ |
|
60 | 60 | # We use getoutput, but we need to strip it because pexpect captures |
|
61 | 61 | # the trailing newline differently from commands.getoutput |
|
62 | 62 | print(self.getoutput(cmd, split=False, depth=1).rstrip(), end='', file=sys.stdout) |
|
63 | 63 | sys.stdout.flush() |
|
64 | 64 | |
|
65 | 65 | |
|
66 | 66 | def _showtraceback(self, etype, evalue, stb): |
|
67 | 67 | """Print the traceback purely on stdout for doctest to capture it. |
|
68 | 68 | """ |
|
69 | 69 | print(self.InteractiveTB.stb2text(stb), file=sys.stdout) |
|
70 | 70 | |
|
71 | 71 | |
|
72 | 72 | def start_ipython(): |
|
73 | 73 | """Start a global IPython shell, which we need for IPython-specific syntax. |
|
74 | 74 | """ |
|
75 | 75 | global get_ipython |
|
76 | 76 | |
|
77 | 77 | # This function should only ever run once! |
|
78 | 78 | if hasattr(start_ipython, 'already_called'): |
|
79 | 79 | return |
|
80 | 80 | start_ipython.already_called = True |
|
81 | 81 | |
|
82 | 82 | # Store certain global objects that IPython modifies |
|
83 | 83 | _displayhook = sys.displayhook |
|
84 | 84 | _excepthook = sys.excepthook |
|
85 | 85 | _main = sys.modules.get('__main__') |
|
86 | 86 | |
|
87 | 87 | # Create custom argv and namespaces for our IPython to be test-friendly |
|
88 | 88 | config = tools.default_config() |
|
89 | 89 | config.TerminalInteractiveShell.simple_prompt = True |
|
90 | 90 | |
|
91 | 91 | # Create and initialize our test-friendly IPython instance. |
|
92 | 92 | shell = TerminalInteractiveShell.instance(config=config, |
|
93 | 93 | ) |
|
94 | 94 | |
|
95 | 95 | # A few more tweaks needed for playing nicely with doctests... |
|
96 | 96 | |
|
97 | 97 | # remove history file |
|
98 | 98 | shell.tempfiles.append(config.HistoryManager.hist_file) |
|
99 | 99 | |
|
100 | 100 | # These traps are normally only active for interactive use, set them |
|
101 | 101 | # permanently since we'll be mocking interactive sessions. |
|
102 | 102 | shell.builtin_trap.activate() |
|
103 | 103 | |
|
104 | 104 | # Modify the IPython system call with one that uses getoutput, so that we |
|
105 | 105 | # can capture subcommands and print them to Python's stdout, otherwise the |
|
106 | 106 | # doctest machinery would miss them. |
|
107 | 107 | shell.system = py3compat.MethodType(xsys, shell) |
|
108 | 108 | |
|
109 | 109 | shell._showtraceback = py3compat.MethodType(_showtraceback, shell) |
|
110 | 110 | |
|
111 | 111 | # IPython is ready, now clean up some global state... |
|
112 | 112 | |
|
113 | 113 | # Deactivate the various python system hooks added by ipython for |
|
114 | 114 | # interactive convenience so we don't confuse the doctest system |
|
115 | 115 | sys.modules['__main__'] = _main |
|
116 | 116 | sys.displayhook = _displayhook |
|
117 | 117 | sys.excepthook = _excepthook |
|
118 | 118 | |
|
119 | 119 | # So that ipython magics and aliases can be doctested (they work by making |
|
120 | 120 | # a call into a global _ip object). Also make the top-level get_ipython |
|
121 | 121 | # now return this without recursively calling here again. |
|
122 | 122 | _ip = shell |
|
123 | 123 | get_ipython = _ip.get_ipython |
|
124 | 124 | builtin_mod._ip = _ip |
|
125 | 125 | builtin_mod.get_ipython = get_ipython |
|
126 | 126 | |
|
127 | 127 | # Override paging, so we don't require user interaction during the tests. |
|
128 | 128 | def nopage(strng, start=0, screen_lines=0, pager_cmd=None): |
|
129 | 129 | if isinstance(strng, dict): |
|
130 | 130 | strng = strng.get('text/plain', '') |
|
131 | 131 | print(strng) |
|
132 | 132 | |
|
133 | 133 | page.orig_page = page.pager_page |
|
134 | 134 | page.pager_page = nopage |
|
135 | 135 | |
|
136 | 136 | return _ip |
@@ -1,766 +1,764 b'' | |||
|
1 | 1 | """Nose Plugin that supports IPython doctests. |
|
2 | 2 | |
|
3 | 3 | Limitations: |
|
4 | 4 | |
|
5 | 5 | - When generating examples for use as doctests, make sure that you have |
|
6 | 6 | pretty-printing OFF. This can be done either by setting the |
|
7 | 7 | ``PlainTextFormatter.pprint`` option in your configuration file to False, or |
|
8 | 8 | by interactively disabling it with %Pprint. This is required so that IPython |
|
9 | 9 | output matches that of normal Python, which is used by doctest for internal |
|
10 | 10 | execution. |
|
11 | 11 | |
|
12 | 12 | - Do not rely on specific prompt numbers for results (such as using |
|
13 | 13 | '_34==True', for example). For IPython tests run via an external process the |
|
14 | 14 | prompt numbers may be different, and IPython tests run as normal python code |
|
15 | 15 | won't even have these special _NN variables set at all. |
|
16 | 16 | """ |
|
17 | 17 | |
|
18 | 18 | #----------------------------------------------------------------------------- |
|
19 | 19 | # Module imports |
|
20 | 20 | |
|
21 | 21 | # From the standard library |
|
22 | import builtins as builtin_mod | |
|
22 | 23 | import doctest |
|
23 | 24 | import inspect |
|
24 | 25 | import logging |
|
25 | 26 | import os |
|
26 | 27 | import re |
|
27 | 28 | import sys |
|
28 | 29 | from importlib import import_module |
|
29 | 30 | from io import StringIO |
|
30 | 31 | |
|
31 | 32 | from testpath import modified_env |
|
32 | 33 | |
|
33 | 34 | from inspect import getmodule |
|
34 | 35 | |
|
35 | 36 | # We are overriding the default doctest runner, so we need to import a few |
|
36 | 37 | # things from doctest directly |
|
37 | 38 | from doctest import (REPORTING_FLAGS, REPORT_ONLY_FIRST_FAILURE, |
|
38 | 39 | _unittest_reportflags, DocTestRunner, |
|
39 | 40 | _extract_future_flags, pdb, _OutputRedirectingPdb, |
|
40 | 41 | _exception_traceback, |
|
41 | 42 | linecache) |
|
42 | 43 | |
|
43 | 44 | # Third-party modules |
|
44 | 45 | |
|
45 | 46 | from nose.plugins import doctests, Plugin |
|
46 | 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 | 50 | # Module globals and other constants |
|
53 | 51 | #----------------------------------------------------------------------------- |
|
54 | 52 | |
|
55 | 53 | log = logging.getLogger(__name__) |
|
56 | 54 | |
|
57 | 55 | |
|
58 | 56 | #----------------------------------------------------------------------------- |
|
59 | 57 | # Classes and functions |
|
60 | 58 | #----------------------------------------------------------------------------- |
|
61 | 59 | |
|
62 | 60 | def is_extension_module(filename): |
|
63 | 61 | """Return whether the given filename is an extension module. |
|
64 | 62 | |
|
65 | 63 | This simply checks that the extension is either .so or .pyd. |
|
66 | 64 | """ |
|
67 | 65 | return os.path.splitext(filename)[1].lower() in ('.so','.pyd') |
|
68 | 66 | |
|
69 | 67 | |
|
70 | 68 | class DocTestSkip(object): |
|
71 | 69 | """Object wrapper for doctests to be skipped.""" |
|
72 | 70 | |
|
73 | 71 | ds_skip = """Doctest to skip. |
|
74 | 72 | >>> 1 #doctest: +SKIP |
|
75 | 73 | """ |
|
76 | 74 | |
|
77 | 75 | def __init__(self,obj): |
|
78 | 76 | self.obj = obj |
|
79 | 77 | |
|
80 | 78 | def __getattribute__(self,key): |
|
81 | 79 | if key == '__doc__': |
|
82 | 80 | return DocTestSkip.ds_skip |
|
83 | 81 | else: |
|
84 | 82 | return getattr(object.__getattribute__(self,'obj'),key) |
|
85 | 83 | |
|
86 | 84 | # Modified version of the one in the stdlib, that fixes a python bug (doctests |
|
87 | 85 | # not found in extension modules, http://bugs.python.org/issue3158) |
|
88 | 86 | class DocTestFinder(doctest.DocTestFinder): |
|
89 | 87 | |
|
90 | 88 | def _from_module(self, module, object): |
|
91 | 89 | """ |
|
92 | 90 | Return true if the given object is defined in the given |
|
93 | 91 | module. |
|
94 | 92 | """ |
|
95 | 93 | if module is None: |
|
96 | 94 | return True |
|
97 | 95 | elif inspect.isfunction(object): |
|
98 | 96 | return module.__dict__ is object.__globals__ |
|
99 | 97 | elif inspect.isbuiltin(object): |
|
100 | 98 | return module.__name__ == object.__module__ |
|
101 | 99 | elif inspect.isclass(object): |
|
102 | 100 | return module.__name__ == object.__module__ |
|
103 | 101 | elif inspect.ismethod(object): |
|
104 | 102 | # This one may be a bug in cython that fails to correctly set the |
|
105 | 103 | # __module__ attribute of methods, but since the same error is easy |
|
106 | 104 | # to make by extension code writers, having this safety in place |
|
107 | 105 | # isn't such a bad idea |
|
108 | 106 | return module.__name__ == object.__self__.__class__.__module__ |
|
109 | 107 | elif inspect.getmodule(object) is not None: |
|
110 | 108 | return module is inspect.getmodule(object) |
|
111 | 109 | elif hasattr(object, '__module__'): |
|
112 | 110 | return module.__name__ == object.__module__ |
|
113 | 111 | elif isinstance(object, property): |
|
114 | 112 | return True # [XX] no way not be sure. |
|
115 | 113 | elif inspect.ismethoddescriptor(object): |
|
116 | 114 | # Unbound PyQt signals reach this point in Python 3.4b3, and we want |
|
117 | 115 | # to avoid throwing an error. See also http://bugs.python.org/issue3158 |
|
118 | 116 | return False |
|
119 | 117 | else: |
|
120 | 118 | raise ValueError("object must be a class or function, got %r" % object) |
|
121 | 119 | |
|
122 | 120 | def _find(self, tests, obj, name, module, source_lines, globs, seen): |
|
123 | 121 | """ |
|
124 | 122 | Find tests for the given object and any contained objects, and |
|
125 | 123 | add them to `tests`. |
|
126 | 124 | """ |
|
127 | 125 | print('_find for:', obj, name, module) # dbg |
|
128 | 126 | if hasattr(obj,"skip_doctest"): |
|
129 | 127 | #print 'SKIPPING DOCTEST FOR:',obj # dbg |
|
130 | 128 | obj = DocTestSkip(obj) |
|
131 | 129 | |
|
132 | 130 | doctest.DocTestFinder._find(self,tests, obj, name, module, |
|
133 | 131 | source_lines, globs, seen) |
|
134 | 132 | |
|
135 | 133 | # Below we re-run pieces of the above method with manual modifications, |
|
136 | 134 | # because the original code is buggy and fails to correctly identify |
|
137 | 135 | # doctests in extension modules. |
|
138 | 136 | |
|
139 | 137 | # Local shorthands |
|
140 | 138 | from inspect import isroutine, isclass |
|
141 | 139 | |
|
142 | 140 | # Look for tests in a module's contained objects. |
|
143 | 141 | if inspect.ismodule(obj) and self._recurse: |
|
144 | 142 | for valname, val in obj.__dict__.items(): |
|
145 | 143 | valname1 = '%s.%s' % (name, valname) |
|
146 | 144 | if ( (isroutine(val) or isclass(val)) |
|
147 | 145 | and self._from_module(module, val) ): |
|
148 | 146 | |
|
149 | 147 | self._find(tests, val, valname1, module, source_lines, |
|
150 | 148 | globs, seen) |
|
151 | 149 | |
|
152 | 150 | # Look for tests in a class's contained objects. |
|
153 | 151 | if inspect.isclass(obj) and self._recurse: |
|
154 | 152 | #print 'RECURSE into class:',obj # dbg |
|
155 | 153 | for valname, val in obj.__dict__.items(): |
|
156 | 154 | # Special handling for staticmethod/classmethod. |
|
157 | 155 | if isinstance(val, staticmethod): |
|
158 | 156 | val = getattr(obj, valname) |
|
159 | 157 | if isinstance(val, classmethod): |
|
160 | 158 | val = getattr(obj, valname).__func__ |
|
161 | 159 | |
|
162 | 160 | # Recurse to methods, properties, and nested classes. |
|
163 | 161 | if ((inspect.isfunction(val) or inspect.isclass(val) or |
|
164 | 162 | inspect.ismethod(val) or |
|
165 | 163 | isinstance(val, property)) and |
|
166 | 164 | self._from_module(module, val)): |
|
167 | 165 | valname = '%s.%s' % (name, valname) |
|
168 | 166 | self._find(tests, val, valname, module, source_lines, |
|
169 | 167 | globs, seen) |
|
170 | 168 | |
|
171 | 169 | |
|
172 | 170 | class IPDoctestOutputChecker(doctest.OutputChecker): |
|
173 | 171 | """Second-chance checker with support for random tests. |
|
174 | 172 | |
|
175 | 173 | If the default comparison doesn't pass, this checker looks in the expected |
|
176 | 174 | output string for flags that tell us to ignore the output. |
|
177 | 175 | """ |
|
178 | 176 | |
|
179 | 177 | random_re = re.compile(r'#\s*random\s+') |
|
180 | 178 | |
|
181 | 179 | def check_output(self, want, got, optionflags): |
|
182 | 180 | """Check output, accepting special markers embedded in the output. |
|
183 | 181 | |
|
184 | 182 | If the output didn't pass the default validation but the special string |
|
185 | 183 | '#random' is included, we accept it.""" |
|
186 | 184 | |
|
187 | 185 | # Let the original tester verify first, in case people have valid tests |
|
188 | 186 | # that happen to have a comment saying '#random' embedded in. |
|
189 | 187 | ret = doctest.OutputChecker.check_output(self, want, got, |
|
190 | 188 | optionflags) |
|
191 | 189 | if not ret and self.random_re.search(want): |
|
192 | 190 | #print >> sys.stderr, 'RANDOM OK:',want # dbg |
|
193 | 191 | return True |
|
194 | 192 | |
|
195 | 193 | return ret |
|
196 | 194 | |
|
197 | 195 | |
|
198 | 196 | class DocTestCase(doctests.DocTestCase): |
|
199 | 197 | """Proxy for DocTestCase: provides an address() method that |
|
200 | 198 | returns the correct address for the doctest case. Otherwise |
|
201 | 199 | acts as a proxy to the test case. To provide hints for address(), |
|
202 | 200 | an obj may also be passed -- this will be used as the test object |
|
203 | 201 | for purposes of determining the test address, if it is provided. |
|
204 | 202 | """ |
|
205 | 203 | |
|
206 | 204 | # Note: this method was taken from numpy's nosetester module. |
|
207 | 205 | |
|
208 | 206 | # Subclass nose.plugins.doctests.DocTestCase to work around a bug in |
|
209 | 207 | # its constructor that blocks non-default arguments from being passed |
|
210 | 208 | # down into doctest.DocTestCase |
|
211 | 209 | |
|
212 | 210 | def __init__(self, test, optionflags=0, setUp=None, tearDown=None, |
|
213 | 211 | checker=None, obj=None, result_var='_'): |
|
214 | 212 | self._result_var = result_var |
|
215 | 213 | doctests.DocTestCase.__init__(self, test, |
|
216 | 214 | optionflags=optionflags, |
|
217 | 215 | setUp=setUp, tearDown=tearDown, |
|
218 | 216 | checker=checker) |
|
219 | 217 | # Now we must actually copy the original constructor from the stdlib |
|
220 | 218 | # doctest class, because we can't call it directly and a bug in nose |
|
221 | 219 | # means it never gets passed the right arguments. |
|
222 | 220 | |
|
223 | 221 | self._dt_optionflags = optionflags |
|
224 | 222 | self._dt_checker = checker |
|
225 | 223 | self._dt_test = test |
|
226 | 224 | self._dt_test_globs_ori = test.globs |
|
227 | 225 | self._dt_setUp = setUp |
|
228 | 226 | self._dt_tearDown = tearDown |
|
229 | 227 | |
|
230 | 228 | # XXX - store this runner once in the object! |
|
231 | 229 | runner = IPDocTestRunner(optionflags=optionflags, |
|
232 | 230 | checker=checker, verbose=False) |
|
233 | 231 | self._dt_runner = runner |
|
234 | 232 | |
|
235 | 233 | |
|
236 | 234 | # Each doctest should remember the directory it was loaded from, so |
|
237 | 235 | # things like %run work without too many contortions |
|
238 | 236 | self._ori_dir = os.path.dirname(test.filename) |
|
239 | 237 | |
|
240 | 238 | # Modified runTest from the default stdlib |
|
241 | 239 | def runTest(self): |
|
242 | 240 | test = self._dt_test |
|
243 | 241 | runner = self._dt_runner |
|
244 | 242 | |
|
245 | 243 | old = sys.stdout |
|
246 | 244 | new = StringIO() |
|
247 | 245 | optionflags = self._dt_optionflags |
|
248 | 246 | |
|
249 | 247 | if not (optionflags & REPORTING_FLAGS): |
|
250 | 248 | # The option flags don't include any reporting flags, |
|
251 | 249 | # so add the default reporting flags |
|
252 | 250 | optionflags |= _unittest_reportflags |
|
253 | 251 | |
|
254 | 252 | try: |
|
255 | 253 | # Save our current directory and switch out to the one where the |
|
256 | 254 | # test was originally created, in case another doctest did a |
|
257 | 255 | # directory change. We'll restore this in the finally clause. |
|
258 | 256 | curdir = os.getcwd() |
|
259 | 257 | #print 'runTest in dir:', self._ori_dir # dbg |
|
260 | 258 | os.chdir(self._ori_dir) |
|
261 | 259 | |
|
262 | 260 | runner.DIVIDER = "-"*70 |
|
263 | 261 | failures, tries = runner.run(test,out=new.write, |
|
264 | 262 | clear_globs=False) |
|
265 | 263 | finally: |
|
266 | 264 | sys.stdout = old |
|
267 | 265 | os.chdir(curdir) |
|
268 | 266 | |
|
269 | 267 | if failures: |
|
270 | 268 | raise self.failureException(self.format_failure(new.getvalue())) |
|
271 | 269 | |
|
272 | 270 | def setUp(self): |
|
273 | 271 | """Modified test setup that syncs with ipython namespace""" |
|
274 | 272 | #print "setUp test", self._dt_test.examples # dbg |
|
275 | 273 | if isinstance(self._dt_test.examples[0], IPExample): |
|
276 | 274 | # for IPython examples *only*, we swap the globals with the ipython |
|
277 | 275 | # namespace, after updating it with the globals (which doctest |
|
278 | 276 | # fills with the necessary info from the module being tested). |
|
279 | 277 | self.user_ns_orig = {} |
|
280 | 278 | self.user_ns_orig.update(_ip.user_ns) |
|
281 | 279 | _ip.user_ns.update(self._dt_test.globs) |
|
282 | 280 | # We must remove the _ key in the namespace, so that Python's |
|
283 | 281 | # doctest code sets it naturally |
|
284 | 282 | _ip.user_ns.pop('_', None) |
|
285 | 283 | _ip.user_ns['__builtins__'] = builtin_mod |
|
286 | 284 | self._dt_test.globs = _ip.user_ns |
|
287 | 285 | |
|
288 | 286 | super(DocTestCase, self).setUp() |
|
289 | 287 | |
|
290 | 288 | def tearDown(self): |
|
291 | 289 | |
|
292 | 290 | # Undo the test.globs reassignment we made, so that the parent class |
|
293 | 291 | # teardown doesn't destroy the ipython namespace |
|
294 | 292 | if isinstance(self._dt_test.examples[0], IPExample): |
|
295 | 293 | self._dt_test.globs = self._dt_test_globs_ori |
|
296 | 294 | _ip.user_ns.clear() |
|
297 | 295 | _ip.user_ns.update(self.user_ns_orig) |
|
298 | 296 | |
|
299 | 297 | # XXX - fperez: I am not sure if this is truly a bug in nose 0.11, but |
|
300 | 298 | # it does look like one to me: its tearDown method tries to run |
|
301 | 299 | # |
|
302 | 300 | # delattr(builtin_mod, self._result_var) |
|
303 | 301 | # |
|
304 | 302 | # without checking that the attribute really is there; it implicitly |
|
305 | 303 | # assumes it should have been set via displayhook. But if the |
|
306 | 304 | # displayhook was never called, this doesn't necessarily happen. I |
|
307 | 305 | # haven't been able to find a little self-contained example outside of |
|
308 | 306 | # ipython that would show the problem so I can report it to the nose |
|
309 | 307 | # team, but it does happen a lot in our code. |
|
310 | 308 | # |
|
311 | 309 | # So here, we just protect as narrowly as possible by trapping an |
|
312 | 310 | # attribute error whose message would be the name of self._result_var, |
|
313 | 311 | # and letting any other error propagate. |
|
314 | 312 | try: |
|
315 | 313 | super(DocTestCase, self).tearDown() |
|
316 | 314 | except AttributeError as exc: |
|
317 | 315 | if exc.args[0] != self._result_var: |
|
318 | 316 | raise |
|
319 | 317 | |
|
320 | 318 | |
|
321 | 319 | # A simple subclassing of the original with a different class name, so we can |
|
322 | 320 | # distinguish and treat differently IPython examples from pure python ones. |
|
323 | 321 | class IPExample(doctest.Example): pass |
|
324 | 322 | |
|
325 | 323 | |
|
326 | 324 | class IPExternalExample(doctest.Example): |
|
327 | 325 | """Doctest examples to be run in an external process.""" |
|
328 | 326 | |
|
329 | 327 | def __init__(self, source, want, exc_msg=None, lineno=0, indent=0, |
|
330 | 328 | options=None): |
|
331 | 329 | # Parent constructor |
|
332 | 330 | doctest.Example.__init__(self,source,want,exc_msg,lineno,indent,options) |
|
333 | 331 | |
|
334 | 332 | # An EXTRA newline is needed to prevent pexpect hangs |
|
335 | 333 | self.source += '\n' |
|
336 | 334 | |
|
337 | 335 | |
|
338 | 336 | class IPDocTestParser(doctest.DocTestParser): |
|
339 | 337 | """ |
|
340 | 338 | A class used to parse strings containing doctest examples. |
|
341 | 339 | |
|
342 | 340 | Note: This is a version modified to properly recognize IPython input and |
|
343 | 341 | convert any IPython examples into valid Python ones. |
|
344 | 342 | """ |
|
345 | 343 | # This regular expression is used to find doctest examples in a |
|
346 | 344 | # string. It defines three groups: `source` is the source code |
|
347 | 345 | # (including leading indentation and prompts); `indent` is the |
|
348 | 346 | # indentation of the first (PS1) line of the source code; and |
|
349 | 347 | # `want` is the expected output (including leading indentation). |
|
350 | 348 | |
|
351 | 349 | # Classic Python prompts or default IPython ones |
|
352 | 350 | _PS1_PY = r'>>>' |
|
353 | 351 | _PS2_PY = r'\.\.\.' |
|
354 | 352 | |
|
355 | 353 | _PS1_IP = r'In\ \[\d+\]:' |
|
356 | 354 | _PS2_IP = r'\ \ \ \.\.\.+:' |
|
357 | 355 | |
|
358 | 356 | _RE_TPL = r''' |
|
359 | 357 | # Source consists of a PS1 line followed by zero or more PS2 lines. |
|
360 | 358 | (?P<source> |
|
361 | 359 | (?:^(?P<indent> [ ]*) (?P<ps1> %s) .*) # PS1 line |
|
362 | 360 | (?:\n [ ]* (?P<ps2> %s) .*)*) # PS2 lines |
|
363 | 361 | \n? # a newline |
|
364 | 362 | # Want consists of any non-blank lines that do not start with PS1. |
|
365 | 363 | (?P<want> (?:(?![ ]*$) # Not a blank line |
|
366 | 364 | (?![ ]*%s) # Not a line starting with PS1 |
|
367 | 365 | (?![ ]*%s) # Not a line starting with PS2 |
|
368 | 366 | .*$\n? # But any other line |
|
369 | 367 | )*) |
|
370 | 368 | ''' |
|
371 | 369 | |
|
372 | 370 | _EXAMPLE_RE_PY = re.compile( _RE_TPL % (_PS1_PY,_PS2_PY,_PS1_PY,_PS2_PY), |
|
373 | 371 | re.MULTILINE | re.VERBOSE) |
|
374 | 372 | |
|
375 | 373 | _EXAMPLE_RE_IP = re.compile( _RE_TPL % (_PS1_IP,_PS2_IP,_PS1_IP,_PS2_IP), |
|
376 | 374 | re.MULTILINE | re.VERBOSE) |
|
377 | 375 | |
|
378 | 376 | # Mark a test as being fully random. In this case, we simply append the |
|
379 | 377 | # random marker ('#random') to each individual example's output. This way |
|
380 | 378 | # we don't need to modify any other code. |
|
381 | 379 | _RANDOM_TEST = re.compile(r'#\s*all-random\s+') |
|
382 | 380 | |
|
383 | 381 | # Mark tests to be executed in an external process - currently unsupported. |
|
384 | 382 | _EXTERNAL_IP = re.compile(r'#\s*ipdoctest:\s*EXTERNAL') |
|
385 | 383 | |
|
386 | 384 | def ip2py(self,source): |
|
387 | 385 | """Convert input IPython source into valid Python.""" |
|
388 | 386 | block = _ip.input_transformer_manager.transform_cell(source) |
|
389 | 387 | if len(block.splitlines()) == 1: |
|
390 | 388 | return _ip.prefilter(block) |
|
391 | 389 | else: |
|
392 | 390 | return block |
|
393 | 391 | |
|
394 | 392 | def parse(self, string, name='<string>'): |
|
395 | 393 | """ |
|
396 | 394 | Divide the given string into examples and intervening text, |
|
397 | 395 | and return them as a list of alternating Examples and strings. |
|
398 | 396 | Line numbers for the Examples are 0-based. The optional |
|
399 | 397 | argument `name` is a name identifying this string, and is only |
|
400 | 398 | used for error messages. |
|
401 | 399 | """ |
|
402 | 400 | |
|
403 | 401 | #print 'Parse string:\n',string # dbg |
|
404 | 402 | |
|
405 | 403 | string = string.expandtabs() |
|
406 | 404 | # If all lines begin with the same indentation, then strip it. |
|
407 | 405 | min_indent = self._min_indent(string) |
|
408 | 406 | if min_indent > 0: |
|
409 | 407 | string = '\n'.join([l[min_indent:] for l in string.split('\n')]) |
|
410 | 408 | |
|
411 | 409 | output = [] |
|
412 | 410 | charno, lineno = 0, 0 |
|
413 | 411 | |
|
414 | 412 | # We make 'all random' tests by adding the '# random' mark to every |
|
415 | 413 | # block of output in the test. |
|
416 | 414 | if self._RANDOM_TEST.search(string): |
|
417 | 415 | random_marker = '\n# random' |
|
418 | 416 | else: |
|
419 | 417 | random_marker = '' |
|
420 | 418 | |
|
421 | 419 | # Whether to convert the input from ipython to python syntax |
|
422 | 420 | ip2py = False |
|
423 | 421 | # Find all doctest examples in the string. First, try them as Python |
|
424 | 422 | # examples, then as IPython ones |
|
425 | 423 | terms = list(self._EXAMPLE_RE_PY.finditer(string)) |
|
426 | 424 | if terms: |
|
427 | 425 | # Normal Python example |
|
428 | 426 | #print '-'*70 # dbg |
|
429 | 427 | #print 'PyExample, Source:\n',string # dbg |
|
430 | 428 | #print '-'*70 # dbg |
|
431 | 429 | Example = doctest.Example |
|
432 | 430 | else: |
|
433 | 431 | # It's an ipython example. Note that IPExamples are run |
|
434 | 432 | # in-process, so their syntax must be turned into valid python. |
|
435 | 433 | # IPExternalExamples are run out-of-process (via pexpect) so they |
|
436 | 434 | # don't need any filtering (a real ipython will be executing them). |
|
437 | 435 | terms = list(self._EXAMPLE_RE_IP.finditer(string)) |
|
438 | 436 | if self._EXTERNAL_IP.search(string): |
|
439 | 437 | #print '-'*70 # dbg |
|
440 | 438 | #print 'IPExternalExample, Source:\n',string # dbg |
|
441 | 439 | #print '-'*70 # dbg |
|
442 | 440 | Example = IPExternalExample |
|
443 | 441 | else: |
|
444 | 442 | #print '-'*70 # dbg |
|
445 | 443 | #print 'IPExample, Source:\n',string # dbg |
|
446 | 444 | #print '-'*70 # dbg |
|
447 | 445 | Example = IPExample |
|
448 | 446 | ip2py = True |
|
449 | 447 | |
|
450 | 448 | for m in terms: |
|
451 | 449 | # Add the pre-example text to `output`. |
|
452 | 450 | output.append(string[charno:m.start()]) |
|
453 | 451 | # Update lineno (lines before this example) |
|
454 | 452 | lineno += string.count('\n', charno, m.start()) |
|
455 | 453 | # Extract info from the regexp match. |
|
456 | 454 | (source, options, want, exc_msg) = \ |
|
457 | 455 | self._parse_example(m, name, lineno,ip2py) |
|
458 | 456 | |
|
459 | 457 | # Append the random-output marker (it defaults to empty in most |
|
460 | 458 | # cases, it's only non-empty for 'all-random' tests): |
|
461 | 459 | want += random_marker |
|
462 | 460 | |
|
463 | 461 | if Example is IPExternalExample: |
|
464 | 462 | options[doctest.NORMALIZE_WHITESPACE] = True |
|
465 | 463 | want += '\n' |
|
466 | 464 | |
|
467 | 465 | # Create an Example, and add it to the list. |
|
468 | 466 | if not self._IS_BLANK_OR_COMMENT(source): |
|
469 | 467 | output.append(Example(source, want, exc_msg, |
|
470 | 468 | lineno=lineno, |
|
471 | 469 | indent=min_indent+len(m.group('indent')), |
|
472 | 470 | options=options)) |
|
473 | 471 | # Update lineno (lines inside this example) |
|
474 | 472 | lineno += string.count('\n', m.start(), m.end()) |
|
475 | 473 | # Update charno. |
|
476 | 474 | charno = m.end() |
|
477 | 475 | # Add any remaining post-example text to `output`. |
|
478 | 476 | output.append(string[charno:]) |
|
479 | 477 | return output |
|
480 | 478 | |
|
481 | 479 | def _parse_example(self, m, name, lineno,ip2py=False): |
|
482 | 480 | """ |
|
483 | 481 | Given a regular expression match from `_EXAMPLE_RE` (`m`), |
|
484 | 482 | return a pair `(source, want)`, where `source` is the matched |
|
485 | 483 | example's source code (with prompts and indentation stripped); |
|
486 | 484 | and `want` is the example's expected output (with indentation |
|
487 | 485 | stripped). |
|
488 | 486 | |
|
489 | 487 | `name` is the string's name, and `lineno` is the line number |
|
490 | 488 | where the example starts; both are used for error messages. |
|
491 | 489 | |
|
492 | 490 | Optional: |
|
493 | 491 | `ip2py`: if true, filter the input via IPython to convert the syntax |
|
494 | 492 | into valid python. |
|
495 | 493 | """ |
|
496 | 494 | |
|
497 | 495 | # Get the example's indentation level. |
|
498 | 496 | indent = len(m.group('indent')) |
|
499 | 497 | |
|
500 | 498 | # Divide source into lines; check that they're properly |
|
501 | 499 | # indented; and then strip their indentation & prompts. |
|
502 | 500 | source_lines = m.group('source').split('\n') |
|
503 | 501 | |
|
504 | 502 | # We're using variable-length input prompts |
|
505 | 503 | ps1 = m.group('ps1') |
|
506 | 504 | ps2 = m.group('ps2') |
|
507 | 505 | ps1_len = len(ps1) |
|
508 | 506 | |
|
509 | 507 | self._check_prompt_blank(source_lines, indent, name, lineno,ps1_len) |
|
510 | 508 | if ps2: |
|
511 | 509 | self._check_prefix(source_lines[1:], ' '*indent + ps2, name, lineno) |
|
512 | 510 | |
|
513 | 511 | source = '\n'.join([sl[indent+ps1_len+1:] for sl in source_lines]) |
|
514 | 512 | |
|
515 | 513 | if ip2py: |
|
516 | 514 | # Convert source input from IPython into valid Python syntax |
|
517 | 515 | source = self.ip2py(source) |
|
518 | 516 | |
|
519 | 517 | # Divide want into lines; check that it's properly indented; and |
|
520 | 518 | # then strip the indentation. Spaces before the last newline should |
|
521 | 519 | # be preserved, so plain rstrip() isn't good enough. |
|
522 | 520 | want = m.group('want') |
|
523 | 521 | want_lines = want.split('\n') |
|
524 | 522 | if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]): |
|
525 | 523 | del want_lines[-1] # forget final newline & spaces after it |
|
526 | 524 | self._check_prefix(want_lines, ' '*indent, name, |
|
527 | 525 | lineno + len(source_lines)) |
|
528 | 526 | |
|
529 | 527 | # Remove ipython output prompt that might be present in the first line |
|
530 | 528 | want_lines[0] = re.sub(r'Out\[\d+\]: \s*?\n?','',want_lines[0]) |
|
531 | 529 | |
|
532 | 530 | want = '\n'.join([wl[indent:] for wl in want_lines]) |
|
533 | 531 | |
|
534 | 532 | # If `want` contains a traceback message, then extract it. |
|
535 | 533 | m = self._EXCEPTION_RE.match(want) |
|
536 | 534 | if m: |
|
537 | 535 | exc_msg = m.group('msg') |
|
538 | 536 | else: |
|
539 | 537 | exc_msg = None |
|
540 | 538 | |
|
541 | 539 | # Extract options from the source. |
|
542 | 540 | options = self._find_options(source, name, lineno) |
|
543 | 541 | |
|
544 | 542 | return source, options, want, exc_msg |
|
545 | 543 | |
|
546 | 544 | def _check_prompt_blank(self, lines, indent, name, lineno, ps1_len): |
|
547 | 545 | """ |
|
548 | 546 | Given the lines of a source string (including prompts and |
|
549 | 547 | leading indentation), check to make sure that every prompt is |
|
550 | 548 | followed by a space character. If any line is not followed by |
|
551 | 549 | a space character, then raise ValueError. |
|
552 | 550 | |
|
553 | 551 | Note: IPython-modified version which takes the input prompt length as a |
|
554 | 552 | parameter, so that prompts of variable length can be dealt with. |
|
555 | 553 | """ |
|
556 | 554 | space_idx = indent+ps1_len |
|
557 | 555 | min_len = space_idx+1 |
|
558 | 556 | for i, line in enumerate(lines): |
|
559 | 557 | if len(line) >= min_len and line[space_idx] != ' ': |
|
560 | 558 | raise ValueError('line %r of the docstring for %s ' |
|
561 | 559 | 'lacks blank after %s: %r' % |
|
562 | 560 | (lineno+i+1, name, |
|
563 | 561 | line[indent:space_idx], line)) |
|
564 | 562 | |
|
565 | 563 | |
|
566 | 564 | SKIP = doctest.register_optionflag('SKIP') |
|
567 | 565 | |
|
568 | 566 | |
|
569 | 567 | class IPDocTestRunner(doctest.DocTestRunner,object): |
|
570 | 568 | """Test runner that synchronizes the IPython namespace with test globals. |
|
571 | 569 | """ |
|
572 | 570 | |
|
573 | 571 | def run(self, test, compileflags=None, out=None, clear_globs=True): |
|
574 | 572 | |
|
575 | 573 | # Hack: ipython needs access to the execution context of the example, |
|
576 | 574 | # so that it can propagate user variables loaded by %run into |
|
577 | 575 | # test.globs. We put them here into our modified %run as a function |
|
578 | 576 | # attribute. Our new %run will then only make the namespace update |
|
579 | 577 | # when called (rather than unconconditionally updating test.globs here |
|
580 | 578 | # for all examples, most of which won't be calling %run anyway). |
|
581 | 579 | #_ip._ipdoctest_test_globs = test.globs |
|
582 | 580 | #_ip._ipdoctest_test_filename = test.filename |
|
583 | 581 | |
|
584 | 582 | test.globs.update(_ip.user_ns) |
|
585 | 583 | |
|
586 | 584 | # Override terminal size to standardise traceback format |
|
587 | 585 | with modified_env({'COLUMNS': '80', 'LINES': '24'}): |
|
588 | 586 | return super(IPDocTestRunner,self).run(test, |
|
589 | 587 | compileflags,out,clear_globs) |
|
590 | 588 | |
|
591 | 589 | |
|
592 | 590 | class DocFileCase(doctest.DocFileCase): |
|
593 | 591 | """Overrides to provide filename |
|
594 | 592 | """ |
|
595 | 593 | def address(self): |
|
596 | 594 | return (self._dt_test.filename, None, None) |
|
597 | 595 | |
|
598 | 596 | |
|
599 | 597 | class ExtensionDoctest(doctests.Doctest): |
|
600 | 598 | """Nose Plugin that supports doctests in extension modules. |
|
601 | 599 | """ |
|
602 | 600 | name = 'extdoctest' # call nosetests with --with-extdoctest |
|
603 | 601 | enabled = True |
|
604 | 602 | |
|
605 | 603 | def options(self, parser, env=os.environ): |
|
606 | 604 | Plugin.options(self, parser, env) |
|
607 | 605 | parser.add_option('--doctest-tests', action='store_true', |
|
608 | 606 | dest='doctest_tests', |
|
609 | 607 | default=env.get('NOSE_DOCTEST_TESTS',True), |
|
610 | 608 | help="Also look for doctests in test modules. " |
|
611 | 609 | "Note that classes, methods and functions should " |
|
612 | 610 | "have either doctests or non-doctest tests, " |
|
613 | 611 | "not both. [NOSE_DOCTEST_TESTS]") |
|
614 | 612 | parser.add_option('--doctest-extension', action="append", |
|
615 | 613 | dest="doctestExtension", |
|
616 | 614 | help="Also look for doctests in files with " |
|
617 | 615 | "this extension [NOSE_DOCTEST_EXTENSION]") |
|
618 | 616 | # Set the default as a list, if given in env; otherwise |
|
619 | 617 | # an additional value set on the command line will cause |
|
620 | 618 | # an error. |
|
621 | 619 | env_setting = env.get('NOSE_DOCTEST_EXTENSION') |
|
622 | 620 | if env_setting is not None: |
|
623 | 621 | parser.set_defaults(doctestExtension=tolist(env_setting)) |
|
624 | 622 | |
|
625 | 623 | |
|
626 | 624 | def configure(self, options, config): |
|
627 | 625 | Plugin.configure(self, options, config) |
|
628 | 626 | # Pull standard doctest plugin out of config; we will do doctesting |
|
629 | 627 | config.plugins.plugins = [p for p in config.plugins.plugins |
|
630 | 628 | if p.name != 'doctest'] |
|
631 | 629 | self.doctest_tests = options.doctest_tests |
|
632 | 630 | self.extension = tolist(options.doctestExtension) |
|
633 | 631 | |
|
634 | 632 | self.parser = doctest.DocTestParser() |
|
635 | 633 | self.finder = DocTestFinder() |
|
636 | 634 | self.checker = IPDoctestOutputChecker() |
|
637 | 635 | self.globs = None |
|
638 | 636 | self.extraglobs = None |
|
639 | 637 | |
|
640 | 638 | |
|
641 | 639 | def loadTestsFromExtensionModule(self,filename): |
|
642 | 640 | bpath,mod = os.path.split(filename) |
|
643 | 641 | modname = os.path.splitext(mod)[0] |
|
644 | 642 | try: |
|
645 | 643 | sys.path.append(bpath) |
|
646 | 644 | module = import_module(modname) |
|
647 | 645 | tests = list(self.loadTestsFromModule(module)) |
|
648 | 646 | finally: |
|
649 | 647 | sys.path.pop() |
|
650 | 648 | return tests |
|
651 | 649 | |
|
652 | 650 | # NOTE: the method below is almost a copy of the original one in nose, with |
|
653 | 651 | # a few modifications to control output checking. |
|
654 | 652 | |
|
655 | 653 | def loadTestsFromModule(self, module): |
|
656 | 654 | #print '*** ipdoctest - lTM',module # dbg |
|
657 | 655 | |
|
658 | 656 | if not self.matches(module.__name__): |
|
659 | 657 | log.debug("Doctest doesn't want module %s", module) |
|
660 | 658 | return |
|
661 | 659 | |
|
662 | 660 | tests = self.finder.find(module,globs=self.globs, |
|
663 | 661 | extraglobs=self.extraglobs) |
|
664 | 662 | if not tests: |
|
665 | 663 | return |
|
666 | 664 | |
|
667 | 665 | # always use whitespace and ellipsis options |
|
668 | 666 | optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS |
|
669 | 667 | |
|
670 | 668 | tests.sort() |
|
671 | 669 | module_file = module.__file__ |
|
672 | 670 | if module_file[-4:] in ('.pyc', '.pyo'): |
|
673 | 671 | module_file = module_file[:-1] |
|
674 | 672 | for test in tests: |
|
675 | 673 | if not test.examples: |
|
676 | 674 | continue |
|
677 | 675 | if not test.filename: |
|
678 | 676 | test.filename = module_file |
|
679 | 677 | |
|
680 | 678 | yield DocTestCase(test, |
|
681 | 679 | optionflags=optionflags, |
|
682 | 680 | checker=self.checker) |
|
683 | 681 | |
|
684 | 682 | |
|
685 | 683 | def loadTestsFromFile(self, filename): |
|
686 | 684 | #print "ipdoctest - from file", filename # dbg |
|
687 | 685 | if is_extension_module(filename): |
|
688 | 686 | for t in self.loadTestsFromExtensionModule(filename): |
|
689 | 687 | yield t |
|
690 | 688 | else: |
|
691 | 689 | if self.extension and anyp(filename.endswith, self.extension): |
|
692 | 690 | name = os.path.basename(filename) |
|
693 | 691 | dh = open(filename) |
|
694 | 692 | try: |
|
695 | 693 | doc = dh.read() |
|
696 | 694 | finally: |
|
697 | 695 | dh.close() |
|
698 | 696 | test = self.parser.get_doctest( |
|
699 | 697 | doc, globs={'__file__': filename}, name=name, |
|
700 | 698 | filename=filename, lineno=0) |
|
701 | 699 | if test.examples: |
|
702 | 700 | #print 'FileCase:',test.examples # dbg |
|
703 | 701 | yield DocFileCase(test) |
|
704 | 702 | else: |
|
705 | 703 | yield False # no tests to load |
|
706 | 704 | |
|
707 | 705 | |
|
708 | 706 | class IPythonDoctest(ExtensionDoctest): |
|
709 | 707 | """Nose Plugin that supports doctests in extension modules. |
|
710 | 708 | """ |
|
711 | 709 | name = 'ipdoctest' # call nosetests with --with-ipdoctest |
|
712 | 710 | enabled = True |
|
713 | 711 | |
|
714 | 712 | def makeTest(self, obj, parent): |
|
715 | 713 | """Look for doctests in the given object, which will be a |
|
716 | 714 | function, method or class. |
|
717 | 715 | """ |
|
718 | 716 | #print 'Plugin analyzing:', obj, parent # dbg |
|
719 | 717 | # always use whitespace and ellipsis options |
|
720 | 718 | optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS |
|
721 | 719 | |
|
722 | 720 | doctests = self.finder.find(obj, module=getmodule(parent)) |
|
723 | 721 | if doctests: |
|
724 | 722 | for test in doctests: |
|
725 | 723 | if len(test.examples) == 0: |
|
726 | 724 | continue |
|
727 | 725 | |
|
728 | 726 | yield DocTestCase(test, obj=obj, |
|
729 | 727 | optionflags=optionflags, |
|
730 | 728 | checker=self.checker) |
|
731 | 729 | |
|
732 | 730 | def options(self, parser, env=os.environ): |
|
733 | 731 | #print "Options for nose plugin:", self.name # dbg |
|
734 | 732 | Plugin.options(self, parser, env) |
|
735 | 733 | parser.add_option('--ipdoctest-tests', action='store_true', |
|
736 | 734 | dest='ipdoctest_tests', |
|
737 | 735 | default=env.get('NOSE_IPDOCTEST_TESTS',True), |
|
738 | 736 | help="Also look for doctests in test modules. " |
|
739 | 737 | "Note that classes, methods and functions should " |
|
740 | 738 | "have either doctests or non-doctest tests, " |
|
741 | 739 | "not both. [NOSE_IPDOCTEST_TESTS]") |
|
742 | 740 | parser.add_option('--ipdoctest-extension', action="append", |
|
743 | 741 | dest="ipdoctest_extension", |
|
744 | 742 | help="Also look for doctests in files with " |
|
745 | 743 | "this extension [NOSE_IPDOCTEST_EXTENSION]") |
|
746 | 744 | # Set the default as a list, if given in env; otherwise |
|
747 | 745 | # an additional value set on the command line will cause |
|
748 | 746 | # an error. |
|
749 | 747 | env_setting = env.get('NOSE_IPDOCTEST_EXTENSION') |
|
750 | 748 | if env_setting is not None: |
|
751 | 749 | parser.set_defaults(ipdoctest_extension=tolist(env_setting)) |
|
752 | 750 | |
|
753 | 751 | def configure(self, options, config): |
|
754 | 752 | #print "Configuring nose plugin:", self.name # dbg |
|
755 | 753 | Plugin.configure(self, options, config) |
|
756 | 754 | # Pull standard doctest plugin out of config; we will do doctesting |
|
757 | 755 | config.plugins.plugins = [p for p in config.plugins.plugins |
|
758 | 756 | if p.name != 'doctest'] |
|
759 | 757 | self.doctest_tests = options.ipdoctest_tests |
|
760 | 758 | self.extension = tolist(options.ipdoctest_extension) |
|
761 | 759 | |
|
762 | 760 | self.parser = IPDocTestParser() |
|
763 | 761 | self.finder = DocTestFinder(parser=self.parser) |
|
764 | 762 | self.checker = IPDoctestOutputChecker() |
|
765 | 763 | self.globs = None |
|
766 | 764 | self.extraglobs = None |
General Comments 0
You need to be logged in to leave comments.
Login now