Show More
@@ -1,1140 +1,1142 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Implementation of execution-related magic functions. |
|
3 | 3 | """ |
|
4 | 4 | #----------------------------------------------------------------------------- |
|
5 | 5 | # Copyright (c) 2012 The IPython Development Team. |
|
6 | 6 | # |
|
7 | 7 | # Distributed under the terms of the Modified BSD License. |
|
8 | 8 | # |
|
9 | 9 | # The full license is in the file COPYING.txt, distributed with this software. |
|
10 | 10 | #----------------------------------------------------------------------------- |
|
11 | 11 | |
|
12 | 12 | #----------------------------------------------------------------------------- |
|
13 | 13 | # Imports |
|
14 | 14 | #----------------------------------------------------------------------------- |
|
15 | 15 | |
|
16 | 16 | # Stdlib |
|
17 | 17 | import __builtin__ as builtin_mod |
|
18 | 18 | import ast |
|
19 | 19 | import bdb |
|
20 | 20 | import os |
|
21 | 21 | import sys |
|
22 | 22 | import time |
|
23 | 23 | from StringIO import StringIO |
|
24 | 24 | |
|
25 | 25 | # cProfile was added in Python2.5 |
|
26 | 26 | try: |
|
27 | 27 | import cProfile as profile |
|
28 | 28 | import pstats |
|
29 | 29 | except ImportError: |
|
30 | 30 | # profile isn't bundled by default in Debian for license reasons |
|
31 | 31 | try: |
|
32 | 32 | import profile, pstats |
|
33 | 33 | except ImportError: |
|
34 | 34 | profile = pstats = None |
|
35 | 35 | |
|
36 | 36 | # Our own packages |
|
37 | 37 | from IPython.core import debugger, oinspect |
|
38 | 38 | from IPython.core import magic_arguments |
|
39 | 39 | from IPython.core import page |
|
40 | 40 | from IPython.core.error import UsageError |
|
41 | 41 | from IPython.core.macro import Macro |
|
42 | 42 | from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic, |
|
43 | 43 | line_cell_magic, on_off, needs_local_scope) |
|
44 | 44 | from IPython.testing.skipdoctest import skip_doctest |
|
45 | 45 | from IPython.utils import py3compat |
|
46 | 46 | from IPython.utils.contexts import preserve_keys |
|
47 | 47 | from IPython.utils.io import capture_output |
|
48 | 48 | from IPython.utils.ipstruct import Struct |
|
49 | 49 | from IPython.utils.module_paths import find_mod |
|
50 | 50 | from IPython.utils.path import get_py_filename, unquote_filename, shellglob |
|
51 | 51 | from IPython.utils.timing import clock, clock2 |
|
52 | 52 | from IPython.utils.warn import warn, error |
|
53 | 53 | |
|
54 | 54 | |
|
55 | 55 | #----------------------------------------------------------------------------- |
|
56 | 56 | # Magic implementation classes |
|
57 | 57 | #----------------------------------------------------------------------------- |
|
58 | 58 | |
|
59 | 59 | @magics_class |
|
60 | 60 | class ExecutionMagics(Magics): |
|
61 | 61 | """Magics related to code execution, debugging, profiling, etc. |
|
62 | 62 | |
|
63 | 63 | """ |
|
64 | 64 | |
|
65 | 65 | def __init__(self, shell): |
|
66 | 66 | super(ExecutionMagics, self).__init__(shell) |
|
67 | 67 | if profile is None: |
|
68 | 68 | self.prun = self.profile_missing_notice |
|
69 | 69 | # Default execution function used to actually run user code. |
|
70 | 70 | self.default_runner = None |
|
71 | 71 | |
|
72 | 72 | def profile_missing_notice(self, *args, **kwargs): |
|
73 | 73 | error("""\ |
|
74 | 74 | The profile module could not be found. It has been removed from the standard |
|
75 | 75 | python packages because of its non-free license. To use profiling, install the |
|
76 | 76 | python-profiler package from non-free.""") |
|
77 | 77 | |
|
78 | 78 | @skip_doctest |
|
79 | 79 | @line_cell_magic |
|
80 | 80 | def prun(self, parameter_s='', cell=None): |
|
81 | 81 | |
|
82 | 82 | """Run a statement through the python code profiler. |
|
83 | 83 | |
|
84 | 84 | Usage, in line mode: |
|
85 | 85 | %prun [options] statement |
|
86 | 86 | |
|
87 | 87 | Usage, in cell mode: |
|
88 | 88 | %%prun [options] [statement] |
|
89 | 89 | code... |
|
90 | 90 | code... |
|
91 | 91 | |
|
92 | 92 | In cell mode, the additional code lines are appended to the (possibly |
|
93 | 93 | empty) statement in the first line. Cell mode allows you to easily |
|
94 | 94 | profile multiline blocks without having to put them in a separate |
|
95 | 95 | function. |
|
96 | 96 | |
|
97 | 97 | The given statement (which doesn't require quote marks) is run via the |
|
98 | 98 | python profiler in a manner similar to the profile.run() function. |
|
99 | 99 | Namespaces are internally managed to work correctly; profile.run |
|
100 | 100 | cannot be used in IPython because it makes certain assumptions about |
|
101 | 101 | namespaces which do not hold under IPython. |
|
102 | 102 | |
|
103 | 103 | Options: |
|
104 | 104 | |
|
105 | 105 | -l <limit>: you can place restrictions on what or how much of the |
|
106 | 106 | profile gets printed. The limit value can be: |
|
107 | 107 | |
|
108 | 108 | * A string: only information for function names containing this string |
|
109 | 109 | is printed. |
|
110 | 110 | |
|
111 | 111 | * An integer: only these many lines are printed. |
|
112 | 112 | |
|
113 | 113 | * A float (between 0 and 1): this fraction of the report is printed |
|
114 | 114 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
115 | 115 | |
|
116 | 116 | You can combine several limits with repeated use of the option. For |
|
117 | 117 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
118 | 118 | information about class constructors. |
|
119 | 119 | |
|
120 | 120 | -r: return the pstats.Stats object generated by the profiling. This |
|
121 | 121 | object has all the information about the profile in it, and you can |
|
122 | 122 | later use it for further analysis or in other functions. |
|
123 | 123 | |
|
124 | 124 | -s <key>: sort profile by given key. You can provide more than one key |
|
125 | 125 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
126 | 126 | default sorting key is 'time'. |
|
127 | 127 | |
|
128 | 128 | The following is copied verbatim from the profile documentation |
|
129 | 129 | referenced below: |
|
130 | 130 | |
|
131 | 131 | When more than one key is provided, additional keys are used as |
|
132 | 132 | secondary criteria when the there is equality in all keys selected |
|
133 | 133 | before them. |
|
134 | 134 | |
|
135 | 135 | Abbreviations can be used for any key names, as long as the |
|
136 | 136 | abbreviation is unambiguous. The following are the keys currently |
|
137 | 137 | defined: |
|
138 | 138 | |
|
139 | 139 | Valid Arg Meaning |
|
140 | 140 | "calls" call count |
|
141 | 141 | "cumulative" cumulative time |
|
142 | 142 | "file" file name |
|
143 | 143 | "module" file name |
|
144 | 144 | "pcalls" primitive call count |
|
145 | 145 | "line" line number |
|
146 | 146 | "name" function name |
|
147 | 147 | "nfl" name/file/line |
|
148 | 148 | "stdname" standard name |
|
149 | 149 | "time" internal time |
|
150 | 150 | |
|
151 | 151 | Note that all sorts on statistics are in descending order (placing |
|
152 | 152 | most time consuming items first), where as name, file, and line number |
|
153 | 153 | searches are in ascending order (i.e., alphabetical). The subtle |
|
154 | 154 | distinction between "nfl" and "stdname" is that the standard name is a |
|
155 | 155 | sort of the name as printed, which means that the embedded line |
|
156 | 156 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
157 | 157 | would (if the file names were the same) appear in the string order |
|
158 | 158 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
159 | 159 | line numbers. In fact, sort_stats("nfl") is the same as |
|
160 | 160 | sort_stats("name", "file", "line"). |
|
161 | 161 | |
|
162 | 162 | -T <filename>: save profile results as shown on screen to a text |
|
163 | 163 | file. The profile is still shown on screen. |
|
164 | 164 | |
|
165 | 165 | -D <filename>: save (via dump_stats) profile statistics to given |
|
166 | 166 | filename. This data is in a format understood by the pstats module, and |
|
167 | 167 | is generated by a call to the dump_stats() method of profile |
|
168 | 168 | objects. The profile is still shown on screen. |
|
169 | 169 | |
|
170 | 170 | -q: suppress output to the pager. Best used with -T and/or -D above. |
|
171 | 171 | |
|
172 | 172 | If you want to run complete programs under the profiler's control, use |
|
173 | 173 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
174 | 174 | contains profiler specific options as described here. |
|
175 | 175 | |
|
176 | 176 | You can read the complete documentation for the profile module with:: |
|
177 | 177 | |
|
178 | 178 | In [1]: import profile; profile.help() |
|
179 | 179 | """ |
|
180 | 180 | opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q', |
|
181 | 181 | list_all=True, posix=False) |
|
182 | 182 | if cell is not None: |
|
183 | 183 | arg_str += '\n' + cell |
|
184 | 184 | return self._run_with_profiler(arg_str, opts, self.shell.user_ns) |
|
185 | 185 | |
|
186 | 186 | def _run_with_profiler(self, code, opts, namespace): |
|
187 | 187 | """ |
|
188 | 188 | Run `code` with profiler. Used by ``%prun`` and ``%run -p``. |
|
189 | 189 | |
|
190 | 190 | Parameters |
|
191 | 191 | ---------- |
|
192 | 192 | code : str |
|
193 | 193 | Code to be executed. |
|
194 | 194 | opts : Struct |
|
195 | 195 | Options parsed by `self.parse_options`. |
|
196 | 196 | namespace : dict |
|
197 | 197 | A dictionary for Python namespace (e.g., `self.shell.user_ns`). |
|
198 | 198 | |
|
199 | 199 | """ |
|
200 | 200 | |
|
201 | 201 | # Fill default values for unspecified options: |
|
202 | 202 | opts.merge(Struct(D=[''], l=[], s=['time'], T=[''])) |
|
203 | 203 | |
|
204 | 204 | prof = profile.Profile() |
|
205 | 205 | try: |
|
206 | 206 | prof = prof.runctx(code, namespace, namespace) |
|
207 | 207 | sys_exit = '' |
|
208 | 208 | except SystemExit: |
|
209 | 209 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
210 | 210 | |
|
211 | 211 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
212 | 212 | |
|
213 | 213 | lims = opts.l |
|
214 | 214 | if lims: |
|
215 | 215 | lims = [] # rebuild lims with ints/floats/strings |
|
216 | 216 | for lim in opts.l: |
|
217 | 217 | try: |
|
218 | 218 | lims.append(int(lim)) |
|
219 | 219 | except ValueError: |
|
220 | 220 | try: |
|
221 | 221 | lims.append(float(lim)) |
|
222 | 222 | except ValueError: |
|
223 | 223 | lims.append(lim) |
|
224 | 224 | |
|
225 | 225 | # Trap output. |
|
226 | 226 | stdout_trap = StringIO() |
|
227 | 227 | stats_stream = stats.stream |
|
228 | 228 | try: |
|
229 | 229 | stats.stream = stdout_trap |
|
230 | 230 | stats.print_stats(*lims) |
|
231 | 231 | finally: |
|
232 | 232 | stats.stream = stats_stream |
|
233 | 233 | |
|
234 | 234 | output = stdout_trap.getvalue() |
|
235 | 235 | output = output.rstrip() |
|
236 | 236 | |
|
237 | 237 | if 'q' not in opts: |
|
238 | 238 | page.page(output) |
|
239 | 239 | print sys_exit, |
|
240 | 240 | |
|
241 | 241 | dump_file = opts.D[0] |
|
242 | 242 | text_file = opts.T[0] |
|
243 | 243 | if dump_file: |
|
244 | 244 | dump_file = unquote_filename(dump_file) |
|
245 | 245 | prof.dump_stats(dump_file) |
|
246 | 246 | print '\n*** Profile stats marshalled to file',\ |
|
247 | 247 | repr(dump_file)+'.',sys_exit |
|
248 | 248 | if text_file: |
|
249 | 249 | text_file = unquote_filename(text_file) |
|
250 | 250 | pfile = open(text_file,'w') |
|
251 | 251 | pfile.write(output) |
|
252 | 252 | pfile.close() |
|
253 | 253 | print '\n*** Profile printout saved to text file',\ |
|
254 | 254 | repr(text_file)+'.',sys_exit |
|
255 | 255 | |
|
256 | 256 | if 'r' in opts: |
|
257 | 257 | return stats |
|
258 | 258 | else: |
|
259 | 259 | return None |
|
260 | 260 | |
|
261 | 261 | @line_magic |
|
262 | 262 | def pdb(self, parameter_s=''): |
|
263 | 263 | """Control the automatic calling of the pdb interactive debugger. |
|
264 | 264 | |
|
265 | 265 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
266 | 266 | argument it works as a toggle. |
|
267 | 267 | |
|
268 | 268 | When an exception is triggered, IPython can optionally call the |
|
269 | 269 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
270 | 270 | this feature on and off. |
|
271 | 271 | |
|
272 | 272 | The initial state of this feature is set in your configuration |
|
273 | 273 | file (the option is ``InteractiveShell.pdb``). |
|
274 | 274 | |
|
275 | 275 | If you want to just activate the debugger AFTER an exception has fired, |
|
276 | 276 | without having to type '%pdb on' and rerunning your code, you can use |
|
277 | 277 | the %debug magic.""" |
|
278 | 278 | |
|
279 | 279 | par = parameter_s.strip().lower() |
|
280 | 280 | |
|
281 | 281 | if par: |
|
282 | 282 | try: |
|
283 | 283 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
284 | 284 | except KeyError: |
|
285 | 285 | print ('Incorrect argument. Use on/1, off/0, ' |
|
286 | 286 | 'or nothing for a toggle.') |
|
287 | 287 | return |
|
288 | 288 | else: |
|
289 | 289 | # toggle |
|
290 | 290 | new_pdb = not self.shell.call_pdb |
|
291 | 291 | |
|
292 | 292 | # set on the shell |
|
293 | 293 | self.shell.call_pdb = new_pdb |
|
294 | 294 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
295 | 295 | |
|
296 | 296 | @line_magic |
|
297 | 297 | def debug(self, parameter_s=''): |
|
298 | 298 | """Activate the interactive debugger in post-mortem mode. |
|
299 | 299 | |
|
300 | 300 | If an exception has just occurred, this lets you inspect its stack |
|
301 | 301 | frames interactively. Note that this will always work only on the last |
|
302 | 302 | traceback that occurred, so you must call this quickly after an |
|
303 | 303 | exception that you wish to inspect has fired, because if another one |
|
304 | 304 | occurs, it clobbers the previous one. |
|
305 | 305 | |
|
306 | 306 | If you want IPython to automatically do this on every exception, see |
|
307 | 307 | the %pdb magic for more details. |
|
308 | 308 | """ |
|
309 | 309 | self.shell.debugger(force=True) |
|
310 | 310 | |
|
311 | 311 | @line_magic |
|
312 | 312 | def tb(self, s): |
|
313 | 313 | """Print the last traceback with the currently active exception mode. |
|
314 | 314 | |
|
315 | 315 | See %xmode for changing exception reporting modes.""" |
|
316 | 316 | self.shell.showtraceback() |
|
317 | 317 | |
|
318 | 318 | @skip_doctest |
|
319 | 319 | @line_magic |
|
320 | 320 | def run(self, parameter_s='', runner=None, |
|
321 | 321 | file_finder=get_py_filename): |
|
322 | 322 | """Run the named file inside IPython as a program. |
|
323 | 323 | |
|
324 |
Usage: |
|
|
325 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options] -G] file [args] | |
|
324 | Usage: | |
|
325 | %run [-n -i -e -G] | |
|
326 | [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )] | |
|
327 | ( -m mod | file ) [args] | |
|
326 | 328 | |
|
327 | 329 | Parameters after the filename are passed as command-line arguments to |
|
328 | 330 | the program (put in sys.argv). Then, control returns to IPython's |
|
329 | 331 | prompt. |
|
330 | 332 | |
|
331 | 333 | This is similar to running at a system prompt:\\ |
|
332 | 334 | $ python file args\\ |
|
333 | 335 | but with the advantage of giving you IPython's tracebacks, and of |
|
334 | 336 | loading all variables into your interactive namespace for further use |
|
335 | 337 | (unless -p is used, see below). |
|
336 | 338 | |
|
337 | 339 | The file is executed in a namespace initially consisting only of |
|
338 | 340 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
339 | 341 | sees its environment as if it were being run as a stand-alone program |
|
340 | 342 | (except for sharing global objects such as previously imported |
|
341 | 343 | modules). But after execution, the IPython interactive namespace gets |
|
342 | 344 | updated with all variables defined in the program (except for __name__ |
|
343 | 345 | and sys.argv). This allows for very convenient loading of code for |
|
344 | 346 | interactive work, while giving each program a 'clean sheet' to run in. |
|
345 | 347 | |
|
346 | 348 | Arguments are expanded using shell-like glob match. Patterns |
|
347 | 349 | '*', '?', '[seq]' and '[!seq]' can be used. Additionally, |
|
348 | 350 | tilde '~' will be expanded into user's home directory. Unlike |
|
349 | 351 | real shells, quotation does not suppress expansions. Use |
|
350 | 352 | *two* back slashes (e.g., '\\\\*') to suppress expansions. |
|
351 | 353 | To completely disable these expansions, you can use -G flag. |
|
352 | 354 | |
|
353 | 355 | Options: |
|
354 | 356 | |
|
355 | 357 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
356 | 358 | without extension (as python does under import). This allows running |
|
357 | 359 | scripts and reloading the definitions in them without calling code |
|
358 | 360 | protected by an ' if __name__ == "__main__" ' clause. |
|
359 | 361 | |
|
360 | 362 | -i: run the file in IPython's namespace instead of an empty one. This |
|
361 | 363 | is useful if you are experimenting with code written in a text editor |
|
362 | 364 | which depends on variables defined interactively. |
|
363 | 365 | |
|
364 | 366 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
365 | 367 | being run. This is particularly useful if IPython is being used to |
|
366 | 368 | run unittests, which always exit with a sys.exit() call. In such |
|
367 | 369 | cases you are interested in the output of the test results, not in |
|
368 | 370 | seeing a traceback of the unittest module. |
|
369 | 371 | |
|
370 | 372 | -t: print timing information at the end of the run. IPython will give |
|
371 | 373 | you an estimated CPU time consumption for your script, which under |
|
372 | 374 | Unix uses the resource module to avoid the wraparound problems of |
|
373 | 375 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
374 | 376 | is also given (for Windows platforms this is reported as 0.0). |
|
375 | 377 | |
|
376 | 378 | If -t is given, an additional -N<N> option can be given, where <N> |
|
377 | 379 | must be an integer indicating how many times you want the script to |
|
378 | 380 | run. The final timing report will include total and per run results. |
|
379 | 381 | |
|
380 | 382 | For example (testing the script uniq_stable.py):: |
|
381 | 383 | |
|
382 | 384 | In [1]: run -t uniq_stable |
|
383 | 385 | |
|
384 | 386 | IPython CPU timings (estimated):\\ |
|
385 | 387 | User : 0.19597 s.\\ |
|
386 | 388 | System: 0.0 s.\\ |
|
387 | 389 | |
|
388 | 390 | In [2]: run -t -N5 uniq_stable |
|
389 | 391 | |
|
390 | 392 | IPython CPU timings (estimated):\\ |
|
391 | 393 | Total runs performed: 5\\ |
|
392 | 394 | Times : Total Per run\\ |
|
393 | 395 | User : 0.910862 s, 0.1821724 s.\\ |
|
394 | 396 | System: 0.0 s, 0.0 s. |
|
395 | 397 | |
|
396 | 398 | -d: run your program under the control of pdb, the Python debugger. |
|
397 | 399 | This allows you to execute your program step by step, watch variables, |
|
398 | 400 | etc. Internally, what IPython does is similar to calling: |
|
399 | 401 | |
|
400 | 402 | pdb.run('execfile("YOURFILENAME")') |
|
401 | 403 | |
|
402 | 404 | with a breakpoint set on line 1 of your file. You can change the line |
|
403 | 405 | number for this automatic breakpoint to be <N> by using the -bN option |
|
404 | 406 | (where N must be an integer). For example:: |
|
405 | 407 | |
|
406 | 408 | %run -d -b40 myscript |
|
407 | 409 | |
|
408 | 410 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
409 | 411 | the first breakpoint must be set on a line which actually does |
|
410 | 412 | something (not a comment or docstring) for it to stop execution. |
|
411 | 413 | |
|
412 | 414 | Or you can specify a breakpoint in a different file:: |
|
413 | 415 | |
|
414 | 416 | %run -d -b myotherfile.py:20 myscript |
|
415 | 417 | |
|
416 | 418 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
417 | 419 | first enter 'c' (without quotes) to start execution up to the first |
|
418 | 420 | breakpoint. |
|
419 | 421 | |
|
420 | 422 | Entering 'help' gives information about the use of the debugger. You |
|
421 | 423 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
422 | 424 | at a prompt. |
|
423 | 425 | |
|
424 | 426 | -p: run program under the control of the Python profiler module (which |
|
425 | 427 | prints a detailed report of execution times, function calls, etc). |
|
426 | 428 | |
|
427 | 429 | You can pass other options after -p which affect the behavior of the |
|
428 | 430 | profiler itself. See the docs for %prun for details. |
|
429 | 431 | |
|
430 | 432 | In this mode, the program's variables do NOT propagate back to the |
|
431 | 433 | IPython interactive namespace (because they remain in the namespace |
|
432 | 434 | where the profiler executes them). |
|
433 | 435 | |
|
434 | 436 | Internally this triggers a call to %prun, see its documentation for |
|
435 | 437 | details on the options available specifically for profiling. |
|
436 | 438 | |
|
437 | 439 | There is one special usage for which the text above doesn't apply: |
|
438 | 440 | if the filename ends with .ipy, the file is run as ipython script, |
|
439 | 441 | just as if the commands were written on IPython prompt. |
|
440 | 442 | |
|
441 | 443 | -m: specify module name to load instead of script path. Similar to |
|
442 | 444 | the -m option for the python interpreter. Use this option last if you |
|
443 | 445 | want to combine with other %run options. Unlike the python interpreter |
|
444 | 446 | only source modules are allowed no .pyc or .pyo files. |
|
445 | 447 | For example:: |
|
446 | 448 | |
|
447 | 449 | %run -m example |
|
448 | 450 | |
|
449 | 451 | will run the example module. |
|
450 | 452 | |
|
451 | 453 | -G: disable shell-like glob expansion of arguments. |
|
452 | 454 | |
|
453 | 455 | """ |
|
454 | 456 | |
|
455 | 457 | # get arguments and set sys.argv for program to be run. |
|
456 | 458 | opts, arg_lst = self.parse_options(parameter_s, |
|
457 | 459 | 'nidtN:b:pD:l:rs:T:em:G', |
|
458 | 460 | mode='list', list_all=1) |
|
459 | 461 | if "m" in opts: |
|
460 | 462 | modulename = opts["m"][0] |
|
461 | 463 | modpath = find_mod(modulename) |
|
462 | 464 | if modpath is None: |
|
463 | 465 | warn('%r is not a valid modulename on sys.path'%modulename) |
|
464 | 466 | return |
|
465 | 467 | arg_lst = [modpath] + arg_lst |
|
466 | 468 | try: |
|
467 | 469 | filename = file_finder(arg_lst[0]) |
|
468 | 470 | except IndexError: |
|
469 | 471 | warn('you must provide at least a filename.') |
|
470 | 472 | print '\n%run:\n', oinspect.getdoc(self.run) |
|
471 | 473 | return |
|
472 | 474 | except IOError as e: |
|
473 | 475 | try: |
|
474 | 476 | msg = str(e) |
|
475 | 477 | except UnicodeError: |
|
476 | 478 | msg = e.message |
|
477 | 479 | error(msg) |
|
478 | 480 | return |
|
479 | 481 | |
|
480 | 482 | if filename.lower().endswith('.ipy'): |
|
481 | 483 | with preserve_keys(self.shell.user_ns, '__file__'): |
|
482 | 484 | self.shell.user_ns['__file__'] = filename |
|
483 | 485 | self.shell.safe_execfile_ipy(filename) |
|
484 | 486 | return |
|
485 | 487 | |
|
486 | 488 | # Control the response to exit() calls made by the script being run |
|
487 | 489 | exit_ignore = 'e' in opts |
|
488 | 490 | |
|
489 | 491 | # Make sure that the running script gets a proper sys.argv as if it |
|
490 | 492 | # were run from a system shell. |
|
491 | 493 | save_argv = sys.argv # save it for later restoring |
|
492 | 494 | |
|
493 | 495 | if 'G' in opts: |
|
494 | 496 | args = arg_lst[1:] |
|
495 | 497 | else: |
|
496 | 498 | # tilde and glob expansion |
|
497 | 499 | args = shellglob(map(os.path.expanduser, arg_lst[1:])) |
|
498 | 500 | |
|
499 | 501 | sys.argv = [filename] + args # put in the proper filename |
|
500 | 502 | # protect sys.argv from potential unicode strings on Python 2: |
|
501 | 503 | if not py3compat.PY3: |
|
502 | 504 | sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ] |
|
503 | 505 | |
|
504 | 506 | if 'i' in opts: |
|
505 | 507 | # Run in user's interactive namespace |
|
506 | 508 | prog_ns = self.shell.user_ns |
|
507 | 509 | __name__save = self.shell.user_ns['__name__'] |
|
508 | 510 | prog_ns['__name__'] = '__main__' |
|
509 | 511 | main_mod = self.shell.new_main_mod(prog_ns) |
|
510 | 512 | else: |
|
511 | 513 | # Run in a fresh, empty namespace |
|
512 | 514 | if 'n' in opts: |
|
513 | 515 | name = os.path.splitext(os.path.basename(filename))[0] |
|
514 | 516 | else: |
|
515 | 517 | name = '__main__' |
|
516 | 518 | |
|
517 | 519 | main_mod = self.shell.new_main_mod() |
|
518 | 520 | prog_ns = main_mod.__dict__ |
|
519 | 521 | prog_ns['__name__'] = name |
|
520 | 522 | |
|
521 | 523 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
522 | 524 | # set the __file__ global in the script's namespace |
|
523 | 525 | prog_ns['__file__'] = filename |
|
524 | 526 | |
|
525 | 527 | # pickle fix. See interactiveshell for an explanation. But we need to |
|
526 | 528 | # make sure that, if we overwrite __main__, we replace it at the end |
|
527 | 529 | main_mod_name = prog_ns['__name__'] |
|
528 | 530 | |
|
529 | 531 | if main_mod_name == '__main__': |
|
530 | 532 | restore_main = sys.modules['__main__'] |
|
531 | 533 | else: |
|
532 | 534 | restore_main = False |
|
533 | 535 | |
|
534 | 536 | # This needs to be undone at the end to prevent holding references to |
|
535 | 537 | # every single object ever created. |
|
536 | 538 | sys.modules[main_mod_name] = main_mod |
|
537 | 539 | |
|
538 | 540 | if 'p' in opts or 'd' in opts: |
|
539 | 541 | if 'm' in opts: |
|
540 | 542 | code = 'run_module(modulename, prog_ns)' |
|
541 | 543 | code_ns = { |
|
542 | 544 | 'run_module': self.shell.safe_run_module, |
|
543 | 545 | 'prog_ns': prog_ns, |
|
544 | 546 | 'modulename': modulename, |
|
545 | 547 | } |
|
546 | 548 | else: |
|
547 | 549 | code = 'execfile(filename, prog_ns)' |
|
548 | 550 | code_ns = { |
|
549 | 551 | 'execfile': self.shell.safe_execfile, |
|
550 | 552 | 'prog_ns': prog_ns, |
|
551 | 553 | 'filename': get_py_filename(filename), |
|
552 | 554 | } |
|
553 | 555 | |
|
554 | 556 | try: |
|
555 | 557 | stats = None |
|
556 | 558 | with self.shell.readline_no_record: |
|
557 | 559 | if 'p' in opts: |
|
558 | 560 | stats = self._run_with_profiler(code, opts, code_ns) |
|
559 | 561 | else: |
|
560 | 562 | if 'd' in opts: |
|
561 | 563 | self._run_with_debugger( |
|
562 | 564 | code, code_ns, opts.get('b', ['1'])[0], filename) |
|
563 | 565 | else: |
|
564 | 566 | if 'm' in opts: |
|
565 | 567 | def run(): |
|
566 | 568 | self.shell.safe_run_module(modulename, prog_ns) |
|
567 | 569 | else: |
|
568 | 570 | if runner is None: |
|
569 | 571 | runner = self.default_runner |
|
570 | 572 | if runner is None: |
|
571 | 573 | runner = self.shell.safe_execfile |
|
572 | 574 | |
|
573 | 575 | def run(): |
|
574 | 576 | runner(filename, prog_ns, prog_ns, |
|
575 | 577 | exit_ignore=exit_ignore) |
|
576 | 578 | |
|
577 | 579 | if 't' in opts: |
|
578 | 580 | # timed execution |
|
579 | 581 | try: |
|
580 | 582 | nruns = int(opts['N'][0]) |
|
581 | 583 | if nruns < 1: |
|
582 | 584 | error('Number of runs must be >=1') |
|
583 | 585 | return |
|
584 | 586 | except (KeyError): |
|
585 | 587 | nruns = 1 |
|
586 | 588 | self._run_with_timing(run, nruns) |
|
587 | 589 | else: |
|
588 | 590 | # regular execution |
|
589 | 591 | run() |
|
590 | 592 | |
|
591 | 593 | if 'i' in opts: |
|
592 | 594 | self.shell.user_ns['__name__'] = __name__save |
|
593 | 595 | else: |
|
594 | 596 | # The shell MUST hold a reference to prog_ns so after %run |
|
595 | 597 | # exits, the python deletion mechanism doesn't zero it out |
|
596 | 598 | # (leaving dangling references). |
|
597 | 599 | self.shell.cache_main_mod(prog_ns, filename) |
|
598 | 600 | # update IPython interactive namespace |
|
599 | 601 | |
|
600 | 602 | # Some forms of read errors on the file may mean the |
|
601 | 603 | # __name__ key was never set; using pop we don't have to |
|
602 | 604 | # worry about a possible KeyError. |
|
603 | 605 | prog_ns.pop('__name__', None) |
|
604 | 606 | |
|
605 | 607 | with preserve_keys(self.shell.user_ns, '__file__'): |
|
606 | 608 | self.shell.user_ns.update(prog_ns) |
|
607 | 609 | finally: |
|
608 | 610 | # It's a bit of a mystery why, but __builtins__ can change from |
|
609 | 611 | # being a module to becoming a dict missing some key data after |
|
610 | 612 | # %run. As best I can see, this is NOT something IPython is doing |
|
611 | 613 | # at all, and similar problems have been reported before: |
|
612 | 614 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
613 | 615 | # Since this seems to be done by the interpreter itself, the best |
|
614 | 616 | # we can do is to at least restore __builtins__ for the user on |
|
615 | 617 | # exit. |
|
616 | 618 | self.shell.user_ns['__builtins__'] = builtin_mod |
|
617 | 619 | |
|
618 | 620 | # Ensure key global structures are restored |
|
619 | 621 | sys.argv = save_argv |
|
620 | 622 | if restore_main: |
|
621 | 623 | sys.modules['__main__'] = restore_main |
|
622 | 624 | else: |
|
623 | 625 | # Remove from sys.modules the reference to main_mod we'd |
|
624 | 626 | # added. Otherwise it will trap references to objects |
|
625 | 627 | # contained therein. |
|
626 | 628 | del sys.modules[main_mod_name] |
|
627 | 629 | |
|
628 | 630 | return stats |
|
629 | 631 | |
|
630 | 632 | def _run_with_debugger(self, code, code_ns, break_point, filename): |
|
631 | 633 | deb = debugger.Pdb(self.shell.colors) |
|
632 | 634 | # reset Breakpoint state, which is moronically kept |
|
633 | 635 | # in a class |
|
634 | 636 | bdb.Breakpoint.next = 1 |
|
635 | 637 | bdb.Breakpoint.bplist = {} |
|
636 | 638 | bdb.Breakpoint.bpbynumber = [None] |
|
637 | 639 | # Set an initial breakpoint to stop execution |
|
638 | 640 | maxtries = 10 |
|
639 | 641 | bp_file, bp_line = parse_breakpoint(break_point, filename) |
|
640 | 642 | checkline = deb.checkline(bp_file, bp_line) |
|
641 | 643 | if not checkline: |
|
642 | 644 | for bp in range(bp_line + 1, bp_line + maxtries + 1): |
|
643 | 645 | if deb.checkline(bp_file, bp): |
|
644 | 646 | break |
|
645 | 647 | else: |
|
646 | 648 | msg = ("\nI failed to find a valid line to set " |
|
647 | 649 | "a breakpoint\n" |
|
648 | 650 | "after trying up to line: %s.\n" |
|
649 | 651 | "Please set a valid breakpoint manually " |
|
650 | 652 | "with the -b option." % bp) |
|
651 | 653 | raise UsageError(msg) |
|
652 | 654 | # if we find a good linenumber, set the breakpoint |
|
653 | 655 | deb.do_break('%s:%s' % (bp_file, bp_line)) |
|
654 | 656 | |
|
655 | 657 | # Mimic Pdb._runscript(...) |
|
656 | 658 | deb._wait_for_mainpyfile = True |
|
657 | 659 | deb.mainpyfile = deb.canonic(filename) |
|
658 | 660 | |
|
659 | 661 | # Start file run |
|
660 | 662 | print "NOTE: Enter 'c' at the", |
|
661 | 663 | print "%s prompt to start your script." % deb.prompt |
|
662 | 664 | try: |
|
663 | 665 | #save filename so it can be used by methods on the deb object |
|
664 | 666 | deb._exec_filename = filename |
|
665 | 667 | deb.run(code, code_ns) |
|
666 | 668 | |
|
667 | 669 | except: |
|
668 | 670 | etype, value, tb = sys.exc_info() |
|
669 | 671 | # Skip three frames in the traceback: the %run one, |
|
670 | 672 | # one inside bdb.py, and the command-line typed by the |
|
671 | 673 | # user (run by exec in pdb itself). |
|
672 | 674 | self.shell.InteractiveTB(etype, value, tb, tb_offset=3) |
|
673 | 675 | |
|
674 | 676 | @staticmethod |
|
675 | 677 | def _run_with_timing(run, nruns): |
|
676 | 678 | twall0 = time.time() |
|
677 | 679 | if nruns == 1: |
|
678 | 680 | t0 = clock2() |
|
679 | 681 | run() |
|
680 | 682 | t1 = clock2() |
|
681 | 683 | t_usr = t1[0] - t0[0] |
|
682 | 684 | t_sys = t1[1] - t0[1] |
|
683 | 685 | print "\nIPython CPU timings (estimated):" |
|
684 | 686 | print " User : %10.2f s." % t_usr |
|
685 | 687 | print " System : %10.2f s." % t_sys |
|
686 | 688 | else: |
|
687 | 689 | runs = range(nruns) |
|
688 | 690 | t0 = clock2() |
|
689 | 691 | for nr in runs: |
|
690 | 692 | run() |
|
691 | 693 | t1 = clock2() |
|
692 | 694 | t_usr = t1[0] - t0[0] |
|
693 | 695 | t_sys = t1[1] - t0[1] |
|
694 | 696 | print "\nIPython CPU timings (estimated):" |
|
695 | 697 | print "Total runs performed:", nruns |
|
696 | 698 | print " Times : %10s %10s" % ('Total', 'Per run') |
|
697 | 699 | print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns) |
|
698 | 700 | print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns) |
|
699 | 701 | twall1 = time.time() |
|
700 | 702 | print "Wall time: %10.2f s." % (twall1 - twall0) |
|
701 | 703 | |
|
702 | 704 | @skip_doctest |
|
703 | 705 | @line_cell_magic |
|
704 | 706 | def timeit(self, line='', cell=None): |
|
705 | 707 | """Time execution of a Python statement or expression |
|
706 | 708 | |
|
707 | 709 | Usage, in line mode: |
|
708 | 710 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
709 | 711 | or in cell mode: |
|
710 | 712 | %%timeit [-n<N> -r<R> [-t|-c]] setup_code |
|
711 | 713 | code |
|
712 | 714 | code... |
|
713 | 715 | |
|
714 | 716 | Time execution of a Python statement or expression using the timeit |
|
715 | 717 | module. This function can be used both as a line and cell magic: |
|
716 | 718 | |
|
717 | 719 | - In line mode you can time a single-line statement (though multiple |
|
718 | 720 | ones can be chained with using semicolons). |
|
719 | 721 | |
|
720 | 722 | - In cell mode, the statement in the first line is used as setup code |
|
721 | 723 | (executed but not timed) and the body of the cell is timed. The cell |
|
722 | 724 | body has access to any variables created in the setup code. |
|
723 | 725 | |
|
724 | 726 | Options: |
|
725 | 727 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
726 | 728 | is not given, a fitting value is chosen. |
|
727 | 729 | |
|
728 | 730 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
729 | 731 | Default: 3 |
|
730 | 732 | |
|
731 | 733 | -t: use time.time to measure the time, which is the default on Unix. |
|
732 | 734 | This function measures wall time. |
|
733 | 735 | |
|
734 | 736 | -c: use time.clock to measure the time, which is the default on |
|
735 | 737 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
736 | 738 | instead and returns the CPU user time. |
|
737 | 739 | |
|
738 | 740 | -p<P>: use a precision of <P> digits to display the timing result. |
|
739 | 741 | Default: 3 |
|
740 | 742 | |
|
741 | 743 | |
|
742 | 744 | Examples |
|
743 | 745 | -------- |
|
744 | 746 | :: |
|
745 | 747 | |
|
746 | 748 | In [1]: %timeit pass |
|
747 | 749 | 10000000 loops, best of 3: 53.3 ns per loop |
|
748 | 750 | |
|
749 | 751 | In [2]: u = None |
|
750 | 752 | |
|
751 | 753 | In [3]: %timeit u is None |
|
752 | 754 | 10000000 loops, best of 3: 184 ns per loop |
|
753 | 755 | |
|
754 | 756 | In [4]: %timeit -r 4 u == None |
|
755 | 757 | 1000000 loops, best of 4: 242 ns per loop |
|
756 | 758 | |
|
757 | 759 | In [5]: import time |
|
758 | 760 | |
|
759 | 761 | In [6]: %timeit -n1 time.sleep(2) |
|
760 | 762 | 1 loops, best of 3: 2 s per loop |
|
761 | 763 | |
|
762 | 764 | |
|
763 | 765 | The times reported by %timeit will be slightly higher than those |
|
764 | 766 | reported by the timeit.py script when variables are accessed. This is |
|
765 | 767 | due to the fact that %timeit executes the statement in the namespace |
|
766 | 768 | of the shell, compared with timeit.py, which uses a single setup |
|
767 | 769 | statement to import function or create variables. Generally, the bias |
|
768 | 770 | does not matter as long as results from timeit.py are not mixed with |
|
769 | 771 | those from %timeit.""" |
|
770 | 772 | |
|
771 | 773 | import timeit |
|
772 | 774 | |
|
773 | 775 | opts, stmt = self.parse_options(line,'n:r:tcp:', |
|
774 | 776 | posix=False, strict=False) |
|
775 | 777 | if stmt == "" and cell is None: |
|
776 | 778 | return |
|
777 | 779 | |
|
778 | 780 | timefunc = timeit.default_timer |
|
779 | 781 | number = int(getattr(opts, "n", 0)) |
|
780 | 782 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
781 | 783 | precision = int(getattr(opts, "p", 3)) |
|
782 | 784 | if hasattr(opts, "t"): |
|
783 | 785 | timefunc = time.time |
|
784 | 786 | if hasattr(opts, "c"): |
|
785 | 787 | timefunc = clock |
|
786 | 788 | |
|
787 | 789 | timer = timeit.Timer(timer=timefunc) |
|
788 | 790 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
789 | 791 | # but is there a better way to achieve that the code stmt has access |
|
790 | 792 | # to the shell namespace? |
|
791 | 793 | transform = self.shell.input_splitter.transform_cell |
|
792 | 794 | |
|
793 | 795 | if cell is None: |
|
794 | 796 | # called as line magic |
|
795 | 797 | ast_setup = ast.parse("pass") |
|
796 | 798 | ast_stmt = ast.parse(transform(stmt)) |
|
797 | 799 | else: |
|
798 | 800 | ast_setup = ast.parse(transform(stmt)) |
|
799 | 801 | ast_stmt = ast.parse(transform(cell)) |
|
800 | 802 | |
|
801 | 803 | ast_setup = self.shell.transform_ast(ast_setup) |
|
802 | 804 | ast_stmt = self.shell.transform_ast(ast_stmt) |
|
803 | 805 | |
|
804 | 806 | # This codestring is taken from timeit.template - we fill it in as an |
|
805 | 807 | # AST, so that we can apply our AST transformations to the user code |
|
806 | 808 | # without affecting the timing code. |
|
807 | 809 | timeit_ast_template = ast.parse('def inner(_it, _timer):\n' |
|
808 | 810 | ' setup\n' |
|
809 | 811 | ' _t0 = _timer()\n' |
|
810 | 812 | ' for _i in _it:\n' |
|
811 | 813 | ' stmt\n' |
|
812 | 814 | ' _t1 = _timer()\n' |
|
813 | 815 | ' return _t1 - _t0\n') |
|
814 | 816 | |
|
815 | 817 | class TimeitTemplateFiller(ast.NodeTransformer): |
|
816 | 818 | "This is quite tightly tied to the template definition above." |
|
817 | 819 | def visit_FunctionDef(self, node): |
|
818 | 820 | "Fill in the setup statement" |
|
819 | 821 | self.generic_visit(node) |
|
820 | 822 | if node.name == "inner": |
|
821 | 823 | node.body[:1] = ast_setup.body |
|
822 | 824 | |
|
823 | 825 | return node |
|
824 | 826 | |
|
825 | 827 | def visit_For(self, node): |
|
826 | 828 | "Fill in the statement to be timed" |
|
827 | 829 | if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt': |
|
828 | 830 | node.body = ast_stmt.body |
|
829 | 831 | return node |
|
830 | 832 | |
|
831 | 833 | timeit_ast = TimeitTemplateFiller().visit(timeit_ast_template) |
|
832 | 834 | timeit_ast = ast.fix_missing_locations(timeit_ast) |
|
833 | 835 | |
|
834 | 836 | # Track compilation time so it can be reported if too long |
|
835 | 837 | # Minimum time above which compilation time will be reported |
|
836 | 838 | tc_min = 0.1 |
|
837 | 839 | |
|
838 | 840 | t0 = clock() |
|
839 | 841 | code = compile(timeit_ast, "<magic-timeit>", "exec") |
|
840 | 842 | tc = clock()-t0 |
|
841 | 843 | |
|
842 | 844 | ns = {} |
|
843 | 845 | exec code in self.shell.user_ns, ns |
|
844 | 846 | timer.inner = ns["inner"] |
|
845 | 847 | |
|
846 | 848 | if number == 0: |
|
847 | 849 | # determine number so that 0.2 <= total time < 2.0 |
|
848 | 850 | number = 1 |
|
849 | 851 | for i in range(1, 10): |
|
850 | 852 | if timer.timeit(number) >= 0.2: |
|
851 | 853 | break |
|
852 | 854 | number *= 10 |
|
853 | 855 | |
|
854 | 856 | best = min(timer.repeat(repeat, number)) / number |
|
855 | 857 | |
|
856 | 858 | print u"%d loops, best of %d: %s per loop" % (number, repeat, |
|
857 | 859 | _format_time(best, precision)) |
|
858 | 860 | if tc > tc_min: |
|
859 | 861 | print "Compiler time: %.2f s" % tc |
|
860 | 862 | |
|
861 | 863 | @skip_doctest |
|
862 | 864 | @needs_local_scope |
|
863 | 865 | @line_cell_magic |
|
864 | 866 | def time(self,line='', cell=None, local_ns=None): |
|
865 | 867 | """Time execution of a Python statement or expression. |
|
866 | 868 | |
|
867 | 869 | The CPU and wall clock times are printed, and the value of the |
|
868 | 870 | expression (if any) is returned. Note that under Win32, system time |
|
869 | 871 | is always reported as 0, since it can not be measured. |
|
870 | 872 | |
|
871 | 873 | This function can be used both as a line and cell magic: |
|
872 | 874 | |
|
873 | 875 | - In line mode you can time a single-line statement (though multiple |
|
874 | 876 | ones can be chained with using semicolons). |
|
875 | 877 | |
|
876 | 878 | - In cell mode, you can time the cell body (a directly |
|
877 | 879 | following statement raises an error). |
|
878 | 880 | |
|
879 | 881 | This function provides very basic timing functionality. Use the timeit |
|
880 | 882 | magic for more controll over the measurement. |
|
881 | 883 | |
|
882 | 884 | Examples |
|
883 | 885 | -------- |
|
884 | 886 | :: |
|
885 | 887 | |
|
886 | 888 | In [1]: %time 2**128 |
|
887 | 889 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
888 | 890 | Wall time: 0.00 |
|
889 | 891 | Out[1]: 340282366920938463463374607431768211456L |
|
890 | 892 | |
|
891 | 893 | In [2]: n = 1000000 |
|
892 | 894 | |
|
893 | 895 | In [3]: %time sum(range(n)) |
|
894 | 896 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
895 | 897 | Wall time: 1.37 |
|
896 | 898 | Out[3]: 499999500000L |
|
897 | 899 | |
|
898 | 900 | In [4]: %time print 'hello world' |
|
899 | 901 | hello world |
|
900 | 902 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
901 | 903 | Wall time: 0.00 |
|
902 | 904 | |
|
903 | 905 | Note that the time needed by Python to compile the given expression |
|
904 | 906 | will be reported if it is more than 0.1s. In this example, the |
|
905 | 907 | actual exponentiation is done by Python at compilation time, so while |
|
906 | 908 | the expression can take a noticeable amount of time to compute, that |
|
907 | 909 | time is purely due to the compilation: |
|
908 | 910 | |
|
909 | 911 | In [5]: %time 3**9999; |
|
910 | 912 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
911 | 913 | Wall time: 0.00 s |
|
912 | 914 | |
|
913 | 915 | In [6]: %time 3**999999; |
|
914 | 916 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
915 | 917 | Wall time: 0.00 s |
|
916 | 918 | Compiler : 0.78 s |
|
917 | 919 | """ |
|
918 | 920 | |
|
919 | 921 | # fail immediately if the given expression can't be compiled |
|
920 | 922 | |
|
921 | 923 | if line and cell: |
|
922 | 924 | raise UsageError("Can't use statement directly after '%%time'!") |
|
923 | 925 | |
|
924 | 926 | if cell: |
|
925 | 927 | expr = self.shell.prefilter(cell,False) |
|
926 | 928 | else: |
|
927 | 929 | expr = self.shell.prefilter(line,False) |
|
928 | 930 | |
|
929 | 931 | # Minimum time above which parse time will be reported |
|
930 | 932 | tp_min = 0.1 |
|
931 | 933 | |
|
932 | 934 | t0 = clock() |
|
933 | 935 | expr_ast = ast.parse(expr) |
|
934 | 936 | tp = clock()-t0 |
|
935 | 937 | |
|
936 | 938 | # Apply AST transformations |
|
937 | 939 | expr_ast = self.shell.transform_ast(expr_ast) |
|
938 | 940 | |
|
939 | 941 | # Minimum time above which compilation time will be reported |
|
940 | 942 | tc_min = 0.1 |
|
941 | 943 | |
|
942 | 944 | if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr): |
|
943 | 945 | mode = 'eval' |
|
944 | 946 | source = '<timed eval>' |
|
945 | 947 | expr_ast = ast.Expression(expr_ast.body[0].value) |
|
946 | 948 | else: |
|
947 | 949 | mode = 'exec' |
|
948 | 950 | source = '<timed exec>' |
|
949 | 951 | t0 = clock() |
|
950 | 952 | code = compile(expr_ast, source, mode) |
|
951 | 953 | tc = clock()-t0 |
|
952 | 954 | |
|
953 | 955 | # skew measurement as little as possible |
|
954 | 956 | glob = self.shell.user_ns |
|
955 | 957 | wtime = time.time |
|
956 | 958 | # time execution |
|
957 | 959 | wall_st = wtime() |
|
958 | 960 | if mode=='eval': |
|
959 | 961 | st = clock2() |
|
960 | 962 | out = eval(code, glob, local_ns) |
|
961 | 963 | end = clock2() |
|
962 | 964 | else: |
|
963 | 965 | st = clock2() |
|
964 | 966 | exec code in glob, local_ns |
|
965 | 967 | end = clock2() |
|
966 | 968 | out = None |
|
967 | 969 | wall_end = wtime() |
|
968 | 970 | # Compute actual times and report |
|
969 | 971 | wall_time = wall_end-wall_st |
|
970 | 972 | cpu_user = end[0]-st[0] |
|
971 | 973 | cpu_sys = end[1]-st[1] |
|
972 | 974 | cpu_tot = cpu_user+cpu_sys |
|
973 | 975 | # On windows cpu_sys is always zero, so no new information to the next print |
|
974 | 976 | if sys.platform != 'win32': |
|
975 | 977 | print "CPU times: user %s, sys: %s, total: %s" % \ |
|
976 | 978 | (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)) |
|
977 | 979 | print "Wall time: %s" % _format_time(wall_time) |
|
978 | 980 | if tc > tc_min: |
|
979 | 981 | print "Compiler : %s" % _format_time(tc) |
|
980 | 982 | if tp > tp_min: |
|
981 | 983 | print "Parser : %s" % _format_time(tp) |
|
982 | 984 | return out |
|
983 | 985 | |
|
984 | 986 | @skip_doctest |
|
985 | 987 | @line_magic |
|
986 | 988 | def macro(self, parameter_s=''): |
|
987 | 989 | """Define a macro for future re-execution. It accepts ranges of history, |
|
988 | 990 | filenames or string objects. |
|
989 | 991 | |
|
990 | 992 | Usage:\\ |
|
991 | 993 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
992 | 994 | |
|
993 | 995 | Options: |
|
994 | 996 | |
|
995 | 997 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
996 | 998 | so that magics are loaded in their transformed version to valid |
|
997 | 999 | Python. If this option is given, the raw input as typed as the |
|
998 | 1000 | command line is used instead. |
|
999 | 1001 | |
|
1000 | 1002 | This will define a global variable called `name` which is a string |
|
1001 | 1003 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1002 | 1004 | above) from your input history into a single string. This variable |
|
1003 | 1005 | acts like an automatic function which re-executes those lines as if |
|
1004 | 1006 | you had typed them. You just type 'name' at the prompt and the code |
|
1005 | 1007 | executes. |
|
1006 | 1008 | |
|
1007 | 1009 | The syntax for indicating input ranges is described in %history. |
|
1008 | 1010 | |
|
1009 | 1011 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1010 | 1012 | notation, where N:M means numbers N through M-1. |
|
1011 | 1013 | |
|
1012 | 1014 | For example, if your history contains (%hist prints it):: |
|
1013 | 1015 | |
|
1014 | 1016 | 44: x=1 |
|
1015 | 1017 | 45: y=3 |
|
1016 | 1018 | 46: z=x+y |
|
1017 | 1019 | 47: print x |
|
1018 | 1020 | 48: a=5 |
|
1019 | 1021 | 49: print 'x',x,'y',y |
|
1020 | 1022 | |
|
1021 | 1023 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1022 | 1024 | called my_macro with:: |
|
1023 | 1025 | |
|
1024 | 1026 | In [55]: %macro my_macro 44-47 49 |
|
1025 | 1027 | |
|
1026 | 1028 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1027 | 1029 | in one pass. |
|
1028 | 1030 | |
|
1029 | 1031 | You don't need to give the line-numbers in order, and any given line |
|
1030 | 1032 | number can appear multiple times. You can assemble macros with any |
|
1031 | 1033 | lines from your input history in any order. |
|
1032 | 1034 | |
|
1033 | 1035 | The macro is a simple object which holds its value in an attribute, |
|
1034 | 1036 | but IPython's display system checks for macros and executes them as |
|
1035 | 1037 | code instead of printing them when you type their name. |
|
1036 | 1038 | |
|
1037 | 1039 | You can view a macro's contents by explicitly printing it with:: |
|
1038 | 1040 | |
|
1039 | 1041 | print macro_name |
|
1040 | 1042 | |
|
1041 | 1043 | """ |
|
1042 | 1044 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
1043 | 1045 | if not args: # List existing macros |
|
1044 | 1046 | return sorted(k for k,v in self.shell.user_ns.iteritems() if\ |
|
1045 | 1047 | isinstance(v, Macro)) |
|
1046 | 1048 | if len(args) == 1: |
|
1047 | 1049 | raise UsageError( |
|
1048 | 1050 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
1049 | 1051 | name, codefrom = args[0], " ".join(args[1:]) |
|
1050 | 1052 | |
|
1051 | 1053 | #print 'rng',ranges # dbg |
|
1052 | 1054 | try: |
|
1053 | 1055 | lines = self.shell.find_user_code(codefrom, 'r' in opts) |
|
1054 | 1056 | except (ValueError, TypeError) as e: |
|
1055 | 1057 | print e.args[0] |
|
1056 | 1058 | return |
|
1057 | 1059 | macro = Macro(lines) |
|
1058 | 1060 | self.shell.define_macro(name, macro) |
|
1059 | 1061 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
1060 | 1062 | print '=== Macro contents: ===' |
|
1061 | 1063 | print macro, |
|
1062 | 1064 | |
|
1063 | 1065 | @magic_arguments.magic_arguments() |
|
1064 | 1066 | @magic_arguments.argument('output', type=str, default='', nargs='?', |
|
1065 | 1067 | help="""The name of the variable in which to store output. |
|
1066 | 1068 | This is a utils.io.CapturedIO object with stdout/err attributes |
|
1067 | 1069 | for the text of the captured output. |
|
1068 | 1070 | |
|
1069 | 1071 | CapturedOutput also has a show() method for displaying the output, |
|
1070 | 1072 | and __call__ as well, so you can use that to quickly display the |
|
1071 | 1073 | output. |
|
1072 | 1074 | |
|
1073 | 1075 | If unspecified, captured output is discarded. |
|
1074 | 1076 | """ |
|
1075 | 1077 | ) |
|
1076 | 1078 | @magic_arguments.argument('--no-stderr', action="store_true", |
|
1077 | 1079 | help="""Don't capture stderr.""" |
|
1078 | 1080 | ) |
|
1079 | 1081 | @magic_arguments.argument('--no-stdout', action="store_true", |
|
1080 | 1082 | help="""Don't capture stdout.""" |
|
1081 | 1083 | ) |
|
1082 | 1084 | @cell_magic |
|
1083 | 1085 | def capture(self, line, cell): |
|
1084 | 1086 | """run the cell, capturing stdout/err""" |
|
1085 | 1087 | args = magic_arguments.parse_argstring(self.capture, line) |
|
1086 | 1088 | out = not args.no_stdout |
|
1087 | 1089 | err = not args.no_stderr |
|
1088 | 1090 | with capture_output(out, err) as io: |
|
1089 | 1091 | self.shell.run_cell(cell) |
|
1090 | 1092 | if args.output: |
|
1091 | 1093 | self.shell.user_ns[args.output] = io |
|
1092 | 1094 | |
|
1093 | 1095 | def parse_breakpoint(text, current_file): |
|
1094 | 1096 | '''Returns (file, line) for file:line and (current_file, line) for line''' |
|
1095 | 1097 | colon = text.find(':') |
|
1096 | 1098 | if colon == -1: |
|
1097 | 1099 | return current_file, int(text) |
|
1098 | 1100 | else: |
|
1099 | 1101 | return text[:colon], int(text[colon+1:]) |
|
1100 | 1102 | |
|
1101 | 1103 | def _format_time(timespan, precision=3): |
|
1102 | 1104 | """Formats the timespan in a human readable form""" |
|
1103 | 1105 | import math |
|
1104 | 1106 | |
|
1105 | 1107 | if timespan >= 60.0: |
|
1106 | 1108 | # we have more than a minute, format that in a human readable form |
|
1107 | 1109 | # Idea from http://snipplr.com/view/5713/ |
|
1108 | 1110 | parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)] |
|
1109 | 1111 | time = [] |
|
1110 | 1112 | leftover = timespan |
|
1111 | 1113 | for suffix, length in parts: |
|
1112 | 1114 | value = int(leftover / length) |
|
1113 | 1115 | if value > 0: |
|
1114 | 1116 | leftover = leftover % length |
|
1115 | 1117 | time.append(u'%s%s' % (str(value), suffix)) |
|
1116 | 1118 | if leftover < 1: |
|
1117 | 1119 | break |
|
1118 | 1120 | return " ".join(time) |
|
1119 | 1121 | |
|
1120 | 1122 | |
|
1121 | 1123 | # Unfortunately the unicode 'micro' symbol can cause problems in |
|
1122 | 1124 | # certain terminals. |
|
1123 | 1125 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1124 | 1126 | # Try to prevent crashes by being more secure than it needs to |
|
1125 | 1127 | # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set. |
|
1126 | 1128 | units = [u"s", u"ms",u'us',"ns"] # the save value |
|
1127 | 1129 | if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding: |
|
1128 | 1130 | try: |
|
1129 | 1131 | u'\xb5'.encode(sys.stdout.encoding) |
|
1130 | 1132 | units = [u"s", u"ms",u'\xb5s',"ns"] |
|
1131 | 1133 | except: |
|
1132 | 1134 | pass |
|
1133 | 1135 | scaling = [1, 1e3, 1e6, 1e9] |
|
1134 | 1136 | |
|
1135 | 1137 | if timespan > 0.0: |
|
1136 | 1138 | order = min(-int(math.floor(math.log10(timespan)) // 3), 3) |
|
1137 | 1139 | else: |
|
1138 | 1140 | order = 3 |
|
1139 | 1141 | ret = u"%.*g %s" % (precision, timespan * scaling[order], units[order]) |
|
1140 | 1142 | return ret |
General Comments 0
You need to be logged in to leave comments.
Login now