Show More
The requested changes are too big and content was truncated. Show full diff
@@ -1,103 +1,103 b'' | |||
|
1 | 1 | """ |
|
2 | 2 | A context manager for managing things injected into :mod:`__builtin__`. |
|
3 | 3 | |
|
4 | 4 | Authors: |
|
5 | 5 | |
|
6 | 6 | * Brian Granger |
|
7 | 7 | * Fernando Perez |
|
8 | 8 | """ |
|
9 | 9 | #----------------------------------------------------------------------------- |
|
10 | 10 | # Copyright (C) 2010-2011 The IPython Development Team. |
|
11 | 11 | # |
|
12 | 12 | # Distributed under the terms of the BSD License. |
|
13 | 13 | # |
|
14 | 14 | # Complete license in the file COPYING.txt, distributed with this software. |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | |
|
17 | 17 | #----------------------------------------------------------------------------- |
|
18 | 18 | # Imports |
|
19 | 19 | #----------------------------------------------------------------------------- |
|
20 | 20 | |
|
21 | 21 | from traitlets.config.configurable import Configurable |
|
22 | 22 | |
|
23 |
from IPython.utils.py3compat import builtin_mod |
|
|
23 | from IPython.utils.py3compat import builtin_mod | |
|
24 | 24 | from traitlets import Instance |
|
25 | 25 | |
|
26 | 26 | #----------------------------------------------------------------------------- |
|
27 | 27 | # Classes and functions |
|
28 | 28 | #----------------------------------------------------------------------------- |
|
29 | 29 | |
|
30 | 30 | class __BuiltinUndefined(object): pass |
|
31 | 31 | BuiltinUndefined = __BuiltinUndefined() |
|
32 | 32 | |
|
33 | 33 | class __HideBuiltin(object): pass |
|
34 | 34 | HideBuiltin = __HideBuiltin() |
|
35 | 35 | |
|
36 | 36 | |
|
37 | 37 | class BuiltinTrap(Configurable): |
|
38 | 38 | |
|
39 | 39 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', |
|
40 | 40 | allow_none=True) |
|
41 | 41 | |
|
42 | 42 | def __init__(self, shell=None): |
|
43 | 43 | super(BuiltinTrap, self).__init__(shell=shell, config=None) |
|
44 | 44 | self._orig_builtins = {} |
|
45 | 45 | # We define this to track if a single BuiltinTrap is nested. |
|
46 | 46 | # Only turn off the trap when the outermost call to __exit__ is made. |
|
47 | 47 | self._nested_level = 0 |
|
48 | 48 | self.shell = shell |
|
49 | 49 | # builtins we always add - if set to HideBuiltin, they will just |
|
50 | 50 | # be removed instead of being replaced by something else |
|
51 | 51 | self.auto_builtins = {'exit': HideBuiltin, |
|
52 | 52 | 'quit': HideBuiltin, |
|
53 | 53 | 'get_ipython': self.shell.get_ipython, |
|
54 | 54 | } |
|
55 | 55 | |
|
56 | 56 | def __enter__(self): |
|
57 | 57 | if self._nested_level == 0: |
|
58 | 58 | self.activate() |
|
59 | 59 | self._nested_level += 1 |
|
60 | 60 | # I return self, so callers can use add_builtin in a with clause. |
|
61 | 61 | return self |
|
62 | 62 | |
|
63 | 63 | def __exit__(self, type, value, traceback): |
|
64 | 64 | if self._nested_level == 1: |
|
65 | 65 | self.deactivate() |
|
66 | 66 | self._nested_level -= 1 |
|
67 | 67 | # Returning False will cause exceptions to propagate |
|
68 | 68 | return False |
|
69 | 69 | |
|
70 | 70 | def add_builtin(self, key, value): |
|
71 | 71 | """Add a builtin and save the original.""" |
|
72 | 72 | bdict = builtin_mod.__dict__ |
|
73 | 73 | orig = bdict.get(key, BuiltinUndefined) |
|
74 | 74 | if value is HideBuiltin: |
|
75 | 75 | if orig is not BuiltinUndefined: #same as 'key in bdict' |
|
76 | 76 | self._orig_builtins[key] = orig |
|
77 | 77 | del bdict[key] |
|
78 | 78 | else: |
|
79 | 79 | self._orig_builtins[key] = orig |
|
80 | 80 | bdict[key] = value |
|
81 | 81 | |
|
82 | 82 | def remove_builtin(self, key, orig): |
|
83 | 83 | """Remove an added builtin and re-set the original.""" |
|
84 | 84 | if orig is BuiltinUndefined: |
|
85 | 85 | del builtin_mod.__dict__[key] |
|
86 | 86 | else: |
|
87 | 87 | builtin_mod.__dict__[key] = orig |
|
88 | 88 | |
|
89 | 89 | def activate(self): |
|
90 | 90 | """Store ipython references in the __builtin__ namespace.""" |
|
91 | 91 | |
|
92 | 92 | add_builtin = self.add_builtin |
|
93 |
for name, func in |
|
|
93 | for name, func in self.auto_builtins.items(): | |
|
94 | 94 | add_builtin(name, func) |
|
95 | 95 | |
|
96 | 96 | def deactivate(self): |
|
97 | 97 | """Remove any builtins which might have been added by add_builtins, or |
|
98 | 98 | restore overwritten ones to their previous values.""" |
|
99 | 99 | remove_builtin = self.remove_builtin |
|
100 |
for key, val in |
|
|
100 | for key, val in self._orig_builtins.items(): | |
|
101 | 101 | remove_builtin(key, val) |
|
102 | 102 | self._orig_builtins.clear() |
|
103 | 103 | self._builtins_added = False |
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
@@ -1,679 +1,679 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """Magic functions for InteractiveShell. |
|
3 | 3 | """ |
|
4 | 4 | |
|
5 | 5 | #----------------------------------------------------------------------------- |
|
6 | 6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
7 | 7 | # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu> |
|
8 | 8 | # Copyright (C) 2008 The IPython Development Team |
|
9 | 9 | |
|
10 | 10 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | 11 | # the file COPYING, distributed as part of this software. |
|
12 | 12 | #----------------------------------------------------------------------------- |
|
13 | 13 | |
|
14 | 14 | import os |
|
15 | 15 | import re |
|
16 | 16 | import sys |
|
17 | 17 | import types |
|
18 | 18 | from getopt import getopt, GetoptError |
|
19 | 19 | |
|
20 | 20 | from traitlets.config.configurable import Configurable |
|
21 | 21 | from IPython.core import oinspect |
|
22 | 22 | from IPython.core.error import UsageError |
|
23 | 23 | from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2 |
|
24 | 24 | from decorator import decorator |
|
25 | 25 | from IPython.utils.ipstruct import Struct |
|
26 | 26 | from IPython.utils.process import arg_split |
|
27 |
from IPython.utils.py3compat import string_types |
|
|
27 | from IPython.utils.py3compat import string_types | |
|
28 | 28 | from IPython.utils.text import dedent |
|
29 | 29 | from traitlets import Bool, Dict, Instance, observe |
|
30 | 30 | from logging import error |
|
31 | 31 | |
|
32 | 32 | #----------------------------------------------------------------------------- |
|
33 | 33 | # Globals |
|
34 | 34 | #----------------------------------------------------------------------------- |
|
35 | 35 | |
|
36 | 36 | # A dict we'll use for each class that has magics, used as temporary storage to |
|
37 | 37 | # pass information between the @line/cell_magic method decorators and the |
|
38 | 38 | # @magics_class class decorator, because the method decorators have no |
|
39 | 39 | # access to the class when they run. See for more details: |
|
40 | 40 | # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class |
|
41 | 41 | |
|
42 | 42 | magics = dict(line={}, cell={}) |
|
43 | 43 | |
|
44 | 44 | magic_kinds = ('line', 'cell') |
|
45 | 45 | magic_spec = ('line', 'cell', 'line_cell') |
|
46 | 46 | magic_escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC2) |
|
47 | 47 | |
|
48 | 48 | #----------------------------------------------------------------------------- |
|
49 | 49 | # Utility classes and functions |
|
50 | 50 | #----------------------------------------------------------------------------- |
|
51 | 51 | |
|
52 | 52 | class Bunch: pass |
|
53 | 53 | |
|
54 | 54 | |
|
55 | 55 | def on_off(tag): |
|
56 | 56 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
57 | 57 | return ['OFF','ON'][tag] |
|
58 | 58 | |
|
59 | 59 | |
|
60 | 60 | def compress_dhist(dh): |
|
61 | 61 | """Compress a directory history into a new one with at most 20 entries. |
|
62 | 62 | |
|
63 | 63 | Return a new list made from the first and last 10 elements of dhist after |
|
64 | 64 | removal of duplicates. |
|
65 | 65 | """ |
|
66 | 66 | head, tail = dh[:-10], dh[-10:] |
|
67 | 67 | |
|
68 | 68 | newhead = [] |
|
69 | 69 | done = set() |
|
70 | 70 | for h in head: |
|
71 | 71 | if h in done: |
|
72 | 72 | continue |
|
73 | 73 | newhead.append(h) |
|
74 | 74 | done.add(h) |
|
75 | 75 | |
|
76 | 76 | return newhead + tail |
|
77 | 77 | |
|
78 | 78 | |
|
79 | 79 | def needs_local_scope(func): |
|
80 | 80 | """Decorator to mark magic functions which need to local scope to run.""" |
|
81 | 81 | func.needs_local_scope = True |
|
82 | 82 | return func |
|
83 | 83 | |
|
84 | 84 | #----------------------------------------------------------------------------- |
|
85 | 85 | # Class and method decorators for registering magics |
|
86 | 86 | #----------------------------------------------------------------------------- |
|
87 | 87 | |
|
88 | 88 | def magics_class(cls): |
|
89 | 89 | """Class decorator for all subclasses of the main Magics class. |
|
90 | 90 | |
|
91 | 91 | Any class that subclasses Magics *must* also apply this decorator, to |
|
92 | 92 | ensure that all the methods that have been decorated as line/cell magics |
|
93 | 93 | get correctly registered in the class instance. This is necessary because |
|
94 | 94 | when method decorators run, the class does not exist yet, so they |
|
95 | 95 | temporarily store their information into a module global. Application of |
|
96 | 96 | this class decorator copies that global data to the class instance and |
|
97 | 97 | clears the global. |
|
98 | 98 | |
|
99 | 99 | Obviously, this mechanism is not thread-safe, which means that the |
|
100 | 100 | *creation* of subclasses of Magic should only be done in a single-thread |
|
101 | 101 | context. Instantiation of the classes has no restrictions. Given that |
|
102 | 102 | these classes are typically created at IPython startup time and before user |
|
103 | 103 | application code becomes active, in practice this should not pose any |
|
104 | 104 | problems. |
|
105 | 105 | """ |
|
106 | 106 | cls.registered = True |
|
107 | 107 | cls.magics = dict(line = magics['line'], |
|
108 | 108 | cell = magics['cell']) |
|
109 | 109 | magics['line'] = {} |
|
110 | 110 | magics['cell'] = {} |
|
111 | 111 | return cls |
|
112 | 112 | |
|
113 | 113 | |
|
114 | 114 | def record_magic(dct, magic_kind, magic_name, func): |
|
115 | 115 | """Utility function to store a function as a magic of a specific kind. |
|
116 | 116 | |
|
117 | 117 | Parameters |
|
118 | 118 | ---------- |
|
119 | 119 | dct : dict |
|
120 | 120 | A dictionary with 'line' and 'cell' subdicts. |
|
121 | 121 | |
|
122 | 122 | magic_kind : str |
|
123 | 123 | Kind of magic to be stored. |
|
124 | 124 | |
|
125 | 125 | magic_name : str |
|
126 | 126 | Key to store the magic as. |
|
127 | 127 | |
|
128 | 128 | func : function |
|
129 | 129 | Callable object to store. |
|
130 | 130 | """ |
|
131 | 131 | if magic_kind == 'line_cell': |
|
132 | 132 | dct['line'][magic_name] = dct['cell'][magic_name] = func |
|
133 | 133 | else: |
|
134 | 134 | dct[magic_kind][magic_name] = func |
|
135 | 135 | |
|
136 | 136 | |
|
137 | 137 | def validate_type(magic_kind): |
|
138 | 138 | """Ensure that the given magic_kind is valid. |
|
139 | 139 | |
|
140 | 140 | Check that the given magic_kind is one of the accepted spec types (stored |
|
141 | 141 | in the global `magic_spec`), raise ValueError otherwise. |
|
142 | 142 | """ |
|
143 | 143 | if magic_kind not in magic_spec: |
|
144 | 144 | raise ValueError('magic_kind must be one of %s, %s given' % |
|
145 | 145 | magic_kinds, magic_kind) |
|
146 | 146 | |
|
147 | 147 | |
|
148 | 148 | # The docstrings for the decorator below will be fairly similar for the two |
|
149 | 149 | # types (method and function), so we generate them here once and reuse the |
|
150 | 150 | # templates below. |
|
151 | 151 | _docstring_template = \ |
|
152 | 152 | """Decorate the given {0} as {1} magic. |
|
153 | 153 | |
|
154 | 154 | The decorator can be used with or without arguments, as follows. |
|
155 | 155 | |
|
156 | 156 | i) without arguments: it will create a {1} magic named as the {0} being |
|
157 | 157 | decorated:: |
|
158 | 158 | |
|
159 | 159 | @deco |
|
160 | 160 | def foo(...) |
|
161 | 161 | |
|
162 | 162 | will create a {1} magic named `foo`. |
|
163 | 163 | |
|
164 | 164 | ii) with one string argument: which will be used as the actual name of the |
|
165 | 165 | resulting magic:: |
|
166 | 166 | |
|
167 | 167 | @deco('bar') |
|
168 | 168 | def foo(...) |
|
169 | 169 | |
|
170 | 170 | will create a {1} magic named `bar`. |
|
171 | 171 | """ |
|
172 | 172 | |
|
173 | 173 | # These two are decorator factories. While they are conceptually very similar, |
|
174 | 174 | # there are enough differences in the details that it's simpler to have them |
|
175 | 175 | # written as completely standalone functions rather than trying to share code |
|
176 | 176 | # and make a single one with convoluted logic. |
|
177 | 177 | |
|
178 | 178 | def _method_magic_marker(magic_kind): |
|
179 | 179 | """Decorator factory for methods in Magics subclasses. |
|
180 | 180 | """ |
|
181 | 181 | |
|
182 | 182 | validate_type(magic_kind) |
|
183 | 183 | |
|
184 | 184 | # This is a closure to capture the magic_kind. We could also use a class, |
|
185 | 185 | # but it's overkill for just that one bit of state. |
|
186 | 186 | def magic_deco(arg): |
|
187 | 187 | call = lambda f, *a, **k: f(*a, **k) |
|
188 | 188 | |
|
189 | 189 | if callable(arg): |
|
190 | 190 | # "Naked" decorator call (just @foo, no args) |
|
191 | 191 | func = arg |
|
192 | 192 | name = func.__name__ |
|
193 | 193 | retval = decorator(call, func) |
|
194 | 194 | record_magic(magics, magic_kind, name, name) |
|
195 | 195 | elif isinstance(arg, string_types): |
|
196 | 196 | # Decorator called with arguments (@foo('bar')) |
|
197 | 197 | name = arg |
|
198 | 198 | def mark(func, *a, **kw): |
|
199 | 199 | record_magic(magics, magic_kind, name, func.__name__) |
|
200 | 200 | return decorator(call, func) |
|
201 | 201 | retval = mark |
|
202 | 202 | else: |
|
203 | 203 | raise TypeError("Decorator can only be called with " |
|
204 | 204 | "string or function") |
|
205 | 205 | return retval |
|
206 | 206 | |
|
207 | 207 | # Ensure the resulting decorator has a usable docstring |
|
208 | 208 | magic_deco.__doc__ = _docstring_template.format('method', magic_kind) |
|
209 | 209 | return magic_deco |
|
210 | 210 | |
|
211 | 211 | |
|
212 | 212 | def _function_magic_marker(magic_kind): |
|
213 | 213 | """Decorator factory for standalone functions. |
|
214 | 214 | """ |
|
215 | 215 | validate_type(magic_kind) |
|
216 | 216 | |
|
217 | 217 | # This is a closure to capture the magic_kind. We could also use a class, |
|
218 | 218 | # but it's overkill for just that one bit of state. |
|
219 | 219 | def magic_deco(arg): |
|
220 | 220 | call = lambda f, *a, **k: f(*a, **k) |
|
221 | 221 | |
|
222 | 222 | # Find get_ipython() in the caller's namespace |
|
223 | 223 | caller = sys._getframe(1) |
|
224 | 224 | for ns in ['f_locals', 'f_globals', 'f_builtins']: |
|
225 | 225 | get_ipython = getattr(caller, ns).get('get_ipython') |
|
226 | 226 | if get_ipython is not None: |
|
227 | 227 | break |
|
228 | 228 | else: |
|
229 | 229 | raise NameError('Decorator can only run in context where ' |
|
230 | 230 | '`get_ipython` exists') |
|
231 | 231 | |
|
232 | 232 | ip = get_ipython() |
|
233 | 233 | |
|
234 | 234 | if callable(arg): |
|
235 | 235 | # "Naked" decorator call (just @foo, no args) |
|
236 | 236 | func = arg |
|
237 | 237 | name = func.__name__ |
|
238 | 238 | ip.register_magic_function(func, magic_kind, name) |
|
239 | 239 | retval = decorator(call, func) |
|
240 | 240 | elif isinstance(arg, string_types): |
|
241 | 241 | # Decorator called with arguments (@foo('bar')) |
|
242 | 242 | name = arg |
|
243 | 243 | def mark(func, *a, **kw): |
|
244 | 244 | ip.register_magic_function(func, magic_kind, name) |
|
245 | 245 | return decorator(call, func) |
|
246 | 246 | retval = mark |
|
247 | 247 | else: |
|
248 | 248 | raise TypeError("Decorator can only be called with " |
|
249 | 249 | "string or function") |
|
250 | 250 | return retval |
|
251 | 251 | |
|
252 | 252 | # Ensure the resulting decorator has a usable docstring |
|
253 | 253 | ds = _docstring_template.format('function', magic_kind) |
|
254 | 254 | |
|
255 | 255 | ds += dedent(""" |
|
256 | 256 | Note: this decorator can only be used in a context where IPython is already |
|
257 | 257 | active, so that the `get_ipython()` call succeeds. You can therefore use |
|
258 | 258 | it in your startup files loaded after IPython initializes, but *not* in the |
|
259 | 259 | IPython configuration file itself, which is executed before IPython is |
|
260 | 260 | fully up and running. Any file located in the `startup` subdirectory of |
|
261 | 261 | your configuration profile will be OK in this sense. |
|
262 | 262 | """) |
|
263 | 263 | |
|
264 | 264 | magic_deco.__doc__ = ds |
|
265 | 265 | return magic_deco |
|
266 | 266 | |
|
267 | 267 | |
|
268 | 268 | # Create the actual decorators for public use |
|
269 | 269 | |
|
270 | 270 | # These three are used to decorate methods in class definitions |
|
271 | 271 | line_magic = _method_magic_marker('line') |
|
272 | 272 | cell_magic = _method_magic_marker('cell') |
|
273 | 273 | line_cell_magic = _method_magic_marker('line_cell') |
|
274 | 274 | |
|
275 | 275 | # These three decorate standalone functions and perform the decoration |
|
276 | 276 | # immediately. They can only run where get_ipython() works |
|
277 | 277 | register_line_magic = _function_magic_marker('line') |
|
278 | 278 | register_cell_magic = _function_magic_marker('cell') |
|
279 | 279 | register_line_cell_magic = _function_magic_marker('line_cell') |
|
280 | 280 | |
|
281 | 281 | #----------------------------------------------------------------------------- |
|
282 | 282 | # Core Magic classes |
|
283 | 283 | #----------------------------------------------------------------------------- |
|
284 | 284 | |
|
285 | 285 | class MagicsManager(Configurable): |
|
286 | 286 | """Object that handles all magic-related functionality for IPython. |
|
287 | 287 | """ |
|
288 | 288 | # Non-configurable class attributes |
|
289 | 289 | |
|
290 | 290 | # A two-level dict, first keyed by magic type, then by magic function, and |
|
291 | 291 | # holding the actual callable object as value. This is the dict used for |
|
292 | 292 | # magic function dispatch |
|
293 | 293 | magics = Dict() |
|
294 | 294 | |
|
295 | 295 | # A registry of the original objects that we've been given holding magics. |
|
296 | 296 | registry = Dict() |
|
297 | 297 | |
|
298 | 298 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) |
|
299 | 299 | |
|
300 | 300 | auto_magic = Bool(True, help= |
|
301 | 301 | "Automatically call line magics without requiring explicit % prefix" |
|
302 | 302 | ).tag(config=True) |
|
303 | 303 | @observe('auto_magic') |
|
304 | 304 | def _auto_magic_changed(self, change): |
|
305 | 305 | self.shell.automagic = change['new'] |
|
306 | 306 | |
|
307 | 307 | _auto_status = [ |
|
308 | 308 | 'Automagic is OFF, % prefix IS needed for line magics.', |
|
309 | 309 | 'Automagic is ON, % prefix IS NOT needed for line magics.'] |
|
310 | 310 | |
|
311 | 311 | user_magics = Instance('IPython.core.magics.UserMagics', allow_none=True) |
|
312 | 312 | |
|
313 | 313 | def __init__(self, shell=None, config=None, user_magics=None, **traits): |
|
314 | 314 | |
|
315 | 315 | super(MagicsManager, self).__init__(shell=shell, config=config, |
|
316 | 316 | user_magics=user_magics, **traits) |
|
317 | 317 | self.magics = dict(line={}, cell={}) |
|
318 | 318 | # Let's add the user_magics to the registry for uniformity, so *all* |
|
319 | 319 | # registered magic containers can be found there. |
|
320 | 320 | self.registry[user_magics.__class__.__name__] = user_magics |
|
321 | 321 | |
|
322 | 322 | def auto_status(self): |
|
323 | 323 | """Return descriptive string with automagic status.""" |
|
324 | 324 | return self._auto_status[self.auto_magic] |
|
325 | 325 | |
|
326 | 326 | def lsmagic(self): |
|
327 | 327 | """Return a dict of currently available magic functions. |
|
328 | 328 | |
|
329 | 329 | The return dict has the keys 'line' and 'cell', corresponding to the |
|
330 | 330 | two types of magics we support. Each value is a list of names. |
|
331 | 331 | """ |
|
332 | 332 | return self.magics |
|
333 | 333 | |
|
334 | 334 | def lsmagic_docs(self, brief=False, missing=''): |
|
335 | 335 | """Return dict of documentation of magic functions. |
|
336 | 336 | |
|
337 | 337 | The return dict has the keys 'line' and 'cell', corresponding to the |
|
338 | 338 | two types of magics we support. Each value is a dict keyed by magic |
|
339 | 339 | name whose value is the function docstring. If a docstring is |
|
340 | 340 | unavailable, the value of `missing` is used instead. |
|
341 | 341 | |
|
342 | 342 | If brief is True, only the first line of each docstring will be returned. |
|
343 | 343 | """ |
|
344 | 344 | docs = {} |
|
345 | 345 | for m_type in self.magics: |
|
346 | 346 | m_docs = {} |
|
347 |
for m_name, m_func in |
|
|
347 | for m_name, m_func in self.magics[m_type].items(): | |
|
348 | 348 | if m_func.__doc__: |
|
349 | 349 | if brief: |
|
350 | 350 | m_docs[m_name] = m_func.__doc__.split('\n', 1)[0] |
|
351 | 351 | else: |
|
352 | 352 | m_docs[m_name] = m_func.__doc__.rstrip() |
|
353 | 353 | else: |
|
354 | 354 | m_docs[m_name] = missing |
|
355 | 355 | docs[m_type] = m_docs |
|
356 | 356 | return docs |
|
357 | 357 | |
|
358 | 358 | def register(self, *magic_objects): |
|
359 | 359 | """Register one or more instances of Magics. |
|
360 | 360 | |
|
361 | 361 | Take one or more classes or instances of classes that subclass the main |
|
362 | 362 | `core.Magic` class, and register them with IPython to use the magic |
|
363 | 363 | functions they provide. The registration process will then ensure that |
|
364 | 364 | any methods that have decorated to provide line and/or cell magics will |
|
365 | 365 | be recognized with the `%x`/`%%x` syntax as a line/cell magic |
|
366 | 366 | respectively. |
|
367 | 367 | |
|
368 | 368 | If classes are given, they will be instantiated with the default |
|
369 | 369 | constructor. If your classes need a custom constructor, you should |
|
370 | 370 | instanitate them first and pass the instance. |
|
371 | 371 | |
|
372 | 372 | The provided arguments can be an arbitrary mix of classes and instances. |
|
373 | 373 | |
|
374 | 374 | Parameters |
|
375 | 375 | ---------- |
|
376 | 376 | magic_objects : one or more classes or instances |
|
377 | 377 | """ |
|
378 | 378 | # Start by validating them to ensure they have all had their magic |
|
379 | 379 | # methods registered at the instance level |
|
380 | 380 | for m in magic_objects: |
|
381 | 381 | if not m.registered: |
|
382 | 382 | raise ValueError("Class of magics %r was constructed without " |
|
383 | 383 | "the @register_magics class decorator") |
|
384 | 384 | if isinstance(m, type): |
|
385 | 385 | # If we're given an uninstantiated class |
|
386 | 386 | m = m(shell=self.shell) |
|
387 | 387 | |
|
388 | 388 | # Now that we have an instance, we can register it and update the |
|
389 | 389 | # table of callables |
|
390 | 390 | self.registry[m.__class__.__name__] = m |
|
391 | 391 | for mtype in magic_kinds: |
|
392 | 392 | self.magics[mtype].update(m.magics[mtype]) |
|
393 | 393 | |
|
394 | 394 | def register_function(self, func, magic_kind='line', magic_name=None): |
|
395 | 395 | """Expose a standalone function as magic function for IPython. |
|
396 | 396 | |
|
397 | 397 | This will create an IPython magic (line, cell or both) from a |
|
398 | 398 | standalone function. The functions should have the following |
|
399 | 399 | signatures: |
|
400 | 400 | |
|
401 | 401 | * For line magics: `def f(line)` |
|
402 | 402 | * For cell magics: `def f(line, cell)` |
|
403 | 403 | * For a function that does both: `def f(line, cell=None)` |
|
404 | 404 | |
|
405 | 405 | In the latter case, the function will be called with `cell==None` when |
|
406 | 406 | invoked as `%f`, and with cell as a string when invoked as `%%f`. |
|
407 | 407 | |
|
408 | 408 | Parameters |
|
409 | 409 | ---------- |
|
410 | 410 | func : callable |
|
411 | 411 | Function to be registered as a magic. |
|
412 | 412 | |
|
413 | 413 | magic_kind : str |
|
414 | 414 | Kind of magic, one of 'line', 'cell' or 'line_cell' |
|
415 | 415 | |
|
416 | 416 | magic_name : optional str |
|
417 | 417 | If given, the name the magic will have in the IPython namespace. By |
|
418 | 418 | default, the name of the function itself is used. |
|
419 | 419 | """ |
|
420 | 420 | |
|
421 | 421 | # Create the new method in the user_magics and register it in the |
|
422 | 422 | # global table |
|
423 | 423 | validate_type(magic_kind) |
|
424 | 424 | magic_name = func.__name__ if magic_name is None else magic_name |
|
425 | 425 | setattr(self.user_magics, magic_name, func) |
|
426 | 426 | record_magic(self.magics, magic_kind, magic_name, func) |
|
427 | 427 | |
|
428 | 428 | def register_alias(self, alias_name, magic_name, magic_kind='line'): |
|
429 | 429 | """Register an alias to a magic function. |
|
430 | 430 | |
|
431 | 431 | The alias is an instance of :class:`MagicAlias`, which holds the |
|
432 | 432 | name and kind of the magic it should call. Binding is done at |
|
433 | 433 | call time, so if the underlying magic function is changed the alias |
|
434 | 434 | will call the new function. |
|
435 | 435 | |
|
436 | 436 | Parameters |
|
437 | 437 | ---------- |
|
438 | 438 | alias_name : str |
|
439 | 439 | The name of the magic to be registered. |
|
440 | 440 | |
|
441 | 441 | magic_name : str |
|
442 | 442 | The name of an existing magic. |
|
443 | 443 | |
|
444 | 444 | magic_kind : str |
|
445 | 445 | Kind of magic, one of 'line' or 'cell' |
|
446 | 446 | """ |
|
447 | 447 | |
|
448 | 448 | # `validate_type` is too permissive, as it allows 'line_cell' |
|
449 | 449 | # which we do not handle. |
|
450 | 450 | if magic_kind not in magic_kinds: |
|
451 | 451 | raise ValueError('magic_kind must be one of %s, %s given' % |
|
452 | 452 | magic_kinds, magic_kind) |
|
453 | 453 | |
|
454 | 454 | alias = MagicAlias(self.shell, magic_name, magic_kind) |
|
455 | 455 | setattr(self.user_magics, alias_name, alias) |
|
456 | 456 | record_magic(self.magics, magic_kind, alias_name, alias) |
|
457 | 457 | |
|
458 | 458 | # Key base class that provides the central functionality for magics. |
|
459 | 459 | |
|
460 | 460 | |
|
461 | 461 | class Magics(Configurable): |
|
462 | 462 | """Base class for implementing magic functions. |
|
463 | 463 | |
|
464 | 464 | Shell functions which can be reached as %function_name. All magic |
|
465 | 465 | functions should accept a string, which they can parse for their own |
|
466 | 466 | needs. This can make some functions easier to type, eg `%cd ../` |
|
467 | 467 | vs. `%cd("../")` |
|
468 | 468 | |
|
469 | 469 | Classes providing magic functions need to subclass this class, and they |
|
470 | 470 | MUST: |
|
471 | 471 | |
|
472 | 472 | - Use the method decorators `@line_magic` and `@cell_magic` to decorate |
|
473 | 473 | individual methods as magic functions, AND |
|
474 | 474 | |
|
475 | 475 | - Use the class decorator `@magics_class` to ensure that the magic |
|
476 | 476 | methods are properly registered at the instance level upon instance |
|
477 | 477 | initialization. |
|
478 | 478 | |
|
479 | 479 | See :mod:`magic_functions` for examples of actual implementation classes. |
|
480 | 480 | """ |
|
481 | 481 | # Dict holding all command-line options for each magic. |
|
482 | 482 | options_table = None |
|
483 | 483 | # Dict for the mapping of magic names to methods, set by class decorator |
|
484 | 484 | magics = None |
|
485 | 485 | # Flag to check that the class decorator was properly applied |
|
486 | 486 | registered = False |
|
487 | 487 | # Instance of IPython shell |
|
488 | 488 | shell = None |
|
489 | 489 | |
|
490 | 490 | def __init__(self, shell=None, **kwargs): |
|
491 | 491 | if not(self.__class__.registered): |
|
492 | 492 | raise ValueError('Magics subclass without registration - ' |
|
493 | 493 | 'did you forget to apply @magics_class?') |
|
494 | 494 | if shell is not None: |
|
495 | 495 | if hasattr(shell, 'configurables'): |
|
496 | 496 | shell.configurables.append(self) |
|
497 | 497 | if hasattr(shell, 'config'): |
|
498 | 498 | kwargs.setdefault('parent', shell) |
|
499 | 499 | |
|
500 | 500 | self.shell = shell |
|
501 | 501 | self.options_table = {} |
|
502 | 502 | # The method decorators are run when the instance doesn't exist yet, so |
|
503 | 503 | # they can only record the names of the methods they are supposed to |
|
504 | 504 | # grab. Only now, that the instance exists, can we create the proper |
|
505 | 505 | # mapping to bound methods. So we read the info off the original names |
|
506 | 506 | # table and replace each method name by the actual bound method. |
|
507 | 507 | # But we mustn't clobber the *class* mapping, in case of multiple instances. |
|
508 | 508 | class_magics = self.magics |
|
509 | 509 | self.magics = {} |
|
510 | 510 | for mtype in magic_kinds: |
|
511 | 511 | tab = self.magics[mtype] = {} |
|
512 | 512 | cls_tab = class_magics[mtype] |
|
513 |
for magic_name, meth_name in |
|
|
513 | for magic_name, meth_name in cls_tab.items(): | |
|
514 | 514 | if isinstance(meth_name, string_types): |
|
515 | 515 | # it's a method name, grab it |
|
516 | 516 | tab[magic_name] = getattr(self, meth_name) |
|
517 | 517 | else: |
|
518 | 518 | # it's the real thing |
|
519 | 519 | tab[magic_name] = meth_name |
|
520 | 520 | # Configurable **needs** to be initiated at the end or the config |
|
521 | 521 | # magics get screwed up. |
|
522 | 522 | super(Magics, self).__init__(**kwargs) |
|
523 | 523 | |
|
524 | 524 | def arg_err(self,func): |
|
525 | 525 | """Print docstring if incorrect arguments were passed""" |
|
526 | 526 | print('Error in arguments:') |
|
527 | 527 | print(oinspect.getdoc(func)) |
|
528 | 528 | |
|
529 | 529 | def format_latex(self, strng): |
|
530 | 530 | """Format a string for latex inclusion.""" |
|
531 | 531 | |
|
532 | 532 | # Characters that need to be escaped for latex: |
|
533 | 533 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
534 | 534 | # Magic command names as headers: |
|
535 | 535 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
536 | 536 | re.MULTILINE) |
|
537 | 537 | # Magic commands |
|
538 | 538 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
539 | 539 | re.MULTILINE) |
|
540 | 540 | # Paragraph continue |
|
541 | 541 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
542 | 542 | |
|
543 | 543 | # The "\n" symbol |
|
544 | 544 | newline_re = re.compile(r'\\n') |
|
545 | 545 | |
|
546 | 546 | # Now build the string for output: |
|
547 | 547 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
548 | 548 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
549 | 549 | strng) |
|
550 | 550 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
551 | 551 | strng = par_re.sub(r'\\\\',strng) |
|
552 | 552 | strng = escape_re.sub(r'\\\1',strng) |
|
553 | 553 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
554 | 554 | return strng |
|
555 | 555 | |
|
556 | 556 | def parse_options(self, arg_str, opt_str, *long_opts, **kw): |
|
557 | 557 | """Parse options passed to an argument string. |
|
558 | 558 | |
|
559 | 559 | The interface is similar to that of :func:`getopt.getopt`, but it |
|
560 | 560 | returns a :class:`~IPython.utils.struct.Struct` with the options as keys |
|
561 | 561 | and the stripped argument string still as a string. |
|
562 | 562 | |
|
563 | 563 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
564 | 564 | This allows us to easily expand variables, glob files, quote |
|
565 | 565 | arguments, etc. |
|
566 | 566 | |
|
567 | 567 | Parameters |
|
568 | 568 | ---------- |
|
569 | 569 | |
|
570 | 570 | arg_str : str |
|
571 | 571 | The arguments to parse. |
|
572 | 572 | |
|
573 | 573 | opt_str : str |
|
574 | 574 | The options specification. |
|
575 | 575 | |
|
576 | 576 | mode : str, default 'string' |
|
577 | 577 | If given as 'list', the argument string is returned as a list (split |
|
578 | 578 | on whitespace) instead of a string. |
|
579 | 579 | |
|
580 | 580 | list_all : bool, default False |
|
581 | 581 | Put all option values in lists. Normally only options |
|
582 | 582 | appearing more than once are put in a list. |
|
583 | 583 | |
|
584 | 584 | posix : bool, default True |
|
585 | 585 | Whether to split the input line in POSIX mode or not, as per the |
|
586 | 586 | conventions outlined in the :mod:`shlex` module from the standard |
|
587 | 587 | library. |
|
588 | 588 | """ |
|
589 | 589 | |
|
590 | 590 | # inject default options at the beginning of the input line |
|
591 | 591 | caller = sys._getframe(1).f_code.co_name |
|
592 | 592 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
593 | 593 | |
|
594 | 594 | mode = kw.get('mode','string') |
|
595 | 595 | if mode not in ['string','list']: |
|
596 | 596 | raise ValueError('incorrect mode given: %s' % mode) |
|
597 | 597 | # Get options |
|
598 | 598 | list_all = kw.get('list_all',0) |
|
599 | 599 | posix = kw.get('posix', os.name == 'posix') |
|
600 | 600 | strict = kw.get('strict', True) |
|
601 | 601 | |
|
602 | 602 | # Check if we have more than one argument to warrant extra processing: |
|
603 | 603 | odict = {} # Dictionary with options |
|
604 | 604 | args = arg_str.split() |
|
605 | 605 | if len(args) >= 1: |
|
606 | 606 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
607 | 607 | # need to look for options |
|
608 | 608 | argv = arg_split(arg_str, posix, strict) |
|
609 | 609 | # Do regular option processing |
|
610 | 610 | try: |
|
611 | 611 | opts,args = getopt(argv, opt_str, long_opts) |
|
612 | 612 | except GetoptError as e: |
|
613 | 613 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
614 | 614 | " ".join(long_opts))) |
|
615 | 615 | for o,a in opts: |
|
616 | 616 | if o.startswith('--'): |
|
617 | 617 | o = o[2:] |
|
618 | 618 | else: |
|
619 | 619 | o = o[1:] |
|
620 | 620 | try: |
|
621 | 621 | odict[o].append(a) |
|
622 | 622 | except AttributeError: |
|
623 | 623 | odict[o] = [odict[o],a] |
|
624 | 624 | except KeyError: |
|
625 | 625 | if list_all: |
|
626 | 626 | odict[o] = [a] |
|
627 | 627 | else: |
|
628 | 628 | odict[o] = a |
|
629 | 629 | |
|
630 | 630 | # Prepare opts,args for return |
|
631 | 631 | opts = Struct(odict) |
|
632 | 632 | if mode == 'string': |
|
633 | 633 | args = ' '.join(args) |
|
634 | 634 | |
|
635 | 635 | return opts,args |
|
636 | 636 | |
|
637 | 637 | def default_option(self, fn, optstr): |
|
638 | 638 | """Make an entry in the options_table for fn, with value optstr""" |
|
639 | 639 | |
|
640 | 640 | if fn not in self.lsmagic(): |
|
641 | 641 | error("%s is not a magic function" % fn) |
|
642 | 642 | self.options_table[fn] = optstr |
|
643 | 643 | |
|
644 | 644 | |
|
645 | 645 | class MagicAlias(object): |
|
646 | 646 | """An alias to another magic function. |
|
647 | 647 | |
|
648 | 648 | An alias is determined by its magic name and magic kind. Lookup |
|
649 | 649 | is done at call time, so if the underlying magic changes the alias |
|
650 | 650 | will call the new function. |
|
651 | 651 | |
|
652 | 652 | Use the :meth:`MagicsManager.register_alias` method or the |
|
653 | 653 | `%alias_magic` magic function to create and register a new alias. |
|
654 | 654 | """ |
|
655 | 655 | def __init__(self, shell, magic_name, magic_kind): |
|
656 | 656 | self.shell = shell |
|
657 | 657 | self.magic_name = magic_name |
|
658 | 658 | self.magic_kind = magic_kind |
|
659 | 659 | |
|
660 | 660 | self.pretty_target = '%s%s' % (magic_escapes[self.magic_kind], self.magic_name) |
|
661 | 661 | self.__doc__ = "Alias for `%s`." % self.pretty_target |
|
662 | 662 | |
|
663 | 663 | self._in_call = False |
|
664 | 664 | |
|
665 | 665 | def __call__(self, *args, **kwargs): |
|
666 | 666 | """Call the magic alias.""" |
|
667 | 667 | fn = self.shell.find_magic(self.magic_name, self.magic_kind) |
|
668 | 668 | if fn is None: |
|
669 | 669 | raise UsageError("Magic `%s` not found." % self.pretty_target) |
|
670 | 670 | |
|
671 | 671 | # Protect against infinite recursion. |
|
672 | 672 | if self._in_call: |
|
673 | 673 | raise UsageError("Infinite recursion detected; " |
|
674 | 674 | "magic aliases cannot call themselves.") |
|
675 | 675 | self._in_call = True |
|
676 | 676 | try: |
|
677 | 677 | return fn(*args, **kwargs) |
|
678 | 678 | finally: |
|
679 | 679 | self._in_call = False |
@@ -1,1373 +1,1372 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 | 10 | import gc |
|
11 | 11 | import itertools |
|
12 | 12 | import os |
|
13 | 13 | import sys |
|
14 | 14 | import time |
|
15 | 15 | import timeit |
|
16 | 16 | import math |
|
17 | 17 | from pdb import Restart |
|
18 | 18 | |
|
19 | 19 | # cProfile was added in Python2.5 |
|
20 | 20 | try: |
|
21 | 21 | import cProfile as profile |
|
22 | 22 | import pstats |
|
23 | 23 | except ImportError: |
|
24 | 24 | # profile isn't bundled by default in Debian for license reasons |
|
25 | 25 | try: |
|
26 | 26 | import profile, pstats |
|
27 | 27 | except ImportError: |
|
28 | 28 | profile = pstats = None |
|
29 | 29 | |
|
30 | 30 | from IPython.core import oinspect |
|
31 | 31 | from IPython.core import magic_arguments |
|
32 | 32 | from IPython.core import page |
|
33 | 33 | from IPython.core.error import UsageError |
|
34 | 34 | from IPython.core.macro import Macro |
|
35 | 35 | from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic, |
|
36 | 36 | line_cell_magic, on_off, needs_local_scope) |
|
37 | 37 | from IPython.testing.skipdoctest import skip_doctest |
|
38 | 38 | from IPython.utils import py3compat |
|
39 |
from IPython.utils.py3compat import builtin_mod, |
|
|
39 | from IPython.utils.py3compat import builtin_mod, PY3 | |
|
40 | 40 | from IPython.utils.contexts import preserve_keys |
|
41 | 41 | from IPython.utils.capture import capture_output |
|
42 | 42 | from IPython.utils.ipstruct import Struct |
|
43 | 43 | from IPython.utils.module_paths import find_mod |
|
44 | 44 | from IPython.utils.path import get_py_filename, shellglob |
|
45 | 45 | from IPython.utils.timing import clock, clock2 |
|
46 | 46 | from warnings import warn |
|
47 | 47 | from logging import error |
|
48 | 48 | |
|
49 | 49 | if PY3: |
|
50 | 50 | from io import StringIO |
|
51 | 51 | else: |
|
52 | 52 | from StringIO import StringIO |
|
53 | 53 | |
|
54 | 54 | #----------------------------------------------------------------------------- |
|
55 | 55 | # Magic implementation classes |
|
56 | 56 | #----------------------------------------------------------------------------- |
|
57 | 57 | |
|
58 | 58 | |
|
59 | 59 | class TimeitResult(object): |
|
60 | 60 | """ |
|
61 | 61 | Object returned by the timeit magic with info about the run. |
|
62 | 62 | |
|
63 | 63 | Contains the following attributes : |
|
64 | 64 | |
|
65 | 65 | loops: (int) number of loops done per measurement |
|
66 | 66 | repeat: (int) number of times the measurement has been repeated |
|
67 | 67 | best: (float) best execution time / number |
|
68 | 68 | all_runs: (list of float) execution time of each run (in s) |
|
69 | 69 | compile_time: (float) time of statement compilation (s) |
|
70 | 70 | |
|
71 | 71 | """ |
|
72 | 72 | def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision): |
|
73 | 73 | self.loops = loops |
|
74 | 74 | self.repeat = repeat |
|
75 | 75 | self.best = best |
|
76 | 76 | self.worst = worst |
|
77 | 77 | self.all_runs = all_runs |
|
78 | 78 | self.compile_time = compile_time |
|
79 | 79 | self._precision = precision |
|
80 | 80 | self.timings = [ dt / self.loops for dt in all_runs] |
|
81 | 81 | |
|
82 | 82 | @property |
|
83 | 83 | def average(self): |
|
84 | 84 | return math.fsum(self.timings) / len(self.timings) |
|
85 | 85 | |
|
86 | 86 | @property |
|
87 | 87 | def stdev(self): |
|
88 | 88 | mean = self.average |
|
89 | 89 | return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5 |
|
90 | 90 | |
|
91 | 91 | def __str__(self): |
|
92 | 92 | return (u"%s loop%s, average of %d: %s +- %s per loop (using standard deviation)" |
|
93 | 93 | % (self.loops,"" if self.loops == 1 else "s", self.repeat, |
|
94 | 94 | _format_time(self.average, self._precision), |
|
95 | 95 | _format_time(self.stdev, self._precision))) |
|
96 | 96 | |
|
97 | 97 | def _repr_pretty_(self, p , cycle): |
|
98 | 98 | unic = self.__str__() |
|
99 | 99 | p.text(u'<TimeitResult : '+unic+u'>') |
|
100 | 100 | |
|
101 | 101 | |
|
102 | 102 | |
|
103 | 103 | class TimeitTemplateFiller(ast.NodeTransformer): |
|
104 | 104 | """Fill in the AST template for timing execution. |
|
105 | 105 | |
|
106 | 106 | This is quite closely tied to the template definition, which is in |
|
107 | 107 | :meth:`ExecutionMagics.timeit`. |
|
108 | 108 | """ |
|
109 | 109 | def __init__(self, ast_setup, ast_stmt): |
|
110 | 110 | self.ast_setup = ast_setup |
|
111 | 111 | self.ast_stmt = ast_stmt |
|
112 | 112 | |
|
113 | 113 | def visit_FunctionDef(self, node): |
|
114 | 114 | "Fill in the setup statement" |
|
115 | 115 | self.generic_visit(node) |
|
116 | 116 | if node.name == "inner": |
|
117 | 117 | node.body[:1] = self.ast_setup.body |
|
118 | 118 | |
|
119 | 119 | return node |
|
120 | 120 | |
|
121 | 121 | def visit_For(self, node): |
|
122 | 122 | "Fill in the statement to be timed" |
|
123 | 123 | if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt': |
|
124 | 124 | node.body = self.ast_stmt.body |
|
125 | 125 | return node |
|
126 | 126 | |
|
127 | 127 | |
|
128 | 128 | class Timer(timeit.Timer): |
|
129 | 129 | """Timer class that explicitly uses self.inner |
|
130 | 130 | |
|
131 | 131 | which is an undocumented implementation detail of CPython, |
|
132 | 132 | not shared by PyPy. |
|
133 | 133 | """ |
|
134 | 134 | # Timer.timeit copied from CPython 3.4.2 |
|
135 | 135 | def timeit(self, number=timeit.default_number): |
|
136 | 136 | """Time 'number' executions of the main statement. |
|
137 | 137 | |
|
138 | 138 | To be precise, this executes the setup statement once, and |
|
139 | 139 | then returns the time it takes to execute the main statement |
|
140 | 140 | a number of times, as a float measured in seconds. The |
|
141 | 141 | argument is the number of times through the loop, defaulting |
|
142 | 142 | to one million. The main statement, the setup statement and |
|
143 | 143 | the timer function to be used are passed to the constructor. |
|
144 | 144 | """ |
|
145 | 145 | it = itertools.repeat(None, number) |
|
146 | 146 | gcold = gc.isenabled() |
|
147 | 147 | gc.disable() |
|
148 | 148 | try: |
|
149 | 149 | timing = self.inner(it, self.timer) |
|
150 | 150 | finally: |
|
151 | 151 | if gcold: |
|
152 | 152 | gc.enable() |
|
153 | 153 | return timing |
|
154 | 154 | |
|
155 | 155 | |
|
156 | 156 | @magics_class |
|
157 | 157 | class ExecutionMagics(Magics): |
|
158 | 158 | """Magics related to code execution, debugging, profiling, etc. |
|
159 | 159 | |
|
160 | 160 | """ |
|
161 | 161 | |
|
162 | 162 | def __init__(self, shell): |
|
163 | 163 | super(ExecutionMagics, self).__init__(shell) |
|
164 | 164 | if profile is None: |
|
165 | 165 | self.prun = self.profile_missing_notice |
|
166 | 166 | # Default execution function used to actually run user code. |
|
167 | 167 | self.default_runner = None |
|
168 | 168 | |
|
169 | 169 | def profile_missing_notice(self, *args, **kwargs): |
|
170 | 170 | error("""\ |
|
171 | 171 | The profile module could not be found. It has been removed from the standard |
|
172 | 172 | python packages because of its non-free license. To use profiling, install the |
|
173 | 173 | python-profiler package from non-free.""") |
|
174 | 174 | |
|
175 | 175 | @skip_doctest |
|
176 | 176 | @line_cell_magic |
|
177 | 177 | def prun(self, parameter_s='', cell=None): |
|
178 | 178 | |
|
179 | 179 | """Run a statement through the python code profiler. |
|
180 | 180 | |
|
181 | 181 | Usage, in line mode: |
|
182 | 182 | %prun [options] statement |
|
183 | 183 | |
|
184 | 184 | Usage, in cell mode: |
|
185 | 185 | %%prun [options] [statement] |
|
186 | 186 | code... |
|
187 | 187 | code... |
|
188 | 188 | |
|
189 | 189 | In cell mode, the additional code lines are appended to the (possibly |
|
190 | 190 | empty) statement in the first line. Cell mode allows you to easily |
|
191 | 191 | profile multiline blocks without having to put them in a separate |
|
192 | 192 | function. |
|
193 | 193 | |
|
194 | 194 | The given statement (which doesn't require quote marks) is run via the |
|
195 | 195 | python profiler in a manner similar to the profile.run() function. |
|
196 | 196 | Namespaces are internally managed to work correctly; profile.run |
|
197 | 197 | cannot be used in IPython because it makes certain assumptions about |
|
198 | 198 | namespaces which do not hold under IPython. |
|
199 | 199 | |
|
200 | 200 | Options: |
|
201 | 201 | |
|
202 | 202 | -l <limit> |
|
203 | 203 | you can place restrictions on what or how much of the |
|
204 | 204 | profile gets printed. The limit value can be: |
|
205 | 205 | |
|
206 | 206 | * A string: only information for function names containing this string |
|
207 | 207 | is printed. |
|
208 | 208 | |
|
209 | 209 | * An integer: only these many lines are printed. |
|
210 | 210 | |
|
211 | 211 | * A float (between 0 and 1): this fraction of the report is printed |
|
212 | 212 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
213 | 213 | |
|
214 | 214 | You can combine several limits with repeated use of the option. For |
|
215 | 215 | example, ``-l __init__ -l 5`` will print only the topmost 5 lines of |
|
216 | 216 | information about class constructors. |
|
217 | 217 | |
|
218 | 218 | -r |
|
219 | 219 | return the pstats.Stats object generated by the profiling. This |
|
220 | 220 | object has all the information about the profile in it, and you can |
|
221 | 221 | later use it for further analysis or in other functions. |
|
222 | 222 | |
|
223 | 223 | -s <key> |
|
224 | 224 | sort profile by given key. You can provide more than one key |
|
225 | 225 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
226 | 226 | default sorting key is 'time'. |
|
227 | 227 | |
|
228 | 228 | The following is copied verbatim from the profile documentation |
|
229 | 229 | referenced below: |
|
230 | 230 | |
|
231 | 231 | When more than one key is provided, additional keys are used as |
|
232 | 232 | secondary criteria when the there is equality in all keys selected |
|
233 | 233 | before them. |
|
234 | 234 | |
|
235 | 235 | Abbreviations can be used for any key names, as long as the |
|
236 | 236 | abbreviation is unambiguous. The following are the keys currently |
|
237 | 237 | defined: |
|
238 | 238 | |
|
239 | 239 | ============ ===================== |
|
240 | 240 | Valid Arg Meaning |
|
241 | 241 | ============ ===================== |
|
242 | 242 | "calls" call count |
|
243 | 243 | "cumulative" cumulative time |
|
244 | 244 | "file" file name |
|
245 | 245 | "module" file name |
|
246 | 246 | "pcalls" primitive call count |
|
247 | 247 | "line" line number |
|
248 | 248 | "name" function name |
|
249 | 249 | "nfl" name/file/line |
|
250 | 250 | "stdname" standard name |
|
251 | 251 | "time" internal time |
|
252 | 252 | ============ ===================== |
|
253 | 253 | |
|
254 | 254 | Note that all sorts on statistics are in descending order (placing |
|
255 | 255 | most time consuming items first), where as name, file, and line number |
|
256 | 256 | searches are in ascending order (i.e., alphabetical). The subtle |
|
257 | 257 | distinction between "nfl" and "stdname" is that the standard name is a |
|
258 | 258 | sort of the name as printed, which means that the embedded line |
|
259 | 259 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
260 | 260 | would (if the file names were the same) appear in the string order |
|
261 | 261 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
262 | 262 | line numbers. In fact, sort_stats("nfl") is the same as |
|
263 | 263 | sort_stats("name", "file", "line"). |
|
264 | 264 | |
|
265 | 265 | -T <filename> |
|
266 | 266 | save profile results as shown on screen to a text |
|
267 | 267 | file. The profile is still shown on screen. |
|
268 | 268 | |
|
269 | 269 | -D <filename> |
|
270 | 270 | save (via dump_stats) profile statistics to given |
|
271 | 271 | filename. This data is in a format understood by the pstats module, and |
|
272 | 272 | is generated by a call to the dump_stats() method of profile |
|
273 | 273 | objects. The profile is still shown on screen. |
|
274 | 274 | |
|
275 | 275 | -q |
|
276 | 276 | suppress output to the pager. Best used with -T and/or -D above. |
|
277 | 277 | |
|
278 | 278 | If you want to run complete programs under the profiler's control, use |
|
279 | 279 | ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts |
|
280 | 280 | contains profiler specific options as described here. |
|
281 | 281 | |
|
282 | 282 | You can read the complete documentation for the profile module with:: |
|
283 | 283 | |
|
284 | 284 | In [1]: import profile; profile.help() |
|
285 | 285 | """ |
|
286 | 286 | opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q', |
|
287 | 287 | list_all=True, posix=False) |
|
288 | 288 | if cell is not None: |
|
289 | 289 | arg_str += '\n' + cell |
|
290 | 290 | arg_str = self.shell.input_splitter.transform_cell(arg_str) |
|
291 | 291 | return self._run_with_profiler(arg_str, opts, self.shell.user_ns) |
|
292 | 292 | |
|
293 | 293 | def _run_with_profiler(self, code, opts, namespace): |
|
294 | 294 | """ |
|
295 | 295 | Run `code` with profiler. Used by ``%prun`` and ``%run -p``. |
|
296 | 296 | |
|
297 | 297 | Parameters |
|
298 | 298 | ---------- |
|
299 | 299 | code : str |
|
300 | 300 | Code to be executed. |
|
301 | 301 | opts : Struct |
|
302 | 302 | Options parsed by `self.parse_options`. |
|
303 | 303 | namespace : dict |
|
304 | 304 | A dictionary for Python namespace (e.g., `self.shell.user_ns`). |
|
305 | 305 | |
|
306 | 306 | """ |
|
307 | 307 | |
|
308 | 308 | # Fill default values for unspecified options: |
|
309 | 309 | opts.merge(Struct(D=[''], l=[], s=['time'], T=[''])) |
|
310 | 310 | |
|
311 | 311 | prof = profile.Profile() |
|
312 | 312 | try: |
|
313 | 313 | prof = prof.runctx(code, namespace, namespace) |
|
314 | 314 | sys_exit = '' |
|
315 | 315 | except SystemExit: |
|
316 | 316 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
317 | 317 | |
|
318 | 318 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
319 | 319 | |
|
320 | 320 | lims = opts.l |
|
321 | 321 | if lims: |
|
322 | 322 | lims = [] # rebuild lims with ints/floats/strings |
|
323 | 323 | for lim in opts.l: |
|
324 | 324 | try: |
|
325 | 325 | lims.append(int(lim)) |
|
326 | 326 | except ValueError: |
|
327 | 327 | try: |
|
328 | 328 | lims.append(float(lim)) |
|
329 | 329 | except ValueError: |
|
330 | 330 | lims.append(lim) |
|
331 | 331 | |
|
332 | 332 | # Trap output. |
|
333 | 333 | stdout_trap = StringIO() |
|
334 | 334 | stats_stream = stats.stream |
|
335 | 335 | try: |
|
336 | 336 | stats.stream = stdout_trap |
|
337 | 337 | stats.print_stats(*lims) |
|
338 | 338 | finally: |
|
339 | 339 | stats.stream = stats_stream |
|
340 | 340 | |
|
341 | 341 | output = stdout_trap.getvalue() |
|
342 | 342 | output = output.rstrip() |
|
343 | 343 | |
|
344 | 344 | if 'q' not in opts: |
|
345 | 345 | page.page(output) |
|
346 | 346 | print(sys_exit, end=' ') |
|
347 | 347 | |
|
348 | 348 | dump_file = opts.D[0] |
|
349 | 349 | text_file = opts.T[0] |
|
350 | 350 | if dump_file: |
|
351 | 351 | prof.dump_stats(dump_file) |
|
352 | 352 | print('\n*** Profile stats marshalled to file',\ |
|
353 | 353 | repr(dump_file)+'.',sys_exit) |
|
354 | 354 | if text_file: |
|
355 | 355 | pfile = open(text_file,'w') |
|
356 | 356 | pfile.write(output) |
|
357 | 357 | pfile.close() |
|
358 | 358 | print('\n*** Profile printout saved to text file',\ |
|
359 | 359 | repr(text_file)+'.',sys_exit) |
|
360 | 360 | |
|
361 | 361 | if 'r' in opts: |
|
362 | 362 | return stats |
|
363 | 363 | else: |
|
364 | 364 | return None |
|
365 | 365 | |
|
366 | 366 | @line_magic |
|
367 | 367 | def pdb(self, parameter_s=''): |
|
368 | 368 | """Control the automatic calling of the pdb interactive debugger. |
|
369 | 369 | |
|
370 | 370 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
371 | 371 | argument it works as a toggle. |
|
372 | 372 | |
|
373 | 373 | When an exception is triggered, IPython can optionally call the |
|
374 | 374 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
375 | 375 | this feature on and off. |
|
376 | 376 | |
|
377 | 377 | The initial state of this feature is set in your configuration |
|
378 | 378 | file (the option is ``InteractiveShell.pdb``). |
|
379 | 379 | |
|
380 | 380 | If you want to just activate the debugger AFTER an exception has fired, |
|
381 | 381 | without having to type '%pdb on' and rerunning your code, you can use |
|
382 | 382 | the %debug magic.""" |
|
383 | 383 | |
|
384 | 384 | par = parameter_s.strip().lower() |
|
385 | 385 | |
|
386 | 386 | if par: |
|
387 | 387 | try: |
|
388 | 388 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
389 | 389 | except KeyError: |
|
390 | 390 | print ('Incorrect argument. Use on/1, off/0, ' |
|
391 | 391 | 'or nothing for a toggle.') |
|
392 | 392 | return |
|
393 | 393 | else: |
|
394 | 394 | # toggle |
|
395 | 395 | new_pdb = not self.shell.call_pdb |
|
396 | 396 | |
|
397 | 397 | # set on the shell |
|
398 | 398 | self.shell.call_pdb = new_pdb |
|
399 | 399 | print('Automatic pdb calling has been turned',on_off(new_pdb)) |
|
400 | 400 | |
|
401 | 401 | @skip_doctest |
|
402 | 402 | @magic_arguments.magic_arguments() |
|
403 | 403 | @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE', |
|
404 | 404 | help=""" |
|
405 | 405 | Set break point at LINE in FILE. |
|
406 | 406 | """ |
|
407 | 407 | ) |
|
408 | 408 | @magic_arguments.argument('statement', nargs='*', |
|
409 | 409 | help=""" |
|
410 | 410 | Code to run in debugger. |
|
411 | 411 | You can omit this in cell magic mode. |
|
412 | 412 | """ |
|
413 | 413 | ) |
|
414 | 414 | @line_cell_magic |
|
415 | 415 | def debug(self, line='', cell=None): |
|
416 | 416 | """Activate the interactive debugger. |
|
417 | 417 | |
|
418 | 418 | This magic command support two ways of activating debugger. |
|
419 | 419 | One is to activate debugger before executing code. This way, you |
|
420 | 420 | can set a break point, to step through the code from the point. |
|
421 | 421 | You can use this mode by giving statements to execute and optionally |
|
422 | 422 | a breakpoint. |
|
423 | 423 | |
|
424 | 424 | The other one is to activate debugger in post-mortem mode. You can |
|
425 | 425 | activate this mode simply running %debug without any argument. |
|
426 | 426 | If an exception has just occurred, this lets you inspect its stack |
|
427 | 427 | frames interactively. Note that this will always work only on the last |
|
428 | 428 | traceback that occurred, so you must call this quickly after an |
|
429 | 429 | exception that you wish to inspect has fired, because if another one |
|
430 | 430 | occurs, it clobbers the previous one. |
|
431 | 431 | |
|
432 | 432 | If you want IPython to automatically do this on every exception, see |
|
433 | 433 | the %pdb magic for more details. |
|
434 | 434 | """ |
|
435 | 435 | args = magic_arguments.parse_argstring(self.debug, line) |
|
436 | 436 | |
|
437 | 437 | if not (args.breakpoint or args.statement or cell): |
|
438 | 438 | self._debug_post_mortem() |
|
439 | 439 | else: |
|
440 | 440 | code = "\n".join(args.statement) |
|
441 | 441 | if cell: |
|
442 | 442 | code += "\n" + cell |
|
443 | 443 | self._debug_exec(code, args.breakpoint) |
|
444 | 444 | |
|
445 | 445 | def _debug_post_mortem(self): |
|
446 | 446 | self.shell.debugger(force=True) |
|
447 | 447 | |
|
448 | 448 | def _debug_exec(self, code, breakpoint): |
|
449 | 449 | if breakpoint: |
|
450 | 450 | (filename, bp_line) = breakpoint.rsplit(':', 1) |
|
451 | 451 | bp_line = int(bp_line) |
|
452 | 452 | else: |
|
453 | 453 | (filename, bp_line) = (None, None) |
|
454 | 454 | self._run_with_debugger(code, self.shell.user_ns, filename, bp_line) |
|
455 | 455 | |
|
456 | 456 | @line_magic |
|
457 | 457 | def tb(self, s): |
|
458 | 458 | """Print the last traceback with the currently active exception mode. |
|
459 | 459 | |
|
460 | 460 | See %xmode for changing exception reporting modes.""" |
|
461 | 461 | self.shell.showtraceback() |
|
462 | 462 | |
|
463 | 463 | @skip_doctest |
|
464 | 464 | @line_magic |
|
465 | 465 | def run(self, parameter_s='', runner=None, |
|
466 | 466 | file_finder=get_py_filename): |
|
467 | 467 | """Run the named file inside IPython as a program. |
|
468 | 468 | |
|
469 | 469 | Usage:: |
|
470 | 470 | |
|
471 | 471 | %run [-n -i -e -G] |
|
472 | 472 | [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )] |
|
473 | 473 | ( -m mod | file ) [args] |
|
474 | 474 | |
|
475 | 475 | Parameters after the filename are passed as command-line arguments to |
|
476 | 476 | the program (put in sys.argv). Then, control returns to IPython's |
|
477 | 477 | prompt. |
|
478 | 478 | |
|
479 | 479 | This is similar to running at a system prompt ``python file args``, |
|
480 | 480 | but with the advantage of giving you IPython's tracebacks, and of |
|
481 | 481 | loading all variables into your interactive namespace for further use |
|
482 | 482 | (unless -p is used, see below). |
|
483 | 483 | |
|
484 | 484 | The file is executed in a namespace initially consisting only of |
|
485 | 485 | ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus |
|
486 | 486 | sees its environment as if it were being run as a stand-alone program |
|
487 | 487 | (except for sharing global objects such as previously imported |
|
488 | 488 | modules). But after execution, the IPython interactive namespace gets |
|
489 | 489 | updated with all variables defined in the program (except for __name__ |
|
490 | 490 | and sys.argv). This allows for very convenient loading of code for |
|
491 | 491 | interactive work, while giving each program a 'clean sheet' to run in. |
|
492 | 492 | |
|
493 | 493 | Arguments are expanded using shell-like glob match. Patterns |
|
494 | 494 | '*', '?', '[seq]' and '[!seq]' can be used. Additionally, |
|
495 | 495 | tilde '~' will be expanded into user's home directory. Unlike |
|
496 | 496 | real shells, quotation does not suppress expansions. Use |
|
497 | 497 | *two* back slashes (e.g. ``\\\\*``) to suppress expansions. |
|
498 | 498 | To completely disable these expansions, you can use -G flag. |
|
499 | 499 | |
|
500 | 500 | Options: |
|
501 | 501 | |
|
502 | 502 | -n |
|
503 | 503 | __name__ is NOT set to '__main__', but to the running file's name |
|
504 | 504 | without extension (as python does under import). This allows running |
|
505 | 505 | scripts and reloading the definitions in them without calling code |
|
506 | 506 | protected by an ``if __name__ == "__main__"`` clause. |
|
507 | 507 | |
|
508 | 508 | -i |
|
509 | 509 | run the file in IPython's namespace instead of an empty one. This |
|
510 | 510 | is useful if you are experimenting with code written in a text editor |
|
511 | 511 | which depends on variables defined interactively. |
|
512 | 512 | |
|
513 | 513 | -e |
|
514 | 514 | ignore sys.exit() calls or SystemExit exceptions in the script |
|
515 | 515 | being run. This is particularly useful if IPython is being used to |
|
516 | 516 | run unittests, which always exit with a sys.exit() call. In such |
|
517 | 517 | cases you are interested in the output of the test results, not in |
|
518 | 518 | seeing a traceback of the unittest module. |
|
519 | 519 | |
|
520 | 520 | -t |
|
521 | 521 | print timing information at the end of the run. IPython will give |
|
522 | 522 | you an estimated CPU time consumption for your script, which under |
|
523 | 523 | Unix uses the resource module to avoid the wraparound problems of |
|
524 | 524 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
525 | 525 | is also given (for Windows platforms this is reported as 0.0). |
|
526 | 526 | |
|
527 | 527 | If -t is given, an additional ``-N<N>`` option can be given, where <N> |
|
528 | 528 | must be an integer indicating how many times you want the script to |
|
529 | 529 | run. The final timing report will include total and per run results. |
|
530 | 530 | |
|
531 | 531 | For example (testing the script uniq_stable.py):: |
|
532 | 532 | |
|
533 | 533 | In [1]: run -t uniq_stable |
|
534 | 534 | |
|
535 | 535 | IPython CPU timings (estimated): |
|
536 | 536 | User : 0.19597 s. |
|
537 | 537 | System: 0.0 s. |
|
538 | 538 | |
|
539 | 539 | In [2]: run -t -N5 uniq_stable |
|
540 | 540 | |
|
541 | 541 | IPython CPU timings (estimated): |
|
542 | 542 | Total runs performed: 5 |
|
543 | 543 | Times : Total Per run |
|
544 | 544 | User : 0.910862 s, 0.1821724 s. |
|
545 | 545 | System: 0.0 s, 0.0 s. |
|
546 | 546 | |
|
547 | 547 | -d |
|
548 | 548 | run your program under the control of pdb, the Python debugger. |
|
549 | 549 | This allows you to execute your program step by step, watch variables, |
|
550 | 550 | etc. Internally, what IPython does is similar to calling:: |
|
551 | 551 | |
|
552 | 552 | pdb.run('execfile("YOURFILENAME")') |
|
553 | 553 | |
|
554 | 554 | with a breakpoint set on line 1 of your file. You can change the line |
|
555 | 555 | number for this automatic breakpoint to be <N> by using the -bN option |
|
556 | 556 | (where N must be an integer). For example:: |
|
557 | 557 | |
|
558 | 558 | %run -d -b40 myscript |
|
559 | 559 | |
|
560 | 560 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
561 | 561 | the first breakpoint must be set on a line which actually does |
|
562 | 562 | something (not a comment or docstring) for it to stop execution. |
|
563 | 563 | |
|
564 | 564 | Or you can specify a breakpoint in a different file:: |
|
565 | 565 | |
|
566 | 566 | %run -d -b myotherfile.py:20 myscript |
|
567 | 567 | |
|
568 | 568 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
569 | 569 | first enter 'c' (without quotes) to start execution up to the first |
|
570 | 570 | breakpoint. |
|
571 | 571 | |
|
572 | 572 | Entering 'help' gives information about the use of the debugger. You |
|
573 | 573 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
574 | 574 | at a prompt. |
|
575 | 575 | |
|
576 | 576 | -p |
|
577 | 577 | run program under the control of the Python profiler module (which |
|
578 | 578 | prints a detailed report of execution times, function calls, etc). |
|
579 | 579 | |
|
580 | 580 | You can pass other options after -p which affect the behavior of the |
|
581 | 581 | profiler itself. See the docs for %prun for details. |
|
582 | 582 | |
|
583 | 583 | In this mode, the program's variables do NOT propagate back to the |
|
584 | 584 | IPython interactive namespace (because they remain in the namespace |
|
585 | 585 | where the profiler executes them). |
|
586 | 586 | |
|
587 | 587 | Internally this triggers a call to %prun, see its documentation for |
|
588 | 588 | details on the options available specifically for profiling. |
|
589 | 589 | |
|
590 | 590 | There is one special usage for which the text above doesn't apply: |
|
591 | 591 | if the filename ends with .ipy[nb], the file is run as ipython script, |
|
592 | 592 | just as if the commands were written on IPython prompt. |
|
593 | 593 | |
|
594 | 594 | -m |
|
595 | 595 | specify module name to load instead of script path. Similar to |
|
596 | 596 | the -m option for the python interpreter. Use this option last if you |
|
597 | 597 | want to combine with other %run options. Unlike the python interpreter |
|
598 | 598 | only source modules are allowed no .pyc or .pyo files. |
|
599 | 599 | For example:: |
|
600 | 600 | |
|
601 | 601 | %run -m example |
|
602 | 602 | |
|
603 | 603 | will run the example module. |
|
604 | 604 | |
|
605 | 605 | -G |
|
606 | 606 | disable shell-like glob expansion of arguments. |
|
607 | 607 | |
|
608 | 608 | """ |
|
609 | 609 | |
|
610 | 610 | # get arguments and set sys.argv for program to be run. |
|
611 | 611 | opts, arg_lst = self.parse_options(parameter_s, |
|
612 | 612 | 'nidtN:b:pD:l:rs:T:em:G', |
|
613 | 613 | mode='list', list_all=1) |
|
614 | 614 | if "m" in opts: |
|
615 | 615 | modulename = opts["m"][0] |
|
616 | 616 | modpath = find_mod(modulename) |
|
617 | 617 | if modpath is None: |
|
618 | 618 | warn('%r is not a valid modulename on sys.path'%modulename) |
|
619 | 619 | return |
|
620 | 620 | arg_lst = [modpath] + arg_lst |
|
621 | 621 | try: |
|
622 | 622 | filename = file_finder(arg_lst[0]) |
|
623 | 623 | except IndexError: |
|
624 | 624 | warn('you must provide at least a filename.') |
|
625 | 625 | print('\n%run:\n', oinspect.getdoc(self.run)) |
|
626 | 626 | return |
|
627 | 627 | except IOError as e: |
|
628 | 628 | try: |
|
629 | 629 | msg = str(e) |
|
630 | 630 | except UnicodeError: |
|
631 | 631 | msg = e.message |
|
632 | 632 | error(msg) |
|
633 | 633 | return |
|
634 | 634 | |
|
635 | 635 | if filename.lower().endswith(('.ipy', '.ipynb')): |
|
636 | 636 | with preserve_keys(self.shell.user_ns, '__file__'): |
|
637 | 637 | self.shell.user_ns['__file__'] = filename |
|
638 | 638 | self.shell.safe_execfile_ipy(filename) |
|
639 | 639 | return |
|
640 | 640 | |
|
641 | 641 | # Control the response to exit() calls made by the script being run |
|
642 | 642 | exit_ignore = 'e' in opts |
|
643 | 643 | |
|
644 | 644 | # Make sure that the running script gets a proper sys.argv as if it |
|
645 | 645 | # were run from a system shell. |
|
646 | 646 | save_argv = sys.argv # save it for later restoring |
|
647 | 647 | |
|
648 | 648 | if 'G' in opts: |
|
649 | 649 | args = arg_lst[1:] |
|
650 | 650 | else: |
|
651 | 651 | # tilde and glob expansion |
|
652 | 652 | args = shellglob(map(os.path.expanduser, arg_lst[1:])) |
|
653 | 653 | |
|
654 | 654 | sys.argv = [filename] + args # put in the proper filename |
|
655 | 655 | # protect sys.argv from potential unicode strings on Python 2: |
|
656 | 656 | if not py3compat.PY3: |
|
657 | 657 | sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ] |
|
658 | 658 | |
|
659 | 659 | if 'i' in opts: |
|
660 | 660 | # Run in user's interactive namespace |
|
661 | 661 | prog_ns = self.shell.user_ns |
|
662 | 662 | __name__save = self.shell.user_ns['__name__'] |
|
663 | 663 | prog_ns['__name__'] = '__main__' |
|
664 | 664 | main_mod = self.shell.user_module |
|
665 | 665 | |
|
666 | 666 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
667 | 667 | # set the __file__ global in the script's namespace |
|
668 | 668 | # TK: Is this necessary in interactive mode? |
|
669 | 669 | prog_ns['__file__'] = filename |
|
670 | 670 | else: |
|
671 | 671 | # Run in a fresh, empty namespace |
|
672 | 672 | if 'n' in opts: |
|
673 | 673 | name = os.path.splitext(os.path.basename(filename))[0] |
|
674 | 674 | else: |
|
675 | 675 | name = '__main__' |
|
676 | 676 | |
|
677 | 677 | # The shell MUST hold a reference to prog_ns so after %run |
|
678 | 678 | # exits, the python deletion mechanism doesn't zero it out |
|
679 | 679 | # (leaving dangling references). See interactiveshell for details |
|
680 | 680 | main_mod = self.shell.new_main_mod(filename, name) |
|
681 | 681 | prog_ns = main_mod.__dict__ |
|
682 | 682 | |
|
683 | 683 | # pickle fix. See interactiveshell for an explanation. But we need to |
|
684 | 684 | # make sure that, if we overwrite __main__, we replace it at the end |
|
685 | 685 | main_mod_name = prog_ns['__name__'] |
|
686 | 686 | |
|
687 | 687 | if main_mod_name == '__main__': |
|
688 | 688 | restore_main = sys.modules['__main__'] |
|
689 | 689 | else: |
|
690 | 690 | restore_main = False |
|
691 | 691 | |
|
692 | 692 | # This needs to be undone at the end to prevent holding references to |
|
693 | 693 | # every single object ever created. |
|
694 | 694 | sys.modules[main_mod_name] = main_mod |
|
695 | 695 | |
|
696 | 696 | if 'p' in opts or 'd' in opts: |
|
697 | 697 | if 'm' in opts: |
|
698 | 698 | code = 'run_module(modulename, prog_ns)' |
|
699 | 699 | code_ns = { |
|
700 | 700 | 'run_module': self.shell.safe_run_module, |
|
701 | 701 | 'prog_ns': prog_ns, |
|
702 | 702 | 'modulename': modulename, |
|
703 | 703 | } |
|
704 | 704 | else: |
|
705 | 705 | if 'd' in opts: |
|
706 | 706 | # allow exceptions to raise in debug mode |
|
707 | 707 | code = 'execfile(filename, prog_ns, raise_exceptions=True)' |
|
708 | 708 | else: |
|
709 | 709 | code = 'execfile(filename, prog_ns)' |
|
710 | 710 | code_ns = { |
|
711 | 711 | 'execfile': self.shell.safe_execfile, |
|
712 | 712 | 'prog_ns': prog_ns, |
|
713 | 713 | 'filename': get_py_filename(filename), |
|
714 | 714 | } |
|
715 | 715 | |
|
716 | 716 | try: |
|
717 | 717 | stats = None |
|
718 | 718 | if 'p' in opts: |
|
719 | 719 | stats = self._run_with_profiler(code, opts, code_ns) |
|
720 | 720 | else: |
|
721 | 721 | if 'd' in opts: |
|
722 | 722 | bp_file, bp_line = parse_breakpoint( |
|
723 | 723 | opts.get('b', ['1'])[0], filename) |
|
724 | 724 | self._run_with_debugger( |
|
725 | 725 | code, code_ns, filename, bp_line, bp_file) |
|
726 | 726 | else: |
|
727 | 727 | if 'm' in opts: |
|
728 | 728 | def run(): |
|
729 | 729 | self.shell.safe_run_module(modulename, prog_ns) |
|
730 | 730 | else: |
|
731 | 731 | if runner is None: |
|
732 | 732 | runner = self.default_runner |
|
733 | 733 | if runner is None: |
|
734 | 734 | runner = self.shell.safe_execfile |
|
735 | 735 | |
|
736 | 736 | def run(): |
|
737 | 737 | runner(filename, prog_ns, prog_ns, |
|
738 | 738 | exit_ignore=exit_ignore) |
|
739 | 739 | |
|
740 | 740 | if 't' in opts: |
|
741 | 741 | # timed execution |
|
742 | 742 | try: |
|
743 | 743 | nruns = int(opts['N'][0]) |
|
744 | 744 | if nruns < 1: |
|
745 | 745 | error('Number of runs must be >=1') |
|
746 | 746 | return |
|
747 | 747 | except (KeyError): |
|
748 | 748 | nruns = 1 |
|
749 | 749 | self._run_with_timing(run, nruns) |
|
750 | 750 | else: |
|
751 | 751 | # regular execution |
|
752 | 752 | run() |
|
753 | 753 | |
|
754 | 754 | if 'i' in opts: |
|
755 | 755 | self.shell.user_ns['__name__'] = __name__save |
|
756 | 756 | else: |
|
757 | 757 | # update IPython interactive namespace |
|
758 | 758 | |
|
759 | 759 | # Some forms of read errors on the file may mean the |
|
760 | 760 | # __name__ key was never set; using pop we don't have to |
|
761 | 761 | # worry about a possible KeyError. |
|
762 | 762 | prog_ns.pop('__name__', None) |
|
763 | 763 | |
|
764 | 764 | with preserve_keys(self.shell.user_ns, '__file__'): |
|
765 | 765 | self.shell.user_ns.update(prog_ns) |
|
766 | 766 | finally: |
|
767 | 767 | # It's a bit of a mystery why, but __builtins__ can change from |
|
768 | 768 | # being a module to becoming a dict missing some key data after |
|
769 | 769 | # %run. As best I can see, this is NOT something IPython is doing |
|
770 | 770 | # at all, and similar problems have been reported before: |
|
771 | 771 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
772 | 772 | # Since this seems to be done by the interpreter itself, the best |
|
773 | 773 | # we can do is to at least restore __builtins__ for the user on |
|
774 | 774 | # exit. |
|
775 | 775 | self.shell.user_ns['__builtins__'] = builtin_mod |
|
776 | 776 | |
|
777 | 777 | # Ensure key global structures are restored |
|
778 | 778 | sys.argv = save_argv |
|
779 | 779 | if restore_main: |
|
780 | 780 | sys.modules['__main__'] = restore_main |
|
781 | 781 | else: |
|
782 | 782 | # Remove from sys.modules the reference to main_mod we'd |
|
783 | 783 | # added. Otherwise it will trap references to objects |
|
784 | 784 | # contained therein. |
|
785 | 785 | del sys.modules[main_mod_name] |
|
786 | 786 | |
|
787 | 787 | return stats |
|
788 | 788 | |
|
789 | 789 | def _run_with_debugger(self, code, code_ns, filename=None, |
|
790 | 790 | bp_line=None, bp_file=None): |
|
791 | 791 | """ |
|
792 | 792 | Run `code` in debugger with a break point. |
|
793 | 793 | |
|
794 | 794 | Parameters |
|
795 | 795 | ---------- |
|
796 | 796 | code : str |
|
797 | 797 | Code to execute. |
|
798 | 798 | code_ns : dict |
|
799 | 799 | A namespace in which `code` is executed. |
|
800 | 800 | filename : str |
|
801 | 801 | `code` is ran as if it is in `filename`. |
|
802 | 802 | bp_line : int, optional |
|
803 | 803 | Line number of the break point. |
|
804 | 804 | bp_file : str, optional |
|
805 | 805 | Path to the file in which break point is specified. |
|
806 | 806 | `filename` is used if not given. |
|
807 | 807 | |
|
808 | 808 | Raises |
|
809 | 809 | ------ |
|
810 | 810 | UsageError |
|
811 | 811 | If the break point given by `bp_line` is not valid. |
|
812 | 812 | |
|
813 | 813 | """ |
|
814 | 814 | deb = self.shell.InteractiveTB.pdb |
|
815 | 815 | if not deb: |
|
816 | 816 | self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls() |
|
817 | 817 | deb = self.shell.InteractiveTB.pdb |
|
818 | 818 | |
|
819 | 819 | # deb.checkline() fails if deb.curframe exists but is None; it can |
|
820 | 820 | # handle it not existing. https://github.com/ipython/ipython/issues/10028 |
|
821 | 821 | if hasattr(deb, 'curframe'): |
|
822 | 822 | del deb.curframe |
|
823 | 823 | |
|
824 | 824 | # reset Breakpoint state, which is moronically kept |
|
825 | 825 | # in a class |
|
826 | 826 | bdb.Breakpoint.next = 1 |
|
827 | 827 | bdb.Breakpoint.bplist = {} |
|
828 | 828 | bdb.Breakpoint.bpbynumber = [None] |
|
829 | 829 | if bp_line is not None: |
|
830 | 830 | # Set an initial breakpoint to stop execution |
|
831 | 831 | maxtries = 10 |
|
832 | 832 | bp_file = bp_file or filename |
|
833 | 833 | checkline = deb.checkline(bp_file, bp_line) |
|
834 | 834 | if not checkline: |
|
835 | 835 | for bp in range(bp_line + 1, bp_line + maxtries + 1): |
|
836 | 836 | if deb.checkline(bp_file, bp): |
|
837 | 837 | break |
|
838 | 838 | else: |
|
839 | 839 | msg = ("\nI failed to find a valid line to set " |
|
840 | 840 | "a breakpoint\n" |
|
841 | 841 | "after trying up to line: %s.\n" |
|
842 | 842 | "Please set a valid breakpoint manually " |
|
843 | 843 | "with the -b option." % bp) |
|
844 | 844 | raise UsageError(msg) |
|
845 | 845 | # if we find a good linenumber, set the breakpoint |
|
846 | 846 | deb.do_break('%s:%s' % (bp_file, bp_line)) |
|
847 | 847 | |
|
848 | 848 | if filename: |
|
849 | 849 | # Mimic Pdb._runscript(...) |
|
850 | 850 | deb._wait_for_mainpyfile = True |
|
851 | 851 | deb.mainpyfile = deb.canonic(filename) |
|
852 | 852 | |
|
853 | 853 | # Start file run |
|
854 | 854 | print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt) |
|
855 | 855 | try: |
|
856 | 856 | if filename: |
|
857 | 857 | # save filename so it can be used by methods on the deb object |
|
858 | 858 | deb._exec_filename = filename |
|
859 | 859 | while True: |
|
860 | 860 | try: |
|
861 | 861 | deb.run(code, code_ns) |
|
862 | 862 | except Restart: |
|
863 | 863 | print("Restarting") |
|
864 | 864 | if filename: |
|
865 | 865 | deb._wait_for_mainpyfile = True |
|
866 | 866 | deb.mainpyfile = deb.canonic(filename) |
|
867 | 867 | continue |
|
868 | 868 | else: |
|
869 | 869 | break |
|
870 | 870 | |
|
871 | 871 | |
|
872 | 872 | except: |
|
873 | 873 | etype, value, tb = sys.exc_info() |
|
874 | 874 | # Skip three frames in the traceback: the %run one, |
|
875 | 875 | # one inside bdb.py, and the command-line typed by the |
|
876 | 876 | # user (run by exec in pdb itself). |
|
877 | 877 | self.shell.InteractiveTB(etype, value, tb, tb_offset=3) |
|
878 | 878 | |
|
879 | 879 | @staticmethod |
|
880 | 880 | def _run_with_timing(run, nruns): |
|
881 | 881 | """ |
|
882 | 882 | Run function `run` and print timing information. |
|
883 | 883 | |
|
884 | 884 | Parameters |
|
885 | 885 | ---------- |
|
886 | 886 | run : callable |
|
887 | 887 | Any callable object which takes no argument. |
|
888 | 888 | nruns : int |
|
889 | 889 | Number of times to execute `run`. |
|
890 | 890 | |
|
891 | 891 | """ |
|
892 | 892 | twall0 = time.time() |
|
893 | 893 | if nruns == 1: |
|
894 | 894 | t0 = clock2() |
|
895 | 895 | run() |
|
896 | 896 | t1 = clock2() |
|
897 | 897 | t_usr = t1[0] - t0[0] |
|
898 | 898 | t_sys = t1[1] - t0[1] |
|
899 | 899 | print("\nIPython CPU timings (estimated):") |
|
900 | 900 | print(" User : %10.2f s." % t_usr) |
|
901 | 901 | print(" System : %10.2f s." % t_sys) |
|
902 | 902 | else: |
|
903 | 903 | runs = range(nruns) |
|
904 | 904 | t0 = clock2() |
|
905 | 905 | for nr in runs: |
|
906 | 906 | run() |
|
907 | 907 | t1 = clock2() |
|
908 | 908 | t_usr = t1[0] - t0[0] |
|
909 | 909 | t_sys = t1[1] - t0[1] |
|
910 | 910 | print("\nIPython CPU timings (estimated):") |
|
911 | 911 | print("Total runs performed:", nruns) |
|
912 | 912 | print(" Times : %10s %10s" % ('Total', 'Per run')) |
|
913 | 913 | print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)) |
|
914 | 914 | print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)) |
|
915 | 915 | twall1 = time.time() |
|
916 | 916 | print("Wall time: %10.2f s." % (twall1 - twall0)) |
|
917 | 917 | |
|
918 | 918 | @skip_doctest |
|
919 | 919 | @line_cell_magic |
|
920 | 920 | def timeit(self, line='', cell=None): |
|
921 | 921 | """Time execution of a Python statement or expression |
|
922 | 922 | |
|
923 | 923 | Usage, in line mode: |
|
924 | 924 | %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement |
|
925 | 925 | or in cell mode: |
|
926 | 926 | %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code |
|
927 | 927 | code |
|
928 | 928 | code... |
|
929 | 929 | |
|
930 | 930 | Time execution of a Python statement or expression using the timeit |
|
931 | 931 | module. This function can be used both as a line and cell magic: |
|
932 | 932 | |
|
933 | 933 | - In line mode you can time a single-line statement (though multiple |
|
934 | 934 | ones can be chained with using semicolons). |
|
935 | 935 | |
|
936 | 936 | - In cell mode, the statement in the first line is used as setup code |
|
937 | 937 | (executed but not timed) and the body of the cell is timed. The cell |
|
938 | 938 | body has access to any variables created in the setup code. |
|
939 | 939 | |
|
940 | 940 | Options: |
|
941 | 941 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
942 | 942 | is not given, a fitting value is chosen. |
|
943 | 943 | |
|
944 | 944 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
945 | 945 | Default: 3 |
|
946 | 946 | |
|
947 | 947 | -t: use time.time to measure the time, which is the default on Unix. |
|
948 | 948 | This function measures wall time. |
|
949 | 949 | |
|
950 | 950 | -c: use time.clock to measure the time, which is the default on |
|
951 | 951 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
952 | 952 | instead and returns the CPU user time. |
|
953 | 953 | |
|
954 | 954 | -p<P>: use a precision of <P> digits to display the timing result. |
|
955 | 955 | Default: 3 |
|
956 | 956 | |
|
957 | 957 | -q: Quiet, do not print result. |
|
958 | 958 | |
|
959 | 959 | -o: return a TimeitResult that can be stored in a variable to inspect |
|
960 | 960 | the result in more details. |
|
961 | 961 | |
|
962 | 962 | |
|
963 | 963 | Examples |
|
964 | 964 | -------- |
|
965 | 965 | :: |
|
966 | 966 | |
|
967 | 967 | In [1]: %timeit pass |
|
968 | 968 | 100000000 loops, average of 7: 5.48 ns +- 0.354 ns per loop (using standard deviation) |
|
969 | 969 | |
|
970 | 970 | In [2]: u = None |
|
971 | 971 | |
|
972 | 972 | In [3]: %timeit u is None |
|
973 | 973 | 10000000 loops, average of 7: 22.7 ns +- 2.33 ns per loop (using standard deviation) |
|
974 | 974 | |
|
975 | 975 | In [4]: %timeit -r 4 u == None |
|
976 | 976 | 10000000 loops, average of 4: 27.5 ns +- 2.91 ns per loop (using standard deviation) |
|
977 | 977 | |
|
978 | 978 | In [5]: import time |
|
979 | 979 | |
|
980 | 980 | In [6]: %timeit -n1 time.sleep(2) |
|
981 | 981 | 1 loop, average of 7: 2 s +- 4.71 Β΅s per loop (using standard deviation) |
|
982 | 982 | |
|
983 | 983 | |
|
984 | 984 | The times reported by %timeit will be slightly higher than those |
|
985 | 985 | reported by the timeit.py script when variables are accessed. This is |
|
986 | 986 | due to the fact that %timeit executes the statement in the namespace |
|
987 | 987 | of the shell, compared with timeit.py, which uses a single setup |
|
988 | 988 | statement to import function or create variables. Generally, the bias |
|
989 | 989 | does not matter as long as results from timeit.py are not mixed with |
|
990 | 990 | those from %timeit.""" |
|
991 | 991 | |
|
992 | 992 | opts, stmt = self.parse_options(line,'n:r:tcp:qo', |
|
993 | 993 | posix=False, strict=False) |
|
994 | 994 | if stmt == "" and cell is None: |
|
995 | 995 | return |
|
996 | 996 | |
|
997 | 997 | timefunc = timeit.default_timer |
|
998 | 998 | number = int(getattr(opts, "n", 0)) |
|
999 | 999 | default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat |
|
1000 | 1000 | repeat = int(getattr(opts, "r", default_repeat)) |
|
1001 | 1001 | precision = int(getattr(opts, "p", 3)) |
|
1002 | 1002 | quiet = 'q' in opts |
|
1003 | 1003 | return_result = 'o' in opts |
|
1004 | 1004 | if hasattr(opts, "t"): |
|
1005 | 1005 | timefunc = time.time |
|
1006 | 1006 | if hasattr(opts, "c"): |
|
1007 | 1007 | timefunc = clock |
|
1008 | 1008 | |
|
1009 | 1009 | timer = Timer(timer=timefunc) |
|
1010 | 1010 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1011 | 1011 | # but is there a better way to achieve that the code stmt has access |
|
1012 | 1012 | # to the shell namespace? |
|
1013 | 1013 | transform = self.shell.input_splitter.transform_cell |
|
1014 | 1014 | |
|
1015 | 1015 | if cell is None: |
|
1016 | 1016 | # called as line magic |
|
1017 | 1017 | ast_setup = self.shell.compile.ast_parse("pass") |
|
1018 | 1018 | ast_stmt = self.shell.compile.ast_parse(transform(stmt)) |
|
1019 | 1019 | else: |
|
1020 | 1020 | ast_setup = self.shell.compile.ast_parse(transform(stmt)) |
|
1021 | 1021 | ast_stmt = self.shell.compile.ast_parse(transform(cell)) |
|
1022 | 1022 | |
|
1023 | 1023 | ast_setup = self.shell.transform_ast(ast_setup) |
|
1024 | 1024 | ast_stmt = self.shell.transform_ast(ast_stmt) |
|
1025 | 1025 | |
|
1026 | 1026 | # This codestring is taken from timeit.template - we fill it in as an |
|
1027 | 1027 | # AST, so that we can apply our AST transformations to the user code |
|
1028 | 1028 | # without affecting the timing code. |
|
1029 | 1029 | timeit_ast_template = ast.parse('def inner(_it, _timer):\n' |
|
1030 | 1030 | ' setup\n' |
|
1031 | 1031 | ' _t0 = _timer()\n' |
|
1032 | 1032 | ' for _i in _it:\n' |
|
1033 | 1033 | ' stmt\n' |
|
1034 | 1034 | ' _t1 = _timer()\n' |
|
1035 | 1035 | ' return _t1 - _t0\n') |
|
1036 | 1036 | |
|
1037 | 1037 | timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template) |
|
1038 | 1038 | timeit_ast = ast.fix_missing_locations(timeit_ast) |
|
1039 | 1039 | |
|
1040 | 1040 | # Track compilation time so it can be reported if too long |
|
1041 | 1041 | # Minimum time above which compilation time will be reported |
|
1042 | 1042 | tc_min = 0.1 |
|
1043 | 1043 | |
|
1044 | 1044 | t0 = clock() |
|
1045 | 1045 | code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec") |
|
1046 | 1046 | tc = clock()-t0 |
|
1047 | 1047 | |
|
1048 | 1048 | ns = {} |
|
1049 | 1049 | exec(code, self.shell.user_ns, ns) |
|
1050 | 1050 | timer.inner = ns["inner"] |
|
1051 | 1051 | |
|
1052 | 1052 | # This is used to check if there is a huge difference between the |
|
1053 | 1053 | # best and worst timings. |
|
1054 | 1054 | # Issue: https://github.com/ipython/ipython/issues/6471 |
|
1055 | 1055 | if number == 0: |
|
1056 | 1056 | # determine number so that 0.2 <= total time < 2.0 |
|
1057 | 1057 | for index in range(0, 10): |
|
1058 | 1058 | number = 10 ** index |
|
1059 | 1059 | time_number = timer.timeit(number) |
|
1060 | 1060 | if time_number >= 0.2: |
|
1061 | 1061 | break |
|
1062 | 1062 | |
|
1063 | 1063 | all_runs = timer.repeat(repeat, number) |
|
1064 | 1064 | best = min(all_runs) / number |
|
1065 | 1065 | worst = max(all_runs) / number |
|
1066 | 1066 | timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision) |
|
1067 | 1067 | |
|
1068 | 1068 | if not quiet : |
|
1069 | 1069 | # Check best timing is greater than zero to avoid a |
|
1070 | 1070 | # ZeroDivisionError. |
|
1071 | 1071 | # In cases where the slowest timing is lesser than a micosecond |
|
1072 | 1072 | # we assume that it does not really matter if the fastest |
|
1073 | 1073 | # timing is 4 times faster than the slowest timing or not. |
|
1074 | 1074 | if worst > 4 * best and best > 0 and worst > 1e-6: |
|
1075 | 1075 | print("The slowest run took %0.2f times longer than the " |
|
1076 | 1076 | "fastest. This could mean that an intermediate result " |
|
1077 | 1077 | "is being cached." % (worst / best)) |
|
1078 | 1078 | |
|
1079 | 1079 | print( timeit_result ) |
|
1080 | 1080 | |
|
1081 | 1081 | if tc > tc_min: |
|
1082 | 1082 | print("Compiler time: %.2f s" % tc) |
|
1083 | 1083 | if return_result: |
|
1084 | 1084 | return timeit_result |
|
1085 | 1085 | |
|
1086 | 1086 | @skip_doctest |
|
1087 | 1087 | @needs_local_scope |
|
1088 | 1088 | @line_cell_magic |
|
1089 | 1089 | def time(self,line='', cell=None, local_ns=None): |
|
1090 | 1090 | """Time execution of a Python statement or expression. |
|
1091 | 1091 | |
|
1092 | 1092 | The CPU and wall clock times are printed, and the value of the |
|
1093 | 1093 | expression (if any) is returned. Note that under Win32, system time |
|
1094 | 1094 | is always reported as 0, since it can not be measured. |
|
1095 | 1095 | |
|
1096 | 1096 | This function can be used both as a line and cell magic: |
|
1097 | 1097 | |
|
1098 | 1098 | - In line mode you can time a single-line statement (though multiple |
|
1099 | 1099 | ones can be chained with using semicolons). |
|
1100 | 1100 | |
|
1101 | 1101 | - In cell mode, you can time the cell body (a directly |
|
1102 | 1102 | following statement raises an error). |
|
1103 | 1103 | |
|
1104 | 1104 | This function provides very basic timing functionality. Use the timeit |
|
1105 | 1105 | magic for more control over the measurement. |
|
1106 | 1106 | |
|
1107 | 1107 | Examples |
|
1108 | 1108 | -------- |
|
1109 | 1109 | :: |
|
1110 | 1110 | |
|
1111 | 1111 | In [1]: %time 2**128 |
|
1112 | 1112 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1113 | 1113 | Wall time: 0.00 |
|
1114 | 1114 | Out[1]: 340282366920938463463374607431768211456L |
|
1115 | 1115 | |
|
1116 | 1116 | In [2]: n = 1000000 |
|
1117 | 1117 | |
|
1118 | 1118 | In [3]: %time sum(range(n)) |
|
1119 | 1119 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1120 | 1120 | Wall time: 1.37 |
|
1121 | 1121 | Out[3]: 499999500000L |
|
1122 | 1122 | |
|
1123 | 1123 | In [4]: %time print 'hello world' |
|
1124 | 1124 | hello world |
|
1125 | 1125 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1126 | 1126 | Wall time: 0.00 |
|
1127 | 1127 | |
|
1128 | 1128 | Note that the time needed by Python to compile the given expression |
|
1129 | 1129 | will be reported if it is more than 0.1s. In this example, the |
|
1130 | 1130 | actual exponentiation is done by Python at compilation time, so while |
|
1131 | 1131 | the expression can take a noticeable amount of time to compute, that |
|
1132 | 1132 | time is purely due to the compilation: |
|
1133 | 1133 | |
|
1134 | 1134 | In [5]: %time 3**9999; |
|
1135 | 1135 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1136 | 1136 | Wall time: 0.00 s |
|
1137 | 1137 | |
|
1138 | 1138 | In [6]: %time 3**999999; |
|
1139 | 1139 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1140 | 1140 | Wall time: 0.00 s |
|
1141 | 1141 | Compiler : 0.78 s |
|
1142 | 1142 | """ |
|
1143 | 1143 | |
|
1144 | 1144 | # fail immediately if the given expression can't be compiled |
|
1145 | 1145 | |
|
1146 | 1146 | if line and cell: |
|
1147 | 1147 | raise UsageError("Can't use statement directly after '%%time'!") |
|
1148 | 1148 | |
|
1149 | 1149 | if cell: |
|
1150 | 1150 | expr = self.shell.input_transformer_manager.transform_cell(cell) |
|
1151 | 1151 | else: |
|
1152 | 1152 | expr = self.shell.input_transformer_manager.transform_cell(line) |
|
1153 | 1153 | |
|
1154 | 1154 | # Minimum time above which parse time will be reported |
|
1155 | 1155 | tp_min = 0.1 |
|
1156 | 1156 | |
|
1157 | 1157 | t0 = clock() |
|
1158 | 1158 | expr_ast = self.shell.compile.ast_parse(expr) |
|
1159 | 1159 | tp = clock()-t0 |
|
1160 | 1160 | |
|
1161 | 1161 | # Apply AST transformations |
|
1162 | 1162 | expr_ast = self.shell.transform_ast(expr_ast) |
|
1163 | 1163 | |
|
1164 | 1164 | # Minimum time above which compilation time will be reported |
|
1165 | 1165 | tc_min = 0.1 |
|
1166 | 1166 | |
|
1167 | 1167 | if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr): |
|
1168 | 1168 | mode = 'eval' |
|
1169 | 1169 | source = '<timed eval>' |
|
1170 | 1170 | expr_ast = ast.Expression(expr_ast.body[0].value) |
|
1171 | 1171 | else: |
|
1172 | 1172 | mode = 'exec' |
|
1173 | 1173 | source = '<timed exec>' |
|
1174 | 1174 | t0 = clock() |
|
1175 | 1175 | code = self.shell.compile(expr_ast, source, mode) |
|
1176 | 1176 | tc = clock()-t0 |
|
1177 | 1177 | |
|
1178 | 1178 | # skew measurement as little as possible |
|
1179 | 1179 | glob = self.shell.user_ns |
|
1180 | 1180 | wtime = time.time |
|
1181 | 1181 | # time execution |
|
1182 | 1182 | wall_st = wtime() |
|
1183 | 1183 | if mode=='eval': |
|
1184 | 1184 | st = clock2() |
|
1185 | 1185 | out = eval(code, glob, local_ns) |
|
1186 | 1186 | end = clock2() |
|
1187 | 1187 | else: |
|
1188 | 1188 | st = clock2() |
|
1189 | 1189 | exec(code, glob, local_ns) |
|
1190 | 1190 | end = clock2() |
|
1191 | 1191 | out = None |
|
1192 | 1192 | wall_end = wtime() |
|
1193 | 1193 | # Compute actual times and report |
|
1194 | 1194 | wall_time = wall_end-wall_st |
|
1195 | 1195 | cpu_user = end[0]-st[0] |
|
1196 | 1196 | cpu_sys = end[1]-st[1] |
|
1197 | 1197 | cpu_tot = cpu_user+cpu_sys |
|
1198 | 1198 | # On windows cpu_sys is always zero, so no new information to the next print |
|
1199 | 1199 | if sys.platform != 'win32': |
|
1200 | 1200 | print("CPU times: user %s, sys: %s, total: %s" % \ |
|
1201 | 1201 | (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot))) |
|
1202 | 1202 | print("Wall time: %s" % _format_time(wall_time)) |
|
1203 | 1203 | if tc > tc_min: |
|
1204 | 1204 | print("Compiler : %s" % _format_time(tc)) |
|
1205 | 1205 | if tp > tp_min: |
|
1206 | 1206 | print("Parser : %s" % _format_time(tp)) |
|
1207 | 1207 | return out |
|
1208 | 1208 | |
|
1209 | 1209 | @skip_doctest |
|
1210 | 1210 | @line_magic |
|
1211 | 1211 | def macro(self, parameter_s=''): |
|
1212 | 1212 | """Define a macro for future re-execution. It accepts ranges of history, |
|
1213 | 1213 | filenames or string objects. |
|
1214 | 1214 | |
|
1215 | 1215 | Usage:\\ |
|
1216 | 1216 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1217 | 1217 | |
|
1218 | 1218 | Options: |
|
1219 | 1219 | |
|
1220 | 1220 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1221 | 1221 | so that magics are loaded in their transformed version to valid |
|
1222 | 1222 | Python. If this option is given, the raw input as typed at the |
|
1223 | 1223 | command line is used instead. |
|
1224 | 1224 | |
|
1225 | 1225 | -q: quiet macro definition. By default, a tag line is printed |
|
1226 | 1226 | to indicate the macro has been created, and then the contents of |
|
1227 | 1227 | the macro are printed. If this option is given, then no printout |
|
1228 | 1228 | is produced once the macro is created. |
|
1229 | 1229 | |
|
1230 | 1230 | This will define a global variable called `name` which is a string |
|
1231 | 1231 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1232 | 1232 | above) from your input history into a single string. This variable |
|
1233 | 1233 | acts like an automatic function which re-executes those lines as if |
|
1234 | 1234 | you had typed them. You just type 'name' at the prompt and the code |
|
1235 | 1235 | executes. |
|
1236 | 1236 | |
|
1237 | 1237 | The syntax for indicating input ranges is described in %history. |
|
1238 | 1238 | |
|
1239 | 1239 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1240 | 1240 | notation, where N:M means numbers N through M-1. |
|
1241 | 1241 | |
|
1242 | 1242 | For example, if your history contains (print using %hist -n ):: |
|
1243 | 1243 | |
|
1244 | 1244 | 44: x=1 |
|
1245 | 1245 | 45: y=3 |
|
1246 | 1246 | 46: z=x+y |
|
1247 | 1247 | 47: print x |
|
1248 | 1248 | 48: a=5 |
|
1249 | 1249 | 49: print 'x',x,'y',y |
|
1250 | 1250 | |
|
1251 | 1251 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1252 | 1252 | called my_macro with:: |
|
1253 | 1253 | |
|
1254 | 1254 | In [55]: %macro my_macro 44-47 49 |
|
1255 | 1255 | |
|
1256 | 1256 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1257 | 1257 | in one pass. |
|
1258 | 1258 | |
|
1259 | 1259 | You don't need to give the line-numbers in order, and any given line |
|
1260 | 1260 | number can appear multiple times. You can assemble macros with any |
|
1261 | 1261 | lines from your input history in any order. |
|
1262 | 1262 | |
|
1263 | 1263 | The macro is a simple object which holds its value in an attribute, |
|
1264 | 1264 | but IPython's display system checks for macros and executes them as |
|
1265 | 1265 | code instead of printing them when you type their name. |
|
1266 | 1266 | |
|
1267 | 1267 | You can view a macro's contents by explicitly printing it with:: |
|
1268 | 1268 | |
|
1269 | 1269 | print macro_name |
|
1270 | 1270 | |
|
1271 | 1271 | """ |
|
1272 | 1272 | opts,args = self.parse_options(parameter_s,'rq',mode='list') |
|
1273 | 1273 | if not args: # List existing macros |
|
1274 |
return sorted(k for k,v in |
|
|
1275 | isinstance(v, Macro)) | |
|
1274 | return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)) | |
|
1276 | 1275 | if len(args) == 1: |
|
1277 | 1276 | raise UsageError( |
|
1278 | 1277 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
1279 | 1278 | name, codefrom = args[0], " ".join(args[1:]) |
|
1280 | 1279 | |
|
1281 | 1280 | #print 'rng',ranges # dbg |
|
1282 | 1281 | try: |
|
1283 | 1282 | lines = self.shell.find_user_code(codefrom, 'r' in opts) |
|
1284 | 1283 | except (ValueError, TypeError) as e: |
|
1285 | 1284 | print(e.args[0]) |
|
1286 | 1285 | return |
|
1287 | 1286 | macro = Macro(lines) |
|
1288 | 1287 | self.shell.define_macro(name, macro) |
|
1289 | 1288 | if not ( 'q' in opts) : |
|
1290 | 1289 | print('Macro `%s` created. To execute, type its name (without quotes).' % name) |
|
1291 | 1290 | print('=== Macro contents: ===') |
|
1292 | 1291 | print(macro, end=' ') |
|
1293 | 1292 | |
|
1294 | 1293 | @magic_arguments.magic_arguments() |
|
1295 | 1294 | @magic_arguments.argument('output', type=str, default='', nargs='?', |
|
1296 | 1295 | help="""The name of the variable in which to store output. |
|
1297 | 1296 | This is a utils.io.CapturedIO object with stdout/err attributes |
|
1298 | 1297 | for the text of the captured output. |
|
1299 | 1298 | |
|
1300 | 1299 | CapturedOutput also has a show() method for displaying the output, |
|
1301 | 1300 | and __call__ as well, so you can use that to quickly display the |
|
1302 | 1301 | output. |
|
1303 | 1302 | |
|
1304 | 1303 | If unspecified, captured output is discarded. |
|
1305 | 1304 | """ |
|
1306 | 1305 | ) |
|
1307 | 1306 | @magic_arguments.argument('--no-stderr', action="store_true", |
|
1308 | 1307 | help="""Don't capture stderr.""" |
|
1309 | 1308 | ) |
|
1310 | 1309 | @magic_arguments.argument('--no-stdout', action="store_true", |
|
1311 | 1310 | help="""Don't capture stdout.""" |
|
1312 | 1311 | ) |
|
1313 | 1312 | @magic_arguments.argument('--no-display', action="store_true", |
|
1314 | 1313 | help="""Don't capture IPython's rich display.""" |
|
1315 | 1314 | ) |
|
1316 | 1315 | @cell_magic |
|
1317 | 1316 | def capture(self, line, cell): |
|
1318 | 1317 | """run the cell, capturing stdout, stderr, and IPython's rich display() calls.""" |
|
1319 | 1318 | args = magic_arguments.parse_argstring(self.capture, line) |
|
1320 | 1319 | out = not args.no_stdout |
|
1321 | 1320 | err = not args.no_stderr |
|
1322 | 1321 | disp = not args.no_display |
|
1323 | 1322 | with capture_output(out, err, disp) as io: |
|
1324 | 1323 | self.shell.run_cell(cell) |
|
1325 | 1324 | if args.output: |
|
1326 | 1325 | self.shell.user_ns[args.output] = io |
|
1327 | 1326 | |
|
1328 | 1327 | def parse_breakpoint(text, current_file): |
|
1329 | 1328 | '''Returns (file, line) for file:line and (current_file, line) for line''' |
|
1330 | 1329 | colon = text.find(':') |
|
1331 | 1330 | if colon == -1: |
|
1332 | 1331 | return current_file, int(text) |
|
1333 | 1332 | else: |
|
1334 | 1333 | return text[:colon], int(text[colon+1:]) |
|
1335 | 1334 | |
|
1336 | 1335 | def _format_time(timespan, precision=3): |
|
1337 | 1336 | """Formats the timespan in a human readable form""" |
|
1338 | 1337 | |
|
1339 | 1338 | if timespan >= 60.0: |
|
1340 | 1339 | # we have more than a minute, format that in a human readable form |
|
1341 | 1340 | # Idea from http://snipplr.com/view/5713/ |
|
1342 | 1341 | parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)] |
|
1343 | 1342 | time = [] |
|
1344 | 1343 | leftover = timespan |
|
1345 | 1344 | for suffix, length in parts: |
|
1346 | 1345 | value = int(leftover / length) |
|
1347 | 1346 | if value > 0: |
|
1348 | 1347 | leftover = leftover % length |
|
1349 | 1348 | time.append(u'%s%s' % (str(value), suffix)) |
|
1350 | 1349 | if leftover < 1: |
|
1351 | 1350 | break |
|
1352 | 1351 | return " ".join(time) |
|
1353 | 1352 | |
|
1354 | 1353 | |
|
1355 | 1354 | # Unfortunately the unicode 'micro' symbol can cause problems in |
|
1356 | 1355 | # certain terminals. |
|
1357 | 1356 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1358 | 1357 | # Try to prevent crashes by being more secure than it needs to |
|
1359 | 1358 | # E.g. eclipse is able to print a Β΅, but has no sys.stdout.encoding set. |
|
1360 | 1359 | units = [u"s", u"ms",u'us',"ns"] # the save value |
|
1361 | 1360 | if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding: |
|
1362 | 1361 | try: |
|
1363 | 1362 | u'\xb5'.encode(sys.stdout.encoding) |
|
1364 | 1363 | units = [u"s", u"ms",u'\xb5s',"ns"] |
|
1365 | 1364 | except: |
|
1366 | 1365 | pass |
|
1367 | 1366 | scaling = [1, 1e3, 1e6, 1e9] |
|
1368 | 1367 | |
|
1369 | 1368 | if timespan > 0.0: |
|
1370 | 1369 | order = min(-int(math.floor(math.log10(timespan)) // 3), 3) |
|
1371 | 1370 | else: |
|
1372 | 1371 | order = 3 |
|
1373 | 1372 | return u"%.*g %s" % (precision, timespan * scaling[order], units[order]) |
@@ -1,867 +1,866 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | Python advanced pretty printer. This pretty printer is intended to |
|
4 | 4 | replace the old `pprint` python module which does not allow developers |
|
5 | 5 | to provide their own pretty print callbacks. |
|
6 | 6 | |
|
7 | 7 | This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`. |
|
8 | 8 | |
|
9 | 9 | |
|
10 | 10 | Example Usage |
|
11 | 11 | ------------- |
|
12 | 12 | |
|
13 | 13 | To directly print the representation of an object use `pprint`:: |
|
14 | 14 | |
|
15 | 15 | from pretty import pprint |
|
16 | 16 | pprint(complex_object) |
|
17 | 17 | |
|
18 | 18 | To get a string of the output use `pretty`:: |
|
19 | 19 | |
|
20 | 20 | from pretty import pretty |
|
21 | 21 | string = pretty(complex_object) |
|
22 | 22 | |
|
23 | 23 | |
|
24 | 24 | Extending |
|
25 | 25 | --------- |
|
26 | 26 | |
|
27 | 27 | The pretty library allows developers to add pretty printing rules for their |
|
28 | 28 | own objects. This process is straightforward. All you have to do is to |
|
29 | 29 | add a `_repr_pretty_` method to your object and call the methods on the |
|
30 | 30 | pretty printer passed:: |
|
31 | 31 | |
|
32 | 32 | class MyObject(object): |
|
33 | 33 | |
|
34 | 34 | def _repr_pretty_(self, p, cycle): |
|
35 | 35 | ... |
|
36 | 36 | |
|
37 | 37 | Here is an example implementation of a `_repr_pretty_` method for a list |
|
38 | 38 | subclass:: |
|
39 | 39 | |
|
40 | 40 | class MyList(list): |
|
41 | 41 | |
|
42 | 42 | def _repr_pretty_(self, p, cycle): |
|
43 | 43 | if cycle: |
|
44 | 44 | p.text('MyList(...)') |
|
45 | 45 | else: |
|
46 | 46 | with p.group(8, 'MyList([', '])'): |
|
47 | 47 | for idx, item in enumerate(self): |
|
48 | 48 | if idx: |
|
49 | 49 | p.text(',') |
|
50 | 50 | p.breakable() |
|
51 | 51 | p.pretty(item) |
|
52 | 52 | |
|
53 | 53 | The `cycle` parameter is `True` if pretty detected a cycle. You *have* to |
|
54 | 54 | react to that or the result is an infinite loop. `p.text()` just adds |
|
55 | 55 | non breaking text to the output, `p.breakable()` either adds a whitespace |
|
56 | 56 | or breaks here. If you pass it an argument it's used instead of the |
|
57 | 57 | default space. `p.pretty` prettyprints another object using the pretty print |
|
58 | 58 | method. |
|
59 | 59 | |
|
60 | 60 | The first parameter to the `group` function specifies the extra indentation |
|
61 | 61 | of the next line. In this example the next item will either be on the same |
|
62 | 62 | line (if the items are short enough) or aligned with the right edge of the |
|
63 | 63 | opening bracket of `MyList`. |
|
64 | 64 | |
|
65 | 65 | If you just want to indent something you can use the group function |
|
66 | 66 | without open / close parameters. You can also use this code:: |
|
67 | 67 | |
|
68 | 68 | with p.indent(2): |
|
69 | 69 | ... |
|
70 | 70 | |
|
71 | 71 | Inheritance diagram: |
|
72 | 72 | |
|
73 | 73 | .. inheritance-diagram:: IPython.lib.pretty |
|
74 | 74 | :parts: 3 |
|
75 | 75 | |
|
76 | 76 | :copyright: 2007 by Armin Ronacher. |
|
77 | 77 | Portions (c) 2009 by Robert Kern. |
|
78 | 78 | :license: BSD License. |
|
79 | 79 | """ |
|
80 | 80 | from contextlib import contextmanager |
|
81 | 81 | import sys |
|
82 | 82 | import types |
|
83 | 83 | import re |
|
84 | 84 | import datetime |
|
85 | 85 | from collections import deque |
|
86 | 86 | |
|
87 | 87 | from IPython.utils.py3compat import PY3, PYPY, cast_unicode, string_types |
|
88 | 88 | from IPython.utils.encoding import get_stream_enc |
|
89 | 89 | |
|
90 | 90 | from io import StringIO |
|
91 | 91 | |
|
92 | 92 | |
|
93 | 93 | __all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter', |
|
94 | 94 | 'for_type', 'for_type_by_name'] |
|
95 | 95 | |
|
96 | 96 | |
|
97 | 97 | MAX_SEQ_LENGTH = 1000 |
|
98 | 98 | _re_pattern_type = type(re.compile('')) |
|
99 | 99 | |
|
100 | 100 | def _safe_getattr(obj, attr, default=None): |
|
101 | 101 | """Safe version of getattr. |
|
102 | 102 | |
|
103 | 103 | Same as getattr, but will return ``default`` on any Exception, |
|
104 | 104 | rather than raising. |
|
105 | 105 | """ |
|
106 | 106 | try: |
|
107 | 107 | return getattr(obj, attr, default) |
|
108 | 108 | except Exception: |
|
109 | 109 | return default |
|
110 | 110 | |
|
111 | 111 | if PY3: |
|
112 | 112 | CUnicodeIO = StringIO |
|
113 | 113 | else: |
|
114 | 114 | class CUnicodeIO(StringIO): |
|
115 | 115 | """StringIO that casts str to unicode on Python 2""" |
|
116 | 116 | def write(self, text): |
|
117 | 117 | return super(CUnicodeIO, self).write( |
|
118 | 118 | cast_unicode(text, encoding=get_stream_enc(sys.stdout))) |
|
119 | 119 | |
|
120 | 120 | |
|
121 | 121 | def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH): |
|
122 | 122 | """ |
|
123 | 123 | Pretty print the object's representation. |
|
124 | 124 | """ |
|
125 | 125 | stream = CUnicodeIO() |
|
126 | 126 | printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length) |
|
127 | 127 | printer.pretty(obj) |
|
128 | 128 | printer.flush() |
|
129 | 129 | return stream.getvalue() |
|
130 | 130 | |
|
131 | 131 | |
|
132 | 132 | def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH): |
|
133 | 133 | """ |
|
134 | 134 | Like `pretty` but print to stdout. |
|
135 | 135 | """ |
|
136 | 136 | printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length) |
|
137 | 137 | printer.pretty(obj) |
|
138 | 138 | printer.flush() |
|
139 | 139 | sys.stdout.write(newline) |
|
140 | 140 | sys.stdout.flush() |
|
141 | 141 | |
|
142 | 142 | class _PrettyPrinterBase(object): |
|
143 | 143 | |
|
144 | 144 | @contextmanager |
|
145 | 145 | def indent(self, indent): |
|
146 | 146 | """with statement support for indenting/dedenting.""" |
|
147 | 147 | self.indentation += indent |
|
148 | 148 | try: |
|
149 | 149 | yield |
|
150 | 150 | finally: |
|
151 | 151 | self.indentation -= indent |
|
152 | 152 | |
|
153 | 153 | @contextmanager |
|
154 | 154 | def group(self, indent=0, open='', close=''): |
|
155 | 155 | """like begin_group / end_group but for the with statement.""" |
|
156 | 156 | self.begin_group(indent, open) |
|
157 | 157 | try: |
|
158 | 158 | yield |
|
159 | 159 | finally: |
|
160 | 160 | self.end_group(indent, close) |
|
161 | 161 | |
|
162 | 162 | class PrettyPrinter(_PrettyPrinterBase): |
|
163 | 163 | """ |
|
164 | 164 | Baseclass for the `RepresentationPrinter` prettyprinter that is used to |
|
165 | 165 | generate pretty reprs of objects. Contrary to the `RepresentationPrinter` |
|
166 | 166 | this printer knows nothing about the default pprinters or the `_repr_pretty_` |
|
167 | 167 | callback method. |
|
168 | 168 | """ |
|
169 | 169 | |
|
170 | 170 | def __init__(self, output, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH): |
|
171 | 171 | self.output = output |
|
172 | 172 | self.max_width = max_width |
|
173 | 173 | self.newline = newline |
|
174 | 174 | self.max_seq_length = max_seq_length |
|
175 | 175 | self.output_width = 0 |
|
176 | 176 | self.buffer_width = 0 |
|
177 | 177 | self.buffer = deque() |
|
178 | 178 | |
|
179 | 179 | root_group = Group(0) |
|
180 | 180 | self.group_stack = [root_group] |
|
181 | 181 | self.group_queue = GroupQueue(root_group) |
|
182 | 182 | self.indentation = 0 |
|
183 | 183 | |
|
184 | 184 | def _break_outer_groups(self): |
|
185 | 185 | while self.max_width < self.output_width + self.buffer_width: |
|
186 | 186 | group = self.group_queue.deq() |
|
187 | 187 | if not group: |
|
188 | 188 | return |
|
189 | 189 | while group.breakables: |
|
190 | 190 | x = self.buffer.popleft() |
|
191 | 191 | self.output_width = x.output(self.output, self.output_width) |
|
192 | 192 | self.buffer_width -= x.width |
|
193 | 193 | while self.buffer and isinstance(self.buffer[0], Text): |
|
194 | 194 | x = self.buffer.popleft() |
|
195 | 195 | self.output_width = x.output(self.output, self.output_width) |
|
196 | 196 | self.buffer_width -= x.width |
|
197 | 197 | |
|
198 | 198 | def text(self, obj): |
|
199 | 199 | """Add literal text to the output.""" |
|
200 | 200 | width = len(obj) |
|
201 | 201 | if self.buffer: |
|
202 | 202 | text = self.buffer[-1] |
|
203 | 203 | if not isinstance(text, Text): |
|
204 | 204 | text = Text() |
|
205 | 205 | self.buffer.append(text) |
|
206 | 206 | text.add(obj, width) |
|
207 | 207 | self.buffer_width += width |
|
208 | 208 | self._break_outer_groups() |
|
209 | 209 | else: |
|
210 | 210 | self.output.write(obj) |
|
211 | 211 | self.output_width += width |
|
212 | 212 | |
|
213 | 213 | def breakable(self, sep=' '): |
|
214 | 214 | """ |
|
215 | 215 | Add a breakable separator to the output. This does not mean that it |
|
216 | 216 | will automatically break here. If no breaking on this position takes |
|
217 | 217 | place the `sep` is inserted which default to one space. |
|
218 | 218 | """ |
|
219 | 219 | width = len(sep) |
|
220 | 220 | group = self.group_stack[-1] |
|
221 | 221 | if group.want_break: |
|
222 | 222 | self.flush() |
|
223 | 223 | self.output.write(self.newline) |
|
224 | 224 | self.output.write(' ' * self.indentation) |
|
225 | 225 | self.output_width = self.indentation |
|
226 | 226 | self.buffer_width = 0 |
|
227 | 227 | else: |
|
228 | 228 | self.buffer.append(Breakable(sep, width, self)) |
|
229 | 229 | self.buffer_width += width |
|
230 | 230 | self._break_outer_groups() |
|
231 | 231 | |
|
232 | 232 | def break_(self): |
|
233 | 233 | """ |
|
234 | 234 | Explicitly insert a newline into the output, maintaining correct indentation. |
|
235 | 235 | """ |
|
236 | 236 | self.flush() |
|
237 | 237 | self.output.write(self.newline) |
|
238 | 238 | self.output.write(' ' * self.indentation) |
|
239 | 239 | self.output_width = self.indentation |
|
240 | 240 | self.buffer_width = 0 |
|
241 | 241 | |
|
242 | 242 | |
|
243 | 243 | def begin_group(self, indent=0, open=''): |
|
244 | 244 | """ |
|
245 | 245 | Begin a group. If you want support for python < 2.5 which doesn't has |
|
246 | 246 | the with statement this is the preferred way: |
|
247 | 247 | |
|
248 | 248 | p.begin_group(1, '{') |
|
249 | 249 | ... |
|
250 | 250 | p.end_group(1, '}') |
|
251 | 251 | |
|
252 | 252 | The python 2.5 expression would be this: |
|
253 | 253 | |
|
254 | 254 | with p.group(1, '{', '}'): |
|
255 | 255 | ... |
|
256 | 256 | |
|
257 | 257 | The first parameter specifies the indentation for the next line (usually |
|
258 | 258 | the width of the opening text), the second the opening text. All |
|
259 | 259 | parameters are optional. |
|
260 | 260 | """ |
|
261 | 261 | if open: |
|
262 | 262 | self.text(open) |
|
263 | 263 | group = Group(self.group_stack[-1].depth + 1) |
|
264 | 264 | self.group_stack.append(group) |
|
265 | 265 | self.group_queue.enq(group) |
|
266 | 266 | self.indentation += indent |
|
267 | 267 | |
|
268 | 268 | def _enumerate(self, seq): |
|
269 | 269 | """like enumerate, but with an upper limit on the number of items""" |
|
270 | 270 | for idx, x in enumerate(seq): |
|
271 | 271 | if self.max_seq_length and idx >= self.max_seq_length: |
|
272 | 272 | self.text(',') |
|
273 | 273 | self.breakable() |
|
274 | 274 | self.text('...') |
|
275 | 275 | return |
|
276 | 276 | yield idx, x |
|
277 | 277 | |
|
278 | 278 | def end_group(self, dedent=0, close=''): |
|
279 | 279 | """End a group. See `begin_group` for more details.""" |
|
280 | 280 | self.indentation -= dedent |
|
281 | 281 | group = self.group_stack.pop() |
|
282 | 282 | if not group.breakables: |
|
283 | 283 | self.group_queue.remove(group) |
|
284 | 284 | if close: |
|
285 | 285 | self.text(close) |
|
286 | 286 | |
|
287 | 287 | def flush(self): |
|
288 | 288 | """Flush data that is left in the buffer.""" |
|
289 | 289 | for data in self.buffer: |
|
290 | 290 | self.output_width += data.output(self.output, self.output_width) |
|
291 | 291 | self.buffer.clear() |
|
292 | 292 | self.buffer_width = 0 |
|
293 | 293 | |
|
294 | 294 | |
|
295 | 295 | def _get_mro(obj_class): |
|
296 | 296 | """ Get a reasonable method resolution order of a class and its superclasses |
|
297 | 297 | for both old-style and new-style classes. |
|
298 | 298 | """ |
|
299 | 299 | if not hasattr(obj_class, '__mro__'): |
|
300 | 300 | # Old-style class. Mix in object to make a fake new-style class. |
|
301 | 301 | try: |
|
302 | 302 | obj_class = type(obj_class.__name__, (obj_class, object), {}) |
|
303 | 303 | except TypeError: |
|
304 | 304 | # Old-style extension type that does not descend from object. |
|
305 | 305 | # FIXME: try to construct a more thorough MRO. |
|
306 | 306 | mro = [obj_class] |
|
307 | 307 | else: |
|
308 | 308 | mro = obj_class.__mro__[1:-1] |
|
309 | 309 | else: |
|
310 | 310 | mro = obj_class.__mro__ |
|
311 | 311 | return mro |
|
312 | 312 | |
|
313 | 313 | |
|
314 | 314 | class RepresentationPrinter(PrettyPrinter): |
|
315 | 315 | """ |
|
316 | 316 | Special pretty printer that has a `pretty` method that calls the pretty |
|
317 | 317 | printer for a python object. |
|
318 | 318 | |
|
319 | 319 | This class stores processing data on `self` so you must *never* use |
|
320 | 320 | this class in a threaded environment. Always lock it or reinstanciate |
|
321 | 321 | it. |
|
322 | 322 | |
|
323 | 323 | Instances also have a verbose flag callbacks can access to control their |
|
324 | 324 | output. For example the default instance repr prints all attributes and |
|
325 | 325 | methods that are not prefixed by an underscore if the printer is in |
|
326 | 326 | verbose mode. |
|
327 | 327 | """ |
|
328 | 328 | |
|
329 | 329 | def __init__(self, output, verbose=False, max_width=79, newline='\n', |
|
330 | 330 | singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None, |
|
331 | 331 | max_seq_length=MAX_SEQ_LENGTH): |
|
332 | 332 | |
|
333 | 333 | PrettyPrinter.__init__(self, output, max_width, newline, max_seq_length=max_seq_length) |
|
334 | 334 | self.verbose = verbose |
|
335 | 335 | self.stack = [] |
|
336 | 336 | if singleton_pprinters is None: |
|
337 | 337 | singleton_pprinters = _singleton_pprinters.copy() |
|
338 | 338 | self.singleton_pprinters = singleton_pprinters |
|
339 | 339 | if type_pprinters is None: |
|
340 | 340 | type_pprinters = _type_pprinters.copy() |
|
341 | 341 | self.type_pprinters = type_pprinters |
|
342 | 342 | if deferred_pprinters is None: |
|
343 | 343 | deferred_pprinters = _deferred_type_pprinters.copy() |
|
344 | 344 | self.deferred_pprinters = deferred_pprinters |
|
345 | 345 | |
|
346 | 346 | def pretty(self, obj): |
|
347 | 347 | """Pretty print the given object.""" |
|
348 | 348 | obj_id = id(obj) |
|
349 | 349 | cycle = obj_id in self.stack |
|
350 | 350 | self.stack.append(obj_id) |
|
351 | 351 | self.begin_group() |
|
352 | 352 | try: |
|
353 | 353 | obj_class = _safe_getattr(obj, '__class__', None) or type(obj) |
|
354 | 354 | # First try to find registered singleton printers for the type. |
|
355 | 355 | try: |
|
356 | 356 | printer = self.singleton_pprinters[obj_id] |
|
357 | 357 | except (TypeError, KeyError): |
|
358 | 358 | pass |
|
359 | 359 | else: |
|
360 | 360 | return printer(obj, self, cycle) |
|
361 | 361 | # Next walk the mro and check for either: |
|
362 | 362 | # 1) a registered printer |
|
363 | 363 | # 2) a _repr_pretty_ method |
|
364 | 364 | for cls in _get_mro(obj_class): |
|
365 | 365 | if cls in self.type_pprinters: |
|
366 | 366 | # printer registered in self.type_pprinters |
|
367 | 367 | return self.type_pprinters[cls](obj, self, cycle) |
|
368 | 368 | else: |
|
369 | 369 | # deferred printer |
|
370 | 370 | printer = self._in_deferred_types(cls) |
|
371 | 371 | if printer is not None: |
|
372 | 372 | return printer(obj, self, cycle) |
|
373 | 373 | else: |
|
374 | 374 | # Finally look for special method names. |
|
375 | 375 | # Some objects automatically create any requested |
|
376 | 376 | # attribute. Try to ignore most of them by checking for |
|
377 | 377 | # callability. |
|
378 | 378 | if '_repr_pretty_' in cls.__dict__: |
|
379 | 379 | meth = cls._repr_pretty_ |
|
380 | 380 | if callable(meth): |
|
381 | 381 | return meth(obj, self, cycle) |
|
382 | 382 | return _default_pprint(obj, self, cycle) |
|
383 | 383 | finally: |
|
384 | 384 | self.end_group() |
|
385 | 385 | self.stack.pop() |
|
386 | 386 | |
|
387 | 387 | def _in_deferred_types(self, cls): |
|
388 | 388 | """ |
|
389 | 389 | Check if the given class is specified in the deferred type registry. |
|
390 | 390 | |
|
391 | 391 | Returns the printer from the registry if it exists, and None if the |
|
392 | 392 | class is not in the registry. Successful matches will be moved to the |
|
393 | 393 | regular type registry for future use. |
|
394 | 394 | """ |
|
395 | 395 | mod = _safe_getattr(cls, '__module__', None) |
|
396 | 396 | name = _safe_getattr(cls, '__name__', None) |
|
397 | 397 | key = (mod, name) |
|
398 | 398 | printer = None |
|
399 | 399 | if key in self.deferred_pprinters: |
|
400 | 400 | # Move the printer over to the regular registry. |
|
401 | 401 | printer = self.deferred_pprinters.pop(key) |
|
402 | 402 | self.type_pprinters[cls] = printer |
|
403 | 403 | return printer |
|
404 | 404 | |
|
405 | 405 | |
|
406 | 406 | class Printable(object): |
|
407 | 407 | |
|
408 | 408 | def output(self, stream, output_width): |
|
409 | 409 | return output_width |
|
410 | 410 | |
|
411 | 411 | |
|
412 | 412 | class Text(Printable): |
|
413 | 413 | |
|
414 | 414 | def __init__(self): |
|
415 | 415 | self.objs = [] |
|
416 | 416 | self.width = 0 |
|
417 | 417 | |
|
418 | 418 | def output(self, stream, output_width): |
|
419 | 419 | for obj in self.objs: |
|
420 | 420 | stream.write(obj) |
|
421 | 421 | return output_width + self.width |
|
422 | 422 | |
|
423 | 423 | def add(self, obj, width): |
|
424 | 424 | self.objs.append(obj) |
|
425 | 425 | self.width += width |
|
426 | 426 | |
|
427 | 427 | |
|
428 | 428 | class Breakable(Printable): |
|
429 | 429 | |
|
430 | 430 | def __init__(self, seq, width, pretty): |
|
431 | 431 | self.obj = seq |
|
432 | 432 | self.width = width |
|
433 | 433 | self.pretty = pretty |
|
434 | 434 | self.indentation = pretty.indentation |
|
435 | 435 | self.group = pretty.group_stack[-1] |
|
436 | 436 | self.group.breakables.append(self) |
|
437 | 437 | |
|
438 | 438 | def output(self, stream, output_width): |
|
439 | 439 | self.group.breakables.popleft() |
|
440 | 440 | if self.group.want_break: |
|
441 | 441 | stream.write(self.pretty.newline) |
|
442 | 442 | stream.write(' ' * self.indentation) |
|
443 | 443 | return self.indentation |
|
444 | 444 | if not self.group.breakables: |
|
445 | 445 | self.pretty.group_queue.remove(self.group) |
|
446 | 446 | stream.write(self.obj) |
|
447 | 447 | return output_width + self.width |
|
448 | 448 | |
|
449 | 449 | |
|
450 | 450 | class Group(Printable): |
|
451 | 451 | |
|
452 | 452 | def __init__(self, depth): |
|
453 | 453 | self.depth = depth |
|
454 | 454 | self.breakables = deque() |
|
455 | 455 | self.want_break = False |
|
456 | 456 | |
|
457 | 457 | |
|
458 | 458 | class GroupQueue(object): |
|
459 | 459 | |
|
460 | 460 | def __init__(self, *groups): |
|
461 | 461 | self.queue = [] |
|
462 | 462 | for group in groups: |
|
463 | 463 | self.enq(group) |
|
464 | 464 | |
|
465 | 465 | def enq(self, group): |
|
466 | 466 | depth = group.depth |
|
467 | 467 | while depth > len(self.queue) - 1: |
|
468 | 468 | self.queue.append([]) |
|
469 | 469 | self.queue[depth].append(group) |
|
470 | 470 | |
|
471 | 471 | def deq(self): |
|
472 | 472 | for stack in self.queue: |
|
473 | 473 | for idx, group in enumerate(reversed(stack)): |
|
474 | 474 | if group.breakables: |
|
475 | 475 | del stack[idx] |
|
476 | 476 | group.want_break = True |
|
477 | 477 | return group |
|
478 | 478 | for group in stack: |
|
479 | 479 | group.want_break = True |
|
480 | 480 | del stack[:] |
|
481 | 481 | |
|
482 | 482 | def remove(self, group): |
|
483 | 483 | try: |
|
484 | 484 | self.queue[group.depth].remove(group) |
|
485 | 485 | except ValueError: |
|
486 | 486 | pass |
|
487 | 487 | |
|
488 | 488 | try: |
|
489 | 489 | _baseclass_reprs = (object.__repr__, types.InstanceType.__repr__) |
|
490 | 490 | except AttributeError: # Python 3 |
|
491 | 491 | _baseclass_reprs = (object.__repr__,) |
|
492 | 492 | |
|
493 | 493 | |
|
494 | 494 | def _default_pprint(obj, p, cycle): |
|
495 | 495 | """ |
|
496 | 496 | The default print function. Used if an object does not provide one and |
|
497 | 497 | it's none of the builtin objects. |
|
498 | 498 | """ |
|
499 | 499 | klass = _safe_getattr(obj, '__class__', None) or type(obj) |
|
500 | 500 | if _safe_getattr(klass, '__repr__', None) not in _baseclass_reprs: |
|
501 | 501 | # A user-provided repr. Find newlines and replace them with p.break_() |
|
502 | 502 | _repr_pprint(obj, p, cycle) |
|
503 | 503 | return |
|
504 | 504 | p.begin_group(1, '<') |
|
505 | 505 | p.pretty(klass) |
|
506 | 506 | p.text(' at 0x%x' % id(obj)) |
|
507 | 507 | if cycle: |
|
508 | 508 | p.text(' ...') |
|
509 | 509 | elif p.verbose: |
|
510 | 510 | first = True |
|
511 | 511 | for key in dir(obj): |
|
512 | 512 | if not key.startswith('_'): |
|
513 | 513 | try: |
|
514 | 514 | value = getattr(obj, key) |
|
515 | 515 | except AttributeError: |
|
516 | 516 | continue |
|
517 | 517 | if isinstance(value, types.MethodType): |
|
518 | 518 | continue |
|
519 | 519 | if not first: |
|
520 | 520 | p.text(',') |
|
521 | 521 | p.breakable() |
|
522 | 522 | p.text(key) |
|
523 | 523 | p.text('=') |
|
524 | 524 | step = len(key) + 1 |
|
525 | 525 | p.indentation += step |
|
526 | 526 | p.pretty(value) |
|
527 | 527 | p.indentation -= step |
|
528 | 528 | first = False |
|
529 | 529 | p.end_group(1, '>') |
|
530 | 530 | |
|
531 | 531 | |
|
532 | 532 | def _seq_pprinter_factory(start, end, basetype): |
|
533 | 533 | """ |
|
534 | 534 | Factory that returns a pprint function useful for sequences. Used by |
|
535 | 535 | the default pprint for tuples, dicts, and lists. |
|
536 | 536 | """ |
|
537 | 537 | def inner(obj, p, cycle): |
|
538 | 538 | typ = type(obj) |
|
539 | 539 | if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__: |
|
540 | 540 | # If the subclass provides its own repr, use it instead. |
|
541 | 541 | return p.text(typ.__repr__(obj)) |
|
542 | 542 | |
|
543 | 543 | if cycle: |
|
544 | 544 | return p.text(start + '...' + end) |
|
545 | 545 | step = len(start) |
|
546 | 546 | p.begin_group(step, start) |
|
547 | 547 | for idx, x in p._enumerate(obj): |
|
548 | 548 | if idx: |
|
549 | 549 | p.text(',') |
|
550 | 550 | p.breakable() |
|
551 | 551 | p.pretty(x) |
|
552 | 552 | if len(obj) == 1 and type(obj) is tuple: |
|
553 | 553 | # Special case for 1-item tuples. |
|
554 | 554 | p.text(',') |
|
555 | 555 | p.end_group(step, end) |
|
556 | 556 | return inner |
|
557 | 557 | |
|
558 | 558 | |
|
559 | 559 | def _set_pprinter_factory(start, end, basetype): |
|
560 | 560 | """ |
|
561 | 561 | Factory that returns a pprint function useful for sets and frozensets. |
|
562 | 562 | """ |
|
563 | 563 | def inner(obj, p, cycle): |
|
564 | 564 | typ = type(obj) |
|
565 | 565 | if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__: |
|
566 | 566 | # If the subclass provides its own repr, use it instead. |
|
567 | 567 | return p.text(typ.__repr__(obj)) |
|
568 | 568 | |
|
569 | 569 | if cycle: |
|
570 | 570 | return p.text(start + '...' + end) |
|
571 | 571 | if len(obj) == 0: |
|
572 | 572 | # Special case. |
|
573 | 573 | p.text(basetype.__name__ + '()') |
|
574 | 574 | else: |
|
575 | 575 | step = len(start) |
|
576 | 576 | p.begin_group(step, start) |
|
577 | 577 | # Like dictionary keys, we will try to sort the items if there aren't too many |
|
578 | 578 | items = obj |
|
579 | 579 | if not (p.max_seq_length and len(obj) >= p.max_seq_length): |
|
580 | 580 | try: |
|
581 | 581 | items = sorted(obj) |
|
582 | 582 | except Exception: |
|
583 | 583 | # Sometimes the items don't sort. |
|
584 | 584 | pass |
|
585 | 585 | for idx, x in p._enumerate(items): |
|
586 | 586 | if idx: |
|
587 | 587 | p.text(',') |
|
588 | 588 | p.breakable() |
|
589 | 589 | p.pretty(x) |
|
590 | 590 | p.end_group(step, end) |
|
591 | 591 | return inner |
|
592 | 592 | |
|
593 | 593 | |
|
594 | 594 | def _dict_pprinter_factory(start, end, basetype=None): |
|
595 | 595 | """ |
|
596 | 596 | Factory that returns a pprint function used by the default pprint of |
|
597 | 597 | dicts and dict proxies. |
|
598 | 598 | """ |
|
599 | 599 | def inner(obj, p, cycle): |
|
600 | 600 | typ = type(obj) |
|
601 | 601 | if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__: |
|
602 | 602 | # If the subclass provides its own repr, use it instead. |
|
603 | 603 | return p.text(typ.__repr__(obj)) |
|
604 | 604 | |
|
605 | 605 | if cycle: |
|
606 | 606 | return p.text('{...}') |
|
607 | 607 | step = len(start) |
|
608 | 608 | p.begin_group(step, start) |
|
609 | 609 | keys = obj.keys() |
|
610 | 610 | # if dict isn't large enough to be truncated, sort keys before displaying |
|
611 | 611 | if not (p.max_seq_length and len(obj) >= p.max_seq_length): |
|
612 | 612 | try: |
|
613 | 613 | keys = sorted(keys) |
|
614 | 614 | except Exception: |
|
615 | 615 | # Sometimes the keys don't sort. |
|
616 | 616 | pass |
|
617 | 617 | for idx, key in p._enumerate(keys): |
|
618 | 618 | if idx: |
|
619 | 619 | p.text(',') |
|
620 | 620 | p.breakable() |
|
621 | 621 | p.pretty(key) |
|
622 | 622 | p.text(': ') |
|
623 | 623 | p.pretty(obj[key]) |
|
624 | 624 | p.end_group(step, end) |
|
625 | 625 | return inner |
|
626 | 626 | |
|
627 | 627 | |
|
628 | 628 | def _super_pprint(obj, p, cycle): |
|
629 | 629 | """The pprint for the super type.""" |
|
630 | 630 | p.begin_group(8, '<super: ') |
|
631 | 631 | p.pretty(obj.__thisclass__) |
|
632 | 632 | p.text(',') |
|
633 | 633 | p.breakable() |
|
634 | 634 | if PYPY: # In PyPy, super() objects don't have __self__ attributes |
|
635 | 635 | dself = obj.__repr__.__self__ |
|
636 | 636 | p.pretty(None if dself is obj else dself) |
|
637 | 637 | else: |
|
638 | 638 | p.pretty(obj.__self__) |
|
639 | 639 | p.end_group(8, '>') |
|
640 | 640 | |
|
641 | 641 | |
|
642 | 642 | def _re_pattern_pprint(obj, p, cycle): |
|
643 | 643 | """The pprint function for regular expression patterns.""" |
|
644 | 644 | p.text('re.compile(') |
|
645 | 645 | pattern = repr(obj.pattern) |
|
646 | 646 | if pattern[:1] in 'uU': |
|
647 | 647 | pattern = pattern[1:] |
|
648 | 648 | prefix = 'ur' |
|
649 | 649 | else: |
|
650 | 650 | prefix = 'r' |
|
651 | 651 | pattern = prefix + pattern.replace('\\\\', '\\') |
|
652 | 652 | p.text(pattern) |
|
653 | 653 | if obj.flags: |
|
654 | 654 | p.text(',') |
|
655 | 655 | p.breakable() |
|
656 | 656 | done_one = False |
|
657 | 657 | for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL', |
|
658 | 658 | 'UNICODE', 'VERBOSE', 'DEBUG'): |
|
659 | 659 | if obj.flags & getattr(re, flag): |
|
660 | 660 | if done_one: |
|
661 | 661 | p.text('|') |
|
662 | 662 | p.text('re.' + flag) |
|
663 | 663 | done_one = True |
|
664 | 664 | p.text(')') |
|
665 | 665 | |
|
666 | 666 | |
|
667 | 667 | def _type_pprint(obj, p, cycle): |
|
668 | 668 | """The pprint for classes and types.""" |
|
669 | 669 | # Heap allocated types might not have the module attribute, |
|
670 | 670 | # and others may set it to None. |
|
671 | 671 | |
|
672 | 672 | # Checks for a __repr__ override in the metaclass. Can't compare the |
|
673 | 673 | # type(obj).__repr__ directly because in PyPy the representation function |
|
674 | 674 | # inherited from type isn't the same type.__repr__ |
|
675 | 675 | if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]: |
|
676 | 676 | _repr_pprint(obj, p, cycle) |
|
677 | 677 | return |
|
678 | 678 | |
|
679 | 679 | mod = _safe_getattr(obj, '__module__', None) |
|
680 | 680 | try: |
|
681 | 681 | name = obj.__qualname__ |
|
682 | 682 | if not isinstance(name, string_types): |
|
683 | 683 | # This can happen if the type implements __qualname__ as a property |
|
684 | 684 | # or other descriptor in Python 2. |
|
685 | 685 | raise Exception("Try __name__") |
|
686 | 686 | except Exception: |
|
687 | 687 | name = obj.__name__ |
|
688 | 688 | if not isinstance(name, string_types): |
|
689 | 689 | name = '<unknown type>' |
|
690 | 690 | |
|
691 | 691 | if mod in (None, '__builtin__', 'builtins', 'exceptions'): |
|
692 | 692 | p.text(name) |
|
693 | 693 | else: |
|
694 | 694 | p.text(mod + '.' + name) |
|
695 | 695 | |
|
696 | 696 | |
|
697 | 697 | def _repr_pprint(obj, p, cycle): |
|
698 | 698 | """A pprint that just redirects to the normal repr function.""" |
|
699 | 699 | # Find newlines and replace them with p.break_() |
|
700 | 700 | output = repr(obj) |
|
701 | 701 | for idx,output_line in enumerate(output.splitlines()): |
|
702 | 702 | if idx: |
|
703 | 703 | p.break_() |
|
704 | 704 | p.text(output_line) |
|
705 | 705 | |
|
706 | 706 | |
|
707 | 707 | def _function_pprint(obj, p, cycle): |
|
708 | 708 | """Base pprint for all functions and builtin functions.""" |
|
709 | 709 | name = _safe_getattr(obj, '__qualname__', obj.__name__) |
|
710 | 710 | mod = obj.__module__ |
|
711 | 711 | if mod and mod not in ('__builtin__', 'builtins', 'exceptions'): |
|
712 | 712 | name = mod + '.' + name |
|
713 | 713 | p.text('<function %s>' % name) |
|
714 | 714 | |
|
715 | 715 | |
|
716 | 716 | def _exception_pprint(obj, p, cycle): |
|
717 | 717 | """Base pprint for all exceptions.""" |
|
718 | 718 | name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__) |
|
719 | 719 | if obj.__class__.__module__ not in ('exceptions', 'builtins'): |
|
720 | 720 | name = '%s.%s' % (obj.__class__.__module__, name) |
|
721 | 721 | step = len(name) + 1 |
|
722 | 722 | p.begin_group(step, name + '(') |
|
723 | 723 | for idx, arg in enumerate(getattr(obj, 'args', ())): |
|
724 | 724 | if idx: |
|
725 | 725 | p.text(',') |
|
726 | 726 | p.breakable() |
|
727 | 727 | p.pretty(arg) |
|
728 | 728 | p.end_group(step, ')') |
|
729 | 729 | |
|
730 | 730 | |
|
731 | 731 | #: the exception base |
|
732 | 732 | try: |
|
733 | 733 | _exception_base = BaseException |
|
734 | 734 | except NameError: |
|
735 | 735 | _exception_base = Exception |
|
736 | 736 | |
|
737 | 737 | |
|
738 | 738 | #: printers for builtin types |
|
739 | 739 | _type_pprinters = { |
|
740 | 740 | int: _repr_pprint, |
|
741 | 741 | float: _repr_pprint, |
|
742 | 742 | str: _repr_pprint, |
|
743 | 743 | tuple: _seq_pprinter_factory('(', ')', tuple), |
|
744 | 744 | list: _seq_pprinter_factory('[', ']', list), |
|
745 | 745 | dict: _dict_pprinter_factory('{', '}', dict), |
|
746 | 746 | |
|
747 | 747 | set: _set_pprinter_factory('{', '}', set), |
|
748 | 748 | frozenset: _set_pprinter_factory('frozenset({', '})', frozenset), |
|
749 | 749 | super: _super_pprint, |
|
750 | 750 | _re_pattern_type: _re_pattern_pprint, |
|
751 | 751 | type: _type_pprint, |
|
752 | 752 | types.FunctionType: _function_pprint, |
|
753 | 753 | types.BuiltinFunctionType: _function_pprint, |
|
754 | 754 | types.MethodType: _repr_pprint, |
|
755 | 755 | |
|
756 | 756 | datetime.datetime: _repr_pprint, |
|
757 | 757 | datetime.timedelta: _repr_pprint, |
|
758 | 758 | _exception_base: _exception_pprint |
|
759 | 759 | } |
|
760 | 760 | |
|
761 | 761 | try: |
|
762 | 762 | # In PyPy, types.DictProxyType is dict, setting the dictproxy printer |
|
763 | 763 | # using dict.setdefault avoids overwritting the dict printer |
|
764 | 764 | _type_pprinters.setdefault(types.DictProxyType, |
|
765 | 765 | _dict_pprinter_factory('dict_proxy({', '})')) |
|
766 | 766 | _type_pprinters[types.ClassType] = _type_pprint |
|
767 | 767 | _type_pprinters[types.SliceType] = _repr_pprint |
|
768 | 768 | except AttributeError: # Python 3 |
|
769 | 769 | _type_pprinters[types.MappingProxyType] = \ |
|
770 | 770 | _dict_pprinter_factory('mappingproxy({', '})') |
|
771 | 771 | _type_pprinters[slice] = _repr_pprint |
|
772 | 772 | |
|
773 | 773 | try: |
|
774 | _type_pprinters[xrange] = _repr_pprint | |
|
775 | 774 | _type_pprinters[long] = _repr_pprint |
|
776 | 775 | _type_pprinters[unicode] = _repr_pprint |
|
777 | 776 | except NameError: |
|
778 | 777 | _type_pprinters[range] = _repr_pprint |
|
779 | 778 | _type_pprinters[bytes] = _repr_pprint |
|
780 | 779 | |
|
781 | 780 | #: printers for types specified by name |
|
782 | 781 | _deferred_type_pprinters = { |
|
783 | 782 | } |
|
784 | 783 | |
|
785 | 784 | def for_type(typ, func): |
|
786 | 785 | """ |
|
787 | 786 | Add a pretty printer for a given type. |
|
788 | 787 | """ |
|
789 | 788 | oldfunc = _type_pprinters.get(typ, None) |
|
790 | 789 | if func is not None: |
|
791 | 790 | # To support easy restoration of old pprinters, we need to ignore Nones. |
|
792 | 791 | _type_pprinters[typ] = func |
|
793 | 792 | return oldfunc |
|
794 | 793 | |
|
795 | 794 | def for_type_by_name(type_module, type_name, func): |
|
796 | 795 | """ |
|
797 | 796 | Add a pretty printer for a type specified by the module and name of a type |
|
798 | 797 | rather than the type object itself. |
|
799 | 798 | """ |
|
800 | 799 | key = (type_module, type_name) |
|
801 | 800 | oldfunc = _deferred_type_pprinters.get(key, None) |
|
802 | 801 | if func is not None: |
|
803 | 802 | # To support easy restoration of old pprinters, we need to ignore Nones. |
|
804 | 803 | _deferred_type_pprinters[key] = func |
|
805 | 804 | return oldfunc |
|
806 | 805 | |
|
807 | 806 | |
|
808 | 807 | #: printers for the default singletons |
|
809 | 808 | _singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis, |
|
810 | 809 | NotImplemented]), _repr_pprint) |
|
811 | 810 | |
|
812 | 811 | |
|
813 | 812 | def _defaultdict_pprint(obj, p, cycle): |
|
814 | 813 | name = obj.__class__.__name__ |
|
815 | 814 | with p.group(len(name) + 1, name + '(', ')'): |
|
816 | 815 | if cycle: |
|
817 | 816 | p.text('...') |
|
818 | 817 | else: |
|
819 | 818 | p.pretty(obj.default_factory) |
|
820 | 819 | p.text(',') |
|
821 | 820 | p.breakable() |
|
822 | 821 | p.pretty(dict(obj)) |
|
823 | 822 | |
|
824 | 823 | def _ordereddict_pprint(obj, p, cycle): |
|
825 | 824 | name = obj.__class__.__name__ |
|
826 | 825 | with p.group(len(name) + 1, name + '(', ')'): |
|
827 | 826 | if cycle: |
|
828 | 827 | p.text('...') |
|
829 | 828 | elif len(obj): |
|
830 | 829 | p.pretty(list(obj.items())) |
|
831 | 830 | |
|
832 | 831 | def _deque_pprint(obj, p, cycle): |
|
833 | 832 | name = obj.__class__.__name__ |
|
834 | 833 | with p.group(len(name) + 1, name + '(', ')'): |
|
835 | 834 | if cycle: |
|
836 | 835 | p.text('...') |
|
837 | 836 | else: |
|
838 | 837 | p.pretty(list(obj)) |
|
839 | 838 | |
|
840 | 839 | |
|
841 | 840 | def _counter_pprint(obj, p, cycle): |
|
842 | 841 | name = obj.__class__.__name__ |
|
843 | 842 | with p.group(len(name) + 1, name + '(', ')'): |
|
844 | 843 | if cycle: |
|
845 | 844 | p.text('...') |
|
846 | 845 | elif len(obj): |
|
847 | 846 | p.pretty(dict(obj)) |
|
848 | 847 | |
|
849 | 848 | for_type_by_name('collections', 'defaultdict', _defaultdict_pprint) |
|
850 | 849 | for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint) |
|
851 | 850 | for_type_by_name('collections', 'deque', _deque_pprint) |
|
852 | 851 | for_type_by_name('collections', 'Counter', _counter_pprint) |
|
853 | 852 | |
|
854 | 853 | if __name__ == '__main__': |
|
855 | 854 | from random import randrange |
|
856 | 855 | class Foo(object): |
|
857 | 856 | def __init__(self): |
|
858 | 857 | self.foo = 1 |
|
859 | 858 | self.bar = re.compile(r'\s+') |
|
860 | 859 | self.blub = dict.fromkeys(range(30), randrange(1, 40)) |
|
861 | 860 | self.hehe = 23424.234234 |
|
862 | 861 | self.list = ["blub", "blah", self] |
|
863 | 862 | |
|
864 | 863 | def get_foo(self): |
|
865 | 864 | print("foo") |
|
866 | 865 | |
|
867 | 866 | pprint(Foo(), verbose=True) |
@@ -1,37 +1,36 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """Utilities for working with data structures like lists, dicts and tuples. |
|
3 | 3 | """ |
|
4 | 4 | |
|
5 | 5 | #----------------------------------------------------------------------------- |
|
6 | 6 | # Copyright (C) 2008-2011 The IPython Development Team |
|
7 | 7 | # |
|
8 | 8 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | 9 | # the file COPYING, distributed as part of this software. |
|
10 | 10 | #----------------------------------------------------------------------------- |
|
11 | 11 | |
|
12 | from .py3compat import xrange | |
|
13 | 12 | |
|
14 | 13 | def uniq_stable(elems): |
|
15 | 14 | """uniq_stable(elems) -> list |
|
16 | 15 | |
|
17 | 16 | Return from an iterable, a list of all the unique elements in the input, |
|
18 | 17 | but maintaining the order in which they first appear. |
|
19 | 18 | |
|
20 | 19 | Note: All elements in the input must be hashable for this routine |
|
21 | 20 | to work, as it internally uses a set for efficiency reasons. |
|
22 | 21 | """ |
|
23 | 22 | seen = set() |
|
24 | 23 | return [x for x in elems if x not in seen and not seen.add(x)] |
|
25 | 24 | |
|
26 | 25 | |
|
27 | 26 | def flatten(seq): |
|
28 | 27 | """Flatten a list of lists (NOT recursive, only works for 2d lists).""" |
|
29 | 28 | |
|
30 | 29 | return [x for subseq in seq for x in subseq] |
|
31 | 30 | |
|
32 | 31 | |
|
33 | 32 | def chop(seq, size): |
|
34 | 33 | """Chop a sequence into chunks of the given size.""" |
|
35 |
return [seq[i:i+size] for i in |
|
|
34 | return [seq[i:i+size] for i in range(0,len(seq),size)] | |
|
36 | 35 | |
|
37 | 36 |
@@ -1,774 +1,774 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """ |
|
3 | 3 | Utilities for working with strings and text. |
|
4 | 4 | |
|
5 | 5 | Inheritance diagram: |
|
6 | 6 | |
|
7 | 7 | .. inheritance-diagram:: IPython.utils.text |
|
8 | 8 | :parts: 3 |
|
9 | 9 | """ |
|
10 | 10 | |
|
11 | 11 | import os |
|
12 | 12 | import re |
|
13 | 13 | import sys |
|
14 | 14 | import textwrap |
|
15 | 15 | from string import Formatter |
|
16 | 16 | try: |
|
17 | 17 | from pathlib import Path |
|
18 | 18 | except ImportError: |
|
19 | 19 | # Python 2 backport |
|
20 | 20 | from pathlib2 import Path |
|
21 | 21 | |
|
22 | 22 | from IPython.utils import py3compat |
|
23 | 23 | |
|
24 | 24 | # datetime.strftime date format for ipython |
|
25 | 25 | if sys.platform == 'win32': |
|
26 | 26 | date_format = "%B %d, %Y" |
|
27 | 27 | else: |
|
28 | 28 | date_format = "%B %-d, %Y" |
|
29 | 29 | |
|
30 | 30 | class LSString(str): |
|
31 | 31 | """String derivative with a special access attributes. |
|
32 | 32 | |
|
33 | 33 | These are normal strings, but with the special attributes: |
|
34 | 34 | |
|
35 | 35 | .l (or .list) : value as list (split on newlines). |
|
36 | 36 | .n (or .nlstr): original value (the string itself). |
|
37 | 37 | .s (or .spstr): value as whitespace-separated string. |
|
38 | 38 | .p (or .paths): list of path objects (requires path.py package) |
|
39 | 39 | |
|
40 | 40 | Any values which require transformations are computed only once and |
|
41 | 41 | cached. |
|
42 | 42 | |
|
43 | 43 | Such strings are very useful to efficiently interact with the shell, which |
|
44 | 44 | typically only understands whitespace-separated options for commands.""" |
|
45 | 45 | |
|
46 | 46 | def get_list(self): |
|
47 | 47 | try: |
|
48 | 48 | return self.__list |
|
49 | 49 | except AttributeError: |
|
50 | 50 | self.__list = self.split('\n') |
|
51 | 51 | return self.__list |
|
52 | 52 | |
|
53 | 53 | l = list = property(get_list) |
|
54 | 54 | |
|
55 | 55 | def get_spstr(self): |
|
56 | 56 | try: |
|
57 | 57 | return self.__spstr |
|
58 | 58 | except AttributeError: |
|
59 | 59 | self.__spstr = self.replace('\n',' ') |
|
60 | 60 | return self.__spstr |
|
61 | 61 | |
|
62 | 62 | s = spstr = property(get_spstr) |
|
63 | 63 | |
|
64 | 64 | def get_nlstr(self): |
|
65 | 65 | return self |
|
66 | 66 | |
|
67 | 67 | n = nlstr = property(get_nlstr) |
|
68 | 68 | |
|
69 | 69 | def get_paths(self): |
|
70 | 70 | try: |
|
71 | 71 | return self.__paths |
|
72 | 72 | except AttributeError: |
|
73 | 73 | self.__paths = [Path(p) for p in self.split('\n') if os.path.exists(p)] |
|
74 | 74 | return self.__paths |
|
75 | 75 | |
|
76 | 76 | p = paths = property(get_paths) |
|
77 | 77 | |
|
78 | 78 | # FIXME: We need to reimplement type specific displayhook and then add this |
|
79 | 79 | # back as a custom printer. This should also be moved outside utils into the |
|
80 | 80 | # core. |
|
81 | 81 | |
|
82 | 82 | # def print_lsstring(arg): |
|
83 | 83 | # """ Prettier (non-repr-like) and more informative printer for LSString """ |
|
84 | 84 | # print "LSString (.p, .n, .l, .s available). Value:" |
|
85 | 85 | # print arg |
|
86 | 86 | # |
|
87 | 87 | # |
|
88 | 88 | # print_lsstring = result_display.when_type(LSString)(print_lsstring) |
|
89 | 89 | |
|
90 | 90 | |
|
91 | 91 | class SList(list): |
|
92 | 92 | """List derivative with a special access attributes. |
|
93 | 93 | |
|
94 | 94 | These are normal lists, but with the special attributes: |
|
95 | 95 | |
|
96 | 96 | * .l (or .list) : value as list (the list itself). |
|
97 | 97 | * .n (or .nlstr): value as a string, joined on newlines. |
|
98 | 98 | * .s (or .spstr): value as a string, joined on spaces. |
|
99 | 99 | * .p (or .paths): list of path objects (requires path.py package) |
|
100 | 100 | |
|
101 | 101 | Any values which require transformations are computed only once and |
|
102 | 102 | cached.""" |
|
103 | 103 | |
|
104 | 104 | def get_list(self): |
|
105 | 105 | return self |
|
106 | 106 | |
|
107 | 107 | l = list = property(get_list) |
|
108 | 108 | |
|
109 | 109 | def get_spstr(self): |
|
110 | 110 | try: |
|
111 | 111 | return self.__spstr |
|
112 | 112 | except AttributeError: |
|
113 | 113 | self.__spstr = ' '.join(self) |
|
114 | 114 | return self.__spstr |
|
115 | 115 | |
|
116 | 116 | s = spstr = property(get_spstr) |
|
117 | 117 | |
|
118 | 118 | def get_nlstr(self): |
|
119 | 119 | try: |
|
120 | 120 | return self.__nlstr |
|
121 | 121 | except AttributeError: |
|
122 | 122 | self.__nlstr = '\n'.join(self) |
|
123 | 123 | return self.__nlstr |
|
124 | 124 | |
|
125 | 125 | n = nlstr = property(get_nlstr) |
|
126 | 126 | |
|
127 | 127 | def get_paths(self): |
|
128 | 128 | try: |
|
129 | 129 | return self.__paths |
|
130 | 130 | except AttributeError: |
|
131 | 131 | self.__paths = [Path(p) for p in self if os.path.exists(p)] |
|
132 | 132 | return self.__paths |
|
133 | 133 | |
|
134 | 134 | p = paths = property(get_paths) |
|
135 | 135 | |
|
136 | 136 | def grep(self, pattern, prune = False, field = None): |
|
137 | 137 | """ Return all strings matching 'pattern' (a regex or callable) |
|
138 | 138 | |
|
139 | 139 | This is case-insensitive. If prune is true, return all items |
|
140 | 140 | NOT matching the pattern. |
|
141 | 141 | |
|
142 | 142 | If field is specified, the match must occur in the specified |
|
143 | 143 | whitespace-separated field. |
|
144 | 144 | |
|
145 | 145 | Examples:: |
|
146 | 146 | |
|
147 | 147 | a.grep( lambda x: x.startswith('C') ) |
|
148 | 148 | a.grep('Cha.*log', prune=1) |
|
149 | 149 | a.grep('chm', field=-1) |
|
150 | 150 | """ |
|
151 | 151 | |
|
152 | 152 | def match_target(s): |
|
153 | 153 | if field is None: |
|
154 | 154 | return s |
|
155 | 155 | parts = s.split() |
|
156 | 156 | try: |
|
157 | 157 | tgt = parts[field] |
|
158 | 158 | return tgt |
|
159 | 159 | except IndexError: |
|
160 | 160 | return "" |
|
161 | 161 | |
|
162 | 162 | if isinstance(pattern, py3compat.string_types): |
|
163 | 163 | pred = lambda x : re.search(pattern, x, re.IGNORECASE) |
|
164 | 164 | else: |
|
165 | 165 | pred = pattern |
|
166 | 166 | if not prune: |
|
167 | 167 | return SList([el for el in self if pred(match_target(el))]) |
|
168 | 168 | else: |
|
169 | 169 | return SList([el for el in self if not pred(match_target(el))]) |
|
170 | 170 | |
|
171 | 171 | def fields(self, *fields): |
|
172 | 172 | """ Collect whitespace-separated fields from string list |
|
173 | 173 | |
|
174 | 174 | Allows quick awk-like usage of string lists. |
|
175 | 175 | |
|
176 | 176 | Example data (in var a, created by 'a = !ls -l'):: |
|
177 | 177 | |
|
178 | 178 | -rwxrwxrwx 1 ville None 18 Dec 14 2006 ChangeLog |
|
179 | 179 | drwxrwxrwx+ 6 ville None 0 Oct 24 18:05 IPython |
|
180 | 180 | |
|
181 | 181 | * ``a.fields(0)`` is ``['-rwxrwxrwx', 'drwxrwxrwx+']`` |
|
182 | 182 | * ``a.fields(1,0)`` is ``['1 -rwxrwxrwx', '6 drwxrwxrwx+']`` |
|
183 | 183 | (note the joining by space). |
|
184 | 184 | * ``a.fields(-1)`` is ``['ChangeLog', 'IPython']`` |
|
185 | 185 | |
|
186 | 186 | IndexErrors are ignored. |
|
187 | 187 | |
|
188 | 188 | Without args, fields() just split()'s the strings. |
|
189 | 189 | """ |
|
190 | 190 | if len(fields) == 0: |
|
191 | 191 | return [el.split() for el in self] |
|
192 | 192 | |
|
193 | 193 | res = SList() |
|
194 | 194 | for el in [f.split() for f in self]: |
|
195 | 195 | lineparts = [] |
|
196 | 196 | |
|
197 | 197 | for fd in fields: |
|
198 | 198 | try: |
|
199 | 199 | lineparts.append(el[fd]) |
|
200 | 200 | except IndexError: |
|
201 | 201 | pass |
|
202 | 202 | if lineparts: |
|
203 | 203 | res.append(" ".join(lineparts)) |
|
204 | 204 | |
|
205 | 205 | return res |
|
206 | 206 | |
|
207 | 207 | def sort(self,field= None, nums = False): |
|
208 | 208 | """ sort by specified fields (see fields()) |
|
209 | 209 | |
|
210 | 210 | Example:: |
|
211 | 211 | |
|
212 | 212 | a.sort(1, nums = True) |
|
213 | 213 | |
|
214 | 214 | Sorts a by second field, in numerical order (so that 21 > 3) |
|
215 | 215 | |
|
216 | 216 | """ |
|
217 | 217 | |
|
218 | 218 | #decorate, sort, undecorate |
|
219 | 219 | if field is not None: |
|
220 | 220 | dsu = [[SList([line]).fields(field), line] for line in self] |
|
221 | 221 | else: |
|
222 | 222 | dsu = [[line, line] for line in self] |
|
223 | 223 | if nums: |
|
224 | 224 | for i in range(len(dsu)): |
|
225 | 225 | numstr = "".join([ch for ch in dsu[i][0] if ch.isdigit()]) |
|
226 | 226 | try: |
|
227 | 227 | n = int(numstr) |
|
228 | 228 | except ValueError: |
|
229 | 229 | n = 0 |
|
230 | 230 | dsu[i][0] = n |
|
231 | 231 | |
|
232 | 232 | |
|
233 | 233 | dsu.sort() |
|
234 | 234 | return SList([t[1] for t in dsu]) |
|
235 | 235 | |
|
236 | 236 | |
|
237 | 237 | # FIXME: We need to reimplement type specific displayhook and then add this |
|
238 | 238 | # back as a custom printer. This should also be moved outside utils into the |
|
239 | 239 | # core. |
|
240 | 240 | |
|
241 | 241 | # def print_slist(arg): |
|
242 | 242 | # """ Prettier (non-repr-like) and more informative printer for SList """ |
|
243 | 243 | # print "SList (.p, .n, .l, .s, .grep(), .fields(), sort() available):" |
|
244 | 244 | # if hasattr(arg, 'hideonce') and arg.hideonce: |
|
245 | 245 | # arg.hideonce = False |
|
246 | 246 | # return |
|
247 | 247 | # |
|
248 | 248 | # nlprint(arg) # This was a nested list printer, now removed. |
|
249 | 249 | # |
|
250 | 250 | # print_slist = result_display.when_type(SList)(print_slist) |
|
251 | 251 | |
|
252 | 252 | |
|
253 | 253 | def indent(instr,nspaces=4, ntabs=0, flatten=False): |
|
254 | 254 | """Indent a string a given number of spaces or tabstops. |
|
255 | 255 | |
|
256 | 256 | indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces. |
|
257 | 257 | |
|
258 | 258 | Parameters |
|
259 | 259 | ---------- |
|
260 | 260 | |
|
261 | 261 | instr : basestring |
|
262 | 262 | The string to be indented. |
|
263 | 263 | nspaces : int (default: 4) |
|
264 | 264 | The number of spaces to be indented. |
|
265 | 265 | ntabs : int (default: 0) |
|
266 | 266 | The number of tabs to be indented. |
|
267 | 267 | flatten : bool (default: False) |
|
268 | 268 | Whether to scrub existing indentation. If True, all lines will be |
|
269 | 269 | aligned to the same indentation. If False, existing indentation will |
|
270 | 270 | be strictly increased. |
|
271 | 271 | |
|
272 | 272 | Returns |
|
273 | 273 | ------- |
|
274 | 274 | |
|
275 | 275 | str|unicode : string indented by ntabs and nspaces. |
|
276 | 276 | |
|
277 | 277 | """ |
|
278 | 278 | if instr is None: |
|
279 | 279 | return |
|
280 | 280 | ind = '\t'*ntabs+' '*nspaces |
|
281 | 281 | if flatten: |
|
282 | 282 | pat = re.compile(r'^\s*', re.MULTILINE) |
|
283 | 283 | else: |
|
284 | 284 | pat = re.compile(r'^', re.MULTILINE) |
|
285 | 285 | outstr = re.sub(pat, ind, instr) |
|
286 | 286 | if outstr.endswith(os.linesep+ind): |
|
287 | 287 | return outstr[:-len(ind)] |
|
288 | 288 | else: |
|
289 | 289 | return outstr |
|
290 | 290 | |
|
291 | 291 | |
|
292 | 292 | def list_strings(arg): |
|
293 | 293 | """Always return a list of strings, given a string or list of strings |
|
294 | 294 | as input. |
|
295 | 295 | |
|
296 | 296 | Examples |
|
297 | 297 | -------- |
|
298 | 298 | :: |
|
299 | 299 | |
|
300 | 300 | In [7]: list_strings('A single string') |
|
301 | 301 | Out[7]: ['A single string'] |
|
302 | 302 | |
|
303 | 303 | In [8]: list_strings(['A single string in a list']) |
|
304 | 304 | Out[8]: ['A single string in a list'] |
|
305 | 305 | |
|
306 | 306 | In [9]: list_strings(['A','list','of','strings']) |
|
307 | 307 | Out[9]: ['A', 'list', 'of', 'strings'] |
|
308 | 308 | """ |
|
309 | 309 | |
|
310 | 310 | if isinstance(arg, py3compat.string_types): return [arg] |
|
311 | 311 | else: return arg |
|
312 | 312 | |
|
313 | 313 | |
|
314 | 314 | def marquee(txt='',width=78,mark='*'): |
|
315 | 315 | """Return the input string centered in a 'marquee'. |
|
316 | 316 | |
|
317 | 317 | Examples |
|
318 | 318 | -------- |
|
319 | 319 | :: |
|
320 | 320 | |
|
321 | 321 | In [16]: marquee('A test',40) |
|
322 | 322 | Out[16]: '**************** A test ****************' |
|
323 | 323 | |
|
324 | 324 | In [17]: marquee('A test',40,'-') |
|
325 | 325 | Out[17]: '---------------- A test ----------------' |
|
326 | 326 | |
|
327 | 327 | In [18]: marquee('A test',40,' ') |
|
328 | 328 | Out[18]: ' A test ' |
|
329 | 329 | |
|
330 | 330 | """ |
|
331 | 331 | if not txt: |
|
332 | 332 | return (mark*width)[:width] |
|
333 | 333 | nmark = (width-len(txt)-2)//len(mark)//2 |
|
334 | 334 | if nmark < 0: nmark =0 |
|
335 | 335 | marks = mark*nmark |
|
336 | 336 | return '%s %s %s' % (marks,txt,marks) |
|
337 | 337 | |
|
338 | 338 | |
|
339 | 339 | ini_spaces_re = re.compile(r'^(\s+)') |
|
340 | 340 | |
|
341 | 341 | def num_ini_spaces(strng): |
|
342 | 342 | """Return the number of initial spaces in a string""" |
|
343 | 343 | |
|
344 | 344 | ini_spaces = ini_spaces_re.match(strng) |
|
345 | 345 | if ini_spaces: |
|
346 | 346 | return ini_spaces.end() |
|
347 | 347 | else: |
|
348 | 348 | return 0 |
|
349 | 349 | |
|
350 | 350 | |
|
351 | 351 | def format_screen(strng): |
|
352 | 352 | """Format a string for screen printing. |
|
353 | 353 | |
|
354 | 354 | This removes some latex-type format codes.""" |
|
355 | 355 | # Paragraph continue |
|
356 | 356 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
357 | 357 | strng = par_re.sub('',strng) |
|
358 | 358 | return strng |
|
359 | 359 | |
|
360 | 360 | |
|
361 | 361 | def dedent(text): |
|
362 | 362 | """Equivalent of textwrap.dedent that ignores unindented first line. |
|
363 | 363 | |
|
364 | 364 | This means it will still dedent strings like: |
|
365 | 365 | '''foo |
|
366 | 366 | is a bar |
|
367 | 367 | ''' |
|
368 | 368 | |
|
369 | 369 | For use in wrap_paragraphs. |
|
370 | 370 | """ |
|
371 | 371 | |
|
372 | 372 | if text.startswith('\n'): |
|
373 | 373 | # text starts with blank line, don't ignore the first line |
|
374 | 374 | return textwrap.dedent(text) |
|
375 | 375 | |
|
376 | 376 | # split first line |
|
377 | 377 | splits = text.split('\n',1) |
|
378 | 378 | if len(splits) == 1: |
|
379 | 379 | # only one line |
|
380 | 380 | return textwrap.dedent(text) |
|
381 | 381 | |
|
382 | 382 | first, rest = splits |
|
383 | 383 | # dedent everything but the first line |
|
384 | 384 | rest = textwrap.dedent(rest) |
|
385 | 385 | return '\n'.join([first, rest]) |
|
386 | 386 | |
|
387 | 387 | |
|
388 | 388 | def wrap_paragraphs(text, ncols=80): |
|
389 | 389 | """Wrap multiple paragraphs to fit a specified width. |
|
390 | 390 | |
|
391 | 391 | This is equivalent to textwrap.wrap, but with support for multiple |
|
392 | 392 | paragraphs, as separated by empty lines. |
|
393 | 393 | |
|
394 | 394 | Returns |
|
395 | 395 | ------- |
|
396 | 396 | |
|
397 | 397 | list of complete paragraphs, wrapped to fill `ncols` columns. |
|
398 | 398 | """ |
|
399 | 399 | paragraph_re = re.compile(r'\n(\s*\n)+', re.MULTILINE) |
|
400 | 400 | text = dedent(text).strip() |
|
401 | 401 | paragraphs = paragraph_re.split(text)[::2] # every other entry is space |
|
402 | 402 | out_ps = [] |
|
403 | 403 | indent_re = re.compile(r'\n\s+', re.MULTILINE) |
|
404 | 404 | for p in paragraphs: |
|
405 | 405 | # presume indentation that survives dedent is meaningful formatting, |
|
406 | 406 | # so don't fill unless text is flush. |
|
407 | 407 | if indent_re.search(p) is None: |
|
408 | 408 | # wrap paragraph |
|
409 | 409 | p = textwrap.fill(p, ncols) |
|
410 | 410 | out_ps.append(p) |
|
411 | 411 | return out_ps |
|
412 | 412 | |
|
413 | 413 | |
|
414 | 414 | def long_substr(data): |
|
415 | 415 | """Return the longest common substring in a list of strings. |
|
416 | 416 | |
|
417 | 417 | Credit: http://stackoverflow.com/questions/2892931/longest-common-substring-from-more-than-two-strings-python |
|
418 | 418 | """ |
|
419 | 419 | substr = '' |
|
420 | 420 | if len(data) > 1 and len(data[0]) > 0: |
|
421 | 421 | for i in range(len(data[0])): |
|
422 | 422 | for j in range(len(data[0])-i+1): |
|
423 | 423 | if j > len(substr) and all(data[0][i:i+j] in x for x in data): |
|
424 | 424 | substr = data[0][i:i+j] |
|
425 | 425 | elif len(data) == 1: |
|
426 | 426 | substr = data[0] |
|
427 | 427 | return substr |
|
428 | 428 | |
|
429 | 429 | |
|
430 | 430 | def strip_email_quotes(text): |
|
431 | 431 | """Strip leading email quotation characters ('>'). |
|
432 | 432 | |
|
433 | 433 | Removes any combination of leading '>' interspersed with whitespace that |
|
434 | 434 | appears *identically* in all lines of the input text. |
|
435 | 435 | |
|
436 | 436 | Parameters |
|
437 | 437 | ---------- |
|
438 | 438 | text : str |
|
439 | 439 | |
|
440 | 440 | Examples |
|
441 | 441 | -------- |
|
442 | 442 | |
|
443 | 443 | Simple uses:: |
|
444 | 444 | |
|
445 | 445 | In [2]: strip_email_quotes('> > text') |
|
446 | 446 | Out[2]: 'text' |
|
447 | 447 | |
|
448 | 448 | In [3]: strip_email_quotes('> > text\\n> > more') |
|
449 | 449 | Out[3]: 'text\\nmore' |
|
450 | 450 | |
|
451 | 451 | Note how only the common prefix that appears in all lines is stripped:: |
|
452 | 452 | |
|
453 | 453 | In [4]: strip_email_quotes('> > text\\n> > more\\n> more...') |
|
454 | 454 | Out[4]: '> text\\n> more\\nmore...' |
|
455 | 455 | |
|
456 | 456 | So if any line has no quote marks ('>') , then none are stripped from any |
|
457 | 457 | of them :: |
|
458 | 458 | |
|
459 | 459 | In [5]: strip_email_quotes('> > text\\n> > more\\nlast different') |
|
460 | 460 | Out[5]: '> > text\\n> > more\\nlast different' |
|
461 | 461 | """ |
|
462 | 462 | lines = text.splitlines() |
|
463 | 463 | matches = set() |
|
464 | 464 | for line in lines: |
|
465 | 465 | prefix = re.match(r'^(\s*>[ >]*)', line) |
|
466 | 466 | if prefix: |
|
467 | 467 | matches.add(prefix.group(1)) |
|
468 | 468 | else: |
|
469 | 469 | break |
|
470 | 470 | else: |
|
471 | 471 | prefix = long_substr(list(matches)) |
|
472 | 472 | if prefix: |
|
473 | 473 | strip = len(prefix) |
|
474 | 474 | text = '\n'.join([ ln[strip:] for ln in lines]) |
|
475 | 475 | return text |
|
476 | 476 | |
|
477 | 477 | def strip_ansi(source): |
|
478 | 478 | """ |
|
479 | 479 | Remove ansi escape codes from text. |
|
480 | 480 | |
|
481 | 481 | Parameters |
|
482 | 482 | ---------- |
|
483 | 483 | source : str |
|
484 | 484 | Source to remove the ansi from |
|
485 | 485 | """ |
|
486 | 486 | return re.sub(r'\033\[(\d|;)+?m', '', source) |
|
487 | 487 | |
|
488 | 488 | |
|
489 | 489 | class EvalFormatter(Formatter): |
|
490 | 490 | """A String Formatter that allows evaluation of simple expressions. |
|
491 | 491 | |
|
492 | 492 | Note that this version interprets a : as specifying a format string (as per |
|
493 | 493 | standard string formatting), so if slicing is required, you must explicitly |
|
494 | 494 | create a slice. |
|
495 | 495 | |
|
496 | 496 | This is to be used in templating cases, such as the parallel batch |
|
497 | 497 | script templates, where simple arithmetic on arguments is useful. |
|
498 | 498 | |
|
499 | 499 | Examples |
|
500 | 500 | -------- |
|
501 | 501 | :: |
|
502 | 502 | |
|
503 | 503 | In [1]: f = EvalFormatter() |
|
504 | 504 | In [2]: f.format('{n//4}', n=8) |
|
505 | 505 | Out[2]: '2' |
|
506 | 506 | |
|
507 | 507 | In [3]: f.format("{greeting[slice(2,4)]}", greeting="Hello") |
|
508 | 508 | Out[3]: 'll' |
|
509 | 509 | """ |
|
510 | 510 | def get_field(self, name, args, kwargs): |
|
511 | 511 | v = eval(name, kwargs) |
|
512 | 512 | return v, name |
|
513 | 513 | |
|
514 | 514 | #XXX: As of Python 3.4, the format string parsing no longer splits on a colon |
|
515 | 515 | # inside [], so EvalFormatter can handle slicing. Once we only support 3.4 and |
|
516 | 516 | # above, it should be possible to remove FullEvalFormatter. |
|
517 | 517 | |
|
518 | 518 | class FullEvalFormatter(Formatter): |
|
519 | 519 | """A String Formatter that allows evaluation of simple expressions. |
|
520 | 520 | |
|
521 | 521 | Any time a format key is not found in the kwargs, |
|
522 | 522 | it will be tried as an expression in the kwargs namespace. |
|
523 | 523 | |
|
524 | 524 | Note that this version allows slicing using [1:2], so you cannot specify |
|
525 | 525 | a format string. Use :class:`EvalFormatter` to permit format strings. |
|
526 | 526 | |
|
527 | 527 | Examples |
|
528 | 528 | -------- |
|
529 | 529 | :: |
|
530 | 530 | |
|
531 | 531 | In [1]: f = FullEvalFormatter() |
|
532 | 532 | In [2]: f.format('{n//4}', n=8) |
|
533 | 533 | Out[2]: '2' |
|
534 | 534 | |
|
535 | 535 | In [3]: f.format('{list(range(5))[2:4]}') |
|
536 | 536 | Out[3]: '[2, 3]' |
|
537 | 537 | |
|
538 | 538 | In [4]: f.format('{3*2}') |
|
539 | 539 | Out[4]: '6' |
|
540 | 540 | """ |
|
541 | 541 | # copied from Formatter._vformat with minor changes to allow eval |
|
542 | 542 | # and replace the format_spec code with slicing |
|
543 | 543 | def vformat(self, format_string, args, kwargs): |
|
544 | 544 | result = [] |
|
545 | 545 | for literal_text, field_name, format_spec, conversion in \ |
|
546 | 546 | self.parse(format_string): |
|
547 | 547 | |
|
548 | 548 | # output the literal text |
|
549 | 549 | if literal_text: |
|
550 | 550 | result.append(literal_text) |
|
551 | 551 | |
|
552 | 552 | # if there's a field, output it |
|
553 | 553 | if field_name is not None: |
|
554 | 554 | # this is some markup, find the object and do |
|
555 | 555 | # the formatting |
|
556 | 556 | |
|
557 | 557 | if format_spec: |
|
558 | 558 | # override format spec, to allow slicing: |
|
559 | 559 | field_name = ':'.join([field_name, format_spec]) |
|
560 | 560 | |
|
561 | 561 | # eval the contents of the field for the object |
|
562 | 562 | # to be formatted |
|
563 | 563 | obj = eval(field_name, kwargs) |
|
564 | 564 | |
|
565 | 565 | # do any conversion on the resulting object |
|
566 | 566 | obj = self.convert_field(obj, conversion) |
|
567 | 567 | |
|
568 | 568 | # format the object and append to the result |
|
569 | 569 | result.append(self.format_field(obj, '')) |
|
570 | 570 | |
|
571 | 571 | return u''.join(py3compat.cast_unicode(s) for s in result) |
|
572 | 572 | |
|
573 | 573 | |
|
574 | 574 | class DollarFormatter(FullEvalFormatter): |
|
575 | 575 | """Formatter allowing Itpl style $foo replacement, for names and attribute |
|
576 | 576 | access only. Standard {foo} replacement also works, and allows full |
|
577 | 577 | evaluation of its arguments. |
|
578 | 578 | |
|
579 | 579 | Examples |
|
580 | 580 | -------- |
|
581 | 581 | :: |
|
582 | 582 | |
|
583 | 583 | In [1]: f = DollarFormatter() |
|
584 | 584 | In [2]: f.format('{n//4}', n=8) |
|
585 | 585 | Out[2]: '2' |
|
586 | 586 | |
|
587 | 587 | In [3]: f.format('23 * 76 is $result', result=23*76) |
|
588 | 588 | Out[3]: '23 * 76 is 1748' |
|
589 | 589 | |
|
590 | 590 | In [4]: f.format('$a or {b}', a=1, b=2) |
|
591 | 591 | Out[4]: '1 or 2' |
|
592 | 592 | """ |
|
593 | 593 | _dollar_pattern = re.compile("(.*?)\$(\$?[\w\.]+)") |
|
594 | 594 | def parse(self, fmt_string): |
|
595 | 595 | for literal_txt, field_name, format_spec, conversion \ |
|
596 | 596 | in Formatter.parse(self, fmt_string): |
|
597 | 597 | |
|
598 | 598 | # Find $foo patterns in the literal text. |
|
599 | 599 | continue_from = 0 |
|
600 | 600 | txt = "" |
|
601 | 601 | for m in self._dollar_pattern.finditer(literal_txt): |
|
602 | 602 | new_txt, new_field = m.group(1,2) |
|
603 | 603 | # $$foo --> $foo |
|
604 | 604 | if new_field.startswith("$"): |
|
605 | 605 | txt += new_txt + new_field |
|
606 | 606 | else: |
|
607 | 607 | yield (txt + new_txt, new_field, "", None) |
|
608 | 608 | txt = "" |
|
609 | 609 | continue_from = m.end() |
|
610 | 610 | |
|
611 | 611 | # Re-yield the {foo} style pattern |
|
612 | 612 | yield (txt + literal_txt[continue_from:], field_name, format_spec, conversion) |
|
613 | 613 | |
|
614 | 614 | #----------------------------------------------------------------------------- |
|
615 | 615 | # Utils to columnize a list of string |
|
616 | 616 | #----------------------------------------------------------------------------- |
|
617 | 617 | |
|
618 | 618 | def _col_chunks(l, max_rows, row_first=False): |
|
619 | 619 | """Yield successive max_rows-sized column chunks from l.""" |
|
620 | 620 | if row_first: |
|
621 | 621 | ncols = (len(l) // max_rows) + (len(l) % max_rows > 0) |
|
622 |
for i in |
|
|
623 |
yield [l[j] for j in |
|
|
622 | for i in range(ncols): | |
|
623 | yield [l[j] for j in range(i, len(l), ncols)] | |
|
624 | 624 | else: |
|
625 |
for i in |
|
|
625 | for i in range(0, len(l), max_rows): | |
|
626 | 626 | yield l[i:(i + max_rows)] |
|
627 | 627 | |
|
628 | 628 | |
|
629 | 629 | def _find_optimal(rlist, row_first=False, separator_size=2, displaywidth=80): |
|
630 | 630 | """Calculate optimal info to columnize a list of string""" |
|
631 | 631 | for max_rows in range(1, len(rlist) + 1): |
|
632 | 632 | col_widths = list(map(max, _col_chunks(rlist, max_rows, row_first))) |
|
633 | 633 | sumlength = sum(col_widths) |
|
634 | 634 | ncols = len(col_widths) |
|
635 | 635 | if sumlength + separator_size * (ncols - 1) <= displaywidth: |
|
636 | 636 | break |
|
637 | 637 | return {'num_columns': ncols, |
|
638 | 638 | 'optimal_separator_width': (displaywidth - sumlength) // (ncols - 1) if (ncols - 1) else 0, |
|
639 | 639 | 'max_rows': max_rows, |
|
640 | 640 | 'column_widths': col_widths |
|
641 | 641 | } |
|
642 | 642 | |
|
643 | 643 | |
|
644 | 644 | def _get_or_default(mylist, i, default=None): |
|
645 | 645 | """return list item number, or default if don't exist""" |
|
646 | 646 | if i >= len(mylist): |
|
647 | 647 | return default |
|
648 | 648 | else : |
|
649 | 649 | return mylist[i] |
|
650 | 650 | |
|
651 | 651 | |
|
652 | 652 | def compute_item_matrix(items, row_first=False, empty=None, *args, **kwargs) : |
|
653 | 653 | """Returns a nested list, and info to columnize items |
|
654 | 654 | |
|
655 | 655 | Parameters |
|
656 | 656 | ---------- |
|
657 | 657 | |
|
658 | 658 | items |
|
659 | 659 | list of strings to columize |
|
660 | 660 | row_first : (default False) |
|
661 | 661 | Whether to compute columns for a row-first matrix instead of |
|
662 | 662 | column-first (default). |
|
663 | 663 | empty : (default None) |
|
664 | 664 | default value to fill list if needed |
|
665 | 665 | separator_size : int (default=2) |
|
666 | 666 | How much caracters will be used as a separation between each columns. |
|
667 | 667 | displaywidth : int (default=80) |
|
668 | 668 | The width of the area onto wich the columns should enter |
|
669 | 669 | |
|
670 | 670 | Returns |
|
671 | 671 | ------- |
|
672 | 672 | |
|
673 | 673 | strings_matrix |
|
674 | 674 | |
|
675 | 675 | nested list of string, the outer most list contains as many list as |
|
676 | 676 | rows, the innermost lists have each as many element as colums. If the |
|
677 | 677 | total number of elements in `items` does not equal the product of |
|
678 | 678 | rows*columns, the last element of some lists are filled with `None`. |
|
679 | 679 | |
|
680 | 680 | dict_info |
|
681 | 681 | some info to make columnize easier: |
|
682 | 682 | |
|
683 | 683 | num_columns |
|
684 | 684 | number of columns |
|
685 | 685 | max_rows |
|
686 | 686 | maximum number of rows (final number may be less) |
|
687 | 687 | column_widths |
|
688 | 688 | list of with of each columns |
|
689 | 689 | optimal_separator_width |
|
690 | 690 | best separator width between columns |
|
691 | 691 | |
|
692 | 692 | Examples |
|
693 | 693 | -------- |
|
694 | 694 | :: |
|
695 | 695 | |
|
696 | 696 | In [1]: l = ['aaa','b','cc','d','eeeee','f','g','h','i','j','k','l'] |
|
697 | 697 | In [2]: list, info = compute_item_matrix(l, displaywidth=12) |
|
698 | 698 | In [3]: list |
|
699 | 699 | Out[3]: [['aaa', 'f', 'k'], ['b', 'g', 'l'], ['cc', 'h', None], ['d', 'i', None], ['eeeee', 'j', None]] |
|
700 | 700 | In [4]: ideal = {'num_columns': 3, 'column_widths': [5, 1, 1], 'optimal_separator_width': 2, 'max_rows': 5} |
|
701 | 701 | In [5]: all((info[k] == ideal[k] for k in ideal.keys())) |
|
702 | 702 | Out[5]: True |
|
703 | 703 | """ |
|
704 | 704 | info = _find_optimal(list(map(len, items)), row_first, *args, **kwargs) |
|
705 | 705 | nrow, ncol = info['max_rows'], info['num_columns'] |
|
706 | 706 | if row_first: |
|
707 | 707 | return ([[_get_or_default(items, r * ncol + c, default=empty) for c in range(ncol)] for r in range(nrow)], info) |
|
708 | 708 | else: |
|
709 | 709 | return ([[_get_or_default(items, c * nrow + r, default=empty) for c in range(ncol)] for r in range(nrow)], info) |
|
710 | 710 | |
|
711 | 711 | |
|
712 | 712 | def columnize(items, row_first=False, separator=' ', displaywidth=80, spread=False): |
|
713 | 713 | """ Transform a list of strings into a single string with columns. |
|
714 | 714 | |
|
715 | 715 | Parameters |
|
716 | 716 | ---------- |
|
717 | 717 | items : sequence of strings |
|
718 | 718 | The strings to process. |
|
719 | 719 | |
|
720 | 720 | row_first : (default False) |
|
721 | 721 | Whether to compute columns for a row-first matrix instead of |
|
722 | 722 | column-first (default). |
|
723 | 723 | |
|
724 | 724 | separator : str, optional [default is two spaces] |
|
725 | 725 | The string that separates columns. |
|
726 | 726 | |
|
727 | 727 | displaywidth : int, optional [default is 80] |
|
728 | 728 | Width of the display in number of characters. |
|
729 | 729 | |
|
730 | 730 | Returns |
|
731 | 731 | ------- |
|
732 | 732 | The formatted string. |
|
733 | 733 | """ |
|
734 | 734 | if not items: |
|
735 | 735 | return '\n' |
|
736 | 736 | matrix, info = compute_item_matrix(items, row_first=row_first, separator_size=len(separator), displaywidth=displaywidth) |
|
737 | 737 | if spread: |
|
738 | 738 | separator = separator.ljust(int(info['optimal_separator_width'])) |
|
739 | 739 | fmatrix = [filter(None, x) for x in matrix] |
|
740 | 740 | sjoin = lambda x : separator.join([ y.ljust(w, ' ') for y, w in zip(x, info['column_widths'])]) |
|
741 | 741 | return '\n'.join(map(sjoin, fmatrix))+'\n' |
|
742 | 742 | |
|
743 | 743 | |
|
744 | 744 | def get_text_list(list_, last_sep=' and ', sep=", ", wrap_item_with=""): |
|
745 | 745 | """ |
|
746 | 746 | Return a string with a natural enumeration of items |
|
747 | 747 | |
|
748 | 748 | >>> get_text_list(['a', 'b', 'c', 'd']) |
|
749 | 749 | 'a, b, c and d' |
|
750 | 750 | >>> get_text_list(['a', 'b', 'c'], ' or ') |
|
751 | 751 | 'a, b or c' |
|
752 | 752 | >>> get_text_list(['a', 'b', 'c'], ', ') |
|
753 | 753 | 'a, b, c' |
|
754 | 754 | >>> get_text_list(['a', 'b'], ' or ') |
|
755 | 755 | 'a or b' |
|
756 | 756 | >>> get_text_list(['a']) |
|
757 | 757 | 'a' |
|
758 | 758 | >>> get_text_list([]) |
|
759 | 759 | '' |
|
760 | 760 | >>> get_text_list(['a', 'b'], wrap_item_with="`") |
|
761 | 761 | '`a` and `b`' |
|
762 | 762 | >>> get_text_list(['a', 'b', 'c', 'd'], " = ", sep=" + ") |
|
763 | 763 | 'a + b + c = d' |
|
764 | 764 | """ |
|
765 | 765 | if len(list_) == 0: |
|
766 | 766 | return '' |
|
767 | 767 | if wrap_item_with: |
|
768 | 768 | list_ = ['%s%s%s' % (wrap_item_with, item, wrap_item_with) for |
|
769 | 769 | item in list_] |
|
770 | 770 | if len(list_) == 1: |
|
771 | 771 | return list_[0] |
|
772 | 772 | return '%s%s%s' % ( |
|
773 | 773 | sep.join(i for i in list_[:-1]), |
|
774 | 774 | last_sep, list_[-1]) |
@@ -1,118 +1,116 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """ |
|
3 | 3 | Utilities for timing code execution. |
|
4 | 4 | """ |
|
5 | 5 | |
|
6 | 6 | #----------------------------------------------------------------------------- |
|
7 | 7 | # Copyright (C) 2008-2011 The IPython Development Team |
|
8 | 8 | # |
|
9 | 9 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | 10 | # the file COPYING, distributed as part of this software. |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | # Imports |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | |
|
17 | 17 | import time |
|
18 | 18 | |
|
19 | from .py3compat import xrange | |
|
20 | ||
|
21 | 19 | #----------------------------------------------------------------------------- |
|
22 | 20 | # Code |
|
23 | 21 | #----------------------------------------------------------------------------- |
|
24 | 22 | |
|
25 | 23 | # If possible (Unix), use the resource module instead of time.clock() |
|
26 | 24 | try: |
|
27 | 25 | import resource |
|
28 | 26 | def clocku(): |
|
29 | 27 | """clocku() -> floating point number |
|
30 | 28 | |
|
31 | 29 | Return the *USER* CPU time in seconds since the start of the process. |
|
32 | 30 | This is done via a call to resource.getrusage, so it avoids the |
|
33 | 31 | wraparound problems in time.clock().""" |
|
34 | 32 | |
|
35 | 33 | return resource.getrusage(resource.RUSAGE_SELF)[0] |
|
36 | 34 | |
|
37 | 35 | def clocks(): |
|
38 | 36 | """clocks() -> floating point number |
|
39 | 37 | |
|
40 | 38 | Return the *SYSTEM* CPU time in seconds since the start of the process. |
|
41 | 39 | This is done via a call to resource.getrusage, so it avoids the |
|
42 | 40 | wraparound problems in time.clock().""" |
|
43 | 41 | |
|
44 | 42 | return resource.getrusage(resource.RUSAGE_SELF)[1] |
|
45 | 43 | |
|
46 | 44 | def clock(): |
|
47 | 45 | """clock() -> floating point number |
|
48 | 46 | |
|
49 | 47 | Return the *TOTAL USER+SYSTEM* CPU time in seconds since the start of |
|
50 | 48 | the process. This is done via a call to resource.getrusage, so it |
|
51 | 49 | avoids the wraparound problems in time.clock().""" |
|
52 | 50 | |
|
53 | 51 | u,s = resource.getrusage(resource.RUSAGE_SELF)[:2] |
|
54 | 52 | return u+s |
|
55 | 53 | |
|
56 | 54 | def clock2(): |
|
57 | 55 | """clock2() -> (t_user,t_system) |
|
58 | 56 | |
|
59 | 57 | Similar to clock(), but return a tuple of user/system times.""" |
|
60 | 58 | return resource.getrusage(resource.RUSAGE_SELF)[:2] |
|
61 | 59 | except ImportError: |
|
62 | 60 | # There is no distinction of user/system time under windows, so we just use |
|
63 | 61 | # time.clock() for everything... |
|
64 | 62 | clocku = clocks = clock = time.clock |
|
65 | 63 | def clock2(): |
|
66 | 64 | """Under windows, system CPU time can't be measured. |
|
67 | 65 | |
|
68 | 66 | This just returns clock() and zero.""" |
|
69 | 67 | return time.clock(),0.0 |
|
70 | 68 | |
|
71 | 69 | |
|
72 | 70 | def timings_out(reps,func,*args,**kw): |
|
73 | 71 | """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output) |
|
74 | 72 | |
|
75 | 73 | Execute a function reps times, return a tuple with the elapsed total |
|
76 | 74 | CPU time in seconds, the time per call and the function's output. |
|
77 | 75 | |
|
78 | 76 | Under Unix, the return value is the sum of user+system time consumed by |
|
79 | 77 | the process, computed via the resource module. This prevents problems |
|
80 | 78 | related to the wraparound effect which the time.clock() function has. |
|
81 | 79 | |
|
82 | 80 | Under Windows the return value is in wall clock seconds. See the |
|
83 | 81 | documentation for the time module for more details.""" |
|
84 | 82 | |
|
85 | 83 | reps = int(reps) |
|
86 | 84 | assert reps >=1, 'reps must be >= 1' |
|
87 | 85 | if reps==1: |
|
88 | 86 | start = clock() |
|
89 | 87 | out = func(*args,**kw) |
|
90 | 88 | tot_time = clock()-start |
|
91 | 89 | else: |
|
92 |
rng = |
|
|
90 | rng = range(reps-1) # the last time is executed separately to store output | |
|
93 | 91 | start = clock() |
|
94 | 92 | for dummy in rng: func(*args,**kw) |
|
95 | 93 | out = func(*args,**kw) # one last time |
|
96 | 94 | tot_time = clock()-start |
|
97 | 95 | av_time = tot_time / reps |
|
98 | 96 | return tot_time,av_time,out |
|
99 | 97 | |
|
100 | 98 | |
|
101 | 99 | def timings(reps,func,*args,**kw): |
|
102 | 100 | """timings(reps,func,*args,**kw) -> (t_total,t_per_call) |
|
103 | 101 | |
|
104 | 102 | Execute a function reps times, return a tuple with the elapsed total CPU |
|
105 | 103 | time in seconds and the time per call. These are just the first two values |
|
106 | 104 | in timings_out().""" |
|
107 | 105 | |
|
108 | 106 | return timings_out(reps,func,*args,**kw)[0:2] |
|
109 | 107 | |
|
110 | 108 | |
|
111 | 109 | def timing(func,*args,**kw): |
|
112 | 110 | """timing(func,*args,**kw) -> t_total |
|
113 | 111 | |
|
114 | 112 | Execute a function once, return the elapsed total CPU time in |
|
115 | 113 | seconds. This is just the first value in timings_out().""" |
|
116 | 114 | |
|
117 | 115 | return timings_out(1,func,*args,**kw)[0] |
|
118 | 116 |
@@ -1,112 +1,111 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Support for wildcard pattern matching in object inspection. |
|
3 | 3 | |
|
4 | 4 | Authors |
|
5 | 5 | ------- |
|
6 | 6 | - JΓΆrgen Stenarson <jorgen.stenarson@bostream.nu> |
|
7 | 7 | - Thomas Kluyver |
|
8 | 8 | """ |
|
9 | 9 | |
|
10 | 10 | #***************************************************************************** |
|
11 | 11 | # Copyright (C) 2005 JΓΆrgen Stenarson <jorgen.stenarson@bostream.nu> |
|
12 | 12 | # |
|
13 | 13 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | 14 | # the file COPYING, distributed as part of this software. |
|
15 | 15 | #***************************************************************************** |
|
16 | 16 | |
|
17 | 17 | import re |
|
18 | 18 | import types |
|
19 | 19 | |
|
20 | 20 | from IPython.utils.dir2 import dir2 |
|
21 | from .py3compat import iteritems | |
|
22 | 21 | |
|
23 | 22 | def create_typestr2type_dicts(dont_include_in_type2typestr=["lambda"]): |
|
24 | 23 | """Return dictionaries mapping lower case typename (e.g. 'tuple') to type |
|
25 | 24 | objects from the types package, and vice versa.""" |
|
26 | 25 | typenamelist = [tname for tname in dir(types) if tname.endswith("Type")] |
|
27 | 26 | typestr2type, type2typestr = {}, {} |
|
28 | 27 | |
|
29 | 28 | for tname in typenamelist: |
|
30 | 29 | name = tname[:-4].lower() # Cut 'Type' off the end of the name |
|
31 | 30 | obj = getattr(types, tname) |
|
32 | 31 | typestr2type[name] = obj |
|
33 | 32 | if name not in dont_include_in_type2typestr: |
|
34 | 33 | type2typestr[obj] = name |
|
35 | 34 | return typestr2type, type2typestr |
|
36 | 35 | |
|
37 | 36 | typestr2type, type2typestr = create_typestr2type_dicts() |
|
38 | 37 | |
|
39 | 38 | def is_type(obj, typestr_or_type): |
|
40 | 39 | """is_type(obj, typestr_or_type) verifies if obj is of a certain type. It |
|
41 | 40 | can take strings or actual python types for the second argument, i.e. |
|
42 | 41 | 'tuple'<->TupleType. 'all' matches all types. |
|
43 | 42 | |
|
44 | 43 | TODO: Should be extended for choosing more than one type.""" |
|
45 | 44 | if typestr_or_type == "all": |
|
46 | 45 | return True |
|
47 | 46 | if type(typestr_or_type) == type: |
|
48 | 47 | test_type = typestr_or_type |
|
49 | 48 | else: |
|
50 | 49 | test_type = typestr2type.get(typestr_or_type, False) |
|
51 | 50 | if test_type: |
|
52 | 51 | return isinstance(obj, test_type) |
|
53 | 52 | return False |
|
54 | 53 | |
|
55 | 54 | def show_hidden(str, show_all=False): |
|
56 | 55 | """Return true for strings starting with single _ if show_all is true.""" |
|
57 | 56 | return show_all or str.startswith("__") or not str.startswith("_") |
|
58 | 57 | |
|
59 | 58 | def dict_dir(obj): |
|
60 | 59 | """Produce a dictionary of an object's attributes. Builds on dir2 by |
|
61 | 60 | checking that a getattr() call actually succeeds.""" |
|
62 | 61 | ns = {} |
|
63 | 62 | for key in dir2(obj): |
|
64 | 63 | # This seemingly unnecessary try/except is actually needed |
|
65 | 64 | # because there is code out there with metaclasses that |
|
66 | 65 | # create 'write only' attributes, where a getattr() call |
|
67 | 66 | # will fail even if the attribute appears listed in the |
|
68 | 67 | # object's dictionary. Properties can actually do the same |
|
69 | 68 | # thing. In particular, Traits use this pattern |
|
70 | 69 | try: |
|
71 | 70 | ns[key] = getattr(obj, key) |
|
72 | 71 | except AttributeError: |
|
73 | 72 | pass |
|
74 | 73 | return ns |
|
75 | 74 | |
|
76 | 75 | def filter_ns(ns, name_pattern="*", type_pattern="all", ignore_case=True, |
|
77 | 76 | show_all=True): |
|
78 | 77 | """Filter a namespace dictionary by name pattern and item type.""" |
|
79 | 78 | pattern = name_pattern.replace("*",".*").replace("?",".") |
|
80 | 79 | if ignore_case: |
|
81 | 80 | reg = re.compile(pattern+"$", re.I) |
|
82 | 81 | else: |
|
83 | 82 | reg = re.compile(pattern+"$") |
|
84 | 83 | |
|
85 | 84 | # Check each one matches regex; shouldn't be hidden; of correct type. |
|
86 |
return dict((key,obj) for key, obj in |
|
|
85 | return dict((key,obj) for key, obj in ns.items() if reg.match(key) \ | |
|
87 | 86 | and show_hidden(key, show_all) \ |
|
88 | 87 | and is_type(obj, type_pattern) ) |
|
89 | 88 | |
|
90 | 89 | def list_namespace(namespace, type_pattern, filter, ignore_case=False, show_all=False): |
|
91 | 90 | """Return dictionary of all objects in a namespace dictionary that match |
|
92 | 91 | type_pattern and filter.""" |
|
93 | 92 | pattern_list=filter.split(".") |
|
94 | 93 | if len(pattern_list) == 1: |
|
95 | 94 | return filter_ns(namespace, name_pattern=pattern_list[0], |
|
96 | 95 | type_pattern=type_pattern, |
|
97 | 96 | ignore_case=ignore_case, show_all=show_all) |
|
98 | 97 | else: |
|
99 | 98 | # This is where we can change if all objects should be searched or |
|
100 | 99 | # only modules. Just change the type_pattern to module to search only |
|
101 | 100 | # modules |
|
102 | 101 | filtered = filter_ns(namespace, name_pattern=pattern_list[0], |
|
103 | 102 | type_pattern="all", |
|
104 | 103 | ignore_case=ignore_case, show_all=show_all) |
|
105 | 104 | results = {} |
|
106 |
for name, obj in iteritems( |
|
|
105 | for name, obj in filtered.items(): | |
|
107 | 106 | ns = list_namespace(dict_dir(obj), type_pattern, |
|
108 | 107 | ".".join(pattern_list[1:]), |
|
109 | 108 | ignore_case=ignore_case, show_all=show_all) |
|
110 |
for inner_name, inner_obj in |
|
|
109 | for inner_name, inner_obj in ns.items(): | |
|
111 | 110 | results["%s.%s"%(name,inner_name)] = inner_obj |
|
112 | 111 | return results |
General Comments 0
You need to be logged in to leave comments.
Login now