Show More
@@ -1,1380 +1,1374 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 | |
|
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 | from io import StringIO | |
|
48 | 49 | |
|
49 | if PY3: | |
|
50 | from io import StringIO | |
|
51 | else: | |
|
52 | from StringIO import StringIO | |
|
53 | 50 | |
|
54 | 51 | #----------------------------------------------------------------------------- |
|
55 | 52 | # Magic implementation classes |
|
56 | 53 | #----------------------------------------------------------------------------- |
|
57 | 54 | |
|
58 | 55 | |
|
59 | 56 | class TimeitResult(object): |
|
60 | 57 | """ |
|
61 | 58 | Object returned by the timeit magic with info about the run. |
|
62 | 59 | |
|
63 | 60 | Contains the following attributes : |
|
64 | 61 | |
|
65 | 62 | loops: (int) number of loops done per measurement |
|
66 | 63 | repeat: (int) number of times the measurement has been repeated |
|
67 | 64 | best: (float) best execution time / number |
|
68 | 65 | all_runs: (list of float) execution time of each run (in s) |
|
69 | 66 | compile_time: (float) time of statement compilation (s) |
|
70 | 67 | |
|
71 | 68 | """ |
|
72 | 69 | def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision): |
|
73 | 70 | self.loops = loops |
|
74 | 71 | self.repeat = repeat |
|
75 | 72 | self.best = best |
|
76 | 73 | self.worst = worst |
|
77 | 74 | self.all_runs = all_runs |
|
78 | 75 | self.compile_time = compile_time |
|
79 | 76 | self._precision = precision |
|
80 | 77 | self.timings = [ dt / self.loops for dt in all_runs] |
|
81 | 78 | |
|
82 | 79 | @property |
|
83 | 80 | def average(self): |
|
84 | 81 | return math.fsum(self.timings) / len(self.timings) |
|
85 | 82 | |
|
86 | 83 | @property |
|
87 | 84 | def stdev(self): |
|
88 | 85 | mean = self.average |
|
89 | 86 | return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5 |
|
90 | 87 | |
|
91 | 88 | def __str__(self): |
|
92 | 89 | return (u"%s loop%s, average of %d: %s +- %s per loop (using standard deviation)" |
|
93 | 90 | % (self.loops,"" if self.loops == 1 else "s", self.repeat, |
|
94 | 91 | _format_time(self.average, self._precision), |
|
95 | 92 | _format_time(self.stdev, self._precision))) |
|
96 | 93 | |
|
97 | 94 | def _repr_pretty_(self, p , cycle): |
|
98 | 95 | unic = self.__str__() |
|
99 | 96 | p.text(u'<TimeitResult : '+unic+u'>') |
|
100 | 97 | |
|
101 | 98 | |
|
102 | 99 | |
|
103 | 100 | class TimeitTemplateFiller(ast.NodeTransformer): |
|
104 | 101 | """Fill in the AST template for timing execution. |
|
105 | 102 | |
|
106 | 103 | This is quite closely tied to the template definition, which is in |
|
107 | 104 | :meth:`ExecutionMagics.timeit`. |
|
108 | 105 | """ |
|
109 | 106 | def __init__(self, ast_setup, ast_stmt): |
|
110 | 107 | self.ast_setup = ast_setup |
|
111 | 108 | self.ast_stmt = ast_stmt |
|
112 | 109 | |
|
113 | 110 | def visit_FunctionDef(self, node): |
|
114 | 111 | "Fill in the setup statement" |
|
115 | 112 | self.generic_visit(node) |
|
116 | 113 | if node.name == "inner": |
|
117 | 114 | node.body[:1] = self.ast_setup.body |
|
118 | 115 | |
|
119 | 116 | return node |
|
120 | 117 | |
|
121 | 118 | def visit_For(self, node): |
|
122 | 119 | "Fill in the statement to be timed" |
|
123 | 120 | if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt': |
|
124 | 121 | node.body = self.ast_stmt.body |
|
125 | 122 | return node |
|
126 | 123 | |
|
127 | 124 | |
|
128 | 125 | class Timer(timeit.Timer): |
|
129 | 126 | """Timer class that explicitly uses self.inner |
|
130 | 127 | |
|
131 | 128 | which is an undocumented implementation detail of CPython, |
|
132 | 129 | not shared by PyPy. |
|
133 | 130 | """ |
|
134 | 131 | # Timer.timeit copied from CPython 3.4.2 |
|
135 | 132 | def timeit(self, number=timeit.default_number): |
|
136 | 133 | """Time 'number' executions of the main statement. |
|
137 | 134 | |
|
138 | 135 | To be precise, this executes the setup statement once, and |
|
139 | 136 | then returns the time it takes to execute the main statement |
|
140 | 137 | a number of times, as a float measured in seconds. The |
|
141 | 138 | argument is the number of times through the loop, defaulting |
|
142 | 139 | to one million. The main statement, the setup statement and |
|
143 | 140 | the timer function to be used are passed to the constructor. |
|
144 | 141 | """ |
|
145 | 142 | it = itertools.repeat(None, number) |
|
146 | 143 | gcold = gc.isenabled() |
|
147 | 144 | gc.disable() |
|
148 | 145 | try: |
|
149 | 146 | timing = self.inner(it, self.timer) |
|
150 | 147 | finally: |
|
151 | 148 | if gcold: |
|
152 | 149 | gc.enable() |
|
153 | 150 | return timing |
|
154 | 151 | |
|
155 | 152 | |
|
156 | 153 | @magics_class |
|
157 | 154 | class ExecutionMagics(Magics): |
|
158 | 155 | """Magics related to code execution, debugging, profiling, etc. |
|
159 | 156 | |
|
160 | 157 | """ |
|
161 | 158 | |
|
162 | 159 | def __init__(self, shell): |
|
163 | 160 | super(ExecutionMagics, self).__init__(shell) |
|
164 | 161 | if profile is None: |
|
165 | 162 | self.prun = self.profile_missing_notice |
|
166 | 163 | # Default execution function used to actually run user code. |
|
167 | 164 | self.default_runner = None |
|
168 | 165 | |
|
169 | 166 | def profile_missing_notice(self, *args, **kwargs): |
|
170 | 167 | error("""\ |
|
171 | 168 | The profile module could not be found. It has been removed from the standard |
|
172 | 169 | python packages because of its non-free license. To use profiling, install the |
|
173 | 170 | python-profiler package from non-free.""") |
|
174 | 171 | |
|
175 | 172 | @skip_doctest |
|
176 | 173 | @line_cell_magic |
|
177 | 174 | def prun(self, parameter_s='', cell=None): |
|
178 | 175 | |
|
179 | 176 | """Run a statement through the python code profiler. |
|
180 | 177 | |
|
181 | 178 | Usage, in line mode: |
|
182 | 179 | %prun [options] statement |
|
183 | 180 | |
|
184 | 181 | Usage, in cell mode: |
|
185 | 182 | %%prun [options] [statement] |
|
186 | 183 | code... |
|
187 | 184 | code... |
|
188 | 185 | |
|
189 | 186 | In cell mode, the additional code lines are appended to the (possibly |
|
190 | 187 | empty) statement in the first line. Cell mode allows you to easily |
|
191 | 188 | profile multiline blocks without having to put them in a separate |
|
192 | 189 | function. |
|
193 | 190 | |
|
194 | 191 | The given statement (which doesn't require quote marks) is run via the |
|
195 | 192 | python profiler in a manner similar to the profile.run() function. |
|
196 | 193 | Namespaces are internally managed to work correctly; profile.run |
|
197 | 194 | cannot be used in IPython because it makes certain assumptions about |
|
198 | 195 | namespaces which do not hold under IPython. |
|
199 | 196 | |
|
200 | 197 | Options: |
|
201 | 198 | |
|
202 | 199 | -l <limit> |
|
203 | 200 | you can place restrictions on what or how much of the |
|
204 | 201 | profile gets printed. The limit value can be: |
|
205 | 202 | |
|
206 | 203 | * A string: only information for function names containing this string |
|
207 | 204 | is printed. |
|
208 | 205 | |
|
209 | 206 | * An integer: only these many lines are printed. |
|
210 | 207 | |
|
211 | 208 | * A float (between 0 and 1): this fraction of the report is printed |
|
212 | 209 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
213 | 210 | |
|
214 | 211 | You can combine several limits with repeated use of the option. For |
|
215 | 212 | example, ``-l __init__ -l 5`` will print only the topmost 5 lines of |
|
216 | 213 | information about class constructors. |
|
217 | 214 | |
|
218 | 215 | -r |
|
219 | 216 | return the pstats.Stats object generated by the profiling. This |
|
220 | 217 | object has all the information about the profile in it, and you can |
|
221 | 218 | later use it for further analysis or in other functions. |
|
222 | 219 | |
|
223 | 220 | -s <key> |
|
224 | 221 | sort profile by given key. You can provide more than one key |
|
225 | 222 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
226 | 223 | default sorting key is 'time'. |
|
227 | 224 | |
|
228 | 225 | The following is copied verbatim from the profile documentation |
|
229 | 226 | referenced below: |
|
230 | 227 | |
|
231 | 228 | When more than one key is provided, additional keys are used as |
|
232 | 229 | secondary criteria when the there is equality in all keys selected |
|
233 | 230 | before them. |
|
234 | 231 | |
|
235 | 232 | Abbreviations can be used for any key names, as long as the |
|
236 | 233 | abbreviation is unambiguous. The following are the keys currently |
|
237 | 234 | defined: |
|
238 | 235 | |
|
239 | 236 | ============ ===================== |
|
240 | 237 | Valid Arg Meaning |
|
241 | 238 | ============ ===================== |
|
242 | 239 | "calls" call count |
|
243 | 240 | "cumulative" cumulative time |
|
244 | 241 | "file" file name |
|
245 | 242 | "module" file name |
|
246 | 243 | "pcalls" primitive call count |
|
247 | 244 | "line" line number |
|
248 | 245 | "name" function name |
|
249 | 246 | "nfl" name/file/line |
|
250 | 247 | "stdname" standard name |
|
251 | 248 | "time" internal time |
|
252 | 249 | ============ ===================== |
|
253 | 250 | |
|
254 | 251 | Note that all sorts on statistics are in descending order (placing |
|
255 | 252 | most time consuming items first), where as name, file, and line number |
|
256 | 253 | searches are in ascending order (i.e., alphabetical). The subtle |
|
257 | 254 | distinction between "nfl" and "stdname" is that the standard name is a |
|
258 | 255 | sort of the name as printed, which means that the embedded line |
|
259 | 256 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
260 | 257 | would (if the file names were the same) appear in the string order |
|
261 | 258 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
262 | 259 | line numbers. In fact, sort_stats("nfl") is the same as |
|
263 | 260 | sort_stats("name", "file", "line"). |
|
264 | 261 | |
|
265 | 262 | -T <filename> |
|
266 | 263 | save profile results as shown on screen to a text |
|
267 | 264 | file. The profile is still shown on screen. |
|
268 | 265 | |
|
269 | 266 | -D <filename> |
|
270 | 267 | save (via dump_stats) profile statistics to given |
|
271 | 268 | filename. This data is in a format understood by the pstats module, and |
|
272 | 269 | is generated by a call to the dump_stats() method of profile |
|
273 | 270 | objects. The profile is still shown on screen. |
|
274 | 271 | |
|
275 | 272 | -q |
|
276 | 273 | suppress output to the pager. Best used with -T and/or -D above. |
|
277 | 274 | |
|
278 | 275 | If you want to run complete programs under the profiler's control, use |
|
279 | 276 | ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts |
|
280 | 277 | contains profiler specific options as described here. |
|
281 | 278 | |
|
282 | 279 | You can read the complete documentation for the profile module with:: |
|
283 | 280 | |
|
284 | 281 | In [1]: import profile; profile.help() |
|
285 | 282 | """ |
|
286 | 283 | opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q', |
|
287 | 284 | list_all=True, posix=False) |
|
288 | 285 | if cell is not None: |
|
289 | 286 | arg_str += '\n' + cell |
|
290 | 287 | arg_str = self.shell.input_splitter.transform_cell(arg_str) |
|
291 | 288 | return self._run_with_profiler(arg_str, opts, self.shell.user_ns) |
|
292 | 289 | |
|
293 | 290 | def _run_with_profiler(self, code, opts, namespace): |
|
294 | 291 | """ |
|
295 | 292 | Run `code` with profiler. Used by ``%prun`` and ``%run -p``. |
|
296 | 293 | |
|
297 | 294 | Parameters |
|
298 | 295 | ---------- |
|
299 | 296 | code : str |
|
300 | 297 | Code to be executed. |
|
301 | 298 | opts : Struct |
|
302 | 299 | Options parsed by `self.parse_options`. |
|
303 | 300 | namespace : dict |
|
304 | 301 | A dictionary for Python namespace (e.g., `self.shell.user_ns`). |
|
305 | 302 | |
|
306 | 303 | """ |
|
307 | 304 | |
|
308 | 305 | # Fill default values for unspecified options: |
|
309 | 306 | opts.merge(Struct(D=[''], l=[], s=['time'], T=[''])) |
|
310 | 307 | |
|
311 | 308 | prof = profile.Profile() |
|
312 | 309 | try: |
|
313 | 310 | prof = prof.runctx(code, namespace, namespace) |
|
314 | 311 | sys_exit = '' |
|
315 | 312 | except SystemExit: |
|
316 | 313 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
317 | 314 | |
|
318 | 315 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
319 | 316 | |
|
320 | 317 | lims = opts.l |
|
321 | 318 | if lims: |
|
322 | 319 | lims = [] # rebuild lims with ints/floats/strings |
|
323 | 320 | for lim in opts.l: |
|
324 | 321 | try: |
|
325 | 322 | lims.append(int(lim)) |
|
326 | 323 | except ValueError: |
|
327 | 324 | try: |
|
328 | 325 | lims.append(float(lim)) |
|
329 | 326 | except ValueError: |
|
330 | 327 | lims.append(lim) |
|
331 | 328 | |
|
332 | 329 | # Trap output. |
|
333 | 330 | stdout_trap = StringIO() |
|
334 | 331 | stats_stream = stats.stream |
|
335 | 332 | try: |
|
336 | 333 | stats.stream = stdout_trap |
|
337 | 334 | stats.print_stats(*lims) |
|
338 | 335 | finally: |
|
339 | 336 | stats.stream = stats_stream |
|
340 | 337 | |
|
341 | 338 | output = stdout_trap.getvalue() |
|
342 | 339 | output = output.rstrip() |
|
343 | 340 | |
|
344 | 341 | if 'q' not in opts: |
|
345 | 342 | page.page(output) |
|
346 | 343 | print(sys_exit, end=' ') |
|
347 | 344 | |
|
348 | 345 | dump_file = opts.D[0] |
|
349 | 346 | text_file = opts.T[0] |
|
350 | 347 | if dump_file: |
|
351 | 348 | prof.dump_stats(dump_file) |
|
352 | 349 | print('\n*** Profile stats marshalled to file',\ |
|
353 | 350 | repr(dump_file)+'.',sys_exit) |
|
354 | 351 | if text_file: |
|
355 | 352 | pfile = open(text_file,'w') |
|
356 | 353 | pfile.write(output) |
|
357 | 354 | pfile.close() |
|
358 | 355 | print('\n*** Profile printout saved to text file',\ |
|
359 | 356 | repr(text_file)+'.',sys_exit) |
|
360 | 357 | |
|
361 | 358 | if 'r' in opts: |
|
362 | 359 | return stats |
|
363 | 360 | else: |
|
364 | 361 | return None |
|
365 | 362 | |
|
366 | 363 | @line_magic |
|
367 | 364 | def pdb(self, parameter_s=''): |
|
368 | 365 | """Control the automatic calling of the pdb interactive debugger. |
|
369 | 366 | |
|
370 | 367 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
371 | 368 | argument it works as a toggle. |
|
372 | 369 | |
|
373 | 370 | When an exception is triggered, IPython can optionally call the |
|
374 | 371 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
375 | 372 | this feature on and off. |
|
376 | 373 | |
|
377 | 374 | The initial state of this feature is set in your configuration |
|
378 | 375 | file (the option is ``InteractiveShell.pdb``). |
|
379 | 376 | |
|
380 | 377 | If you want to just activate the debugger AFTER an exception has fired, |
|
381 | 378 | without having to type '%pdb on' and rerunning your code, you can use |
|
382 | 379 | the %debug magic.""" |
|
383 | 380 | |
|
384 | 381 | par = parameter_s.strip().lower() |
|
385 | 382 | |
|
386 | 383 | if par: |
|
387 | 384 | try: |
|
388 | 385 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
389 | 386 | except KeyError: |
|
390 | 387 | print ('Incorrect argument. Use on/1, off/0, ' |
|
391 | 388 | 'or nothing for a toggle.') |
|
392 | 389 | return |
|
393 | 390 | else: |
|
394 | 391 | # toggle |
|
395 | 392 | new_pdb = not self.shell.call_pdb |
|
396 | 393 | |
|
397 | 394 | # set on the shell |
|
398 | 395 | self.shell.call_pdb = new_pdb |
|
399 | 396 | print('Automatic pdb calling has been turned',on_off(new_pdb)) |
|
400 | 397 | |
|
401 | 398 | @skip_doctest |
|
402 | 399 | @magic_arguments.magic_arguments() |
|
403 | 400 | @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE', |
|
404 | 401 | help=""" |
|
405 | 402 | Set break point at LINE in FILE. |
|
406 | 403 | """ |
|
407 | 404 | ) |
|
408 | 405 | @magic_arguments.argument('statement', nargs='*', |
|
409 | 406 | help=""" |
|
410 | 407 | Code to run in debugger. |
|
411 | 408 | You can omit this in cell magic mode. |
|
412 | 409 | """ |
|
413 | 410 | ) |
|
414 | 411 | @line_cell_magic |
|
415 | 412 | def debug(self, line='', cell=None): |
|
416 | 413 | """Activate the interactive debugger. |
|
417 | 414 | |
|
418 | 415 | This magic command support two ways of activating debugger. |
|
419 | 416 | One is to activate debugger before executing code. This way, you |
|
420 | 417 | can set a break point, to step through the code from the point. |
|
421 | 418 | You can use this mode by giving statements to execute and optionally |
|
422 | 419 | a breakpoint. |
|
423 | 420 | |
|
424 | 421 | The other one is to activate debugger in post-mortem mode. You can |
|
425 | 422 | activate this mode simply running %debug without any argument. |
|
426 | 423 | If an exception has just occurred, this lets you inspect its stack |
|
427 | 424 | frames interactively. Note that this will always work only on the last |
|
428 | 425 | traceback that occurred, so you must call this quickly after an |
|
429 | 426 | exception that you wish to inspect has fired, because if another one |
|
430 | 427 | occurs, it clobbers the previous one. |
|
431 | 428 | |
|
432 | 429 | If you want IPython to automatically do this on every exception, see |
|
433 | 430 | the %pdb magic for more details. |
|
434 | 431 | """ |
|
435 | 432 | args = magic_arguments.parse_argstring(self.debug, line) |
|
436 | 433 | |
|
437 | 434 | if not (args.breakpoint or args.statement or cell): |
|
438 | 435 | self._debug_post_mortem() |
|
439 | 436 | else: |
|
440 | 437 | code = "\n".join(args.statement) |
|
441 | 438 | if cell: |
|
442 | 439 | code += "\n" + cell |
|
443 | 440 | self._debug_exec(code, args.breakpoint) |
|
444 | 441 | |
|
445 | 442 | def _debug_post_mortem(self): |
|
446 | 443 | self.shell.debugger(force=True) |
|
447 | 444 | |
|
448 | 445 | def _debug_exec(self, code, breakpoint): |
|
449 | 446 | if breakpoint: |
|
450 | 447 | (filename, bp_line) = breakpoint.rsplit(':', 1) |
|
451 | 448 | bp_line = int(bp_line) |
|
452 | 449 | else: |
|
453 | 450 | (filename, bp_line) = (None, None) |
|
454 | 451 | self._run_with_debugger(code, self.shell.user_ns, filename, bp_line) |
|
455 | 452 | |
|
456 | 453 | @line_magic |
|
457 | 454 | def tb(self, s): |
|
458 | 455 | """Print the last traceback with the currently active exception mode. |
|
459 | 456 | |
|
460 | 457 | See %xmode for changing exception reporting modes.""" |
|
461 | 458 | self.shell.showtraceback() |
|
462 | 459 | |
|
463 | 460 | @skip_doctest |
|
464 | 461 | @line_magic |
|
465 | 462 | def run(self, parameter_s='', runner=None, |
|
466 | 463 | file_finder=get_py_filename): |
|
467 | 464 | """Run the named file inside IPython as a program. |
|
468 | 465 | |
|
469 | 466 | Usage:: |
|
470 | 467 | |
|
471 | 468 | %run [-n -i -e -G] |
|
472 | 469 | [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )] |
|
473 | 470 | ( -m mod | file ) [args] |
|
474 | 471 | |
|
475 | 472 | Parameters after the filename are passed as command-line arguments to |
|
476 | 473 | the program (put in sys.argv). Then, control returns to IPython's |
|
477 | 474 | prompt. |
|
478 | 475 | |
|
479 | 476 | This is similar to running at a system prompt ``python file args``, |
|
480 | 477 | but with the advantage of giving you IPython's tracebacks, and of |
|
481 | 478 | loading all variables into your interactive namespace for further use |
|
482 | 479 | (unless -p is used, see below). |
|
483 | 480 | |
|
484 | 481 | The file is executed in a namespace initially consisting only of |
|
485 | 482 | ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus |
|
486 | 483 | sees its environment as if it were being run as a stand-alone program |
|
487 | 484 | (except for sharing global objects such as previously imported |
|
488 | 485 | modules). But after execution, the IPython interactive namespace gets |
|
489 | 486 | updated with all variables defined in the program (except for __name__ |
|
490 | 487 | and sys.argv). This allows for very convenient loading of code for |
|
491 | 488 | interactive work, while giving each program a 'clean sheet' to run in. |
|
492 | 489 | |
|
493 | 490 | Arguments are expanded using shell-like glob match. Patterns |
|
494 | 491 | '*', '?', '[seq]' and '[!seq]' can be used. Additionally, |
|
495 | 492 | tilde '~' will be expanded into user's home directory. Unlike |
|
496 | 493 | real shells, quotation does not suppress expansions. Use |
|
497 | 494 | *two* back slashes (e.g. ``\\\\*``) to suppress expansions. |
|
498 | 495 | To completely disable these expansions, you can use -G flag. |
|
499 | 496 | |
|
500 | 497 | Options: |
|
501 | 498 | |
|
502 | 499 | -n |
|
503 | 500 | __name__ is NOT set to '__main__', but to the running file's name |
|
504 | 501 | without extension (as python does under import). This allows running |
|
505 | 502 | scripts and reloading the definitions in them without calling code |
|
506 | 503 | protected by an ``if __name__ == "__main__"`` clause. |
|
507 | 504 | |
|
508 | 505 | -i |
|
509 | 506 | run the file in IPython's namespace instead of an empty one. This |
|
510 | 507 | is useful if you are experimenting with code written in a text editor |
|
511 | 508 | which depends on variables defined interactively. |
|
512 | 509 | |
|
513 | 510 | -e |
|
514 | 511 | ignore sys.exit() calls or SystemExit exceptions in the script |
|
515 | 512 | being run. This is particularly useful if IPython is being used to |
|
516 | 513 | run unittests, which always exit with a sys.exit() call. In such |
|
517 | 514 | cases you are interested in the output of the test results, not in |
|
518 | 515 | seeing a traceback of the unittest module. |
|
519 | 516 | |
|
520 | 517 | -t |
|
521 | 518 | print timing information at the end of the run. IPython will give |
|
522 | 519 | you an estimated CPU time consumption for your script, which under |
|
523 | 520 | Unix uses the resource module to avoid the wraparound problems of |
|
524 | 521 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
525 | 522 | is also given (for Windows platforms this is reported as 0.0). |
|
526 | 523 | |
|
527 | 524 | If -t is given, an additional ``-N<N>`` option can be given, where <N> |
|
528 | 525 | must be an integer indicating how many times you want the script to |
|
529 | 526 | run. The final timing report will include total and per run results. |
|
530 | 527 | |
|
531 | 528 | For example (testing the script uniq_stable.py):: |
|
532 | 529 | |
|
533 | 530 | In [1]: run -t uniq_stable |
|
534 | 531 | |
|
535 | 532 | IPython CPU timings (estimated): |
|
536 | 533 | User : 0.19597 s. |
|
537 | 534 | System: 0.0 s. |
|
538 | 535 | |
|
539 | 536 | In [2]: run -t -N5 uniq_stable |
|
540 | 537 | |
|
541 | 538 | IPython CPU timings (estimated): |
|
542 | 539 | Total runs performed: 5 |
|
543 | 540 | Times : Total Per run |
|
544 | 541 | User : 0.910862 s, 0.1821724 s. |
|
545 | 542 | System: 0.0 s, 0.0 s. |
|
546 | 543 | |
|
547 | 544 | -d |
|
548 | 545 | run your program under the control of pdb, the Python debugger. |
|
549 | 546 | This allows you to execute your program step by step, watch variables, |
|
550 | 547 | etc. Internally, what IPython does is similar to calling:: |
|
551 | 548 | |
|
552 | 549 | pdb.run('execfile("YOURFILENAME")') |
|
553 | 550 | |
|
554 | 551 | with a breakpoint set on line 1 of your file. You can change the line |
|
555 | 552 | number for this automatic breakpoint to be <N> by using the -bN option |
|
556 | 553 | (where N must be an integer). For example:: |
|
557 | 554 | |
|
558 | 555 | %run -d -b40 myscript |
|
559 | 556 | |
|
560 | 557 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
561 | 558 | the first breakpoint must be set on a line which actually does |
|
562 | 559 | something (not a comment or docstring) for it to stop execution. |
|
563 | 560 | |
|
564 | 561 | Or you can specify a breakpoint in a different file:: |
|
565 | 562 | |
|
566 | 563 | %run -d -b myotherfile.py:20 myscript |
|
567 | 564 | |
|
568 | 565 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
569 | 566 | first enter 'c' (without quotes) to start execution up to the first |
|
570 | 567 | breakpoint. |
|
571 | 568 | |
|
572 | 569 | Entering 'help' gives information about the use of the debugger. You |
|
573 | 570 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
574 | 571 | at a prompt. |
|
575 | 572 | |
|
576 | 573 | -p |
|
577 | 574 | run program under the control of the Python profiler module (which |
|
578 | 575 | prints a detailed report of execution times, function calls, etc). |
|
579 | 576 | |
|
580 | 577 | You can pass other options after -p which affect the behavior of the |
|
581 | 578 | profiler itself. See the docs for %prun for details. |
|
582 | 579 | |
|
583 | 580 | In this mode, the program's variables do NOT propagate back to the |
|
584 | 581 | IPython interactive namespace (because they remain in the namespace |
|
585 | 582 | where the profiler executes them). |
|
586 | 583 | |
|
587 | 584 | Internally this triggers a call to %prun, see its documentation for |
|
588 | 585 | details on the options available specifically for profiling. |
|
589 | 586 | |
|
590 | 587 | There is one special usage for which the text above doesn't apply: |
|
591 | 588 | if the filename ends with .ipy[nb], the file is run as ipython script, |
|
592 | 589 | just as if the commands were written on IPython prompt. |
|
593 | 590 | |
|
594 | 591 | -m |
|
595 | 592 | specify module name to load instead of script path. Similar to |
|
596 | 593 | the -m option for the python interpreter. Use this option last if you |
|
597 | 594 | want to combine with other %run options. Unlike the python interpreter |
|
598 | 595 | only source modules are allowed no .pyc or .pyo files. |
|
599 | 596 | For example:: |
|
600 | 597 | |
|
601 | 598 | %run -m example |
|
602 | 599 | |
|
603 | 600 | will run the example module. |
|
604 | 601 | |
|
605 | 602 | -G |
|
606 | 603 | disable shell-like glob expansion of arguments. |
|
607 | 604 | |
|
608 | 605 | """ |
|
609 | 606 | |
|
610 | 607 | # get arguments and set sys.argv for program to be run. |
|
611 | 608 | opts, arg_lst = self.parse_options(parameter_s, |
|
612 | 609 | 'nidtN:b:pD:l:rs:T:em:G', |
|
613 | 610 | mode='list', list_all=1) |
|
614 | 611 | if "m" in opts: |
|
615 | 612 | modulename = opts["m"][0] |
|
616 | 613 | modpath = find_mod(modulename) |
|
617 | 614 | if modpath is None: |
|
618 | 615 | warn('%r is not a valid modulename on sys.path'%modulename) |
|
619 | 616 | return |
|
620 | 617 | arg_lst = [modpath] + arg_lst |
|
621 | 618 | try: |
|
622 | 619 | filename = file_finder(arg_lst[0]) |
|
623 | 620 | except IndexError: |
|
624 | 621 | warn('you must provide at least a filename.') |
|
625 | 622 | print('\n%run:\n', oinspect.getdoc(self.run)) |
|
626 | 623 | return |
|
627 | 624 | except IOError as e: |
|
628 | 625 | try: |
|
629 | 626 | msg = str(e) |
|
630 | 627 | except UnicodeError: |
|
631 | 628 | msg = e.message |
|
632 | 629 | error(msg) |
|
633 | 630 | return |
|
634 | 631 | |
|
635 | 632 | if filename.lower().endswith(('.ipy', '.ipynb')): |
|
636 | 633 | with preserve_keys(self.shell.user_ns, '__file__'): |
|
637 | 634 | self.shell.user_ns['__file__'] = filename |
|
638 | 635 | self.shell.safe_execfile_ipy(filename) |
|
639 | 636 | return |
|
640 | 637 | |
|
641 | 638 | # Control the response to exit() calls made by the script being run |
|
642 | 639 | exit_ignore = 'e' in opts |
|
643 | 640 | |
|
644 | 641 | # Make sure that the running script gets a proper sys.argv as if it |
|
645 | 642 | # were run from a system shell. |
|
646 | 643 | save_argv = sys.argv # save it for later restoring |
|
647 | 644 | |
|
648 | 645 | if 'G' in opts: |
|
649 | 646 | args = arg_lst[1:] |
|
650 | 647 | else: |
|
651 | 648 | # tilde and glob expansion |
|
652 | 649 | args = shellglob(map(os.path.expanduser, arg_lst[1:])) |
|
653 | 650 | |
|
654 | 651 | sys.argv = [filename] + args # put in the proper filename |
|
655 | # protect sys.argv from potential unicode strings on Python 2: | |
|
656 | if not py3compat.PY3: | |
|
657 | sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ] | |
|
658 | 652 | |
|
659 | 653 | if 'i' in opts: |
|
660 | 654 | # Run in user's interactive namespace |
|
661 | 655 | prog_ns = self.shell.user_ns |
|
662 | 656 | __name__save = self.shell.user_ns['__name__'] |
|
663 | 657 | prog_ns['__name__'] = '__main__' |
|
664 | 658 | main_mod = self.shell.user_module |
|
665 | 659 | |
|
666 | 660 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
667 | 661 | # set the __file__ global in the script's namespace |
|
668 | 662 | # TK: Is this necessary in interactive mode? |
|
669 | 663 | prog_ns['__file__'] = filename |
|
670 | 664 | else: |
|
671 | 665 | # Run in a fresh, empty namespace |
|
672 | 666 | if 'n' in opts: |
|
673 | 667 | name = os.path.splitext(os.path.basename(filename))[0] |
|
674 | 668 | else: |
|
675 | 669 | name = '__main__' |
|
676 | 670 | |
|
677 | 671 | # The shell MUST hold a reference to prog_ns so after %run |
|
678 | 672 | # exits, the python deletion mechanism doesn't zero it out |
|
679 | 673 | # (leaving dangling references). See interactiveshell for details |
|
680 | 674 | main_mod = self.shell.new_main_mod(filename, name) |
|
681 | 675 | prog_ns = main_mod.__dict__ |
|
682 | 676 | |
|
683 | 677 | # pickle fix. See interactiveshell for an explanation. But we need to |
|
684 | 678 | # make sure that, if we overwrite __main__, we replace it at the end |
|
685 | 679 | main_mod_name = prog_ns['__name__'] |
|
686 | 680 | |
|
687 | 681 | if main_mod_name == '__main__': |
|
688 | 682 | restore_main = sys.modules['__main__'] |
|
689 | 683 | else: |
|
690 | 684 | restore_main = False |
|
691 | 685 | |
|
692 | 686 | # This needs to be undone at the end to prevent holding references to |
|
693 | 687 | # every single object ever created. |
|
694 | 688 | sys.modules[main_mod_name] = main_mod |
|
695 | 689 | |
|
696 | 690 | if 'p' in opts or 'd' in opts: |
|
697 | 691 | if 'm' in opts: |
|
698 | 692 | code = 'run_module(modulename, prog_ns)' |
|
699 | 693 | code_ns = { |
|
700 | 694 | 'run_module': self.shell.safe_run_module, |
|
701 | 695 | 'prog_ns': prog_ns, |
|
702 | 696 | 'modulename': modulename, |
|
703 | 697 | } |
|
704 | 698 | else: |
|
705 | 699 | if 'd' in opts: |
|
706 | 700 | # allow exceptions to raise in debug mode |
|
707 | 701 | code = 'execfile(filename, prog_ns, raise_exceptions=True)' |
|
708 | 702 | else: |
|
709 | 703 | code = 'execfile(filename, prog_ns)' |
|
710 | 704 | code_ns = { |
|
711 | 705 | 'execfile': self.shell.safe_execfile, |
|
712 | 706 | 'prog_ns': prog_ns, |
|
713 | 707 | 'filename': get_py_filename(filename), |
|
714 | 708 | } |
|
715 | 709 | |
|
716 | 710 | try: |
|
717 | 711 | stats = None |
|
718 | 712 | if 'p' in opts: |
|
719 | 713 | stats = self._run_with_profiler(code, opts, code_ns) |
|
720 | 714 | else: |
|
721 | 715 | if 'd' in opts: |
|
722 | 716 | bp_file, bp_line = parse_breakpoint( |
|
723 | 717 | opts.get('b', ['1'])[0], filename) |
|
724 | 718 | self._run_with_debugger( |
|
725 | 719 | code, code_ns, filename, bp_line, bp_file) |
|
726 | 720 | else: |
|
727 | 721 | if 'm' in opts: |
|
728 | 722 | def run(): |
|
729 | 723 | self.shell.safe_run_module(modulename, prog_ns) |
|
730 | 724 | else: |
|
731 | 725 | if runner is None: |
|
732 | 726 | runner = self.default_runner |
|
733 | 727 | if runner is None: |
|
734 | 728 | runner = self.shell.safe_execfile |
|
735 | 729 | |
|
736 | 730 | def run(): |
|
737 | 731 | runner(filename, prog_ns, prog_ns, |
|
738 | 732 | exit_ignore=exit_ignore) |
|
739 | 733 | |
|
740 | 734 | if 't' in opts: |
|
741 | 735 | # timed execution |
|
742 | 736 | try: |
|
743 | 737 | nruns = int(opts['N'][0]) |
|
744 | 738 | if nruns < 1: |
|
745 | 739 | error('Number of runs must be >=1') |
|
746 | 740 | return |
|
747 | 741 | except (KeyError): |
|
748 | 742 | nruns = 1 |
|
749 | 743 | self._run_with_timing(run, nruns) |
|
750 | 744 | else: |
|
751 | 745 | # regular execution |
|
752 | 746 | run() |
|
753 | 747 | |
|
754 | 748 | if 'i' in opts: |
|
755 | 749 | self.shell.user_ns['__name__'] = __name__save |
|
756 | 750 | else: |
|
757 | 751 | # update IPython interactive namespace |
|
758 | 752 | |
|
759 | 753 | # Some forms of read errors on the file may mean the |
|
760 | 754 | # __name__ key was never set; using pop we don't have to |
|
761 | 755 | # worry about a possible KeyError. |
|
762 | 756 | prog_ns.pop('__name__', None) |
|
763 | 757 | |
|
764 | 758 | with preserve_keys(self.shell.user_ns, '__file__'): |
|
765 | 759 | self.shell.user_ns.update(prog_ns) |
|
766 | 760 | finally: |
|
767 | 761 | # It's a bit of a mystery why, but __builtins__ can change from |
|
768 | 762 | # being a module to becoming a dict missing some key data after |
|
769 | 763 | # %run. As best I can see, this is NOT something IPython is doing |
|
770 | 764 | # at all, and similar problems have been reported before: |
|
771 | 765 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
772 | 766 | # Since this seems to be done by the interpreter itself, the best |
|
773 | 767 | # we can do is to at least restore __builtins__ for the user on |
|
774 | 768 | # exit. |
|
775 | 769 | self.shell.user_ns['__builtins__'] = builtin_mod |
|
776 | 770 | |
|
777 | 771 | # Ensure key global structures are restored |
|
778 | 772 | sys.argv = save_argv |
|
779 | 773 | if restore_main: |
|
780 | 774 | sys.modules['__main__'] = restore_main |
|
781 | 775 | else: |
|
782 | 776 | # Remove from sys.modules the reference to main_mod we'd |
|
783 | 777 | # added. Otherwise it will trap references to objects |
|
784 | 778 | # contained therein. |
|
785 | 779 | del sys.modules[main_mod_name] |
|
786 | 780 | |
|
787 | 781 | return stats |
|
788 | 782 | |
|
789 | 783 | def _run_with_debugger(self, code, code_ns, filename=None, |
|
790 | 784 | bp_line=None, bp_file=None): |
|
791 | 785 | """ |
|
792 | 786 | Run `code` in debugger with a break point. |
|
793 | 787 | |
|
794 | 788 | Parameters |
|
795 | 789 | ---------- |
|
796 | 790 | code : str |
|
797 | 791 | Code to execute. |
|
798 | 792 | code_ns : dict |
|
799 | 793 | A namespace in which `code` is executed. |
|
800 | 794 | filename : str |
|
801 | 795 | `code` is ran as if it is in `filename`. |
|
802 | 796 | bp_line : int, optional |
|
803 | 797 | Line number of the break point. |
|
804 | 798 | bp_file : str, optional |
|
805 | 799 | Path to the file in which break point is specified. |
|
806 | 800 | `filename` is used if not given. |
|
807 | 801 | |
|
808 | 802 | Raises |
|
809 | 803 | ------ |
|
810 | 804 | UsageError |
|
811 | 805 | If the break point given by `bp_line` is not valid. |
|
812 | 806 | |
|
813 | 807 | """ |
|
814 | 808 | deb = self.shell.InteractiveTB.pdb |
|
815 | 809 | if not deb: |
|
816 | 810 | self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls() |
|
817 | 811 | deb = self.shell.InteractiveTB.pdb |
|
818 | 812 | |
|
819 | 813 | # deb.checkline() fails if deb.curframe exists but is None; it can |
|
820 | 814 | # handle it not existing. https://github.com/ipython/ipython/issues/10028 |
|
821 | 815 | if hasattr(deb, 'curframe'): |
|
822 | 816 | del deb.curframe |
|
823 | 817 | |
|
824 | 818 | # reset Breakpoint state, which is moronically kept |
|
825 | 819 | # in a class |
|
826 | 820 | bdb.Breakpoint.next = 1 |
|
827 | 821 | bdb.Breakpoint.bplist = {} |
|
828 | 822 | bdb.Breakpoint.bpbynumber = [None] |
|
829 | 823 | if bp_line is not None: |
|
830 | 824 | # Set an initial breakpoint to stop execution |
|
831 | 825 | maxtries = 10 |
|
832 | 826 | bp_file = bp_file or filename |
|
833 | 827 | checkline = deb.checkline(bp_file, bp_line) |
|
834 | 828 | if not checkline: |
|
835 | 829 | for bp in range(bp_line + 1, bp_line + maxtries + 1): |
|
836 | 830 | if deb.checkline(bp_file, bp): |
|
837 | 831 | break |
|
838 | 832 | else: |
|
839 | 833 | msg = ("\nI failed to find a valid line to set " |
|
840 | 834 | "a breakpoint\n" |
|
841 | 835 | "after trying up to line: %s.\n" |
|
842 | 836 | "Please set a valid breakpoint manually " |
|
843 | 837 | "with the -b option." % bp) |
|
844 | 838 | raise UsageError(msg) |
|
845 | 839 | # if we find a good linenumber, set the breakpoint |
|
846 | 840 | deb.do_break('%s:%s' % (bp_file, bp_line)) |
|
847 | 841 | |
|
848 | 842 | if filename: |
|
849 | 843 | # Mimic Pdb._runscript(...) |
|
850 | 844 | deb._wait_for_mainpyfile = True |
|
851 | 845 | deb.mainpyfile = deb.canonic(filename) |
|
852 | 846 | |
|
853 | 847 | # Start file run |
|
854 | 848 | print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt) |
|
855 | 849 | try: |
|
856 | 850 | if filename: |
|
857 | 851 | # save filename so it can be used by methods on the deb object |
|
858 | 852 | deb._exec_filename = filename |
|
859 | 853 | while True: |
|
860 | 854 | try: |
|
861 | 855 | deb.run(code, code_ns) |
|
862 | 856 | except Restart: |
|
863 | 857 | print("Restarting") |
|
864 | 858 | if filename: |
|
865 | 859 | deb._wait_for_mainpyfile = True |
|
866 | 860 | deb.mainpyfile = deb.canonic(filename) |
|
867 | 861 | continue |
|
868 | 862 | else: |
|
869 | 863 | break |
|
870 | 864 | |
|
871 | 865 | |
|
872 | 866 | except: |
|
873 | 867 | etype, value, tb = sys.exc_info() |
|
874 | 868 | # Skip three frames in the traceback: the %run one, |
|
875 | 869 | # one inside bdb.py, and the command-line typed by the |
|
876 | 870 | # user (run by exec in pdb itself). |
|
877 | 871 | self.shell.InteractiveTB(etype, value, tb, tb_offset=3) |
|
878 | 872 | |
|
879 | 873 | @staticmethod |
|
880 | 874 | def _run_with_timing(run, nruns): |
|
881 | 875 | """ |
|
882 | 876 | Run function `run` and print timing information. |
|
883 | 877 | |
|
884 | 878 | Parameters |
|
885 | 879 | ---------- |
|
886 | 880 | run : callable |
|
887 | 881 | Any callable object which takes no argument. |
|
888 | 882 | nruns : int |
|
889 | 883 | Number of times to execute `run`. |
|
890 | 884 | |
|
891 | 885 | """ |
|
892 | 886 | twall0 = time.time() |
|
893 | 887 | if nruns == 1: |
|
894 | 888 | t0 = clock2() |
|
895 | 889 | run() |
|
896 | 890 | t1 = clock2() |
|
897 | 891 | t_usr = t1[0] - t0[0] |
|
898 | 892 | t_sys = t1[1] - t0[1] |
|
899 | 893 | print("\nIPython CPU timings (estimated):") |
|
900 | 894 | print(" User : %10.2f s." % t_usr) |
|
901 | 895 | print(" System : %10.2f s." % t_sys) |
|
902 | 896 | else: |
|
903 | 897 | runs = range(nruns) |
|
904 | 898 | t0 = clock2() |
|
905 | 899 | for nr in runs: |
|
906 | 900 | run() |
|
907 | 901 | t1 = clock2() |
|
908 | 902 | t_usr = t1[0] - t0[0] |
|
909 | 903 | t_sys = t1[1] - t0[1] |
|
910 | 904 | print("\nIPython CPU timings (estimated):") |
|
911 | 905 | print("Total runs performed:", nruns) |
|
912 | 906 | print(" Times : %10s %10s" % ('Total', 'Per run')) |
|
913 | 907 | print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)) |
|
914 | 908 | print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)) |
|
915 | 909 | twall1 = time.time() |
|
916 | 910 | print("Wall time: %10.2f s." % (twall1 - twall0)) |
|
917 | 911 | |
|
918 | 912 | @skip_doctest |
|
919 | 913 | @line_cell_magic |
|
920 | 914 | def timeit(self, line='', cell=None): |
|
921 | 915 | """Time execution of a Python statement or expression |
|
922 | 916 | |
|
923 | 917 | Usage, in line mode: |
|
924 | 918 | %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement |
|
925 | 919 | or in cell mode: |
|
926 | 920 | %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code |
|
927 | 921 | code |
|
928 | 922 | code... |
|
929 | 923 | |
|
930 | 924 | Time execution of a Python statement or expression using the timeit |
|
931 | 925 | module. This function can be used both as a line and cell magic: |
|
932 | 926 | |
|
933 | 927 | - In line mode you can time a single-line statement (though multiple |
|
934 | 928 | ones can be chained with using semicolons). |
|
935 | 929 | |
|
936 | 930 | - In cell mode, the statement in the first line is used as setup code |
|
937 | 931 | (executed but not timed) and the body of the cell is timed. The cell |
|
938 | 932 | body has access to any variables created in the setup code. |
|
939 | 933 | |
|
940 | 934 | Options: |
|
941 | 935 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
942 | 936 | is not given, a fitting value is chosen. |
|
943 | 937 | |
|
944 | 938 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
945 | 939 | Default: 3 |
|
946 | 940 | |
|
947 | 941 | -t: use time.time to measure the time, which is the default on Unix. |
|
948 | 942 | This function measures wall time. |
|
949 | 943 | |
|
950 | 944 | -c: use time.clock to measure the time, which is the default on |
|
951 | 945 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
952 | 946 | instead and returns the CPU user time. |
|
953 | 947 | |
|
954 | 948 | -p<P>: use a precision of <P> digits to display the timing result. |
|
955 | 949 | Default: 3 |
|
956 | 950 | |
|
957 | 951 | -q: Quiet, do not print result. |
|
958 | 952 | |
|
959 | 953 | -o: return a TimeitResult that can be stored in a variable to inspect |
|
960 | 954 | the result in more details. |
|
961 | 955 | |
|
962 | 956 | |
|
963 | 957 | Examples |
|
964 | 958 | -------- |
|
965 | 959 | :: |
|
966 | 960 | |
|
967 | 961 | In [1]: %timeit pass |
|
968 | 962 | 100000000 loops, average of 7: 5.48 ns +- 0.354 ns per loop (using standard deviation) |
|
969 | 963 | |
|
970 | 964 | In [2]: u = None |
|
971 | 965 | |
|
972 | 966 | In [3]: %timeit u is None |
|
973 | 967 | 10000000 loops, average of 7: 22.7 ns +- 2.33 ns per loop (using standard deviation) |
|
974 | 968 | |
|
975 | 969 | In [4]: %timeit -r 4 u == None |
|
976 | 970 | 10000000 loops, average of 4: 27.5 ns +- 2.91 ns per loop (using standard deviation) |
|
977 | 971 | |
|
978 | 972 | In [5]: import time |
|
979 | 973 | |
|
980 | 974 | In [6]: %timeit -n1 time.sleep(2) |
|
981 | 975 | 1 loop, average of 7: 2 s +- 4.71 Β΅s per loop (using standard deviation) |
|
982 | 976 | |
|
983 | 977 | |
|
984 | 978 | The times reported by %timeit will be slightly higher than those |
|
985 | 979 | reported by the timeit.py script when variables are accessed. This is |
|
986 | 980 | due to the fact that %timeit executes the statement in the namespace |
|
987 | 981 | of the shell, compared with timeit.py, which uses a single setup |
|
988 | 982 | statement to import function or create variables. Generally, the bias |
|
989 | 983 | does not matter as long as results from timeit.py are not mixed with |
|
990 | 984 | those from %timeit.""" |
|
991 | 985 | |
|
992 | 986 | opts, stmt = self.parse_options(line,'n:r:tcp:qo', |
|
993 | 987 | posix=False, strict=False) |
|
994 | 988 | if stmt == "" and cell is None: |
|
995 | 989 | return |
|
996 | 990 | |
|
997 | 991 | timefunc = timeit.default_timer |
|
998 | 992 | number = int(getattr(opts, "n", 0)) |
|
999 | 993 | default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat |
|
1000 | 994 | repeat = int(getattr(opts, "r", default_repeat)) |
|
1001 | 995 | precision = int(getattr(opts, "p", 3)) |
|
1002 | 996 | quiet = 'q' in opts |
|
1003 | 997 | return_result = 'o' in opts |
|
1004 | 998 | if hasattr(opts, "t"): |
|
1005 | 999 | timefunc = time.time |
|
1006 | 1000 | if hasattr(opts, "c"): |
|
1007 | 1001 | timefunc = clock |
|
1008 | 1002 | |
|
1009 | 1003 | timer = Timer(timer=timefunc) |
|
1010 | 1004 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1011 | 1005 | # but is there a better way to achieve that the code stmt has access |
|
1012 | 1006 | # to the shell namespace? |
|
1013 | 1007 | transform = self.shell.input_splitter.transform_cell |
|
1014 | 1008 | |
|
1015 | 1009 | if cell is None: |
|
1016 | 1010 | # called as line magic |
|
1017 | 1011 | ast_setup = self.shell.compile.ast_parse("pass") |
|
1018 | 1012 | ast_stmt = self.shell.compile.ast_parse(transform(stmt)) |
|
1019 | 1013 | else: |
|
1020 | 1014 | ast_setup = self.shell.compile.ast_parse(transform(stmt)) |
|
1021 | 1015 | ast_stmt = self.shell.compile.ast_parse(transform(cell)) |
|
1022 | 1016 | |
|
1023 | 1017 | ast_setup = self.shell.transform_ast(ast_setup) |
|
1024 | 1018 | ast_stmt = self.shell.transform_ast(ast_stmt) |
|
1025 | 1019 | |
|
1026 | 1020 | # This codestring is taken from timeit.template - we fill it in as an |
|
1027 | 1021 | # AST, so that we can apply our AST transformations to the user code |
|
1028 | 1022 | # without affecting the timing code. |
|
1029 | 1023 | timeit_ast_template = ast.parse('def inner(_it, _timer):\n' |
|
1030 | 1024 | ' setup\n' |
|
1031 | 1025 | ' _t0 = _timer()\n' |
|
1032 | 1026 | ' for _i in _it:\n' |
|
1033 | 1027 | ' stmt\n' |
|
1034 | 1028 | ' _t1 = _timer()\n' |
|
1035 | 1029 | ' return _t1 - _t0\n') |
|
1036 | 1030 | |
|
1037 | 1031 | timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template) |
|
1038 | 1032 | timeit_ast = ast.fix_missing_locations(timeit_ast) |
|
1039 | 1033 | |
|
1040 | 1034 | # Track compilation time so it can be reported if too long |
|
1041 | 1035 | # Minimum time above which compilation time will be reported |
|
1042 | 1036 | tc_min = 0.1 |
|
1043 | 1037 | |
|
1044 | 1038 | t0 = clock() |
|
1045 | 1039 | code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec") |
|
1046 | 1040 | tc = clock()-t0 |
|
1047 | 1041 | |
|
1048 | 1042 | ns = {} |
|
1049 | 1043 | exec(code, self.shell.user_ns, ns) |
|
1050 | 1044 | timer.inner = ns["inner"] |
|
1051 | 1045 | |
|
1052 | 1046 | # This is used to check if there is a huge difference between the |
|
1053 | 1047 | # best and worst timings. |
|
1054 | 1048 | # Issue: https://github.com/ipython/ipython/issues/6471 |
|
1055 | 1049 | if number == 0: |
|
1056 | 1050 | # determine number so that 0.2 <= total time < 2.0 |
|
1057 | 1051 | for index in range(0, 10): |
|
1058 | 1052 | number = 10 ** index |
|
1059 | 1053 | time_number = timer.timeit(number) |
|
1060 | 1054 | if time_number >= 0.2: |
|
1061 | 1055 | break |
|
1062 | 1056 | |
|
1063 | 1057 | all_runs = timer.repeat(repeat, number) |
|
1064 | 1058 | best = min(all_runs) / number |
|
1065 | 1059 | worst = max(all_runs) / number |
|
1066 | 1060 | timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision) |
|
1067 | 1061 | |
|
1068 | 1062 | if not quiet : |
|
1069 | 1063 | # Check best timing is greater than zero to avoid a |
|
1070 | 1064 | # ZeroDivisionError. |
|
1071 | 1065 | # In cases where the slowest timing is lesser than a micosecond |
|
1072 | 1066 | # we assume that it does not really matter if the fastest |
|
1073 | 1067 | # timing is 4 times faster than the slowest timing or not. |
|
1074 | 1068 | if worst > 4 * best and best > 0 and worst > 1e-6: |
|
1075 | 1069 | print("The slowest run took %0.2f times longer than the " |
|
1076 | 1070 | "fastest. This could mean that an intermediate result " |
|
1077 | 1071 | "is being cached." % (worst / best)) |
|
1078 | 1072 | |
|
1079 | 1073 | print( timeit_result ) |
|
1080 | 1074 | |
|
1081 | 1075 | if tc > tc_min: |
|
1082 | 1076 | print("Compiler time: %.2f s" % tc) |
|
1083 | 1077 | if return_result: |
|
1084 | 1078 | return timeit_result |
|
1085 | 1079 | |
|
1086 | 1080 | @skip_doctest |
|
1087 | 1081 | @needs_local_scope |
|
1088 | 1082 | @line_cell_magic |
|
1089 | 1083 | def time(self,line='', cell=None, local_ns=None): |
|
1090 | 1084 | """Time execution of a Python statement or expression. |
|
1091 | 1085 | |
|
1092 | 1086 | The CPU and wall clock times are printed, and the value of the |
|
1093 | 1087 | expression (if any) is returned. Note that under Win32, system time |
|
1094 | 1088 | is always reported as 0, since it can not be measured. |
|
1095 | 1089 | |
|
1096 | 1090 | This function can be used both as a line and cell magic: |
|
1097 | 1091 | |
|
1098 | 1092 | - In line mode you can time a single-line statement (though multiple |
|
1099 | 1093 | ones can be chained with using semicolons). |
|
1100 | 1094 | |
|
1101 | 1095 | - In cell mode, you can time the cell body (a directly |
|
1102 | 1096 | following statement raises an error). |
|
1103 | 1097 | |
|
1104 | 1098 | This function provides very basic timing functionality. Use the timeit |
|
1105 | 1099 | magic for more control over the measurement. |
|
1106 | 1100 | |
|
1107 | 1101 | Examples |
|
1108 | 1102 | -------- |
|
1109 | 1103 | :: |
|
1110 | 1104 | |
|
1111 | 1105 | In [1]: %time 2**128 |
|
1112 | 1106 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1113 | 1107 | Wall time: 0.00 |
|
1114 | 1108 | Out[1]: 340282366920938463463374607431768211456L |
|
1115 | 1109 | |
|
1116 | 1110 | In [2]: n = 1000000 |
|
1117 | 1111 | |
|
1118 | 1112 | In [3]: %time sum(range(n)) |
|
1119 | 1113 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1120 | 1114 | Wall time: 1.37 |
|
1121 | 1115 | Out[3]: 499999500000L |
|
1122 | 1116 | |
|
1123 | 1117 | In [4]: %time print 'hello world' |
|
1124 | 1118 | hello world |
|
1125 | 1119 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1126 | 1120 | Wall time: 0.00 |
|
1127 | 1121 | |
|
1128 | 1122 | Note that the time needed by Python to compile the given expression |
|
1129 | 1123 | will be reported if it is more than 0.1s. In this example, the |
|
1130 | 1124 | actual exponentiation is done by Python at compilation time, so while |
|
1131 | 1125 | the expression can take a noticeable amount of time to compute, that |
|
1132 | 1126 | time is purely due to the compilation: |
|
1133 | 1127 | |
|
1134 | 1128 | In [5]: %time 3**9999; |
|
1135 | 1129 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1136 | 1130 | Wall time: 0.00 s |
|
1137 | 1131 | |
|
1138 | 1132 | In [6]: %time 3**999999; |
|
1139 | 1133 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1140 | 1134 | Wall time: 0.00 s |
|
1141 | 1135 | Compiler : 0.78 s |
|
1142 | 1136 | """ |
|
1143 | 1137 | |
|
1144 | 1138 | # fail immediately if the given expression can't be compiled |
|
1145 | 1139 | |
|
1146 | 1140 | if line and cell: |
|
1147 | 1141 | raise UsageError("Can't use statement directly after '%%time'!") |
|
1148 | 1142 | |
|
1149 | 1143 | if cell: |
|
1150 | 1144 | expr = self.shell.input_transformer_manager.transform_cell(cell) |
|
1151 | 1145 | else: |
|
1152 | 1146 | expr = self.shell.input_transformer_manager.transform_cell(line) |
|
1153 | 1147 | |
|
1154 | 1148 | # Minimum time above which parse time will be reported |
|
1155 | 1149 | tp_min = 0.1 |
|
1156 | 1150 | |
|
1157 | 1151 | t0 = clock() |
|
1158 | 1152 | expr_ast = self.shell.compile.ast_parse(expr) |
|
1159 | 1153 | tp = clock()-t0 |
|
1160 | 1154 | |
|
1161 | 1155 | # Apply AST transformations |
|
1162 | 1156 | expr_ast = self.shell.transform_ast(expr_ast) |
|
1163 | 1157 | |
|
1164 | 1158 | # Minimum time above which compilation time will be reported |
|
1165 | 1159 | tc_min = 0.1 |
|
1166 | 1160 | |
|
1167 | 1161 | if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr): |
|
1168 | 1162 | mode = 'eval' |
|
1169 | 1163 | source = '<timed eval>' |
|
1170 | 1164 | expr_ast = ast.Expression(expr_ast.body[0].value) |
|
1171 | 1165 | else: |
|
1172 | 1166 | mode = 'exec' |
|
1173 | 1167 | source = '<timed exec>' |
|
1174 | 1168 | t0 = clock() |
|
1175 | 1169 | code = self.shell.compile(expr_ast, source, mode) |
|
1176 | 1170 | tc = clock()-t0 |
|
1177 | 1171 | |
|
1178 | 1172 | # skew measurement as little as possible |
|
1179 | 1173 | glob = self.shell.user_ns |
|
1180 | 1174 | wtime = time.time |
|
1181 | 1175 | # time execution |
|
1182 | 1176 | wall_st = wtime() |
|
1183 | 1177 | if mode=='eval': |
|
1184 | 1178 | st = clock2() |
|
1185 | 1179 | try: |
|
1186 | 1180 | out = eval(code, glob, local_ns) |
|
1187 | 1181 | except: |
|
1188 | 1182 | self.shell.showtraceback() |
|
1189 | 1183 | return |
|
1190 | 1184 | end = clock2() |
|
1191 | 1185 | else: |
|
1192 | 1186 | st = clock2() |
|
1193 | 1187 | try: |
|
1194 | 1188 | exec(code, glob, local_ns) |
|
1195 | 1189 | except: |
|
1196 | 1190 | self.shell.showtraceback() |
|
1197 | 1191 | return |
|
1198 | 1192 | end = clock2() |
|
1199 | 1193 | out = None |
|
1200 | 1194 | wall_end = wtime() |
|
1201 | 1195 | # Compute actual times and report |
|
1202 | 1196 | wall_time = wall_end-wall_st |
|
1203 | 1197 | cpu_user = end[0]-st[0] |
|
1204 | 1198 | cpu_sys = end[1]-st[1] |
|
1205 | 1199 | cpu_tot = cpu_user+cpu_sys |
|
1206 | 1200 | # On windows cpu_sys is always zero, so no new information to the next print |
|
1207 | 1201 | if sys.platform != 'win32': |
|
1208 | 1202 | print("CPU times: user %s, sys: %s, total: %s" % \ |
|
1209 | 1203 | (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot))) |
|
1210 | 1204 | print("Wall time: %s" % _format_time(wall_time)) |
|
1211 | 1205 | if tc > tc_min: |
|
1212 | 1206 | print("Compiler : %s" % _format_time(tc)) |
|
1213 | 1207 | if tp > tp_min: |
|
1214 | 1208 | print("Parser : %s" % _format_time(tp)) |
|
1215 | 1209 | return out |
|
1216 | 1210 | |
|
1217 | 1211 | @skip_doctest |
|
1218 | 1212 | @line_magic |
|
1219 | 1213 | def macro(self, parameter_s=''): |
|
1220 | 1214 | """Define a macro for future re-execution. It accepts ranges of history, |
|
1221 | 1215 | filenames or string objects. |
|
1222 | 1216 | |
|
1223 | 1217 | Usage:\\ |
|
1224 | 1218 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1225 | 1219 | |
|
1226 | 1220 | Options: |
|
1227 | 1221 | |
|
1228 | 1222 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1229 | 1223 | so that magics are loaded in their transformed version to valid |
|
1230 | 1224 | Python. If this option is given, the raw input as typed at the |
|
1231 | 1225 | command line is used instead. |
|
1232 | 1226 | |
|
1233 | 1227 | -q: quiet macro definition. By default, a tag line is printed |
|
1234 | 1228 | to indicate the macro has been created, and then the contents of |
|
1235 | 1229 | the macro are printed. If this option is given, then no printout |
|
1236 | 1230 | is produced once the macro is created. |
|
1237 | 1231 | |
|
1238 | 1232 | This will define a global variable called `name` which is a string |
|
1239 | 1233 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1240 | 1234 | above) from your input history into a single string. This variable |
|
1241 | 1235 | acts like an automatic function which re-executes those lines as if |
|
1242 | 1236 | you had typed them. You just type 'name' at the prompt and the code |
|
1243 | 1237 | executes. |
|
1244 | 1238 | |
|
1245 | 1239 | The syntax for indicating input ranges is described in %history. |
|
1246 | 1240 | |
|
1247 | 1241 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1248 | 1242 | notation, where N:M means numbers N through M-1. |
|
1249 | 1243 | |
|
1250 | 1244 | For example, if your history contains (print using %hist -n ):: |
|
1251 | 1245 | |
|
1252 | 1246 | 44: x=1 |
|
1253 | 1247 | 45: y=3 |
|
1254 | 1248 | 46: z=x+y |
|
1255 | 1249 | 47: print x |
|
1256 | 1250 | 48: a=5 |
|
1257 | 1251 | 49: print 'x',x,'y',y |
|
1258 | 1252 | |
|
1259 | 1253 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1260 | 1254 | called my_macro with:: |
|
1261 | 1255 | |
|
1262 | 1256 | In [55]: %macro my_macro 44-47 49 |
|
1263 | 1257 | |
|
1264 | 1258 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1265 | 1259 | in one pass. |
|
1266 | 1260 | |
|
1267 | 1261 | You don't need to give the line-numbers in order, and any given line |
|
1268 | 1262 | number can appear multiple times. You can assemble macros with any |
|
1269 | 1263 | lines from your input history in any order. |
|
1270 | 1264 | |
|
1271 | 1265 | The macro is a simple object which holds its value in an attribute, |
|
1272 | 1266 | but IPython's display system checks for macros and executes them as |
|
1273 | 1267 | code instead of printing them when you type their name. |
|
1274 | 1268 | |
|
1275 | 1269 | You can view a macro's contents by explicitly printing it with:: |
|
1276 | 1270 | |
|
1277 | 1271 | print macro_name |
|
1278 | 1272 | |
|
1279 | 1273 | """ |
|
1280 | 1274 | opts,args = self.parse_options(parameter_s,'rq',mode='list') |
|
1281 | 1275 | if not args: # List existing macros |
|
1282 | 1276 | return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)) |
|
1283 | 1277 | if len(args) == 1: |
|
1284 | 1278 | raise UsageError( |
|
1285 | 1279 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
1286 | 1280 | name, codefrom = args[0], " ".join(args[1:]) |
|
1287 | 1281 | |
|
1288 | 1282 | #print 'rng',ranges # dbg |
|
1289 | 1283 | try: |
|
1290 | 1284 | lines = self.shell.find_user_code(codefrom, 'r' in opts) |
|
1291 | 1285 | except (ValueError, TypeError) as e: |
|
1292 | 1286 | print(e.args[0]) |
|
1293 | 1287 | return |
|
1294 | 1288 | macro = Macro(lines) |
|
1295 | 1289 | self.shell.define_macro(name, macro) |
|
1296 | 1290 | if not ( 'q' in opts) : |
|
1297 | 1291 | print('Macro `%s` created. To execute, type its name (without quotes).' % name) |
|
1298 | 1292 | print('=== Macro contents: ===') |
|
1299 | 1293 | print(macro, end=' ') |
|
1300 | 1294 | |
|
1301 | 1295 | @magic_arguments.magic_arguments() |
|
1302 | 1296 | @magic_arguments.argument('output', type=str, default='', nargs='?', |
|
1303 | 1297 | help="""The name of the variable in which to store output. |
|
1304 | 1298 | This is a utils.io.CapturedIO object with stdout/err attributes |
|
1305 | 1299 | for the text of the captured output. |
|
1306 | 1300 | |
|
1307 | 1301 | CapturedOutput also has a show() method for displaying the output, |
|
1308 | 1302 | and __call__ as well, so you can use that to quickly display the |
|
1309 | 1303 | output. |
|
1310 | 1304 | |
|
1311 | 1305 | If unspecified, captured output is discarded. |
|
1312 | 1306 | """ |
|
1313 | 1307 | ) |
|
1314 | 1308 | @magic_arguments.argument('--no-stderr', action="store_true", |
|
1315 | 1309 | help="""Don't capture stderr.""" |
|
1316 | 1310 | ) |
|
1317 | 1311 | @magic_arguments.argument('--no-stdout', action="store_true", |
|
1318 | 1312 | help="""Don't capture stdout.""" |
|
1319 | 1313 | ) |
|
1320 | 1314 | @magic_arguments.argument('--no-display', action="store_true", |
|
1321 | 1315 | help="""Don't capture IPython's rich display.""" |
|
1322 | 1316 | ) |
|
1323 | 1317 | @cell_magic |
|
1324 | 1318 | def capture(self, line, cell): |
|
1325 | 1319 | """run the cell, capturing stdout, stderr, and IPython's rich display() calls.""" |
|
1326 | 1320 | args = magic_arguments.parse_argstring(self.capture, line) |
|
1327 | 1321 | out = not args.no_stdout |
|
1328 | 1322 | err = not args.no_stderr |
|
1329 | 1323 | disp = not args.no_display |
|
1330 | 1324 | with capture_output(out, err, disp) as io: |
|
1331 | 1325 | self.shell.run_cell(cell) |
|
1332 | 1326 | if args.output: |
|
1333 | 1327 | self.shell.user_ns[args.output] = io |
|
1334 | 1328 | |
|
1335 | 1329 | def parse_breakpoint(text, current_file): |
|
1336 | 1330 | '''Returns (file, line) for file:line and (current_file, line) for line''' |
|
1337 | 1331 | colon = text.find(':') |
|
1338 | 1332 | if colon == -1: |
|
1339 | 1333 | return current_file, int(text) |
|
1340 | 1334 | else: |
|
1341 | 1335 | return text[:colon], int(text[colon+1:]) |
|
1342 | 1336 | |
|
1343 | 1337 | def _format_time(timespan, precision=3): |
|
1344 | 1338 | """Formats the timespan in a human readable form""" |
|
1345 | 1339 | |
|
1346 | 1340 | if timespan >= 60.0: |
|
1347 | 1341 | # we have more than a minute, format that in a human readable form |
|
1348 | 1342 | # Idea from http://snipplr.com/view/5713/ |
|
1349 | 1343 | parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)] |
|
1350 | 1344 | time = [] |
|
1351 | 1345 | leftover = timespan |
|
1352 | 1346 | for suffix, length in parts: |
|
1353 | 1347 | value = int(leftover / length) |
|
1354 | 1348 | if value > 0: |
|
1355 | 1349 | leftover = leftover % length |
|
1356 | 1350 | time.append(u'%s%s' % (str(value), suffix)) |
|
1357 | 1351 | if leftover < 1: |
|
1358 | 1352 | break |
|
1359 | 1353 | return " ".join(time) |
|
1360 | 1354 | |
|
1361 | 1355 | |
|
1362 | 1356 | # Unfortunately the unicode 'micro' symbol can cause problems in |
|
1363 | 1357 | # certain terminals. |
|
1364 | 1358 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1365 | 1359 | # Try to prevent crashes by being more secure than it needs to |
|
1366 | 1360 | # E.g. eclipse is able to print a Β΅, but has no sys.stdout.encoding set. |
|
1367 | 1361 | units = [u"s", u"ms",u'us',"ns"] # the save value |
|
1368 | 1362 | if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding: |
|
1369 | 1363 | try: |
|
1370 | 1364 | u'\xb5'.encode(sys.stdout.encoding) |
|
1371 | 1365 | units = [u"s", u"ms",u'\xb5s',"ns"] |
|
1372 | 1366 | except: |
|
1373 | 1367 | pass |
|
1374 | 1368 | scaling = [1, 1e3, 1e6, 1e9] |
|
1375 | 1369 | |
|
1376 | 1370 | if timespan > 0.0: |
|
1377 | 1371 | order = min(-int(math.floor(math.log10(timespan)) // 3), 3) |
|
1378 | 1372 | else: |
|
1379 | 1373 | order = 3 |
|
1380 | 1374 | return u"%.*g %s" % (precision, timespan * scaling[order], units[order]) |
@@ -1,42 +1,39 b'' | |||
|
1 | 1 | # coding: utf-8 |
|
2 | 2 | import nose.tools as nt |
|
3 | 3 | |
|
4 | 4 | from IPython.core.splitinput import split_user_input, LineInfo |
|
5 | 5 | from IPython.testing import tools as tt |
|
6 | 6 | from IPython.utils import py3compat |
|
7 | 7 | |
|
8 | 8 | tests = [ |
|
9 | 9 | ('x=1', ('', '', 'x', '=1')), |
|
10 | 10 | ('?', ('', '?', '', '')), |
|
11 | 11 | ('??', ('', '??', '', '')), |
|
12 | 12 | (' ?', (' ', '?', '', '')), |
|
13 | 13 | (' ??', (' ', '??', '', '')), |
|
14 | 14 | ('??x', ('', '??', 'x', '')), |
|
15 | 15 | ('?x=1', ('', '?', 'x', '=1')), |
|
16 | 16 | ('!ls', ('', '!', 'ls', '')), |
|
17 | 17 | (' !ls', (' ', '!', 'ls', '')), |
|
18 | 18 | ('!!ls', ('', '!!', 'ls', '')), |
|
19 | 19 | (' !!ls', (' ', '!!', 'ls', '')), |
|
20 | 20 | (',ls', ('', ',', 'ls', '')), |
|
21 | 21 | (';ls', ('', ';', 'ls', '')), |
|
22 | 22 | (' ;ls', (' ', ';', 'ls', '')), |
|
23 | 23 | ('f.g(x)', ('', '', 'f.g', '(x)')), |
|
24 | 24 | ('f.g (x)', ('', '', 'f.g', '(x)')), |
|
25 | 25 | ('?%hist1', ('', '?', '%hist1', '')), |
|
26 | 26 | ('?%%hist2', ('', '?', '%%hist2', '')), |
|
27 | 27 | ('??%hist3', ('', '??', '%hist3', '')), |
|
28 | 28 | ('??%%hist4', ('', '??', '%%hist4', '')), |
|
29 | 29 | ('?x*', ('', '?', 'x*', '')), |
|
30 | 30 | ] |
|
31 | if py3compat.PY3: | |
|
32 | tests.append((u"PΓ©rez Fernando", (u'', u'', u'PΓ©rez', u'Fernando'))) | |
|
33 | else: | |
|
34 | tests.append((u"PΓ©rez Fernando", (u'', u'', u'P', u'Γ©rez Fernando'))) | |
|
31 | tests.append((u"PΓ©rez Fernando", (u'', u'', u'PΓ©rez', u'Fernando'))) | |
|
35 | 32 | |
|
36 | 33 | def test_split_user_input(): |
|
37 | 34 | return tt.check_pairs(split_user_input, tests) |
|
38 | 35 | |
|
39 | 36 | def test_LineInfo(): |
|
40 | 37 | """Simple test for LineInfo construction and str()""" |
|
41 | 38 | linfo = LineInfo(' %cd /home') |
|
42 | 39 | nt.assert_equal(str(linfo), 'LineInfo [ |%|cd|/home]') |
@@ -1,1469 +1,1462 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | Verbose and colourful traceback formatting. |
|
4 | 4 | |
|
5 | 5 | **ColorTB** |
|
6 | 6 | |
|
7 | 7 | I've always found it a bit hard to visually parse tracebacks in Python. The |
|
8 | 8 | ColorTB class is a solution to that problem. It colors the different parts of a |
|
9 | 9 | traceback in a manner similar to what you would expect from a syntax-highlighting |
|
10 | 10 | text editor. |
|
11 | 11 | |
|
12 | 12 | Installation instructions for ColorTB:: |
|
13 | 13 | |
|
14 | 14 | import sys,ultratb |
|
15 | 15 | sys.excepthook = ultratb.ColorTB() |
|
16 | 16 | |
|
17 | 17 | **VerboseTB** |
|
18 | 18 | |
|
19 | 19 | I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds |
|
20 | 20 | of useful info when a traceback occurs. Ping originally had it spit out HTML |
|
21 | 21 | and intended it for CGI programmers, but why should they have all the fun? I |
|
22 | 22 | altered it to spit out colored text to the terminal. It's a bit overwhelming, |
|
23 | 23 | but kind of neat, and maybe useful for long-running programs that you believe |
|
24 | 24 | are bug-free. If a crash *does* occur in that type of program you want details. |
|
25 | 25 | Give it a shot--you'll love it or you'll hate it. |
|
26 | 26 | |
|
27 | 27 | .. note:: |
|
28 | 28 | |
|
29 | 29 | The Verbose mode prints the variables currently visible where the exception |
|
30 | 30 | happened (shortening their strings if too long). This can potentially be |
|
31 | 31 | very slow, if you happen to have a huge data structure whose string |
|
32 | 32 | representation is complex to compute. Your computer may appear to freeze for |
|
33 | 33 | a while with cpu usage at 100%. If this occurs, you can cancel the traceback |
|
34 | 34 | with Ctrl-C (maybe hitting it more than once). |
|
35 | 35 | |
|
36 | 36 | If you encounter this kind of situation often, you may want to use the |
|
37 | 37 | Verbose_novars mode instead of the regular Verbose, which avoids formatting |
|
38 | 38 | variables (but otherwise includes the information and context given by |
|
39 | 39 | Verbose). |
|
40 | 40 | |
|
41 | 41 | .. note:: |
|
42 | 42 | |
|
43 | 43 | The verbose mode print all variables in the stack, which means it can |
|
44 | 44 | potentially leak sensitive information like access keys, or unencryted |
|
45 | 45 | password. |
|
46 | 46 | |
|
47 | 47 | Installation instructions for VerboseTB:: |
|
48 | 48 | |
|
49 | 49 | import sys,ultratb |
|
50 | 50 | sys.excepthook = ultratb.VerboseTB() |
|
51 | 51 | |
|
52 | 52 | Note: Much of the code in this module was lifted verbatim from the standard |
|
53 | 53 | library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'. |
|
54 | 54 | |
|
55 | 55 | Color schemes |
|
56 | 56 | ------------- |
|
57 | 57 | |
|
58 | 58 | The colors are defined in the class TBTools through the use of the |
|
59 | 59 | ColorSchemeTable class. Currently the following exist: |
|
60 | 60 | |
|
61 | 61 | - NoColor: allows all of this module to be used in any terminal (the color |
|
62 | 62 | escapes are just dummy blank strings). |
|
63 | 63 | |
|
64 | 64 | - Linux: is meant to look good in a terminal like the Linux console (black |
|
65 | 65 | or very dark background). |
|
66 | 66 | |
|
67 | 67 | - LightBG: similar to Linux but swaps dark/light colors to be more readable |
|
68 | 68 | in light background terminals. |
|
69 | 69 | |
|
70 | 70 | - Neutral: a neutral color scheme that should be readable on both light and |
|
71 | 71 | dark background |
|
72 | 72 | |
|
73 | 73 | You can implement other color schemes easily, the syntax is fairly |
|
74 | 74 | self-explanatory. Please send back new schemes you develop to the author for |
|
75 | 75 | possible inclusion in future releases. |
|
76 | 76 | |
|
77 | 77 | Inheritance diagram: |
|
78 | 78 | |
|
79 | 79 | .. inheritance-diagram:: IPython.core.ultratb |
|
80 | 80 | :parts: 3 |
|
81 | 81 | """ |
|
82 | 82 | |
|
83 | 83 | #***************************************************************************** |
|
84 | 84 | # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu> |
|
85 | 85 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> |
|
86 | 86 | # |
|
87 | 87 | # Distributed under the terms of the BSD License. The full license is in |
|
88 | 88 | # the file COPYING, distributed as part of this software. |
|
89 | 89 | #***************************************************************************** |
|
90 | 90 | |
|
91 | 91 | |
|
92 | 92 | import dis |
|
93 | 93 | import inspect |
|
94 | 94 | import keyword |
|
95 | 95 | import linecache |
|
96 | 96 | import os |
|
97 | 97 | import pydoc |
|
98 | 98 | import re |
|
99 | 99 | import sys |
|
100 | 100 | import time |
|
101 | 101 | import tokenize |
|
102 | 102 | import traceback |
|
103 | 103 | import types |
|
104 | 104 | |
|
105 | 105 | try: # Python 2 |
|
106 | 106 | generate_tokens = tokenize.generate_tokens |
|
107 | 107 | except AttributeError: # Python 3 |
|
108 | 108 | generate_tokens = tokenize.tokenize |
|
109 | 109 | |
|
110 | 110 | # For purposes of monkeypatching inspect to fix a bug in it. |
|
111 | 111 | from inspect import getsourcefile, getfile, getmodule, \ |
|
112 | 112 | ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode |
|
113 | 113 | |
|
114 | 114 | # IPython's own modules |
|
115 | 115 | from IPython import get_ipython |
|
116 | 116 | from IPython.core import debugger |
|
117 | 117 | from IPython.core.display_trap import DisplayTrap |
|
118 | 118 | from IPython.core.excolors import exception_colors |
|
119 | 119 | from IPython.utils import PyColorize |
|
120 | 120 | from IPython.utils import openpy |
|
121 | 121 | from IPython.utils import path as util_path |
|
122 | 122 | from IPython.utils import py3compat |
|
123 | 123 | from IPython.utils import ulinecache |
|
124 | 124 | from IPython.utils.data import uniq_stable |
|
125 | 125 | from IPython.utils.terminal import get_terminal_size |
|
126 | 126 | from logging import info, error |
|
127 | 127 | |
|
128 | 128 | import IPython.utils.colorable as colorable |
|
129 | 129 | |
|
130 | 130 | # Globals |
|
131 | 131 | # amount of space to put line numbers before verbose tracebacks |
|
132 | 132 | INDENT_SIZE = 8 |
|
133 | 133 | |
|
134 | 134 | # Default color scheme. This is used, for example, by the traceback |
|
135 | 135 | # formatter. When running in an actual IPython instance, the user's rc.colors |
|
136 | 136 | # value is used, but having a module global makes this functionality available |
|
137 | 137 | # to users of ultratb who are NOT running inside ipython. |
|
138 | 138 | DEFAULT_SCHEME = 'NoColor' |
|
139 | 139 | |
|
140 | 140 | # --------------------------------------------------------------------------- |
|
141 | 141 | # Code begins |
|
142 | 142 | |
|
143 | 143 | # Utility functions |
|
144 | 144 | def inspect_error(): |
|
145 | 145 | """Print a message about internal inspect errors. |
|
146 | 146 | |
|
147 | 147 | These are unfortunately quite common.""" |
|
148 | 148 | |
|
149 | 149 | error('Internal Python error in the inspect module.\n' |
|
150 | 150 | 'Below is the traceback from this internal error.\n') |
|
151 | 151 | |
|
152 | 152 | |
|
153 | 153 | # This function is a monkeypatch we apply to the Python inspect module. We have |
|
154 | 154 | # now found when it's needed (see discussion on issue gh-1456), and we have a |
|
155 | 155 | # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if |
|
156 | 156 | # the monkeypatch is not applied. TK, Aug 2012. |
|
157 | 157 | def findsource(object): |
|
158 | 158 | """Return the entire source file and starting line number for an object. |
|
159 | 159 | |
|
160 | 160 | The argument may be a module, class, method, function, traceback, frame, |
|
161 | 161 | or code object. The source code is returned as a list of all the lines |
|
162 | 162 | in the file and the line number indexes a line in that list. An IOError |
|
163 | 163 | is raised if the source code cannot be retrieved. |
|
164 | 164 | |
|
165 | 165 | FIXED version with which we monkeypatch the stdlib to work around a bug.""" |
|
166 | 166 | |
|
167 | 167 | file = getsourcefile(object) or getfile(object) |
|
168 | 168 | # If the object is a frame, then trying to get the globals dict from its |
|
169 | 169 | # module won't work. Instead, the frame object itself has the globals |
|
170 | 170 | # dictionary. |
|
171 | 171 | globals_dict = None |
|
172 | 172 | if inspect.isframe(object): |
|
173 | 173 | # XXX: can this ever be false? |
|
174 | 174 | globals_dict = object.f_globals |
|
175 | 175 | else: |
|
176 | 176 | module = getmodule(object, file) |
|
177 | 177 | if module: |
|
178 | 178 | globals_dict = module.__dict__ |
|
179 | 179 | lines = linecache.getlines(file, globals_dict) |
|
180 | 180 | if not lines: |
|
181 | 181 | raise IOError('could not get source code') |
|
182 | 182 | |
|
183 | 183 | if ismodule(object): |
|
184 | 184 | return lines, 0 |
|
185 | 185 | |
|
186 | 186 | if isclass(object): |
|
187 | 187 | name = object.__name__ |
|
188 | 188 | pat = re.compile(r'^(\s*)class\s*' + name + r'\b') |
|
189 | 189 | # make some effort to find the best matching class definition: |
|
190 | 190 | # use the one with the least indentation, which is the one |
|
191 | 191 | # that's most probably not inside a function definition. |
|
192 | 192 | candidates = [] |
|
193 | 193 | for i in range(len(lines)): |
|
194 | 194 | match = pat.match(lines[i]) |
|
195 | 195 | if match: |
|
196 | 196 | # if it's at toplevel, it's already the best one |
|
197 | 197 | if lines[i][0] == 'c': |
|
198 | 198 | return lines, i |
|
199 | 199 | # else add whitespace to candidate list |
|
200 | 200 | candidates.append((match.group(1), i)) |
|
201 | 201 | if candidates: |
|
202 | 202 | # this will sort by whitespace, and by line number, |
|
203 | 203 | # less whitespace first |
|
204 | 204 | candidates.sort() |
|
205 | 205 | return lines, candidates[0][1] |
|
206 | 206 | else: |
|
207 | 207 | raise IOError('could not find class definition') |
|
208 | 208 | |
|
209 | 209 | if ismethod(object): |
|
210 | 210 | object = object.__func__ |
|
211 | 211 | if isfunction(object): |
|
212 | 212 | object = object.__code__ |
|
213 | 213 | if istraceback(object): |
|
214 | 214 | object = object.tb_frame |
|
215 | 215 | if isframe(object): |
|
216 | 216 | object = object.f_code |
|
217 | 217 | if iscode(object): |
|
218 | 218 | if not hasattr(object, 'co_firstlineno'): |
|
219 | 219 | raise IOError('could not find function definition') |
|
220 | 220 | pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') |
|
221 | 221 | pmatch = pat.match |
|
222 | 222 | # fperez - fix: sometimes, co_firstlineno can give a number larger than |
|
223 | 223 | # the length of lines, which causes an error. Safeguard against that. |
|
224 | 224 | lnum = min(object.co_firstlineno, len(lines)) - 1 |
|
225 | 225 | while lnum > 0: |
|
226 | 226 | if pmatch(lines[lnum]): |
|
227 | 227 | break |
|
228 | 228 | lnum -= 1 |
|
229 | 229 | |
|
230 | 230 | return lines, lnum |
|
231 | 231 | raise IOError('could not find code object') |
|
232 | 232 | |
|
233 | 233 | |
|
234 | 234 | # This is a patched version of inspect.getargs that applies the (unmerged) |
|
235 | 235 | # patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes |
|
236 | 236 | # https://github.com/ipython/ipython/issues/8205 and |
|
237 | 237 | # https://github.com/ipython/ipython/issues/8293 |
|
238 | 238 | def getargs(co): |
|
239 | 239 | """Get information about the arguments accepted by a code object. |
|
240 | 240 | |
|
241 | 241 | Three things are returned: (args, varargs, varkw), where 'args' is |
|
242 | 242 | a list of argument names (possibly containing nested lists), and |
|
243 | 243 | 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" |
|
244 | 244 | if not iscode(co): |
|
245 | 245 | raise TypeError('{!r} is not a code object'.format(co)) |
|
246 | 246 | |
|
247 | 247 | nargs = co.co_argcount |
|
248 | 248 | names = co.co_varnames |
|
249 | 249 | args = list(names[:nargs]) |
|
250 | 250 | step = 0 |
|
251 | 251 | |
|
252 | 252 | # The following acrobatics are for anonymous (tuple) arguments. |
|
253 | 253 | for i in range(nargs): |
|
254 | 254 | if args[i][:1] in ('', '.'): |
|
255 | 255 | stack, remain, count = [], [], [] |
|
256 | 256 | while step < len(co.co_code): |
|
257 | 257 | op = ord(co.co_code[step]) |
|
258 | 258 | step = step + 1 |
|
259 | 259 | if op >= dis.HAVE_ARGUMENT: |
|
260 | 260 | opname = dis.opname[op] |
|
261 | 261 | value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256 |
|
262 | 262 | step = step + 2 |
|
263 | 263 | if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'): |
|
264 | 264 | remain.append(value) |
|
265 | 265 | count.append(value) |
|
266 | 266 | elif opname in ('STORE_FAST', 'STORE_DEREF'): |
|
267 | 267 | if op in dis.haslocal: |
|
268 | 268 | stack.append(co.co_varnames[value]) |
|
269 | 269 | elif op in dis.hasfree: |
|
270 | 270 | stack.append((co.co_cellvars + co.co_freevars)[value]) |
|
271 | 271 | # Special case for sublists of length 1: def foo((bar)) |
|
272 | 272 | # doesn't generate the UNPACK_TUPLE bytecode, so if |
|
273 | 273 | # `remain` is empty here, we have such a sublist. |
|
274 | 274 | if not remain: |
|
275 | 275 | stack[0] = [stack[0]] |
|
276 | 276 | break |
|
277 | 277 | else: |
|
278 | 278 | remain[-1] = remain[-1] - 1 |
|
279 | 279 | while remain[-1] == 0: |
|
280 | 280 | remain.pop() |
|
281 | 281 | size = count.pop() |
|
282 | 282 | stack[-size:] = [stack[-size:]] |
|
283 | 283 | if not remain: |
|
284 | 284 | break |
|
285 | 285 | remain[-1] = remain[-1] - 1 |
|
286 | 286 | if not remain: |
|
287 | 287 | break |
|
288 | 288 | args[i] = stack[0] |
|
289 | 289 | |
|
290 | 290 | varargs = None |
|
291 | 291 | if co.co_flags & inspect.CO_VARARGS: |
|
292 | 292 | varargs = co.co_varnames[nargs] |
|
293 | 293 | nargs = nargs + 1 |
|
294 | 294 | varkw = None |
|
295 | 295 | if co.co_flags & inspect.CO_VARKEYWORDS: |
|
296 | 296 | varkw = co.co_varnames[nargs] |
|
297 | 297 | return inspect.Arguments(args, varargs, varkw) |
|
298 | 298 | |
|
299 | 299 | |
|
300 | 300 | # Monkeypatch inspect to apply our bugfix. |
|
301 | 301 | def with_patch_inspect(f): |
|
302 | """decorator for monkeypatching inspect.findsource""" | |
|
302 | """ | |
|
303 | Deprecated since IPython 6.0 | |
|
304 | decorator for monkeypatching inspect.findsource | |
|
305 | """ | |
|
303 | 306 | |
|
304 | 307 | def wrapped(*args, **kwargs): |
|
305 | 308 | save_findsource = inspect.findsource |
|
306 | 309 | save_getargs = inspect.getargs |
|
307 | 310 | inspect.findsource = findsource |
|
308 | 311 | inspect.getargs = getargs |
|
309 | 312 | try: |
|
310 | 313 | return f(*args, **kwargs) |
|
311 | 314 | finally: |
|
312 | 315 | inspect.findsource = save_findsource |
|
313 | 316 | inspect.getargs = save_getargs |
|
314 | 317 | |
|
315 | 318 | return wrapped |
|
316 | 319 | |
|
317 | 320 | |
|
318 | if py3compat.PY3: | |
|
319 | fixed_getargvalues = inspect.getargvalues | |
|
320 | else: | |
|
321 | # Fixes for https://github.com/ipython/ipython/issues/8293 | |
|
322 | # and https://github.com/ipython/ipython/issues/8205. | |
|
323 | # The relevant bug is caused by failure to correctly handle anonymous tuple | |
|
324 | # unpacking, which only exists in Python 2. | |
|
325 | fixed_getargvalues = with_patch_inspect(inspect.getargvalues) | |
|
326 | ||
|
327 | ||
|
328 | 321 | def fix_frame_records_filenames(records): |
|
329 | 322 | """Try to fix the filenames in each record from inspect.getinnerframes(). |
|
330 | 323 | |
|
331 | 324 | Particularly, modules loaded from within zip files have useless filenames |
|
332 | 325 | attached to their code object, and inspect.getinnerframes() just uses it. |
|
333 | 326 | """ |
|
334 | 327 | fixed_records = [] |
|
335 | 328 | for frame, filename, line_no, func_name, lines, index in records: |
|
336 | 329 | # Look inside the frame's globals dictionary for __file__, |
|
337 | 330 | # which should be better. However, keep Cython filenames since |
|
338 | 331 | # we prefer the source filenames over the compiled .so file. |
|
339 | 332 | filename = py3compat.cast_unicode_py2(filename, "utf-8") |
|
340 | 333 | if not filename.endswith(('.pyx', '.pxd', '.pxi')): |
|
341 | 334 | better_fn = frame.f_globals.get('__file__', None) |
|
342 | 335 | if isinstance(better_fn, str): |
|
343 | 336 | # Check the type just in case someone did something weird with |
|
344 | 337 | # __file__. It might also be None if the error occurred during |
|
345 | 338 | # import. |
|
346 | 339 | filename = better_fn |
|
347 | 340 | fixed_records.append((frame, filename, line_no, func_name, lines, index)) |
|
348 | 341 | return fixed_records |
|
349 | 342 | |
|
350 | 343 | |
|
351 | 344 | @with_patch_inspect |
|
352 | 345 | def _fixed_getinnerframes(etb, context=1, tb_offset=0): |
|
353 | 346 | LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5 |
|
354 | 347 | |
|
355 | 348 | records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) |
|
356 | 349 | # If the error is at the console, don't build any context, since it would |
|
357 | 350 | # otherwise produce 5 blank lines printed out (there is no file at the |
|
358 | 351 | # console) |
|
359 | 352 | rec_check = records[tb_offset:] |
|
360 | 353 | try: |
|
361 | 354 | rname = rec_check[0][1] |
|
362 | 355 | if rname == '<ipython console>' or rname.endswith('<string>'): |
|
363 | 356 | return rec_check |
|
364 | 357 | except IndexError: |
|
365 | 358 | pass |
|
366 | 359 | |
|
367 | 360 | aux = traceback.extract_tb(etb) |
|
368 | 361 | assert len(records) == len(aux) |
|
369 | 362 | for i, (file, lnum, _, _) in zip(range(len(records)), aux): |
|
370 | 363 | maybeStart = lnum - 1 - context // 2 |
|
371 | 364 | start = max(maybeStart, 0) |
|
372 | 365 | end = start + context |
|
373 | 366 | lines = ulinecache.getlines(file)[start:end] |
|
374 | 367 | buf = list(records[i]) |
|
375 | 368 | buf[LNUM_POS] = lnum |
|
376 | 369 | buf[INDEX_POS] = lnum - 1 - start |
|
377 | 370 | buf[LINES_POS] = lines |
|
378 | 371 | records[i] = tuple(buf) |
|
379 | 372 | return records[tb_offset:] |
|
380 | 373 | |
|
381 | 374 | # Helper function -- largely belongs to VerboseTB, but we need the same |
|
382 | 375 | # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they |
|
383 | 376 | # can be recognized properly by ipython.el's py-traceback-line-re |
|
384 | 377 | # (SyntaxErrors have to be treated specially because they have no traceback) |
|
385 | 378 | |
|
386 | 379 | |
|
387 | 380 | def _format_traceback_lines(lnum, index, lines, Colors, lvals=None, _line_format=(lambda x,_:x,None)): |
|
388 | 381 | numbers_width = INDENT_SIZE - 1 |
|
389 | 382 | res = [] |
|
390 | 383 | i = lnum - index |
|
391 | 384 | |
|
392 | 385 | for line in lines: |
|
393 | 386 | line = py3compat.cast_unicode(line) |
|
394 | 387 | |
|
395 | 388 | new_line, err = _line_format(line, 'str') |
|
396 | 389 | if not err: line = new_line |
|
397 | 390 | |
|
398 | 391 | if i == lnum: |
|
399 | 392 | # This is the line with the error |
|
400 | 393 | pad = numbers_width - len(str(i)) |
|
401 | 394 | num = '%s%s' % (debugger.make_arrow(pad), str(lnum)) |
|
402 | 395 | line = '%s%s%s %s%s' % (Colors.linenoEm, num, |
|
403 | 396 | Colors.line, line, Colors.Normal) |
|
404 | 397 | else: |
|
405 | 398 | num = '%*s' % (numbers_width, i) |
|
406 | 399 | line = '%s%s%s %s' % (Colors.lineno, num, |
|
407 | 400 | Colors.Normal, line) |
|
408 | 401 | |
|
409 | 402 | res.append(line) |
|
410 | 403 | if lvals and i == lnum: |
|
411 | 404 | res.append(lvals + '\n') |
|
412 | 405 | i = i + 1 |
|
413 | 406 | return res |
|
414 | 407 | |
|
415 | 408 | def is_recursion_error(etype, value, records): |
|
416 | 409 | try: |
|
417 | 410 | # RecursionError is new in Python 3.5 |
|
418 | 411 | recursion_error_type = RecursionError |
|
419 | 412 | except NameError: |
|
420 | 413 | recursion_error_type = RuntimeError |
|
421 | 414 | |
|
422 | 415 | # The default recursion limit is 1000, but some of that will be taken up |
|
423 | 416 | # by stack frames in IPython itself. >500 frames probably indicates |
|
424 | 417 | # a recursion error. |
|
425 | 418 | return (etype is recursion_error_type) \ |
|
426 | 419 | and "recursion" in str(value).lower() \ |
|
427 | 420 | and len(records) > 500 |
|
428 | 421 | |
|
429 | 422 | def find_recursion(etype, value, records): |
|
430 | 423 | """Identify the repeating stack frames from a RecursionError traceback |
|
431 | 424 | |
|
432 | 425 | 'records' is a list as returned by VerboseTB.get_records() |
|
433 | 426 | |
|
434 | 427 | Returns (last_unique, repeat_length) |
|
435 | 428 | """ |
|
436 | 429 | # This involves a bit of guesswork - we want to show enough of the traceback |
|
437 | 430 | # to indicate where the recursion is occurring. We guess that the innermost |
|
438 | 431 | # quarter of the traceback (250 frames by default) is repeats, and find the |
|
439 | 432 | # first frame (from in to out) that looks different. |
|
440 | 433 | if not is_recursion_error(etype, value, records): |
|
441 | 434 | return len(records), 0 |
|
442 | 435 | |
|
443 | 436 | # Select filename, lineno, func_name to track frames with |
|
444 | 437 | records = [r[1:4] for r in records] |
|
445 | 438 | inner_frames = records[-(len(records)//4):] |
|
446 | 439 | frames_repeated = set(inner_frames) |
|
447 | 440 | |
|
448 | 441 | last_seen_at = {} |
|
449 | 442 | longest_repeat = 0 |
|
450 | 443 | i = len(records) |
|
451 | 444 | for frame in reversed(records): |
|
452 | 445 | i -= 1 |
|
453 | 446 | if frame not in frames_repeated: |
|
454 | 447 | last_unique = i |
|
455 | 448 | break |
|
456 | 449 | |
|
457 | 450 | if frame in last_seen_at: |
|
458 | 451 | distance = last_seen_at[frame] - i |
|
459 | 452 | longest_repeat = max(longest_repeat, distance) |
|
460 | 453 | |
|
461 | 454 | last_seen_at[frame] = i |
|
462 | 455 | else: |
|
463 | 456 | last_unique = 0 # The whole traceback was recursion |
|
464 | 457 | |
|
465 | 458 | return last_unique, longest_repeat |
|
466 | 459 | |
|
467 | 460 | #--------------------------------------------------------------------------- |
|
468 | 461 | # Module classes |
|
469 | 462 | class TBTools(colorable.Colorable): |
|
470 | 463 | """Basic tools used by all traceback printer classes.""" |
|
471 | 464 | |
|
472 | 465 | # Number of frames to skip when reporting tracebacks |
|
473 | 466 | tb_offset = 0 |
|
474 | 467 | |
|
475 | 468 | def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None): |
|
476 | 469 | # Whether to call the interactive pdb debugger after printing |
|
477 | 470 | # tracebacks or not |
|
478 | 471 | super(TBTools, self).__init__(parent=parent, config=config) |
|
479 | 472 | self.call_pdb = call_pdb |
|
480 | 473 | |
|
481 | 474 | # Output stream to write to. Note that we store the original value in |
|
482 | 475 | # a private attribute and then make the public ostream a property, so |
|
483 | 476 | # that we can delay accessing sys.stdout until runtime. The way |
|
484 | 477 | # things are written now, the sys.stdout object is dynamically managed |
|
485 | 478 | # so a reference to it should NEVER be stored statically. This |
|
486 | 479 | # property approach confines this detail to a single location, and all |
|
487 | 480 | # subclasses can simply access self.ostream for writing. |
|
488 | 481 | self._ostream = ostream |
|
489 | 482 | |
|
490 | 483 | # Create color table |
|
491 | 484 | self.color_scheme_table = exception_colors() |
|
492 | 485 | |
|
493 | 486 | self.set_colors(color_scheme) |
|
494 | 487 | self.old_scheme = color_scheme # save initial value for toggles |
|
495 | 488 | |
|
496 | 489 | if call_pdb: |
|
497 | 490 | self.pdb = debugger.Pdb() |
|
498 | 491 | else: |
|
499 | 492 | self.pdb = None |
|
500 | 493 | |
|
501 | 494 | def _get_ostream(self): |
|
502 | 495 | """Output stream that exceptions are written to. |
|
503 | 496 | |
|
504 | 497 | Valid values are: |
|
505 | 498 | |
|
506 | 499 | - None: the default, which means that IPython will dynamically resolve |
|
507 | 500 | to sys.stdout. This ensures compatibility with most tools, including |
|
508 | 501 | Windows (where plain stdout doesn't recognize ANSI escapes). |
|
509 | 502 | |
|
510 | 503 | - Any object with 'write' and 'flush' attributes. |
|
511 | 504 | """ |
|
512 | 505 | return sys.stdout if self._ostream is None else self._ostream |
|
513 | 506 | |
|
514 | 507 | def _set_ostream(self, val): |
|
515 | 508 | assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush')) |
|
516 | 509 | self._ostream = val |
|
517 | 510 | |
|
518 | 511 | ostream = property(_get_ostream, _set_ostream) |
|
519 | 512 | |
|
520 | 513 | def set_colors(self, *args, **kw): |
|
521 | 514 | """Shorthand access to the color table scheme selector method.""" |
|
522 | 515 | |
|
523 | 516 | # Set own color table |
|
524 | 517 | self.color_scheme_table.set_active_scheme(*args, **kw) |
|
525 | 518 | # for convenience, set Colors to the active scheme |
|
526 | 519 | self.Colors = self.color_scheme_table.active_colors |
|
527 | 520 | # Also set colors of debugger |
|
528 | 521 | if hasattr(self, 'pdb') and self.pdb is not None: |
|
529 | 522 | self.pdb.set_colors(*args, **kw) |
|
530 | 523 | |
|
531 | 524 | def color_toggle(self): |
|
532 | 525 | """Toggle between the currently active color scheme and NoColor.""" |
|
533 | 526 | |
|
534 | 527 | if self.color_scheme_table.active_scheme_name == 'NoColor': |
|
535 | 528 | self.color_scheme_table.set_active_scheme(self.old_scheme) |
|
536 | 529 | self.Colors = self.color_scheme_table.active_colors |
|
537 | 530 | else: |
|
538 | 531 | self.old_scheme = self.color_scheme_table.active_scheme_name |
|
539 | 532 | self.color_scheme_table.set_active_scheme('NoColor') |
|
540 | 533 | self.Colors = self.color_scheme_table.active_colors |
|
541 | 534 | |
|
542 | 535 | def stb2text(self, stb): |
|
543 | 536 | """Convert a structured traceback (a list) to a string.""" |
|
544 | 537 | return '\n'.join(stb) |
|
545 | 538 | |
|
546 | 539 | def text(self, etype, value, tb, tb_offset=None, context=5): |
|
547 | 540 | """Return formatted traceback. |
|
548 | 541 | |
|
549 | 542 | Subclasses may override this if they add extra arguments. |
|
550 | 543 | """ |
|
551 | 544 | tb_list = self.structured_traceback(etype, value, tb, |
|
552 | 545 | tb_offset, context) |
|
553 | 546 | return self.stb2text(tb_list) |
|
554 | 547 | |
|
555 | 548 | def structured_traceback(self, etype, evalue, tb, tb_offset=None, |
|
556 | 549 | context=5, mode=None): |
|
557 | 550 | """Return a list of traceback frames. |
|
558 | 551 | |
|
559 | 552 | Must be implemented by each class. |
|
560 | 553 | """ |
|
561 | 554 | raise NotImplementedError() |
|
562 | 555 | |
|
563 | 556 | |
|
564 | 557 | #--------------------------------------------------------------------------- |
|
565 | 558 | class ListTB(TBTools): |
|
566 | 559 | """Print traceback information from a traceback list, with optional color. |
|
567 | 560 | |
|
568 | 561 | Calling requires 3 arguments: (etype, evalue, elist) |
|
569 | 562 | as would be obtained by:: |
|
570 | 563 | |
|
571 | 564 | etype, evalue, tb = sys.exc_info() |
|
572 | 565 | if tb: |
|
573 | 566 | elist = traceback.extract_tb(tb) |
|
574 | 567 | else: |
|
575 | 568 | elist = None |
|
576 | 569 | |
|
577 | 570 | It can thus be used by programs which need to process the traceback before |
|
578 | 571 | printing (such as console replacements based on the code module from the |
|
579 | 572 | standard library). |
|
580 | 573 | |
|
581 | 574 | Because they are meant to be called without a full traceback (only a |
|
582 | 575 | list), instances of this class can't call the interactive pdb debugger.""" |
|
583 | 576 | |
|
584 | 577 | def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None): |
|
585 | 578 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
586 | 579 | ostream=ostream, parent=parent,config=config) |
|
587 | 580 | |
|
588 | 581 | def __call__(self, etype, value, elist): |
|
589 | 582 | self.ostream.flush() |
|
590 | 583 | self.ostream.write(self.text(etype, value, elist)) |
|
591 | 584 | self.ostream.write('\n') |
|
592 | 585 | |
|
593 | 586 | def structured_traceback(self, etype, value, elist, tb_offset=None, |
|
594 | 587 | context=5): |
|
595 | 588 | """Return a color formatted string with the traceback info. |
|
596 | 589 | |
|
597 | 590 | Parameters |
|
598 | 591 | ---------- |
|
599 | 592 | etype : exception type |
|
600 | 593 | Type of the exception raised. |
|
601 | 594 | |
|
602 | 595 | value : object |
|
603 | 596 | Data stored in the exception |
|
604 | 597 | |
|
605 | 598 | elist : list |
|
606 | 599 | List of frames, see class docstring for details. |
|
607 | 600 | |
|
608 | 601 | tb_offset : int, optional |
|
609 | 602 | Number of frames in the traceback to skip. If not given, the |
|
610 | 603 | instance value is used (set in constructor). |
|
611 | 604 | |
|
612 | 605 | context : int, optional |
|
613 | 606 | Number of lines of context information to print. |
|
614 | 607 | |
|
615 | 608 | Returns |
|
616 | 609 | ------- |
|
617 | 610 | String with formatted exception. |
|
618 | 611 | """ |
|
619 | 612 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
620 | 613 | Colors = self.Colors |
|
621 | 614 | out_list = [] |
|
622 | 615 | if elist: |
|
623 | 616 | |
|
624 | 617 | if tb_offset and len(elist) > tb_offset: |
|
625 | 618 | elist = elist[tb_offset:] |
|
626 | 619 | |
|
627 | 620 | out_list.append('Traceback %s(most recent call last)%s:' % |
|
628 | 621 | (Colors.normalEm, Colors.Normal) + '\n') |
|
629 | 622 | out_list.extend(self._format_list(elist)) |
|
630 | 623 | # The exception info should be a single entry in the list. |
|
631 | 624 | lines = ''.join(self._format_exception_only(etype, value)) |
|
632 | 625 | out_list.append(lines) |
|
633 | 626 | |
|
634 | 627 | # Note: this code originally read: |
|
635 | 628 | |
|
636 | 629 | ## for line in lines[:-1]: |
|
637 | 630 | ## out_list.append(" "+line) |
|
638 | 631 | ## out_list.append(lines[-1]) |
|
639 | 632 | |
|
640 | 633 | # This means it was indenting everything but the last line by a little |
|
641 | 634 | # bit. I've disabled this for now, but if we see ugliness somewhere we |
|
642 | 635 | # can restore it. |
|
643 | 636 | |
|
644 | 637 | return out_list |
|
645 | 638 | |
|
646 | 639 | def _format_list(self, extracted_list): |
|
647 | 640 | """Format a list of traceback entry tuples for printing. |
|
648 | 641 | |
|
649 | 642 | Given a list of tuples as returned by extract_tb() or |
|
650 | 643 | extract_stack(), return a list of strings ready for printing. |
|
651 | 644 | Each string in the resulting list corresponds to the item with the |
|
652 | 645 | same index in the argument list. Each string ends in a newline; |
|
653 | 646 | the strings may contain internal newlines as well, for those items |
|
654 | 647 | whose source text line is not None. |
|
655 | 648 | |
|
656 | 649 | Lifted almost verbatim from traceback.py |
|
657 | 650 | """ |
|
658 | 651 | |
|
659 | 652 | Colors = self.Colors |
|
660 | 653 | list = [] |
|
661 | 654 | for filename, lineno, name, line in extracted_list[:-1]: |
|
662 | 655 | item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \ |
|
663 | 656 | (Colors.filename, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.Normal, |
|
664 | 657 | Colors.lineno, lineno, Colors.Normal, |
|
665 | 658 | Colors.name, py3compat.cast_unicode_py2(name, "utf-8"), Colors.Normal) |
|
666 | 659 | if line: |
|
667 | 660 | item += ' %s\n' % line.strip() |
|
668 | 661 | list.append(item) |
|
669 | 662 | # Emphasize the last entry |
|
670 | 663 | filename, lineno, name, line = extracted_list[-1] |
|
671 | 664 | item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \ |
|
672 | 665 | (Colors.normalEm, |
|
673 | 666 | Colors.filenameEm, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.normalEm, |
|
674 | 667 | Colors.linenoEm, lineno, Colors.normalEm, |
|
675 | 668 | Colors.nameEm, py3compat.cast_unicode_py2(name, "utf-8"), Colors.normalEm, |
|
676 | 669 | Colors.Normal) |
|
677 | 670 | if line: |
|
678 | 671 | item += '%s %s%s\n' % (Colors.line, line.strip(), |
|
679 | 672 | Colors.Normal) |
|
680 | 673 | list.append(item) |
|
681 | 674 | return list |
|
682 | 675 | |
|
683 | 676 | def _format_exception_only(self, etype, value): |
|
684 | 677 | """Format the exception part of a traceback. |
|
685 | 678 | |
|
686 | 679 | The arguments are the exception type and value such as given by |
|
687 | 680 | sys.exc_info()[:2]. The return value is a list of strings, each ending |
|
688 | 681 | in a newline. Normally, the list contains a single string; however, |
|
689 | 682 | for SyntaxError exceptions, it contains several lines that (when |
|
690 | 683 | printed) display detailed information about where the syntax error |
|
691 | 684 | occurred. The message indicating which exception occurred is the |
|
692 | 685 | always last string in the list. |
|
693 | 686 | |
|
694 | 687 | Also lifted nearly verbatim from traceback.py |
|
695 | 688 | """ |
|
696 | 689 | have_filedata = False |
|
697 | 690 | Colors = self.Colors |
|
698 | 691 | list = [] |
|
699 | 692 | stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal) |
|
700 | 693 | if value is None: |
|
701 | 694 | # Not sure if this can still happen in Python 2.6 and above |
|
702 | 695 | list.append(stype + '\n') |
|
703 | 696 | else: |
|
704 | 697 | if issubclass(etype, SyntaxError): |
|
705 | 698 | have_filedata = True |
|
706 | 699 | if not value.filename: value.filename = "<string>" |
|
707 | 700 | if value.lineno: |
|
708 | 701 | lineno = value.lineno |
|
709 | 702 | textline = ulinecache.getline(value.filename, value.lineno) |
|
710 | 703 | else: |
|
711 | 704 | lineno = 'unknown' |
|
712 | 705 | textline = '' |
|
713 | 706 | list.append('%s File %s"%s"%s, line %s%s%s\n' % \ |
|
714 | 707 | (Colors.normalEm, |
|
715 | 708 | Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm, |
|
716 | 709 | Colors.linenoEm, lineno, Colors.Normal )) |
|
717 | 710 | if textline == '': |
|
718 | 711 | textline = py3compat.cast_unicode(value.text, "utf-8") |
|
719 | 712 | |
|
720 | 713 | if textline is not None: |
|
721 | 714 | i = 0 |
|
722 | 715 | while i < len(textline) and textline[i].isspace(): |
|
723 | 716 | i += 1 |
|
724 | 717 | list.append('%s %s%s\n' % (Colors.line, |
|
725 | 718 | textline.strip(), |
|
726 | 719 | Colors.Normal)) |
|
727 | 720 | if value.offset is not None: |
|
728 | 721 | s = ' ' |
|
729 | 722 | for c in textline[i:value.offset - 1]: |
|
730 | 723 | if c.isspace(): |
|
731 | 724 | s += c |
|
732 | 725 | else: |
|
733 | 726 | s += ' ' |
|
734 | 727 | list.append('%s%s^%s\n' % (Colors.caret, s, |
|
735 | 728 | Colors.Normal)) |
|
736 | 729 | |
|
737 | 730 | try: |
|
738 | 731 | s = value.msg |
|
739 | 732 | except Exception: |
|
740 | 733 | s = self._some_str(value) |
|
741 | 734 | if s: |
|
742 | 735 | list.append('%s%s:%s %s\n' % (stype, Colors.excName, |
|
743 | 736 | Colors.Normal, s)) |
|
744 | 737 | else: |
|
745 | 738 | list.append('%s\n' % stype) |
|
746 | 739 | |
|
747 | 740 | # sync with user hooks |
|
748 | 741 | if have_filedata: |
|
749 | 742 | ipinst = get_ipython() |
|
750 | 743 | if ipinst is not None: |
|
751 | 744 | ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0) |
|
752 | 745 | |
|
753 | 746 | return list |
|
754 | 747 | |
|
755 | 748 | def get_exception_only(self, etype, value): |
|
756 | 749 | """Only print the exception type and message, without a traceback. |
|
757 | 750 | |
|
758 | 751 | Parameters |
|
759 | 752 | ---------- |
|
760 | 753 | etype : exception type |
|
761 | 754 | value : exception value |
|
762 | 755 | """ |
|
763 | 756 | return ListTB.structured_traceback(self, etype, value, []) |
|
764 | 757 | |
|
765 | 758 | def show_exception_only(self, etype, evalue): |
|
766 | 759 | """Only print the exception type and message, without a traceback. |
|
767 | 760 | |
|
768 | 761 | Parameters |
|
769 | 762 | ---------- |
|
770 | 763 | etype : exception type |
|
771 | 764 | value : exception value |
|
772 | 765 | """ |
|
773 | 766 | # This method needs to use __call__ from *this* class, not the one from |
|
774 | 767 | # a subclass whose signature or behavior may be different |
|
775 | 768 | ostream = self.ostream |
|
776 | 769 | ostream.flush() |
|
777 | 770 | ostream.write('\n'.join(self.get_exception_only(etype, evalue))) |
|
778 | 771 | ostream.flush() |
|
779 | 772 | |
|
780 | 773 | def _some_str(self, value): |
|
781 | 774 | # Lifted from traceback.py |
|
782 | 775 | try: |
|
783 | 776 | return py3compat.cast_unicode(str(value)) |
|
784 | 777 | except: |
|
785 | 778 | return u'<unprintable %s object>' % type(value).__name__ |
|
786 | 779 | |
|
787 | 780 | |
|
788 | 781 | #---------------------------------------------------------------------------- |
|
789 | 782 | class VerboseTB(TBTools): |
|
790 | 783 | """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead |
|
791 | 784 | of HTML. Requires inspect and pydoc. Crazy, man. |
|
792 | 785 | |
|
793 | 786 | Modified version which optionally strips the topmost entries from the |
|
794 | 787 | traceback, to be used with alternate interpreters (because their own code |
|
795 | 788 | would appear in the traceback).""" |
|
796 | 789 | |
|
797 | 790 | def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None, |
|
798 | 791 | tb_offset=0, long_header=False, include_vars=True, |
|
799 | 792 | check_cache=None, debugger_cls = None, |
|
800 | 793 | parent=None, config=None): |
|
801 | 794 | """Specify traceback offset, headers and color scheme. |
|
802 | 795 | |
|
803 | 796 | Define how many frames to drop from the tracebacks. Calling it with |
|
804 | 797 | tb_offset=1 allows use of this handler in interpreters which will have |
|
805 | 798 | their own code at the top of the traceback (VerboseTB will first |
|
806 | 799 | remove that frame before printing the traceback info).""" |
|
807 | 800 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
808 | 801 | ostream=ostream, parent=parent, config=config) |
|
809 | 802 | self.tb_offset = tb_offset |
|
810 | 803 | self.long_header = long_header |
|
811 | 804 | self.include_vars = include_vars |
|
812 | 805 | # By default we use linecache.checkcache, but the user can provide a |
|
813 | 806 | # different check_cache implementation. This is used by the IPython |
|
814 | 807 | # kernel to provide tracebacks for interactive code that is cached, |
|
815 | 808 | # by a compiler instance that flushes the linecache but preserves its |
|
816 | 809 | # own code cache. |
|
817 | 810 | if check_cache is None: |
|
818 | 811 | check_cache = linecache.checkcache |
|
819 | 812 | self.check_cache = check_cache |
|
820 | 813 | |
|
821 | 814 | self.debugger_cls = debugger_cls or debugger.Pdb |
|
822 | 815 | |
|
823 | 816 | def format_records(self, records, last_unique, recursion_repeat): |
|
824 | 817 | """Format the stack frames of the traceback""" |
|
825 | 818 | frames = [] |
|
826 | 819 | for r in records[:last_unique+recursion_repeat+1]: |
|
827 | 820 | #print '*** record:',file,lnum,func,lines,index # dbg |
|
828 | 821 | frames.append(self.format_record(*r)) |
|
829 | 822 | |
|
830 | 823 | if recursion_repeat: |
|
831 | 824 | frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat) |
|
832 | 825 | frames.append(self.format_record(*records[last_unique+recursion_repeat+1])) |
|
833 | 826 | |
|
834 | 827 | return frames |
|
835 | 828 | |
|
836 | 829 | def format_record(self, frame, file, lnum, func, lines, index): |
|
837 | 830 | """Format a single stack frame""" |
|
838 | 831 | Colors = self.Colors # just a shorthand + quicker name lookup |
|
839 | 832 | ColorsNormal = Colors.Normal # used a lot |
|
840 | 833 | col_scheme = self.color_scheme_table.active_scheme_name |
|
841 | 834 | indent = ' ' * INDENT_SIZE |
|
842 | 835 | em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal) |
|
843 | 836 | undefined = '%sundefined%s' % (Colors.em, ColorsNormal) |
|
844 | 837 | tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal) |
|
845 | 838 | tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, |
|
846 | 839 | ColorsNormal) |
|
847 | 840 | tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \ |
|
848 | 841 | (Colors.vName, Colors.valEm, ColorsNormal) |
|
849 | 842 | tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal) |
|
850 | 843 | tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal, |
|
851 | 844 | Colors.vName, ColorsNormal) |
|
852 | 845 | tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal) |
|
853 | 846 | |
|
854 | 847 | tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal) |
|
855 | 848 | tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm, Colors.line, |
|
856 | 849 | ColorsNormal) |
|
857 | 850 | |
|
858 | 851 | abspath = os.path.abspath |
|
859 | 852 | |
|
860 | 853 | |
|
861 | 854 | if not file: |
|
862 | 855 | file = '?' |
|
863 | 856 | elif file.startswith(str("<")) and file.endswith(str(">")): |
|
864 | 857 | # Not a real filename, no problem... |
|
865 | 858 | pass |
|
866 | 859 | elif not os.path.isabs(file): |
|
867 | 860 | # Try to make the filename absolute by trying all |
|
868 | 861 | # sys.path entries (which is also what linecache does) |
|
869 | 862 | for dirname in sys.path: |
|
870 | 863 | try: |
|
871 | 864 | fullname = os.path.join(dirname, file) |
|
872 | 865 | if os.path.isfile(fullname): |
|
873 | 866 | file = os.path.abspath(fullname) |
|
874 | 867 | break |
|
875 | 868 | except Exception: |
|
876 | 869 | # Just in case that sys.path contains very |
|
877 | 870 | # strange entries... |
|
878 | 871 | pass |
|
879 | 872 | |
|
880 | 873 | file = py3compat.cast_unicode(file, util_path.fs_encoding) |
|
881 | 874 | link = tpl_link % file |
|
882 |
args, varargs, varkw, locals = |
|
|
875 | args, varargs, varkw, locals = inspect.getargvalues(frame) | |
|
883 | 876 | |
|
884 | 877 | if func == '?': |
|
885 | 878 | call = '' |
|
886 | 879 | else: |
|
887 | 880 | # Decide whether to include variable details or not |
|
888 | 881 | var_repr = self.include_vars and eqrepr or nullrepr |
|
889 | 882 | try: |
|
890 | 883 | call = tpl_call % (func, inspect.formatargvalues(args, |
|
891 | 884 | varargs, varkw, |
|
892 | 885 | locals, formatvalue=var_repr)) |
|
893 | 886 | except KeyError: |
|
894 | 887 | # This happens in situations like errors inside generator |
|
895 | 888 | # expressions, where local variables are listed in the |
|
896 | 889 | # line, but can't be extracted from the frame. I'm not |
|
897 | 890 | # 100% sure this isn't actually a bug in inspect itself, |
|
898 | 891 | # but since there's no info for us to compute with, the |
|
899 | 892 | # best we can do is report the failure and move on. Here |
|
900 | 893 | # we must *not* call any traceback construction again, |
|
901 | 894 | # because that would mess up use of %debug later on. So we |
|
902 | 895 | # simply report the failure and move on. The only |
|
903 | 896 | # limitation will be that this frame won't have locals |
|
904 | 897 | # listed in the call signature. Quite subtle problem... |
|
905 | 898 | # I can't think of a good way to validate this in a unit |
|
906 | 899 | # test, but running a script consisting of: |
|
907 | 900 | # dict( (k,v.strip()) for (k,v) in range(10) ) |
|
908 | 901 | # will illustrate the error, if this exception catch is |
|
909 | 902 | # disabled. |
|
910 | 903 | call = tpl_call_fail % func |
|
911 | 904 | |
|
912 | 905 | # Don't attempt to tokenize binary files. |
|
913 | 906 | if file.endswith(('.so', '.pyd', '.dll')): |
|
914 | 907 | return '%s %s\n' % (link, call) |
|
915 | 908 | |
|
916 | 909 | elif file.endswith(('.pyc', '.pyo')): |
|
917 | 910 | # Look up the corresponding source file. |
|
918 | 911 | try: |
|
919 | 912 | file = openpy.source_from_cache(file) |
|
920 | 913 | except ValueError: |
|
921 | 914 | # Failed to get the source file for some reason |
|
922 | 915 | # E.g. https://github.com/ipython/ipython/issues/9486 |
|
923 | 916 | return '%s %s\n' % (link, call) |
|
924 | 917 | |
|
925 | 918 | def linereader(file=file, lnum=[lnum], getline=ulinecache.getline): |
|
926 | 919 | line = getline(file, lnum[0]) |
|
927 | 920 | lnum[0] += 1 |
|
928 | 921 | return line |
|
929 | 922 | |
|
930 | 923 | # Build the list of names on this line of code where the exception |
|
931 | 924 | # occurred. |
|
932 | 925 | try: |
|
933 | 926 | names = [] |
|
934 | 927 | name_cont = False |
|
935 | 928 | |
|
936 | 929 | for token_type, token, start, end, line in generate_tokens(linereader): |
|
937 | 930 | # build composite names |
|
938 | 931 | if token_type == tokenize.NAME and token not in keyword.kwlist: |
|
939 | 932 | if name_cont: |
|
940 | 933 | # Continuation of a dotted name |
|
941 | 934 | try: |
|
942 | 935 | names[-1].append(token) |
|
943 | 936 | except IndexError: |
|
944 | 937 | names.append([token]) |
|
945 | 938 | name_cont = False |
|
946 | 939 | else: |
|
947 | 940 | # Regular new names. We append everything, the caller |
|
948 | 941 | # will be responsible for pruning the list later. It's |
|
949 | 942 | # very tricky to try to prune as we go, b/c composite |
|
950 | 943 | # names can fool us. The pruning at the end is easy |
|
951 | 944 | # to do (or the caller can print a list with repeated |
|
952 | 945 | # names if so desired. |
|
953 | 946 | names.append([token]) |
|
954 | 947 | elif token == '.': |
|
955 | 948 | name_cont = True |
|
956 | 949 | elif token_type == tokenize.NEWLINE: |
|
957 | 950 | break |
|
958 | 951 | |
|
959 | 952 | except (IndexError, UnicodeDecodeError, SyntaxError): |
|
960 | 953 | # signals exit of tokenizer |
|
961 | 954 | # SyntaxError can occur if the file is not actually Python |
|
962 | 955 | # - see gh-6300 |
|
963 | 956 | pass |
|
964 | 957 | except tokenize.TokenError as msg: |
|
965 | 958 | _m = ("An unexpected error occurred while tokenizing input\n" |
|
966 | 959 | "The following traceback may be corrupted or invalid\n" |
|
967 | 960 | "The error message is: %s\n" % msg) |
|
968 | 961 | error(_m) |
|
969 | 962 | |
|
970 | 963 | # Join composite names (e.g. "dict.fromkeys") |
|
971 | 964 | names = ['.'.join(n) for n in names] |
|
972 | 965 | # prune names list of duplicates, but keep the right order |
|
973 | 966 | unique_names = uniq_stable(names) |
|
974 | 967 | |
|
975 | 968 | # Start loop over vars |
|
976 | 969 | lvals = [] |
|
977 | 970 | if self.include_vars: |
|
978 | 971 | for name_full in unique_names: |
|
979 | 972 | name_base = name_full.split('.', 1)[0] |
|
980 | 973 | if name_base in frame.f_code.co_varnames: |
|
981 | 974 | if name_base in locals: |
|
982 | 975 | try: |
|
983 | 976 | value = repr(eval(name_full, locals)) |
|
984 | 977 | except: |
|
985 | 978 | value = undefined |
|
986 | 979 | else: |
|
987 | 980 | value = undefined |
|
988 | 981 | name = tpl_local_var % name_full |
|
989 | 982 | else: |
|
990 | 983 | if name_base in frame.f_globals: |
|
991 | 984 | try: |
|
992 | 985 | value = repr(eval(name_full, frame.f_globals)) |
|
993 | 986 | except: |
|
994 | 987 | value = undefined |
|
995 | 988 | else: |
|
996 | 989 | value = undefined |
|
997 | 990 | name = tpl_global_var % name_full |
|
998 | 991 | lvals.append(tpl_name_val % (name, value)) |
|
999 | 992 | if lvals: |
|
1000 | 993 | lvals = '%s%s' % (indent, em_normal.join(lvals)) |
|
1001 | 994 | else: |
|
1002 | 995 | lvals = '' |
|
1003 | 996 | |
|
1004 | 997 | level = '%s %s\n' % (link, call) |
|
1005 | 998 | |
|
1006 | 999 | if index is None: |
|
1007 | 1000 | return level |
|
1008 | 1001 | else: |
|
1009 | 1002 | _line_format = PyColorize.Parser(style=col_scheme, parent=self).format2 |
|
1010 | 1003 | return '%s%s' % (level, ''.join( |
|
1011 | 1004 | _format_traceback_lines(lnum, index, lines, Colors, lvals, |
|
1012 | 1005 | _line_format))) |
|
1013 | 1006 | |
|
1014 | 1007 | def prepare_chained_exception_message(self, cause): |
|
1015 | 1008 | direct_cause = "\nThe above exception was the direct cause of the following exception:\n" |
|
1016 | 1009 | exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n" |
|
1017 | 1010 | |
|
1018 | 1011 | if cause: |
|
1019 | 1012 | message = [[direct_cause]] |
|
1020 | 1013 | else: |
|
1021 | 1014 | message = [[exception_during_handling]] |
|
1022 | 1015 | return message |
|
1023 | 1016 | |
|
1024 | 1017 | def prepare_header(self, etype, long_version=False): |
|
1025 | 1018 | colors = self.Colors # just a shorthand + quicker name lookup |
|
1026 | 1019 | colorsnormal = colors.Normal # used a lot |
|
1027 | 1020 | exc = '%s%s%s' % (colors.excName, etype, colorsnormal) |
|
1028 | 1021 | width = min(75, get_terminal_size()[0]) |
|
1029 | 1022 | if long_version: |
|
1030 | 1023 | # Header with the exception type, python version, and date |
|
1031 | 1024 | pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable |
|
1032 | 1025 | date = time.ctime(time.time()) |
|
1033 | 1026 | |
|
1034 | 1027 | head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal, |
|
1035 | 1028 | exc, ' ' * (width - len(str(etype)) - len(pyver)), |
|
1036 | 1029 | pyver, date.rjust(width) ) |
|
1037 | 1030 | head += "\nA problem occurred executing Python code. Here is the sequence of function" \ |
|
1038 | 1031 | "\ncalls leading up to the error, with the most recent (innermost) call last." |
|
1039 | 1032 | else: |
|
1040 | 1033 | # Simplified header |
|
1041 | 1034 | head = '%s%s' % (exc, 'Traceback (most recent call last)'. \ |
|
1042 | 1035 | rjust(width - len(str(etype))) ) |
|
1043 | 1036 | |
|
1044 | 1037 | return head |
|
1045 | 1038 | |
|
1046 | 1039 | def format_exception(self, etype, evalue): |
|
1047 | 1040 | colors = self.Colors # just a shorthand + quicker name lookup |
|
1048 | 1041 | colorsnormal = colors.Normal # used a lot |
|
1049 | 1042 | indent = ' ' * INDENT_SIZE |
|
1050 | 1043 | # Get (safely) a string form of the exception info |
|
1051 | 1044 | try: |
|
1052 | 1045 | etype_str, evalue_str = map(str, (etype, evalue)) |
|
1053 | 1046 | except: |
|
1054 | 1047 | # User exception is improperly defined. |
|
1055 | 1048 | etype, evalue = str, sys.exc_info()[:2] |
|
1056 | 1049 | etype_str, evalue_str = map(str, (etype, evalue)) |
|
1057 | 1050 | # ... and format it |
|
1058 | 1051 | return ['%s%s%s: %s' % (colors.excName, etype_str, |
|
1059 | 1052 | colorsnormal, py3compat.cast_unicode(evalue_str))] |
|
1060 | 1053 | |
|
1061 | 1054 | def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset): |
|
1062 | 1055 | """Formats the header, traceback and exception message for a single exception. |
|
1063 | 1056 | |
|
1064 | 1057 | This may be called multiple times by Python 3 exception chaining |
|
1065 | 1058 | (PEP 3134). |
|
1066 | 1059 | """ |
|
1067 | 1060 | # some locals |
|
1068 | 1061 | orig_etype = etype |
|
1069 | 1062 | try: |
|
1070 | 1063 | etype = etype.__name__ |
|
1071 | 1064 | except AttributeError: |
|
1072 | 1065 | pass |
|
1073 | 1066 | |
|
1074 | 1067 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
1075 | 1068 | head = self.prepare_header(etype, self.long_header) |
|
1076 | 1069 | records = self.get_records(etb, number_of_lines_of_context, tb_offset) |
|
1077 | 1070 | |
|
1078 | 1071 | if records is None: |
|
1079 | 1072 | return "" |
|
1080 | 1073 | |
|
1081 | 1074 | last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records) |
|
1082 | 1075 | |
|
1083 | 1076 | frames = self.format_records(records, last_unique, recursion_repeat) |
|
1084 | 1077 | |
|
1085 | 1078 | formatted_exception = self.format_exception(etype, evalue) |
|
1086 | 1079 | if records: |
|
1087 | 1080 | filepath, lnum = records[-1][1:3] |
|
1088 | 1081 | filepath = os.path.abspath(filepath) |
|
1089 | 1082 | ipinst = get_ipython() |
|
1090 | 1083 | if ipinst is not None: |
|
1091 | 1084 | ipinst.hooks.synchronize_with_editor(filepath, lnum, 0) |
|
1092 | 1085 | |
|
1093 | 1086 | return [[head] + frames + [''.join(formatted_exception[0])]] |
|
1094 | 1087 | |
|
1095 | 1088 | def get_records(self, etb, number_of_lines_of_context, tb_offset): |
|
1096 | 1089 | try: |
|
1097 | 1090 | # Try the default getinnerframes and Alex's: Alex's fixes some |
|
1098 | 1091 | # problems, but it generates empty tracebacks for console errors |
|
1099 | 1092 | # (5 blanks lines) where none should be returned. |
|
1100 | 1093 | return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset) |
|
1101 | 1094 | except UnicodeDecodeError: |
|
1102 | 1095 | # This can occur if a file's encoding magic comment is wrong. |
|
1103 | 1096 | # I can't see a way to recover without duplicating a bunch of code |
|
1104 | 1097 | # from the stdlib traceback module. --TK |
|
1105 | 1098 | error('\nUnicodeDecodeError while processing traceback.\n') |
|
1106 | 1099 | return None |
|
1107 | 1100 | except: |
|
1108 | 1101 | # FIXME: I've been getting many crash reports from python 2.3 |
|
1109 | 1102 | # users, traceable to inspect.py. If I can find a small test-case |
|
1110 | 1103 | # to reproduce this, I should either write a better workaround or |
|
1111 | 1104 | # file a bug report against inspect (if that's the real problem). |
|
1112 | 1105 | # So far, I haven't been able to find an isolated example to |
|
1113 | 1106 | # reproduce the problem. |
|
1114 | 1107 | inspect_error() |
|
1115 | 1108 | traceback.print_exc(file=self.ostream) |
|
1116 | 1109 | info('\nUnfortunately, your original traceback can not be constructed.\n') |
|
1117 | 1110 | return None |
|
1118 | 1111 | |
|
1119 | 1112 | def get_parts_of_chained_exception(self, evalue): |
|
1120 | 1113 | def get_chained_exception(exception_value): |
|
1121 | 1114 | cause = getattr(exception_value, '__cause__', None) |
|
1122 | 1115 | if cause: |
|
1123 | 1116 | return cause |
|
1124 | 1117 | if getattr(exception_value, '__suppress_context__', False): |
|
1125 | 1118 | return None |
|
1126 | 1119 | return getattr(exception_value, '__context__', None) |
|
1127 | 1120 | |
|
1128 | 1121 | chained_evalue = get_chained_exception(evalue) |
|
1129 | 1122 | |
|
1130 | 1123 | if chained_evalue: |
|
1131 | 1124 | return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__ |
|
1132 | 1125 | |
|
1133 | 1126 | def structured_traceback(self, etype, evalue, etb, tb_offset=None, |
|
1134 | 1127 | number_of_lines_of_context=5): |
|
1135 | 1128 | """Return a nice text document describing the traceback.""" |
|
1136 | 1129 | |
|
1137 | 1130 | formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context, |
|
1138 | 1131 | tb_offset) |
|
1139 | 1132 | |
|
1140 | 1133 | colors = self.Colors # just a shorthand + quicker name lookup |
|
1141 | 1134 | colorsnormal = colors.Normal # used a lot |
|
1142 | 1135 | head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal) |
|
1143 | 1136 | structured_traceback_parts = [head] |
|
1144 | 1137 | if py3compat.PY3: |
|
1145 | 1138 | chained_exceptions_tb_offset = 0 |
|
1146 | 1139 | lines_of_context = 3 |
|
1147 | 1140 | formatted_exceptions = formatted_exception |
|
1148 | 1141 | exception = self.get_parts_of_chained_exception(evalue) |
|
1149 | 1142 | if exception: |
|
1150 | 1143 | formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__) |
|
1151 | 1144 | etype, evalue, etb = exception |
|
1152 | 1145 | else: |
|
1153 | 1146 | evalue = None |
|
1154 | 1147 | chained_exc_ids = set() |
|
1155 | 1148 | while evalue: |
|
1156 | 1149 | formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context, |
|
1157 | 1150 | chained_exceptions_tb_offset) |
|
1158 | 1151 | exception = self.get_parts_of_chained_exception(evalue) |
|
1159 | 1152 | |
|
1160 | 1153 | if exception and not id(exception[1]) in chained_exc_ids: |
|
1161 | 1154 | chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop |
|
1162 | 1155 | formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__) |
|
1163 | 1156 | etype, evalue, etb = exception |
|
1164 | 1157 | else: |
|
1165 | 1158 | evalue = None |
|
1166 | 1159 | |
|
1167 | 1160 | # we want to see exceptions in a reversed order: |
|
1168 | 1161 | # the first exception should be on top |
|
1169 | 1162 | for formatted_exception in reversed(formatted_exceptions): |
|
1170 | 1163 | structured_traceback_parts += formatted_exception |
|
1171 | 1164 | else: |
|
1172 | 1165 | structured_traceback_parts += formatted_exception[0] |
|
1173 | 1166 | |
|
1174 | 1167 | return structured_traceback_parts |
|
1175 | 1168 | |
|
1176 | 1169 | def debugger(self, force=False): |
|
1177 | 1170 | """Call up the pdb debugger if desired, always clean up the tb |
|
1178 | 1171 | reference. |
|
1179 | 1172 | |
|
1180 | 1173 | Keywords: |
|
1181 | 1174 | |
|
1182 | 1175 | - force(False): by default, this routine checks the instance call_pdb |
|
1183 | 1176 | flag and does not actually invoke the debugger if the flag is false. |
|
1184 | 1177 | The 'force' option forces the debugger to activate even if the flag |
|
1185 | 1178 | is false. |
|
1186 | 1179 | |
|
1187 | 1180 | If the call_pdb flag is set, the pdb interactive debugger is |
|
1188 | 1181 | invoked. In all cases, the self.tb reference to the current traceback |
|
1189 | 1182 | is deleted to prevent lingering references which hamper memory |
|
1190 | 1183 | management. |
|
1191 | 1184 | |
|
1192 | 1185 | Note that each call to pdb() does an 'import readline', so if your app |
|
1193 | 1186 | requires a special setup for the readline completers, you'll have to |
|
1194 | 1187 | fix that by hand after invoking the exception handler.""" |
|
1195 | 1188 | |
|
1196 | 1189 | if force or self.call_pdb: |
|
1197 | 1190 | if self.pdb is None: |
|
1198 | 1191 | self.pdb = self.debugger_cls() |
|
1199 | 1192 | # the system displayhook may have changed, restore the original |
|
1200 | 1193 | # for pdb |
|
1201 | 1194 | display_trap = DisplayTrap(hook=sys.__displayhook__) |
|
1202 | 1195 | with display_trap: |
|
1203 | 1196 | self.pdb.reset() |
|
1204 | 1197 | # Find the right frame so we don't pop up inside ipython itself |
|
1205 | 1198 | if hasattr(self, 'tb') and self.tb is not None: |
|
1206 | 1199 | etb = self.tb |
|
1207 | 1200 | else: |
|
1208 | 1201 | etb = self.tb = sys.last_traceback |
|
1209 | 1202 | while self.tb is not None and self.tb.tb_next is not None: |
|
1210 | 1203 | self.tb = self.tb.tb_next |
|
1211 | 1204 | if etb and etb.tb_next: |
|
1212 | 1205 | etb = etb.tb_next |
|
1213 | 1206 | self.pdb.botframe = etb.tb_frame |
|
1214 | 1207 | self.pdb.interaction(self.tb.tb_frame, self.tb) |
|
1215 | 1208 | |
|
1216 | 1209 | if hasattr(self, 'tb'): |
|
1217 | 1210 | del self.tb |
|
1218 | 1211 | |
|
1219 | 1212 | def handler(self, info=None): |
|
1220 | 1213 | (etype, evalue, etb) = info or sys.exc_info() |
|
1221 | 1214 | self.tb = etb |
|
1222 | 1215 | ostream = self.ostream |
|
1223 | 1216 | ostream.flush() |
|
1224 | 1217 | ostream.write(self.text(etype, evalue, etb)) |
|
1225 | 1218 | ostream.write('\n') |
|
1226 | 1219 | ostream.flush() |
|
1227 | 1220 | |
|
1228 | 1221 | # Changed so an instance can just be called as VerboseTB_inst() and print |
|
1229 | 1222 | # out the right info on its own. |
|
1230 | 1223 | def __call__(self, etype=None, evalue=None, etb=None): |
|
1231 | 1224 | """This hook can replace sys.excepthook (for Python 2.1 or higher).""" |
|
1232 | 1225 | if etb is None: |
|
1233 | 1226 | self.handler() |
|
1234 | 1227 | else: |
|
1235 | 1228 | self.handler((etype, evalue, etb)) |
|
1236 | 1229 | try: |
|
1237 | 1230 | self.debugger() |
|
1238 | 1231 | except KeyboardInterrupt: |
|
1239 | 1232 | print("\nKeyboardInterrupt") |
|
1240 | 1233 | |
|
1241 | 1234 | |
|
1242 | 1235 | #---------------------------------------------------------------------------- |
|
1243 | 1236 | class FormattedTB(VerboseTB, ListTB): |
|
1244 | 1237 | """Subclass ListTB but allow calling with a traceback. |
|
1245 | 1238 | |
|
1246 | 1239 | It can thus be used as a sys.excepthook for Python > 2.1. |
|
1247 | 1240 | |
|
1248 | 1241 | Also adds 'Context' and 'Verbose' modes, not available in ListTB. |
|
1249 | 1242 | |
|
1250 | 1243 | Allows a tb_offset to be specified. This is useful for situations where |
|
1251 | 1244 | one needs to remove a number of topmost frames from the traceback (such as |
|
1252 | 1245 | occurs with python programs that themselves execute other python code, |
|
1253 | 1246 | like Python shells). """ |
|
1254 | 1247 | |
|
1255 | 1248 | def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False, |
|
1256 | 1249 | ostream=None, |
|
1257 | 1250 | tb_offset=0, long_header=False, include_vars=False, |
|
1258 | 1251 | check_cache=None, debugger_cls=None, |
|
1259 | 1252 | parent=None, config=None): |
|
1260 | 1253 | |
|
1261 | 1254 | # NEVER change the order of this list. Put new modes at the end: |
|
1262 | 1255 | self.valid_modes = ['Plain', 'Context', 'Verbose'] |
|
1263 | 1256 | self.verbose_modes = self.valid_modes[1:3] |
|
1264 | 1257 | |
|
1265 | 1258 | VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
1266 | 1259 | ostream=ostream, tb_offset=tb_offset, |
|
1267 | 1260 | long_header=long_header, include_vars=include_vars, |
|
1268 | 1261 | check_cache=check_cache, debugger_cls=debugger_cls, |
|
1269 | 1262 | parent=parent, config=config) |
|
1270 | 1263 | |
|
1271 | 1264 | # Different types of tracebacks are joined with different separators to |
|
1272 | 1265 | # form a single string. They are taken from this dict |
|
1273 | 1266 | self._join_chars = dict(Plain='', Context='\n', Verbose='\n') |
|
1274 | 1267 | # set_mode also sets the tb_join_char attribute |
|
1275 | 1268 | self.set_mode(mode) |
|
1276 | 1269 | |
|
1277 | 1270 | def _extract_tb(self, tb): |
|
1278 | 1271 | if tb: |
|
1279 | 1272 | return traceback.extract_tb(tb) |
|
1280 | 1273 | else: |
|
1281 | 1274 | return None |
|
1282 | 1275 | |
|
1283 | 1276 | def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5): |
|
1284 | 1277 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
1285 | 1278 | mode = self.mode |
|
1286 | 1279 | if mode in self.verbose_modes: |
|
1287 | 1280 | # Verbose modes need a full traceback |
|
1288 | 1281 | return VerboseTB.structured_traceback( |
|
1289 | 1282 | self, etype, value, tb, tb_offset, number_of_lines_of_context |
|
1290 | 1283 | ) |
|
1291 | 1284 | else: |
|
1292 | 1285 | # We must check the source cache because otherwise we can print |
|
1293 | 1286 | # out-of-date source code. |
|
1294 | 1287 | self.check_cache() |
|
1295 | 1288 | # Now we can extract and format the exception |
|
1296 | 1289 | elist = self._extract_tb(tb) |
|
1297 | 1290 | return ListTB.structured_traceback( |
|
1298 | 1291 | self, etype, value, elist, tb_offset, number_of_lines_of_context |
|
1299 | 1292 | ) |
|
1300 | 1293 | |
|
1301 | 1294 | def stb2text(self, stb): |
|
1302 | 1295 | """Convert a structured traceback (a list) to a string.""" |
|
1303 | 1296 | return self.tb_join_char.join(stb) |
|
1304 | 1297 | |
|
1305 | 1298 | |
|
1306 | 1299 | def set_mode(self, mode=None): |
|
1307 | 1300 | """Switch to the desired mode. |
|
1308 | 1301 | |
|
1309 | 1302 | If mode is not specified, cycles through the available modes.""" |
|
1310 | 1303 | |
|
1311 | 1304 | if not mode: |
|
1312 | 1305 | new_idx = (self.valid_modes.index(self.mode) + 1 ) % \ |
|
1313 | 1306 | len(self.valid_modes) |
|
1314 | 1307 | self.mode = self.valid_modes[new_idx] |
|
1315 | 1308 | elif mode not in self.valid_modes: |
|
1316 | 1309 | raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n' |
|
1317 | 1310 | 'Valid modes: ' + str(self.valid_modes)) |
|
1318 | 1311 | else: |
|
1319 | 1312 | self.mode = mode |
|
1320 | 1313 | # include variable details only in 'Verbose' mode |
|
1321 | 1314 | self.include_vars = (self.mode == self.valid_modes[2]) |
|
1322 | 1315 | # Set the join character for generating text tracebacks |
|
1323 | 1316 | self.tb_join_char = self._join_chars[self.mode] |
|
1324 | 1317 | |
|
1325 | 1318 | # some convenient shortcuts |
|
1326 | 1319 | def plain(self): |
|
1327 | 1320 | self.set_mode(self.valid_modes[0]) |
|
1328 | 1321 | |
|
1329 | 1322 | def context(self): |
|
1330 | 1323 | self.set_mode(self.valid_modes[1]) |
|
1331 | 1324 | |
|
1332 | 1325 | def verbose(self): |
|
1333 | 1326 | self.set_mode(self.valid_modes[2]) |
|
1334 | 1327 | |
|
1335 | 1328 | |
|
1336 | 1329 | #---------------------------------------------------------------------------- |
|
1337 | 1330 | class AutoFormattedTB(FormattedTB): |
|
1338 | 1331 | """A traceback printer which can be called on the fly. |
|
1339 | 1332 | |
|
1340 | 1333 | It will find out about exceptions by itself. |
|
1341 | 1334 | |
|
1342 | 1335 | A brief example:: |
|
1343 | 1336 | |
|
1344 | 1337 | AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux') |
|
1345 | 1338 | try: |
|
1346 | 1339 | ... |
|
1347 | 1340 | except: |
|
1348 | 1341 | AutoTB() # or AutoTB(out=logfile) where logfile is an open file object |
|
1349 | 1342 | """ |
|
1350 | 1343 | |
|
1351 | 1344 | def __call__(self, etype=None, evalue=None, etb=None, |
|
1352 | 1345 | out=None, tb_offset=None): |
|
1353 | 1346 | """Print out a formatted exception traceback. |
|
1354 | 1347 | |
|
1355 | 1348 | Optional arguments: |
|
1356 | 1349 | - out: an open file-like object to direct output to. |
|
1357 | 1350 | |
|
1358 | 1351 | - tb_offset: the number of frames to skip over in the stack, on a |
|
1359 | 1352 | per-call basis (this overrides temporarily the instance's tb_offset |
|
1360 | 1353 | given at initialization time. """ |
|
1361 | 1354 | |
|
1362 | 1355 | if out is None: |
|
1363 | 1356 | out = self.ostream |
|
1364 | 1357 | out.flush() |
|
1365 | 1358 | out.write(self.text(etype, evalue, etb, tb_offset)) |
|
1366 | 1359 | out.write('\n') |
|
1367 | 1360 | out.flush() |
|
1368 | 1361 | # FIXME: we should remove the auto pdb behavior from here and leave |
|
1369 | 1362 | # that to the clients. |
|
1370 | 1363 | try: |
|
1371 | 1364 | self.debugger() |
|
1372 | 1365 | except KeyboardInterrupt: |
|
1373 | 1366 | print("\nKeyboardInterrupt") |
|
1374 | 1367 | |
|
1375 | 1368 | def structured_traceback(self, etype=None, value=None, tb=None, |
|
1376 | 1369 | tb_offset=None, number_of_lines_of_context=5): |
|
1377 | 1370 | if etype is None: |
|
1378 | 1371 | etype, value, tb = sys.exc_info() |
|
1379 | 1372 | self.tb = tb |
|
1380 | 1373 | return FormattedTB.structured_traceback( |
|
1381 | 1374 | self, etype, value, tb, tb_offset, number_of_lines_of_context) |
|
1382 | 1375 | |
|
1383 | 1376 | |
|
1384 | 1377 | #--------------------------------------------------------------------------- |
|
1385 | 1378 | |
|
1386 | 1379 | # A simple class to preserve Nathan's original functionality. |
|
1387 | 1380 | class ColorTB(FormattedTB): |
|
1388 | 1381 | """Shorthand to initialize a FormattedTB in Linux colors mode.""" |
|
1389 | 1382 | |
|
1390 | 1383 | def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs): |
|
1391 | 1384 | FormattedTB.__init__(self, color_scheme=color_scheme, |
|
1392 | 1385 | call_pdb=call_pdb, **kwargs) |
|
1393 | 1386 | |
|
1394 | 1387 | |
|
1395 | 1388 | class SyntaxTB(ListTB): |
|
1396 | 1389 | """Extension which holds some state: the last exception value""" |
|
1397 | 1390 | |
|
1398 | 1391 | def __init__(self, color_scheme='NoColor', parent=None, config=None): |
|
1399 | 1392 | ListTB.__init__(self, color_scheme, parent=parent, config=config) |
|
1400 | 1393 | self.last_syntax_error = None |
|
1401 | 1394 | |
|
1402 | 1395 | def __call__(self, etype, value, elist): |
|
1403 | 1396 | self.last_syntax_error = value |
|
1404 | 1397 | |
|
1405 | 1398 | ListTB.__call__(self, etype, value, elist) |
|
1406 | 1399 | |
|
1407 | 1400 | def structured_traceback(self, etype, value, elist, tb_offset=None, |
|
1408 | 1401 | context=5): |
|
1409 | 1402 | # If the source file has been edited, the line in the syntax error can |
|
1410 | 1403 | # be wrong (retrieved from an outdated cache). This replaces it with |
|
1411 | 1404 | # the current value. |
|
1412 | 1405 | if isinstance(value, SyntaxError) \ |
|
1413 | 1406 | and isinstance(value.filename, str) \ |
|
1414 | 1407 | and isinstance(value.lineno, int): |
|
1415 | 1408 | linecache.checkcache(value.filename) |
|
1416 | 1409 | newtext = ulinecache.getline(value.filename, value.lineno) |
|
1417 | 1410 | if newtext: |
|
1418 | 1411 | value.text = newtext |
|
1419 | 1412 | self.last_syntax_error = value |
|
1420 | 1413 | return super(SyntaxTB, self).structured_traceback(etype, value, elist, |
|
1421 | 1414 | tb_offset=tb_offset, context=context) |
|
1422 | 1415 | |
|
1423 | 1416 | def clear_err_state(self): |
|
1424 | 1417 | """Return the current error state and clear it""" |
|
1425 | 1418 | e = self.last_syntax_error |
|
1426 | 1419 | self.last_syntax_error = None |
|
1427 | 1420 | return e |
|
1428 | 1421 | |
|
1429 | 1422 | def stb2text(self, stb): |
|
1430 | 1423 | """Convert a structured traceback (a list) to a string.""" |
|
1431 | 1424 | return ''.join(stb) |
|
1432 | 1425 | |
|
1433 | 1426 | |
|
1434 | 1427 | # some internal-use functions |
|
1435 | 1428 | def text_repr(value): |
|
1436 | 1429 | """Hopefully pretty robust repr equivalent.""" |
|
1437 | 1430 | # this is pretty horrible but should always return *something* |
|
1438 | 1431 | try: |
|
1439 | 1432 | return pydoc.text.repr(value) |
|
1440 | 1433 | except KeyboardInterrupt: |
|
1441 | 1434 | raise |
|
1442 | 1435 | except: |
|
1443 | 1436 | try: |
|
1444 | 1437 | return repr(value) |
|
1445 | 1438 | except KeyboardInterrupt: |
|
1446 | 1439 | raise |
|
1447 | 1440 | except: |
|
1448 | 1441 | try: |
|
1449 | 1442 | # all still in an except block so we catch |
|
1450 | 1443 | # getattr raising |
|
1451 | 1444 | name = getattr(value, '__name__', None) |
|
1452 | 1445 | if name: |
|
1453 | 1446 | # ick, recursion |
|
1454 | 1447 | return text_repr(name) |
|
1455 | 1448 | klass = getattr(value, '__class__', None) |
|
1456 | 1449 | if klass: |
|
1457 | 1450 | return '%s instance' % text_repr(klass) |
|
1458 | 1451 | except KeyboardInterrupt: |
|
1459 | 1452 | raise |
|
1460 | 1453 | except: |
|
1461 | 1454 | return 'UNRECOVERABLE REPR FAILURE' |
|
1462 | 1455 | |
|
1463 | 1456 | |
|
1464 | 1457 | def eqrepr(value, repr=text_repr): |
|
1465 | 1458 | return '=%s' % repr(value) |
|
1466 | 1459 | |
|
1467 | 1460 | |
|
1468 | 1461 | def nullrepr(value, repr=text_repr): |
|
1469 | 1462 | return '' |
@@ -1,108 +1,106 b'' | |||
|
1 | 1 | """prompt-toolkit utilities |
|
2 | 2 | |
|
3 | 3 | Everything in this module is a private API, |
|
4 | 4 | not to be used outside IPython. |
|
5 | 5 | """ |
|
6 | 6 | |
|
7 | 7 | # Copyright (c) IPython Development Team. |
|
8 | 8 | # Distributed under the terms of the Modified BSD License. |
|
9 | 9 | |
|
10 | 10 | import unicodedata |
|
11 | 11 | from wcwidth import wcwidth |
|
12 | 12 | |
|
13 | from IPython.utils.py3compat import PY3 | |
|
14 | ||
|
15 | 13 | from IPython.core.completer import IPCompleter |
|
16 | 14 | from prompt_toolkit.completion import Completer, Completion |
|
17 | 15 | from prompt_toolkit.layout.lexers import Lexer |
|
18 | 16 | from prompt_toolkit.layout.lexers import PygmentsLexer |
|
19 | 17 | |
|
20 | 18 | import pygments.lexers as pygments_lexers |
|
21 | 19 | |
|
22 | 20 | |
|
23 | 21 | class IPythonPTCompleter(Completer): |
|
24 | 22 | """Adaptor to provide IPython completions to prompt_toolkit""" |
|
25 | 23 | def __init__(self, ipy_completer=None, shell=None): |
|
26 | 24 | if shell is None and ipy_completer is None: |
|
27 | 25 | raise TypeError("Please pass shell=an InteractiveShell instance.") |
|
28 | 26 | self._ipy_completer = ipy_completer |
|
29 | 27 | self.shell = shell |
|
30 | 28 | |
|
31 | 29 | @property |
|
32 | 30 | def ipy_completer(self): |
|
33 | 31 | if self._ipy_completer: |
|
34 | 32 | return self._ipy_completer |
|
35 | 33 | else: |
|
36 | 34 | return self.shell.Completer |
|
37 | 35 | |
|
38 | 36 | def get_completions(self, document, complete_event): |
|
39 | 37 | if not document.current_line.strip(): |
|
40 | 38 | return |
|
41 | 39 | |
|
42 | 40 | used, matches = self.ipy_completer.complete( |
|
43 | 41 | line_buffer=document.current_line, |
|
44 | 42 | cursor_pos=document.cursor_position_col |
|
45 | 43 | ) |
|
46 | 44 | start_pos = -len(used) |
|
47 | 45 | for m in matches: |
|
48 | 46 | if not m: |
|
49 | 47 | # Guard against completion machinery giving us an empty string. |
|
50 | 48 | continue |
|
51 | 49 | |
|
52 | 50 | m = unicodedata.normalize('NFC', m) |
|
53 | 51 | |
|
54 | 52 | # When the first character of the completion has a zero length, |
|
55 | 53 | # then it's probably a decomposed unicode character. E.g. caused by |
|
56 | 54 | # the "\dot" completion. Try to compose again with the previous |
|
57 | 55 | # character. |
|
58 | 56 | if wcwidth(m[0]) == 0: |
|
59 | 57 | if document.cursor_position + start_pos > 0: |
|
60 | 58 | char_before = document.text[document.cursor_position + start_pos - 1] |
|
61 | 59 | m = unicodedata.normalize('NFC', char_before + m) |
|
62 | 60 | |
|
63 | 61 | # Yield the modified completion instead, if this worked. |
|
64 | 62 | if wcwidth(m[0:1]) == 1: |
|
65 | 63 | yield Completion(m, start_position=start_pos - 1) |
|
66 | 64 | continue |
|
67 | 65 | |
|
68 | 66 | # TODO: Use Jedi to determine meta_text |
|
69 | 67 | # (Jedi currently has a bug that results in incorrect information.) |
|
70 | 68 | # meta_text = '' |
|
71 | 69 | # yield Completion(m, start_position=start_pos, |
|
72 | 70 | # display_meta=meta_text) |
|
73 | 71 | yield Completion(m, start_position=start_pos) |
|
74 | 72 | |
|
75 | 73 | class IPythonPTLexer(Lexer): |
|
76 | 74 | """ |
|
77 | 75 | Wrapper around PythonLexer and BashLexer. |
|
78 | 76 | """ |
|
79 | 77 | def __init__(self): |
|
80 | 78 | l = pygments_lexers |
|
81 |
self.python_lexer = PygmentsLexer(l.Python3Lexer |
|
|
79 | self.python_lexer = PygmentsLexer(l.Python3Lexer) | |
|
82 | 80 | self.shell_lexer = PygmentsLexer(l.BashLexer) |
|
83 | 81 | |
|
84 | 82 | self.magic_lexers = { |
|
85 | 83 | 'HTML': PygmentsLexer(l.HtmlLexer), |
|
86 | 84 | 'html': PygmentsLexer(l.HtmlLexer), |
|
87 | 85 | 'javascript': PygmentsLexer(l.JavascriptLexer), |
|
88 | 86 | 'js': PygmentsLexer(l.JavascriptLexer), |
|
89 | 87 | 'perl': PygmentsLexer(l.PerlLexer), |
|
90 | 88 | 'ruby': PygmentsLexer(l.RubyLexer), |
|
91 | 89 | 'latex': PygmentsLexer(l.TexLexer), |
|
92 | 90 | } |
|
93 | 91 | |
|
94 | 92 | def lex_document(self, cli, document): |
|
95 | 93 | text = document.text.lstrip() |
|
96 | 94 | |
|
97 | 95 | lexer = self.python_lexer |
|
98 | 96 | |
|
99 | 97 | if text.startswith('!') or text.startswith('%%bash'): |
|
100 | 98 | lexer = self.shell_lexer |
|
101 | 99 | |
|
102 | 100 | elif text.startswith('%%'): |
|
103 | 101 | for magic, l in self.magic_lexers.items(): |
|
104 | 102 | if text.startswith('%%' + magic): |
|
105 | 103 | lexer = l |
|
106 | 104 | break |
|
107 | 105 | |
|
108 | 106 | return lexer.lex_document(cli, document) |
@@ -1,85 +1,81 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """Tests for io.py""" |
|
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 io as stdlib_io |
|
9 | 9 | import os.path |
|
10 | 10 | import stat |
|
11 | 11 | import sys |
|
12 | from io import StringIO | |
|
12 | 13 | |
|
13 | 14 | from subprocess import Popen, PIPE |
|
14 | 15 | import unittest |
|
15 | 16 | |
|
16 | 17 | import nose.tools as nt |
|
17 | 18 | |
|
18 | 19 | from IPython.testing.decorators import skipif, skip_win32 |
|
19 | 20 | from IPython.utils.io import Tee, capture_output |
|
20 |
from IPython.utils.py3compat import doctest_refactor_print |
|
|
21 | from IPython.utils.py3compat import doctest_refactor_print | |
|
21 | 22 | from IPython.utils.tempdir import TemporaryDirectory |
|
22 | 23 | |
|
23 | if PY3: | |
|
24 | from io import StringIO | |
|
25 | else: | |
|
26 | from StringIO import StringIO | |
|
27 | ||
|
28 | 24 | |
|
29 | 25 | def test_tee_simple(): |
|
30 | 26 | "Very simple check with stdout only" |
|
31 | 27 | chan = StringIO() |
|
32 | 28 | text = 'Hello' |
|
33 | 29 | tee = Tee(chan, channel='stdout') |
|
34 | 30 | print(text, file=chan) |
|
35 | 31 | nt.assert_equal(chan.getvalue(), text+"\n") |
|
36 | 32 | |
|
37 | 33 | |
|
38 | 34 | class TeeTestCase(unittest.TestCase): |
|
39 | 35 | |
|
40 | 36 | def tchan(self, channel, check='close'): |
|
41 | 37 | trap = StringIO() |
|
42 | 38 | chan = StringIO() |
|
43 | 39 | text = 'Hello' |
|
44 | 40 | |
|
45 | 41 | std_ori = getattr(sys, channel) |
|
46 | 42 | setattr(sys, channel, trap) |
|
47 | 43 | |
|
48 | 44 | tee = Tee(chan, channel=channel) |
|
49 | 45 | print(text, end='', file=chan) |
|
50 | 46 | setattr(sys, channel, std_ori) |
|
51 | 47 | trap_val = trap.getvalue() |
|
52 | 48 | nt.assert_equal(chan.getvalue(), text) |
|
53 | 49 | if check=='close': |
|
54 | 50 | tee.close() |
|
55 | 51 | else: |
|
56 | 52 | del tee |
|
57 | 53 | |
|
58 | 54 | def test(self): |
|
59 | 55 | for chan in ['stdout', 'stderr']: |
|
60 | 56 | for check in ['close', 'del']: |
|
61 | 57 | self.tchan(chan, check) |
|
62 | 58 | |
|
63 | 59 | def test_io_init(): |
|
64 | 60 | """Test that io.stdin/out/err exist at startup""" |
|
65 | 61 | for name in ('stdin', 'stdout', 'stderr'): |
|
66 | 62 | cmd = doctest_refactor_print("from IPython.utils import io;print io.%s.__class__"%name) |
|
67 | 63 | p = Popen([sys.executable, '-c', cmd], |
|
68 | 64 | stdout=PIPE) |
|
69 | 65 | p.wait() |
|
70 | 66 | classname = p.stdout.read().strip().decode('ascii') |
|
71 | 67 | # __class__ is a reference to the class object in Python 3, so we can't |
|
72 | 68 | # just test for string equality. |
|
73 | 69 | assert 'IPython.utils.io.IOStream' in classname, classname |
|
74 | 70 | |
|
75 | 71 | def test_capture_output(): |
|
76 | 72 | """capture_output() context works""" |
|
77 | 73 | |
|
78 | 74 | with capture_output() as io: |
|
79 | 75 | print('hi, stdout') |
|
80 | 76 | print('hi, stderr', file=sys.stderr) |
|
81 | 77 | |
|
82 | 78 | nt.assert_equal(io.stdout, 'hi, stdout\n') |
|
83 | 79 | nt.assert_equal(io.stderr, 'hi, stderr\n') |
|
84 | 80 | |
|
85 | 81 |
General Comments 0
You need to be logged in to leave comments.
Login now