##// END OF EJS Templates
Use shell futures environment for code in %time and %timeit...
Thomas Kluyver -
Show More
@@ -1,1314 +1,1314 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Implementation of execution-related magic functions.
3 3 """
4 4 from __future__ import print_function
5 5 #-----------------------------------------------------------------------------
6 6 # Copyright (c) 2012 The IPython Development Team.
7 7 #
8 8 # Distributed under the terms of the Modified BSD License.
9 9 #
10 10 # The full license is in the file COPYING.txt, distributed with this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 # Stdlib
18 18 import ast
19 19 import bdb
20 20 import os
21 21 import sys
22 22 import time
23 23 from pdb import Restart
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.py3compat import builtin_mod, iteritems, PY3
47 47 from IPython.utils.contexts import preserve_keys
48 48 from IPython.utils.io import capture_output
49 49 from IPython.utils.ipstruct import Struct
50 50 from IPython.utils.module_paths import find_mod
51 51 from IPython.utils.path import get_py_filename, unquote_filename, shellglob
52 52 from IPython.utils.timing import clock, clock2
53 53 from IPython.utils.warn import warn, error
54 54
55 55 if PY3:
56 56 from io import StringIO
57 57 else:
58 58 from StringIO import StringIO
59 59
60 60 #-----------------------------------------------------------------------------
61 61 # Magic implementation classes
62 62 #-----------------------------------------------------------------------------
63 63
64 64
65 65 class TimeitResult(object):
66 66 """
67 67 Object returned by the timeit magic with info about the run.
68 68
69 69 Contain the following attributes :
70 70
71 71 loops: (int) number of loop done per measurement
72 72 repeat: (int) number of time the mesurement has been repeated
73 73 best: (float) best execusion time / number
74 74 all_runs: (list of float) execusion time of each run (in s)
75 75 compile_time: (float) time of statement compilation (s)
76 76
77 77 """
78 78
79 79 def __init__(self, loops, repeat, best, all_runs, compile_time, precision):
80 80 self.loops = loops
81 81 self.repeat = repeat
82 82 self.best = best
83 83 self.all_runs = all_runs
84 84 self.compile_time = compile_time
85 85 self._precision = precision
86 86
87 87 def _repr_pretty_(self, p , cycle):
88 88 unic = u"%d loops, best of %d: %s per loop" % (self.loops, self.repeat,
89 89 _format_time(self.best, self._precision))
90 90 p.text(u'<TimeitResult : '+unic+u'>')
91 91
92 92
93 93 class TimeitTemplateFiller(ast.NodeTransformer):
94 94 """Fill in the AST template for timing execution.
95 95
96 96 This is quite closely tied to the template definition, which is in
97 97 :meth:`ExecutionMagics.timeit`.
98 98 """
99 99 def __init__(self, ast_setup, ast_stmt):
100 100 self.ast_setup = ast_setup
101 101 self.ast_stmt = ast_stmt
102 102
103 103 def visit_FunctionDef(self, node):
104 104 "Fill in the setup statement"
105 105 self.generic_visit(node)
106 106 if node.name == "inner":
107 107 node.body[:1] = self.ast_setup.body
108 108
109 109 return node
110 110
111 111 def visit_For(self, node):
112 112 "Fill in the statement to be timed"
113 113 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
114 114 node.body = self.ast_stmt.body
115 115 return node
116 116
117 117
118 118 @magics_class
119 119 class ExecutionMagics(Magics):
120 120 """Magics related to code execution, debugging, profiling, etc.
121 121
122 122 """
123 123
124 124 def __init__(self, shell):
125 125 super(ExecutionMagics, self).__init__(shell)
126 126 if profile is None:
127 127 self.prun = self.profile_missing_notice
128 128 # Default execution function used to actually run user code.
129 129 self.default_runner = None
130 130
131 131 def profile_missing_notice(self, *args, **kwargs):
132 132 error("""\
133 133 The profile module could not be found. It has been removed from the standard
134 134 python packages because of its non-free license. To use profiling, install the
135 135 python-profiler package from non-free.""")
136 136
137 137 @skip_doctest
138 138 @line_cell_magic
139 139 def prun(self, parameter_s='', cell=None):
140 140
141 141 """Run a statement through the python code profiler.
142 142
143 143 Usage, in line mode:
144 144 %prun [options] statement
145 145
146 146 Usage, in cell mode:
147 147 %%prun [options] [statement]
148 148 code...
149 149 code...
150 150
151 151 In cell mode, the additional code lines are appended to the (possibly
152 152 empty) statement in the first line. Cell mode allows you to easily
153 153 profile multiline blocks without having to put them in a separate
154 154 function.
155 155
156 156 The given statement (which doesn't require quote marks) is run via the
157 157 python profiler in a manner similar to the profile.run() function.
158 158 Namespaces are internally managed to work correctly; profile.run
159 159 cannot be used in IPython because it makes certain assumptions about
160 160 namespaces which do not hold under IPython.
161 161
162 162 Options:
163 163
164 164 -l <limit>
165 165 you can place restrictions on what or how much of the
166 166 profile gets printed. The limit value can be:
167 167
168 168 * A string: only information for function names containing this string
169 169 is printed.
170 170
171 171 * An integer: only these many lines are printed.
172 172
173 173 * A float (between 0 and 1): this fraction of the report is printed
174 174 (for example, use a limit of 0.4 to see the topmost 40% only).
175 175
176 176 You can combine several limits with repeated use of the option. For
177 177 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
178 178 information about class constructors.
179 179
180 180 -r
181 181 return the pstats.Stats object generated by the profiling. This
182 182 object has all the information about the profile in it, and you can
183 183 later use it for further analysis or in other functions.
184 184
185 185 -s <key>
186 186 sort profile by given key. You can provide more than one key
187 187 by using the option several times: '-s key1 -s key2 -s key3...'. The
188 188 default sorting key is 'time'.
189 189
190 190 The following is copied verbatim from the profile documentation
191 191 referenced below:
192 192
193 193 When more than one key is provided, additional keys are used as
194 194 secondary criteria when the there is equality in all keys selected
195 195 before them.
196 196
197 197 Abbreviations can be used for any key names, as long as the
198 198 abbreviation is unambiguous. The following are the keys currently
199 199 defined:
200 200
201 201 ============ =====================
202 202 Valid Arg Meaning
203 203 ============ =====================
204 204 "calls" call count
205 205 "cumulative" cumulative time
206 206 "file" file name
207 207 "module" file name
208 208 "pcalls" primitive call count
209 209 "line" line number
210 210 "name" function name
211 211 "nfl" name/file/line
212 212 "stdname" standard name
213 213 "time" internal time
214 214 ============ =====================
215 215
216 216 Note that all sorts on statistics are in descending order (placing
217 217 most time consuming items first), where as name, file, and line number
218 218 searches are in ascending order (i.e., alphabetical). The subtle
219 219 distinction between "nfl" and "stdname" is that the standard name is a
220 220 sort of the name as printed, which means that the embedded line
221 221 numbers get compared in an odd way. For example, lines 3, 20, and 40
222 222 would (if the file names were the same) appear in the string order
223 223 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
224 224 line numbers. In fact, sort_stats("nfl") is the same as
225 225 sort_stats("name", "file", "line").
226 226
227 227 -T <filename>
228 228 save profile results as shown on screen to a text
229 229 file. The profile is still shown on screen.
230 230
231 231 -D <filename>
232 232 save (via dump_stats) profile statistics to given
233 233 filename. This data is in a format understood by the pstats module, and
234 234 is generated by a call to the dump_stats() method of profile
235 235 objects. The profile is still shown on screen.
236 236
237 237 -q
238 238 suppress output to the pager. Best used with -T and/or -D above.
239 239
240 240 If you want to run complete programs under the profiler's control, use
241 241 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
242 242 contains profiler specific options as described here.
243 243
244 244 You can read the complete documentation for the profile module with::
245 245
246 246 In [1]: import profile; profile.help()
247 247 """
248 248 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
249 249 list_all=True, posix=False)
250 250 if cell is not None:
251 251 arg_str += '\n' + cell
252 252 arg_str = self.shell.input_splitter.transform_cell(arg_str)
253 253 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
254 254
255 255 def _run_with_profiler(self, code, opts, namespace):
256 256 """
257 257 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
258 258
259 259 Parameters
260 260 ----------
261 261 code : str
262 262 Code to be executed.
263 263 opts : Struct
264 264 Options parsed by `self.parse_options`.
265 265 namespace : dict
266 266 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
267 267
268 268 """
269 269
270 270 # Fill default values for unspecified options:
271 271 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
272 272
273 273 prof = profile.Profile()
274 274 try:
275 275 prof = prof.runctx(code, namespace, namespace)
276 276 sys_exit = ''
277 277 except SystemExit:
278 278 sys_exit = """*** SystemExit exception caught in code being profiled."""
279 279
280 280 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
281 281
282 282 lims = opts.l
283 283 if lims:
284 284 lims = [] # rebuild lims with ints/floats/strings
285 285 for lim in opts.l:
286 286 try:
287 287 lims.append(int(lim))
288 288 except ValueError:
289 289 try:
290 290 lims.append(float(lim))
291 291 except ValueError:
292 292 lims.append(lim)
293 293
294 294 # Trap output.
295 295 stdout_trap = StringIO()
296 296 stats_stream = stats.stream
297 297 try:
298 298 stats.stream = stdout_trap
299 299 stats.print_stats(*lims)
300 300 finally:
301 301 stats.stream = stats_stream
302 302
303 303 output = stdout_trap.getvalue()
304 304 output = output.rstrip()
305 305
306 306 if 'q' not in opts:
307 307 page.page(output)
308 308 print(sys_exit, end=' ')
309 309
310 310 dump_file = opts.D[0]
311 311 text_file = opts.T[0]
312 312 if dump_file:
313 313 dump_file = unquote_filename(dump_file)
314 314 prof.dump_stats(dump_file)
315 315 print('\n*** Profile stats marshalled to file',\
316 316 repr(dump_file)+'.',sys_exit)
317 317 if text_file:
318 318 text_file = unquote_filename(text_file)
319 319 pfile = open(text_file,'w')
320 320 pfile.write(output)
321 321 pfile.close()
322 322 print('\n*** Profile printout saved to text file',\
323 323 repr(text_file)+'.',sys_exit)
324 324
325 325 if 'r' in opts:
326 326 return stats
327 327 else:
328 328 return None
329 329
330 330 @line_magic
331 331 def pdb(self, parameter_s=''):
332 332 """Control the automatic calling of the pdb interactive debugger.
333 333
334 334 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
335 335 argument it works as a toggle.
336 336
337 337 When an exception is triggered, IPython can optionally call the
338 338 interactive pdb debugger after the traceback printout. %pdb toggles
339 339 this feature on and off.
340 340
341 341 The initial state of this feature is set in your configuration
342 342 file (the option is ``InteractiveShell.pdb``).
343 343
344 344 If you want to just activate the debugger AFTER an exception has fired,
345 345 without having to type '%pdb on' and rerunning your code, you can use
346 346 the %debug magic."""
347 347
348 348 par = parameter_s.strip().lower()
349 349
350 350 if par:
351 351 try:
352 352 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
353 353 except KeyError:
354 354 print ('Incorrect argument. Use on/1, off/0, '
355 355 'or nothing for a toggle.')
356 356 return
357 357 else:
358 358 # toggle
359 359 new_pdb = not self.shell.call_pdb
360 360
361 361 # set on the shell
362 362 self.shell.call_pdb = new_pdb
363 363 print('Automatic pdb calling has been turned',on_off(new_pdb))
364 364
365 365 @skip_doctest
366 366 @magic_arguments.magic_arguments()
367 367 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
368 368 help="""
369 369 Set break point at LINE in FILE.
370 370 """
371 371 )
372 372 @magic_arguments.argument('statement', nargs='*',
373 373 help="""
374 374 Code to run in debugger.
375 375 You can omit this in cell magic mode.
376 376 """
377 377 )
378 378 @line_cell_magic
379 379 def debug(self, line='', cell=None):
380 380 """Activate the interactive debugger.
381 381
382 382 This magic command support two ways of activating debugger.
383 383 One is to activate debugger before executing code. This way, you
384 384 can set a break point, to step through the code from the point.
385 385 You can use this mode by giving statements to execute and optionally
386 386 a breakpoint.
387 387
388 388 The other one is to activate debugger in post-mortem mode. You can
389 389 activate this mode simply running %debug without any argument.
390 390 If an exception has just occurred, this lets you inspect its stack
391 391 frames interactively. Note that this will always work only on the last
392 392 traceback that occurred, so you must call this quickly after an
393 393 exception that you wish to inspect has fired, because if another one
394 394 occurs, it clobbers the previous one.
395 395
396 396 If you want IPython to automatically do this on every exception, see
397 397 the %pdb magic for more details.
398 398 """
399 399 args = magic_arguments.parse_argstring(self.debug, line)
400 400
401 401 if not (args.breakpoint or args.statement or cell):
402 402 self._debug_post_mortem()
403 403 else:
404 404 code = "\n".join(args.statement)
405 405 if cell:
406 406 code += "\n" + cell
407 407 self._debug_exec(code, args.breakpoint)
408 408
409 409 def _debug_post_mortem(self):
410 410 self.shell.debugger(force=True)
411 411
412 412 def _debug_exec(self, code, breakpoint):
413 413 if breakpoint:
414 414 (filename, bp_line) = breakpoint.split(':', 1)
415 415 bp_line = int(bp_line)
416 416 else:
417 417 (filename, bp_line) = (None, None)
418 418 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
419 419
420 420 @line_magic
421 421 def tb(self, s):
422 422 """Print the last traceback with the currently active exception mode.
423 423
424 424 See %xmode for changing exception reporting modes."""
425 425 self.shell.showtraceback()
426 426
427 427 @skip_doctest
428 428 @line_magic
429 429 def run(self, parameter_s='', runner=None,
430 430 file_finder=get_py_filename):
431 431 """Run the named file inside IPython as a program.
432 432
433 433 Usage::
434 434
435 435 %run [-n -i -e -G]
436 436 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
437 437 ( -m mod | file ) [args]
438 438
439 439 Parameters after the filename are passed as command-line arguments to
440 440 the program (put in sys.argv). Then, control returns to IPython's
441 441 prompt.
442 442
443 443 This is similar to running at a system prompt ``python file args``,
444 444 but with the advantage of giving you IPython's tracebacks, and of
445 445 loading all variables into your interactive namespace for further use
446 446 (unless -p is used, see below).
447 447
448 448 The file is executed in a namespace initially consisting only of
449 449 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
450 450 sees its environment as if it were being run as a stand-alone program
451 451 (except for sharing global objects such as previously imported
452 452 modules). But after execution, the IPython interactive namespace gets
453 453 updated with all variables defined in the program (except for __name__
454 454 and sys.argv). This allows for very convenient loading of code for
455 455 interactive work, while giving each program a 'clean sheet' to run in.
456 456
457 457 Arguments are expanded using shell-like glob match. Patterns
458 458 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
459 459 tilde '~' will be expanded into user's home directory. Unlike
460 460 real shells, quotation does not suppress expansions. Use
461 461 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
462 462 To completely disable these expansions, you can use -G flag.
463 463
464 464 Options:
465 465
466 466 -n
467 467 __name__ is NOT set to '__main__', but to the running file's name
468 468 without extension (as python does under import). This allows running
469 469 scripts and reloading the definitions in them without calling code
470 470 protected by an ``if __name__ == "__main__"`` clause.
471 471
472 472 -i
473 473 run the file in IPython's namespace instead of an empty one. This
474 474 is useful if you are experimenting with code written in a text editor
475 475 which depends on variables defined interactively.
476 476
477 477 -e
478 478 ignore sys.exit() calls or SystemExit exceptions in the script
479 479 being run. This is particularly useful if IPython is being used to
480 480 run unittests, which always exit with a sys.exit() call. In such
481 481 cases you are interested in the output of the test results, not in
482 482 seeing a traceback of the unittest module.
483 483
484 484 -t
485 485 print timing information at the end of the run. IPython will give
486 486 you an estimated CPU time consumption for your script, which under
487 487 Unix uses the resource module to avoid the wraparound problems of
488 488 time.clock(). Under Unix, an estimate of time spent on system tasks
489 489 is also given (for Windows platforms this is reported as 0.0).
490 490
491 491 If -t is given, an additional ``-N<N>`` option can be given, where <N>
492 492 must be an integer indicating how many times you want the script to
493 493 run. The final timing report will include total and per run results.
494 494
495 495 For example (testing the script uniq_stable.py)::
496 496
497 497 In [1]: run -t uniq_stable
498 498
499 499 IPython CPU timings (estimated):
500 500 User : 0.19597 s.
501 501 System: 0.0 s.
502 502
503 503 In [2]: run -t -N5 uniq_stable
504 504
505 505 IPython CPU timings (estimated):
506 506 Total runs performed: 5
507 507 Times : Total Per run
508 508 User : 0.910862 s, 0.1821724 s.
509 509 System: 0.0 s, 0.0 s.
510 510
511 511 -d
512 512 run your program under the control of pdb, the Python debugger.
513 513 This allows you to execute your program step by step, watch variables,
514 514 etc. Internally, what IPython does is similar to calling::
515 515
516 516 pdb.run('execfile("YOURFILENAME")')
517 517
518 518 with a breakpoint set on line 1 of your file. You can change the line
519 519 number for this automatic breakpoint to be <N> by using the -bN option
520 520 (where N must be an integer). For example::
521 521
522 522 %run -d -b40 myscript
523 523
524 524 will set the first breakpoint at line 40 in myscript.py. Note that
525 525 the first breakpoint must be set on a line which actually does
526 526 something (not a comment or docstring) for it to stop execution.
527 527
528 528 Or you can specify a breakpoint in a different file::
529 529
530 530 %run -d -b myotherfile.py:20 myscript
531 531
532 532 When the pdb debugger starts, you will see a (Pdb) prompt. You must
533 533 first enter 'c' (without quotes) to start execution up to the first
534 534 breakpoint.
535 535
536 536 Entering 'help' gives information about the use of the debugger. You
537 537 can easily see pdb's full documentation with "import pdb;pdb.help()"
538 538 at a prompt.
539 539
540 540 -p
541 541 run program under the control of the Python profiler module (which
542 542 prints a detailed report of execution times, function calls, etc).
543 543
544 544 You can pass other options after -p which affect the behavior of the
545 545 profiler itself. See the docs for %prun for details.
546 546
547 547 In this mode, the program's variables do NOT propagate back to the
548 548 IPython interactive namespace (because they remain in the namespace
549 549 where the profiler executes them).
550 550
551 551 Internally this triggers a call to %prun, see its documentation for
552 552 details on the options available specifically for profiling.
553 553
554 554 There is one special usage for which the text above doesn't apply:
555 555 if the filename ends with .ipy[nb], the file is run as ipython script,
556 556 just as if the commands were written on IPython prompt.
557 557
558 558 -m
559 559 specify module name to load instead of script path. Similar to
560 560 the -m option for the python interpreter. Use this option last if you
561 561 want to combine with other %run options. Unlike the python interpreter
562 562 only source modules are allowed no .pyc or .pyo files.
563 563 For example::
564 564
565 565 %run -m example
566 566
567 567 will run the example module.
568 568
569 569 -G
570 570 disable shell-like glob expansion of arguments.
571 571
572 572 """
573 573
574 574 # get arguments and set sys.argv for program to be run.
575 575 opts, arg_lst = self.parse_options(parameter_s,
576 576 'nidtN:b:pD:l:rs:T:em:G',
577 577 mode='list', list_all=1)
578 578 if "m" in opts:
579 579 modulename = opts["m"][0]
580 580 modpath = find_mod(modulename)
581 581 if modpath is None:
582 582 warn('%r is not a valid modulename on sys.path'%modulename)
583 583 return
584 584 arg_lst = [modpath] + arg_lst
585 585 try:
586 586 filename = file_finder(arg_lst[0])
587 587 except IndexError:
588 588 warn('you must provide at least a filename.')
589 589 print('\n%run:\n', oinspect.getdoc(self.run))
590 590 return
591 591 except IOError as e:
592 592 try:
593 593 msg = str(e)
594 594 except UnicodeError:
595 595 msg = e.message
596 596 error(msg)
597 597 return
598 598
599 599 if filename.lower().endswith(('.ipy', '.ipynb')):
600 600 with preserve_keys(self.shell.user_ns, '__file__'):
601 601 self.shell.user_ns['__file__'] = filename
602 602 self.shell.safe_execfile_ipy(filename)
603 603 return
604 604
605 605 # Control the response to exit() calls made by the script being run
606 606 exit_ignore = 'e' in opts
607 607
608 608 # Make sure that the running script gets a proper sys.argv as if it
609 609 # were run from a system shell.
610 610 save_argv = sys.argv # save it for later restoring
611 611
612 612 if 'G' in opts:
613 613 args = arg_lst[1:]
614 614 else:
615 615 # tilde and glob expansion
616 616 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
617 617
618 618 sys.argv = [filename] + args # put in the proper filename
619 619 # protect sys.argv from potential unicode strings on Python 2:
620 620 if not py3compat.PY3:
621 621 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
622 622
623 623 if 'i' in opts:
624 624 # Run in user's interactive namespace
625 625 prog_ns = self.shell.user_ns
626 626 __name__save = self.shell.user_ns['__name__']
627 627 prog_ns['__name__'] = '__main__'
628 628 main_mod = self.shell.user_module
629 629
630 630 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
631 631 # set the __file__ global in the script's namespace
632 632 # TK: Is this necessary in interactive mode?
633 633 prog_ns['__file__'] = filename
634 634 else:
635 635 # Run in a fresh, empty namespace
636 636 if 'n' in opts:
637 637 name = os.path.splitext(os.path.basename(filename))[0]
638 638 else:
639 639 name = '__main__'
640 640
641 641 # The shell MUST hold a reference to prog_ns so after %run
642 642 # exits, the python deletion mechanism doesn't zero it out
643 643 # (leaving dangling references). See interactiveshell for details
644 644 main_mod = self.shell.new_main_mod(filename, name)
645 645 prog_ns = main_mod.__dict__
646 646
647 647 # pickle fix. See interactiveshell for an explanation. But we need to
648 648 # make sure that, if we overwrite __main__, we replace it at the end
649 649 main_mod_name = prog_ns['__name__']
650 650
651 651 if main_mod_name == '__main__':
652 652 restore_main = sys.modules['__main__']
653 653 else:
654 654 restore_main = False
655 655
656 656 # This needs to be undone at the end to prevent holding references to
657 657 # every single object ever created.
658 658 sys.modules[main_mod_name] = main_mod
659 659
660 660 if 'p' in opts or 'd' in opts:
661 661 if 'm' in opts:
662 662 code = 'run_module(modulename, prog_ns)'
663 663 code_ns = {
664 664 'run_module': self.shell.safe_run_module,
665 665 'prog_ns': prog_ns,
666 666 'modulename': modulename,
667 667 }
668 668 else:
669 669 if 'd' in opts:
670 670 # allow exceptions to raise in debug mode
671 671 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
672 672 else:
673 673 code = 'execfile(filename, prog_ns)'
674 674 code_ns = {
675 675 'execfile': self.shell.safe_execfile,
676 676 'prog_ns': prog_ns,
677 677 'filename': get_py_filename(filename),
678 678 }
679 679
680 680 try:
681 681 stats = None
682 682 with self.shell.readline_no_record:
683 683 if 'p' in opts:
684 684 stats = self._run_with_profiler(code, opts, code_ns)
685 685 else:
686 686 if 'd' in opts:
687 687 bp_file, bp_line = parse_breakpoint(
688 688 opts.get('b', ['1'])[0], filename)
689 689 self._run_with_debugger(
690 690 code, code_ns, filename, bp_line, bp_file)
691 691 else:
692 692 if 'm' in opts:
693 693 def run():
694 694 self.shell.safe_run_module(modulename, prog_ns)
695 695 else:
696 696 if runner is None:
697 697 runner = self.default_runner
698 698 if runner is None:
699 699 runner = self.shell.safe_execfile
700 700
701 701 def run():
702 702 runner(filename, prog_ns, prog_ns,
703 703 exit_ignore=exit_ignore)
704 704
705 705 if 't' in opts:
706 706 # timed execution
707 707 try:
708 708 nruns = int(opts['N'][0])
709 709 if nruns < 1:
710 710 error('Number of runs must be >=1')
711 711 return
712 712 except (KeyError):
713 713 nruns = 1
714 714 self._run_with_timing(run, nruns)
715 715 else:
716 716 # regular execution
717 717 run()
718 718
719 719 if 'i' in opts:
720 720 self.shell.user_ns['__name__'] = __name__save
721 721 else:
722 722 # update IPython interactive namespace
723 723
724 724 # Some forms of read errors on the file may mean the
725 725 # __name__ key was never set; using pop we don't have to
726 726 # worry about a possible KeyError.
727 727 prog_ns.pop('__name__', None)
728 728
729 729 with preserve_keys(self.shell.user_ns, '__file__'):
730 730 self.shell.user_ns.update(prog_ns)
731 731 finally:
732 732 # It's a bit of a mystery why, but __builtins__ can change from
733 733 # being a module to becoming a dict missing some key data after
734 734 # %run. As best I can see, this is NOT something IPython is doing
735 735 # at all, and similar problems have been reported before:
736 736 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
737 737 # Since this seems to be done by the interpreter itself, the best
738 738 # we can do is to at least restore __builtins__ for the user on
739 739 # exit.
740 740 self.shell.user_ns['__builtins__'] = builtin_mod
741 741
742 742 # Ensure key global structures are restored
743 743 sys.argv = save_argv
744 744 if restore_main:
745 745 sys.modules['__main__'] = restore_main
746 746 else:
747 747 # Remove from sys.modules the reference to main_mod we'd
748 748 # added. Otherwise it will trap references to objects
749 749 # contained therein.
750 750 del sys.modules[main_mod_name]
751 751
752 752 return stats
753 753
754 754 def _run_with_debugger(self, code, code_ns, filename=None,
755 755 bp_line=None, bp_file=None):
756 756 """
757 757 Run `code` in debugger with a break point.
758 758
759 759 Parameters
760 760 ----------
761 761 code : str
762 762 Code to execute.
763 763 code_ns : dict
764 764 A namespace in which `code` is executed.
765 765 filename : str
766 766 `code` is ran as if it is in `filename`.
767 767 bp_line : int, optional
768 768 Line number of the break point.
769 769 bp_file : str, optional
770 770 Path to the file in which break point is specified.
771 771 `filename` is used if not given.
772 772
773 773 Raises
774 774 ------
775 775 UsageError
776 776 If the break point given by `bp_line` is not valid.
777 777
778 778 """
779 779 deb = debugger.Pdb(self.shell.colors)
780 780 # reset Breakpoint state, which is moronically kept
781 781 # in a class
782 782 bdb.Breakpoint.next = 1
783 783 bdb.Breakpoint.bplist = {}
784 784 bdb.Breakpoint.bpbynumber = [None]
785 785 if bp_line is not None:
786 786 # Set an initial breakpoint to stop execution
787 787 maxtries = 10
788 788 bp_file = bp_file or filename
789 789 checkline = deb.checkline(bp_file, bp_line)
790 790 if not checkline:
791 791 for bp in range(bp_line + 1, bp_line + maxtries + 1):
792 792 if deb.checkline(bp_file, bp):
793 793 break
794 794 else:
795 795 msg = ("\nI failed to find a valid line to set "
796 796 "a breakpoint\n"
797 797 "after trying up to line: %s.\n"
798 798 "Please set a valid breakpoint manually "
799 799 "with the -b option." % bp)
800 800 raise UsageError(msg)
801 801 # if we find a good linenumber, set the breakpoint
802 802 deb.do_break('%s:%s' % (bp_file, bp_line))
803 803
804 804 if filename:
805 805 # Mimic Pdb._runscript(...)
806 806 deb._wait_for_mainpyfile = True
807 807 deb.mainpyfile = deb.canonic(filename)
808 808
809 809 # Start file run
810 810 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
811 811 try:
812 812 if filename:
813 813 # save filename so it can be used by methods on the deb object
814 814 deb._exec_filename = filename
815 815 while True:
816 816 try:
817 817 deb.run(code, code_ns)
818 818 except Restart:
819 819 print("Restarting")
820 820 if filename:
821 821 deb._wait_for_mainpyfile = True
822 822 deb.mainpyfile = deb.canonic(filename)
823 823 continue
824 824 else:
825 825 break
826 826
827 827
828 828 except:
829 829 etype, value, tb = sys.exc_info()
830 830 # Skip three frames in the traceback: the %run one,
831 831 # one inside bdb.py, and the command-line typed by the
832 832 # user (run by exec in pdb itself).
833 833 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
834 834
835 835 @staticmethod
836 836 def _run_with_timing(run, nruns):
837 837 """
838 838 Run function `run` and print timing information.
839 839
840 840 Parameters
841 841 ----------
842 842 run : callable
843 843 Any callable object which takes no argument.
844 844 nruns : int
845 845 Number of times to execute `run`.
846 846
847 847 """
848 848 twall0 = time.time()
849 849 if nruns == 1:
850 850 t0 = clock2()
851 851 run()
852 852 t1 = clock2()
853 853 t_usr = t1[0] - t0[0]
854 854 t_sys = t1[1] - t0[1]
855 855 print("\nIPython CPU timings (estimated):")
856 856 print(" User : %10.2f s." % t_usr)
857 857 print(" System : %10.2f s." % t_sys)
858 858 else:
859 859 runs = range(nruns)
860 860 t0 = clock2()
861 861 for nr in runs:
862 862 run()
863 863 t1 = clock2()
864 864 t_usr = t1[0] - t0[0]
865 865 t_sys = t1[1] - t0[1]
866 866 print("\nIPython CPU timings (estimated):")
867 867 print("Total runs performed:", nruns)
868 868 print(" Times : %10s %10s" % ('Total', 'Per run'))
869 869 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
870 870 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
871 871 twall1 = time.time()
872 872 print("Wall time: %10.2f s." % (twall1 - twall0))
873 873
874 874 @skip_doctest
875 875 @line_cell_magic
876 876 def timeit(self, line='', cell=None):
877 877 """Time execution of a Python statement or expression
878 878
879 879 Usage, in line mode:
880 880 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
881 881 or in cell mode:
882 882 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
883 883 code
884 884 code...
885 885
886 886 Time execution of a Python statement or expression using the timeit
887 887 module. This function can be used both as a line and cell magic:
888 888
889 889 - In line mode you can time a single-line statement (though multiple
890 890 ones can be chained with using semicolons).
891 891
892 892 - In cell mode, the statement in the first line is used as setup code
893 893 (executed but not timed) and the body of the cell is timed. The cell
894 894 body has access to any variables created in the setup code.
895 895
896 896 Options:
897 897 -n<N>: execute the given statement <N> times in a loop. If this value
898 898 is not given, a fitting value is chosen.
899 899
900 900 -r<R>: repeat the loop iteration <R> times and take the best result.
901 901 Default: 3
902 902
903 903 -t: use time.time to measure the time, which is the default on Unix.
904 904 This function measures wall time.
905 905
906 906 -c: use time.clock to measure the time, which is the default on
907 907 Windows and measures wall time. On Unix, resource.getrusage is used
908 908 instead and returns the CPU user time.
909 909
910 910 -p<P>: use a precision of <P> digits to display the timing result.
911 911 Default: 3
912 912
913 913 -q: Quiet, do not print result.
914 914
915 915 -o: return a TimeitResult that can be stored in a variable to inspect
916 916 the result in more details.
917 917
918 918
919 919 Examples
920 920 --------
921 921 ::
922 922
923 923 In [1]: %timeit pass
924 924 10000000 loops, best of 3: 53.3 ns per loop
925 925
926 926 In [2]: u = None
927 927
928 928 In [3]: %timeit u is None
929 929 10000000 loops, best of 3: 184 ns per loop
930 930
931 931 In [4]: %timeit -r 4 u == None
932 932 1000000 loops, best of 4: 242 ns per loop
933 933
934 934 In [5]: import time
935 935
936 936 In [6]: %timeit -n1 time.sleep(2)
937 937 1 loops, best of 3: 2 s per loop
938 938
939 939
940 940 The times reported by %timeit will be slightly higher than those
941 941 reported by the timeit.py script when variables are accessed. This is
942 942 due to the fact that %timeit executes the statement in the namespace
943 943 of the shell, compared with timeit.py, which uses a single setup
944 944 statement to import function or create variables. Generally, the bias
945 945 does not matter as long as results from timeit.py are not mixed with
946 946 those from %timeit."""
947 947
948 948 import timeit
949 949
950 950 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
951 951 posix=False, strict=False)
952 952 if stmt == "" and cell is None:
953 953 return
954 954
955 955 timefunc = timeit.default_timer
956 956 number = int(getattr(opts, "n", 0))
957 957 repeat = int(getattr(opts, "r", timeit.default_repeat))
958 958 precision = int(getattr(opts, "p", 3))
959 959 quiet = 'q' in opts
960 960 return_result = 'o' in opts
961 961 if hasattr(opts, "t"):
962 962 timefunc = time.time
963 963 if hasattr(opts, "c"):
964 964 timefunc = clock
965 965
966 966 timer = timeit.Timer(timer=timefunc)
967 967 # this code has tight coupling to the inner workings of timeit.Timer,
968 968 # but is there a better way to achieve that the code stmt has access
969 969 # to the shell namespace?
970 970 transform = self.shell.input_splitter.transform_cell
971 971
972 972 if cell is None:
973 973 # called as line magic
974 ast_setup = ast.parse("pass")
975 ast_stmt = ast.parse(transform(stmt))
974 ast_setup = self.shell.compile.ast_parse("pass")
975 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
976 976 else:
977 ast_setup = ast.parse(transform(stmt))
978 ast_stmt = ast.parse(transform(cell))
977 ast_setup = self.shell.compile.ast_parse(transform(stmt))
978 ast_stmt = self.shell.compile.ast_parse(transform(cell))
979 979
980 980 ast_setup = self.shell.transform_ast(ast_setup)
981 981 ast_stmt = self.shell.transform_ast(ast_stmt)
982 982
983 983 # This codestring is taken from timeit.template - we fill it in as an
984 984 # AST, so that we can apply our AST transformations to the user code
985 985 # without affecting the timing code.
986 986 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
987 987 ' setup\n'
988 988 ' _t0 = _timer()\n'
989 989 ' for _i in _it:\n'
990 990 ' stmt\n'
991 991 ' _t1 = _timer()\n'
992 992 ' return _t1 - _t0\n')
993 993
994 994 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
995 995 timeit_ast = ast.fix_missing_locations(timeit_ast)
996 996
997 997 # Track compilation time so it can be reported if too long
998 998 # Minimum time above which compilation time will be reported
999 999 tc_min = 0.1
1000 1000
1001 1001 t0 = clock()
1002 code = compile(timeit_ast, "<magic-timeit>", "exec")
1002 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1003 1003 tc = clock()-t0
1004 1004
1005 1005 ns = {}
1006 1006 exec(code, self.shell.user_ns, ns)
1007 1007 timer.inner = ns["inner"]
1008 1008
1009 1009 if number == 0:
1010 1010 # determine number so that 0.2 <= total time < 2.0
1011 1011 number = 1
1012 1012 for _ in range(1, 10):
1013 1013 if timer.timeit(number) >= 0.2:
1014 1014 break
1015 1015 number *= 10
1016 1016 all_runs = timer.repeat(repeat, number)
1017 1017 best = min(all_runs) / number
1018 1018 if not quiet :
1019 1019 print(u"%d loops, best of %d: %s per loop" % (number, repeat,
1020 1020 _format_time(best, precision)))
1021 1021 if tc > tc_min:
1022 1022 print("Compiler time: %.2f s" % tc)
1023 1023 if return_result:
1024 1024 return TimeitResult(number, repeat, best, all_runs, tc, precision)
1025 1025
1026 1026 @skip_doctest
1027 1027 @needs_local_scope
1028 1028 @line_cell_magic
1029 1029 def time(self,line='', cell=None, local_ns=None):
1030 1030 """Time execution of a Python statement or expression.
1031 1031
1032 1032 The CPU and wall clock times are printed, and the value of the
1033 1033 expression (if any) is returned. Note that under Win32, system time
1034 1034 is always reported as 0, since it can not be measured.
1035 1035
1036 1036 This function can be used both as a line and cell magic:
1037 1037
1038 1038 - In line mode you can time a single-line statement (though multiple
1039 1039 ones can be chained with using semicolons).
1040 1040
1041 1041 - In cell mode, you can time the cell body (a directly
1042 1042 following statement raises an error).
1043 1043
1044 1044 This function provides very basic timing functionality. Use the timeit
1045 1045 magic for more controll over the measurement.
1046 1046
1047 1047 Examples
1048 1048 --------
1049 1049 ::
1050 1050
1051 1051 In [1]: %time 2**128
1052 1052 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1053 1053 Wall time: 0.00
1054 1054 Out[1]: 340282366920938463463374607431768211456L
1055 1055
1056 1056 In [2]: n = 1000000
1057 1057
1058 1058 In [3]: %time sum(range(n))
1059 1059 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1060 1060 Wall time: 1.37
1061 1061 Out[3]: 499999500000L
1062 1062
1063 1063 In [4]: %time print 'hello world'
1064 1064 hello world
1065 1065 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1066 1066 Wall time: 0.00
1067 1067
1068 1068 Note that the time needed by Python to compile the given expression
1069 1069 will be reported if it is more than 0.1s. In this example, the
1070 1070 actual exponentiation is done by Python at compilation time, so while
1071 1071 the expression can take a noticeable amount of time to compute, that
1072 1072 time is purely due to the compilation:
1073 1073
1074 1074 In [5]: %time 3**9999;
1075 1075 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1076 1076 Wall time: 0.00 s
1077 1077
1078 1078 In [6]: %time 3**999999;
1079 1079 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1080 1080 Wall time: 0.00 s
1081 1081 Compiler : 0.78 s
1082 1082 """
1083 1083
1084 1084 # fail immediately if the given expression can't be compiled
1085 1085
1086 1086 if line and cell:
1087 1087 raise UsageError("Can't use statement directly after '%%time'!")
1088 1088
1089 1089 if cell:
1090 1090 expr = self.shell.input_transformer_manager.transform_cell(cell)
1091 1091 else:
1092 1092 expr = self.shell.input_transformer_manager.transform_cell(line)
1093 1093
1094 1094 # Minimum time above which parse time will be reported
1095 1095 tp_min = 0.1
1096 1096
1097 1097 t0 = clock()
1098 expr_ast = ast.parse(expr)
1098 expr_ast = self.shell.compile.ast_parse(expr)
1099 1099 tp = clock()-t0
1100 1100
1101 1101 # Apply AST transformations
1102 1102 expr_ast = self.shell.transform_ast(expr_ast)
1103 1103
1104 1104 # Minimum time above which compilation time will be reported
1105 1105 tc_min = 0.1
1106 1106
1107 1107 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1108 1108 mode = 'eval'
1109 1109 source = '<timed eval>'
1110 1110 expr_ast = ast.Expression(expr_ast.body[0].value)
1111 1111 else:
1112 1112 mode = 'exec'
1113 1113 source = '<timed exec>'
1114 1114 t0 = clock()
1115 code = compile(expr_ast, source, mode)
1115 code = self.shell.compile(expr_ast, source, mode)
1116 1116 tc = clock()-t0
1117 1117
1118 1118 # skew measurement as little as possible
1119 1119 glob = self.shell.user_ns
1120 1120 wtime = time.time
1121 1121 # time execution
1122 1122 wall_st = wtime()
1123 1123 if mode=='eval':
1124 1124 st = clock2()
1125 1125 out = eval(code, glob, local_ns)
1126 1126 end = clock2()
1127 1127 else:
1128 1128 st = clock2()
1129 1129 exec(code, glob, local_ns)
1130 1130 end = clock2()
1131 1131 out = None
1132 1132 wall_end = wtime()
1133 1133 # Compute actual times and report
1134 1134 wall_time = wall_end-wall_st
1135 1135 cpu_user = end[0]-st[0]
1136 1136 cpu_sys = end[1]-st[1]
1137 1137 cpu_tot = cpu_user+cpu_sys
1138 1138 # On windows cpu_sys is always zero, so no new information to the next print
1139 1139 if sys.platform != 'win32':
1140 1140 print("CPU times: user %s, sys: %s, total: %s" % \
1141 1141 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1142 1142 print("Wall time: %s" % _format_time(wall_time))
1143 1143 if tc > tc_min:
1144 1144 print("Compiler : %s" % _format_time(tc))
1145 1145 if tp > tp_min:
1146 1146 print("Parser : %s" % _format_time(tp))
1147 1147 return out
1148 1148
1149 1149 @skip_doctest
1150 1150 @line_magic
1151 1151 def macro(self, parameter_s=''):
1152 1152 """Define a macro for future re-execution. It accepts ranges of history,
1153 1153 filenames or string objects.
1154 1154
1155 1155 Usage:\\
1156 1156 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1157 1157
1158 1158 Options:
1159 1159
1160 1160 -r: use 'raw' input. By default, the 'processed' history is used,
1161 1161 so that magics are loaded in their transformed version to valid
1162 1162 Python. If this option is given, the raw input as typed at the
1163 1163 command line is used instead.
1164 1164
1165 1165 -q: quiet macro definition. By default, a tag line is printed
1166 1166 to indicate the macro has been created, and then the contents of
1167 1167 the macro are printed. If this option is given, then no printout
1168 1168 is produced once the macro is created.
1169 1169
1170 1170 This will define a global variable called `name` which is a string
1171 1171 made of joining the slices and lines you specify (n1,n2,... numbers
1172 1172 above) from your input history into a single string. This variable
1173 1173 acts like an automatic function which re-executes those lines as if
1174 1174 you had typed them. You just type 'name' at the prompt and the code
1175 1175 executes.
1176 1176
1177 1177 The syntax for indicating input ranges is described in %history.
1178 1178
1179 1179 Note: as a 'hidden' feature, you can also use traditional python slice
1180 1180 notation, where N:M means numbers N through M-1.
1181 1181
1182 1182 For example, if your history contains (print using %hist -n )::
1183 1183
1184 1184 44: x=1
1185 1185 45: y=3
1186 1186 46: z=x+y
1187 1187 47: print x
1188 1188 48: a=5
1189 1189 49: print 'x',x,'y',y
1190 1190
1191 1191 you can create a macro with lines 44 through 47 (included) and line 49
1192 1192 called my_macro with::
1193 1193
1194 1194 In [55]: %macro my_macro 44-47 49
1195 1195
1196 1196 Now, typing `my_macro` (without quotes) will re-execute all this code
1197 1197 in one pass.
1198 1198
1199 1199 You don't need to give the line-numbers in order, and any given line
1200 1200 number can appear multiple times. You can assemble macros with any
1201 1201 lines from your input history in any order.
1202 1202
1203 1203 The macro is a simple object which holds its value in an attribute,
1204 1204 but IPython's display system checks for macros and executes them as
1205 1205 code instead of printing them when you type their name.
1206 1206
1207 1207 You can view a macro's contents by explicitly printing it with::
1208 1208
1209 1209 print macro_name
1210 1210
1211 1211 """
1212 1212 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1213 1213 if not args: # List existing macros
1214 1214 return sorted(k for k,v in iteritems(self.shell.user_ns) if\
1215 1215 isinstance(v, Macro))
1216 1216 if len(args) == 1:
1217 1217 raise UsageError(
1218 1218 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1219 1219 name, codefrom = args[0], " ".join(args[1:])
1220 1220
1221 1221 #print 'rng',ranges # dbg
1222 1222 try:
1223 1223 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1224 1224 except (ValueError, TypeError) as e:
1225 1225 print(e.args[0])
1226 1226 return
1227 1227 macro = Macro(lines)
1228 1228 self.shell.define_macro(name, macro)
1229 1229 if not ( 'q' in opts) :
1230 1230 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1231 1231 print('=== Macro contents: ===')
1232 1232 print(macro, end=' ')
1233 1233
1234 1234 @magic_arguments.magic_arguments()
1235 1235 @magic_arguments.argument('output', type=str, default='', nargs='?',
1236 1236 help="""The name of the variable in which to store output.
1237 1237 This is a utils.io.CapturedIO object with stdout/err attributes
1238 1238 for the text of the captured output.
1239 1239
1240 1240 CapturedOutput also has a show() method for displaying the output,
1241 1241 and __call__ as well, so you can use that to quickly display the
1242 1242 output.
1243 1243
1244 1244 If unspecified, captured output is discarded.
1245 1245 """
1246 1246 )
1247 1247 @magic_arguments.argument('--no-stderr', action="store_true",
1248 1248 help="""Don't capture stderr."""
1249 1249 )
1250 1250 @magic_arguments.argument('--no-stdout', action="store_true",
1251 1251 help="""Don't capture stdout."""
1252 1252 )
1253 1253 @magic_arguments.argument('--no-display', action="store_true",
1254 1254 help="""Don't capture IPython's rich display."""
1255 1255 )
1256 1256 @cell_magic
1257 1257 def capture(self, line, cell):
1258 1258 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1259 1259 args = magic_arguments.parse_argstring(self.capture, line)
1260 1260 out = not args.no_stdout
1261 1261 err = not args.no_stderr
1262 1262 disp = not args.no_display
1263 1263 with capture_output(out, err, disp) as io:
1264 1264 self.shell.run_cell(cell)
1265 1265 if args.output:
1266 1266 self.shell.user_ns[args.output] = io
1267 1267
1268 1268 def parse_breakpoint(text, current_file):
1269 1269 '''Returns (file, line) for file:line and (current_file, line) for line'''
1270 1270 colon = text.find(':')
1271 1271 if colon == -1:
1272 1272 return current_file, int(text)
1273 1273 else:
1274 1274 return text[:colon], int(text[colon+1:])
1275 1275
1276 1276 def _format_time(timespan, precision=3):
1277 1277 """Formats the timespan in a human readable form"""
1278 1278 import math
1279 1279
1280 1280 if timespan >= 60.0:
1281 1281 # we have more than a minute, format that in a human readable form
1282 1282 # Idea from http://snipplr.com/view/5713/
1283 1283 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1284 1284 time = []
1285 1285 leftover = timespan
1286 1286 for suffix, length in parts:
1287 1287 value = int(leftover / length)
1288 1288 if value > 0:
1289 1289 leftover = leftover % length
1290 1290 time.append(u'%s%s' % (str(value), suffix))
1291 1291 if leftover < 1:
1292 1292 break
1293 1293 return " ".join(time)
1294 1294
1295 1295
1296 1296 # Unfortunately the unicode 'micro' symbol can cause problems in
1297 1297 # certain terminals.
1298 1298 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1299 1299 # Try to prevent crashes by being more secure than it needs to
1300 1300 # E.g. eclipse is able to print a Β΅, but has no sys.stdout.encoding set.
1301 1301 units = [u"s", u"ms",u'us',"ns"] # the save value
1302 1302 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1303 1303 try:
1304 1304 u'\xb5'.encode(sys.stdout.encoding)
1305 1305 units = [u"s", u"ms",u'\xb5s',"ns"]
1306 1306 except:
1307 1307 pass
1308 1308 scaling = [1, 1e3, 1e6, 1e9]
1309 1309
1310 1310 if timespan > 0.0:
1311 1311 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1312 1312 else:
1313 1313 order = 3
1314 1314 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
@@ -1,990 +1,991 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Tests for various magic functions.
3 3
4 4 Needs to be run by nose (to make ipython session available).
5 5 """
6 6 from __future__ import absolute_import
7 7
8 8 #-----------------------------------------------------------------------------
9 9 # Imports
10 10 #-----------------------------------------------------------------------------
11 11
12 12 import io
13 13 import os
14 14 import sys
15 15 from unittest import TestCase, skipIf
16 16
17 17 try:
18 18 from importlib import invalidate_caches # Required from Python 3.3
19 19 except ImportError:
20 20 def invalidate_caches():
21 21 pass
22 22
23 23 import nose.tools as nt
24 24
25 25 from IPython.core import magic
26 26 from IPython.core.magic import (Magics, magics_class, line_magic,
27 27 cell_magic, line_cell_magic,
28 28 register_line_magic, register_cell_magic,
29 29 register_line_cell_magic)
30 30 from IPython.core.magics import execution, script, code
31 31 from IPython.testing import decorators as dec
32 32 from IPython.testing import tools as tt
33 33 from IPython.utils import py3compat
34 34 from IPython.utils.io import capture_output
35 35 from IPython.utils.tempdir import TemporaryDirectory
36 36 from IPython.utils.process import find_cmd
37 37
38 38 if py3compat.PY3:
39 39 from io import StringIO
40 40 else:
41 41 from StringIO import StringIO
42 42
43 43 #-----------------------------------------------------------------------------
44 44 # Test functions begin
45 45 #-----------------------------------------------------------------------------
46 46
47 47 @magic.magics_class
48 48 class DummyMagics(magic.Magics): pass
49 49
50 50 def test_extract_code_ranges():
51 51 instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :"
52 52 expected = [(0, 1),
53 53 (2, 3),
54 54 (4, 6),
55 55 (6, 9),
56 56 (9, 14),
57 57 (16, None),
58 58 (None, 9),
59 59 (9, None),
60 60 (None, 13),
61 61 (None, None)]
62 62 actual = list(code.extract_code_ranges(instr))
63 63 nt.assert_equal(actual, expected)
64 64
65 65 def test_extract_symbols():
66 66 source = """import foo\na = 10\ndef b():\n return 42\n\n\nclass A: pass\n\n\n"""
67 67 symbols_args = ["a", "b", "A", "A,b", "A,a", "z"]
68 68 expected = [([], ['a']),
69 69 (["def b():\n return 42\n"], []),
70 70 (["class A: pass\n"], []),
71 71 (["class A: pass\n", "def b():\n return 42\n"], []),
72 72 (["class A: pass\n"], ['a']),
73 73 ([], ['z'])]
74 74 for symbols, exp in zip(symbols_args, expected):
75 75 nt.assert_equal(code.extract_symbols(source, symbols), exp)
76 76
77 77
78 78 def test_extract_symbols_raises_exception_with_non_python_code():
79 79 source = ("=begin A Ruby program :)=end\n"
80 80 "def hello\n"
81 81 "puts 'Hello world'\n"
82 82 "end")
83 83 with nt.assert_raises(SyntaxError):
84 84 code.extract_symbols(source, "hello")
85 85
86 86 def test_config():
87 87 """ test that config magic does not raise
88 88 can happen if Configurable init is moved too early into
89 89 Magics.__init__ as then a Config object will be registerd as a
90 90 magic.
91 91 """
92 92 ## should not raise.
93 93 _ip.magic('config')
94 94
95 95 def test_rehashx():
96 96 # clear up everything
97 97 _ip = get_ipython()
98 98 _ip.alias_manager.clear_aliases()
99 99 del _ip.db['syscmdlist']
100 100
101 101 _ip.magic('rehashx')
102 102 # Practically ALL ipython development systems will have more than 10 aliases
103 103
104 104 nt.assert_true(len(_ip.alias_manager.aliases) > 10)
105 105 for name, cmd in _ip.alias_manager.aliases:
106 106 # we must strip dots from alias names
107 107 nt.assert_not_in('.', name)
108 108
109 109 # rehashx must fill up syscmdlist
110 110 scoms = _ip.db['syscmdlist']
111 111 nt.assert_true(len(scoms) > 10)
112 112
113 113
114 114 def test_magic_parse_options():
115 115 """Test that we don't mangle paths when parsing magic options."""
116 116 ip = get_ipython()
117 117 path = 'c:\\x'
118 118 m = DummyMagics(ip)
119 119 opts = m.parse_options('-f %s' % path,'f:')[0]
120 120 # argv splitting is os-dependent
121 121 if os.name == 'posix':
122 122 expected = 'c:x'
123 123 else:
124 124 expected = path
125 125 nt.assert_equal(opts['f'], expected)
126 126
127 127 def test_magic_parse_long_options():
128 128 """Magic.parse_options can handle --foo=bar long options"""
129 129 ip = get_ipython()
130 130 m = DummyMagics(ip)
131 131 opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
132 132 nt.assert_in('foo', opts)
133 133 nt.assert_in('bar', opts)
134 134 nt.assert_equal(opts['bar'], "bubble")
135 135
136 136
137 137 @dec.skip_without('sqlite3')
138 138 def doctest_hist_f():
139 139 """Test %hist -f with temporary filename.
140 140
141 141 In [9]: import tempfile
142 142
143 143 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
144 144
145 145 In [11]: %hist -nl -f $tfile 3
146 146
147 147 In [13]: import os; os.unlink(tfile)
148 148 """
149 149
150 150
151 151 @dec.skip_without('sqlite3')
152 152 def doctest_hist_r():
153 153 """Test %hist -r
154 154
155 155 XXX - This test is not recording the output correctly. For some reason, in
156 156 testing mode the raw history isn't getting populated. No idea why.
157 157 Disabling the output checking for now, though at least we do run it.
158 158
159 159 In [1]: 'hist' in _ip.lsmagic()
160 160 Out[1]: True
161 161
162 162 In [2]: x=1
163 163
164 164 In [3]: %hist -rl 2
165 165 x=1 # random
166 166 %hist -r 2
167 167 """
168 168
169 169
170 170 @dec.skip_without('sqlite3')
171 171 def doctest_hist_op():
172 172 """Test %hist -op
173 173
174 174 In [1]: class b(float):
175 175 ...: pass
176 176 ...:
177 177
178 178 In [2]: class s(object):
179 179 ...: def __str__(self):
180 180 ...: return 's'
181 181 ...:
182 182
183 183 In [3]:
184 184
185 185 In [4]: class r(b):
186 186 ...: def __repr__(self):
187 187 ...: return 'r'
188 188 ...:
189 189
190 190 In [5]: class sr(s,r): pass
191 191 ...:
192 192
193 193 In [6]:
194 194
195 195 In [7]: bb=b()
196 196
197 197 In [8]: ss=s()
198 198
199 199 In [9]: rr=r()
200 200
201 201 In [10]: ssrr=sr()
202 202
203 203 In [11]: 4.5
204 204 Out[11]: 4.5
205 205
206 206 In [12]: str(ss)
207 207 Out[12]: 's'
208 208
209 209 In [13]:
210 210
211 211 In [14]: %hist -op
212 212 >>> class b:
213 213 ... pass
214 214 ...
215 215 >>> class s(b):
216 216 ... def __str__(self):
217 217 ... return 's'
218 218 ...
219 219 >>>
220 220 >>> class r(b):
221 221 ... def __repr__(self):
222 222 ... return 'r'
223 223 ...
224 224 >>> class sr(s,r): pass
225 225 >>>
226 226 >>> bb=b()
227 227 >>> ss=s()
228 228 >>> rr=r()
229 229 >>> ssrr=sr()
230 230 >>> 4.5
231 231 4.5
232 232 >>> str(ss)
233 233 's'
234 234 >>>
235 235 """
236 236
237 237 def test_hist_pof():
238 238 ip = get_ipython()
239 239 ip.run_cell(u"1+2", store_history=True)
240 240 #raise Exception(ip.history_manager.session_number)
241 241 #raise Exception(list(ip.history_manager._get_range_session()))
242 242 with TemporaryDirectory() as td:
243 243 tf = os.path.join(td, 'hist.py')
244 244 ip.run_line_magic('history', '-pof %s' % tf)
245 245 assert os.path.isfile(tf)
246 246
247 247
248 248 @dec.skip_without('sqlite3')
249 249 def test_macro():
250 250 ip = get_ipython()
251 251 ip.history_manager.reset() # Clear any existing history.
252 252 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
253 253 for i, cmd in enumerate(cmds, start=1):
254 254 ip.history_manager.store_inputs(i, cmd)
255 255 ip.magic("macro test 1-3")
256 256 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
257 257
258 258 # List macros
259 259 nt.assert_in("test", ip.magic("macro"))
260 260
261 261
262 262 @dec.skip_without('sqlite3')
263 263 def test_macro_run():
264 264 """Test that we can run a multi-line macro successfully."""
265 265 ip = get_ipython()
266 266 ip.history_manager.reset()
267 267 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
268 268 "%macro test 2-3"]
269 269 for cmd in cmds:
270 270 ip.run_cell(cmd, store_history=True)
271 271 nt.assert_equal(ip.user_ns["test"].value,
272 272 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
273 273 with tt.AssertPrints("12"):
274 274 ip.run_cell("test")
275 275 with tt.AssertPrints("13"):
276 276 ip.run_cell("test")
277 277
278 278
279 279 def test_magic_magic():
280 280 """Test %magic"""
281 281 ip = get_ipython()
282 282 with capture_output() as captured:
283 283 ip.magic("magic")
284 284
285 285 stdout = captured.stdout
286 286 nt.assert_in('%magic', stdout)
287 287 nt.assert_in('IPython', stdout)
288 288 nt.assert_in('Available', stdout)
289 289
290 290
291 291 @dec.skipif_not_numpy
292 292 def test_numpy_reset_array_undec():
293 293 "Test '%reset array' functionality"
294 294 _ip.ex('import numpy as np')
295 295 _ip.ex('a = np.empty(2)')
296 296 nt.assert_in('a', _ip.user_ns)
297 297 _ip.magic('reset -f array')
298 298 nt.assert_not_in('a', _ip.user_ns)
299 299
300 300 def test_reset_out():
301 301 "Test '%reset out' magic"
302 302 _ip.run_cell("parrot = 'dead'", store_history=True)
303 303 # test '%reset -f out', make an Out prompt
304 304 _ip.run_cell("parrot", store_history=True)
305 305 nt.assert_true('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
306 306 _ip.magic('reset -f out')
307 307 nt.assert_false('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
308 308 nt.assert_equal(len(_ip.user_ns['Out']), 0)
309 309
310 310 def test_reset_in():
311 311 "Test '%reset in' magic"
312 312 # test '%reset -f in'
313 313 _ip.run_cell("parrot", store_history=True)
314 314 nt.assert_true('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
315 315 _ip.magic('%reset -f in')
316 316 nt.assert_false('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
317 317 nt.assert_equal(len(set(_ip.user_ns['In'])), 1)
318 318
319 319 def test_reset_dhist():
320 320 "Test '%reset dhist' magic"
321 321 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
322 322 _ip.magic('cd ' + os.path.dirname(nt.__file__))
323 323 _ip.magic('cd -')
324 324 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
325 325 _ip.magic('reset -f dhist')
326 326 nt.assert_equal(len(_ip.user_ns['_dh']), 0)
327 327 _ip.run_cell("_dh = [d for d in tmp]") #restore
328 328
329 329 def test_reset_in_length():
330 330 "Test that '%reset in' preserves In[] length"
331 331 _ip.run_cell("print 'foo'")
332 332 _ip.run_cell("reset -f in")
333 333 nt.assert_equal(len(_ip.user_ns['In']), _ip.displayhook.prompt_count+1)
334 334
335 335 def test_tb_syntaxerror():
336 336 """test %tb after a SyntaxError"""
337 337 ip = get_ipython()
338 338 ip.run_cell("for")
339 339
340 340 # trap and validate stdout
341 341 save_stdout = sys.stdout
342 342 try:
343 343 sys.stdout = StringIO()
344 344 ip.run_cell("%tb")
345 345 out = sys.stdout.getvalue()
346 346 finally:
347 347 sys.stdout = save_stdout
348 348 # trim output, and only check the last line
349 349 last_line = out.rstrip().splitlines()[-1].strip()
350 350 nt.assert_equal(last_line, "SyntaxError: invalid syntax")
351 351
352 352
353 353 def test_time():
354 354 ip = get_ipython()
355 355
356 356 with tt.AssertPrints("Wall time: "):
357 357 ip.run_cell("%time None")
358 358
359 359 ip.run_cell("def f(kmjy):\n"
360 360 " %time print (2*kmjy)")
361 361
362 362 with tt.AssertPrints("Wall time: "):
363 363 with tt.AssertPrints("hihi", suppress=False):
364 364 ip.run_cell("f('hi')")
365 365
366 366
367 367 @dec.skip_win32
368 368 def test_time2():
369 369 ip = get_ipython()
370 370
371 371 with tt.AssertPrints("CPU times: user "):
372 372 ip.run_cell("%time None")
373 373
374 374 def test_time3():
375 375 """Erroneous magic function calls, issue gh-3334"""
376 376 ip = get_ipython()
377 377 ip.user_ns.pop('run', None)
378 378
379 379 with tt.AssertNotPrints("not found", channel='stderr'):
380 380 ip.run_cell("%%time\n"
381 381 "run = 0\n"
382 382 "run += 1")
383 383
384 384 @dec.skipif(sys.version_info[0] >= 3, "no differences with __future__ in py3")
385 385 def test_time_futures():
386 386 "Test %time with __future__ environments"
387 387 ip = get_ipython()
388 ip.autocall = 0
388 389 ip.run_cell("from __future__ import division")
389 390 with tt.AssertPrints('0.25'):
390 391 ip.run_line_magic('time', 'print(1/4)')
391 392 ip.compile.reset_compiler_flags()
392 393 with tt.AssertNotPrints('0.25'):
393 394 ip.run_line_magic('time', 'print(1/4)')
394 395
395 396 def test_doctest_mode():
396 397 "Toggle doctest_mode twice, it should be a no-op and run without error"
397 398 _ip.magic('doctest_mode')
398 399 _ip.magic('doctest_mode')
399 400
400 401
401 402 def test_parse_options():
402 403 """Tests for basic options parsing in magics."""
403 404 # These are only the most minimal of tests, more should be added later. At
404 405 # the very least we check that basic text/unicode calls work OK.
405 406 m = DummyMagics(_ip)
406 407 nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
407 408 nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
408 409
409 410
410 411 def test_dirops():
411 412 """Test various directory handling operations."""
412 413 # curpath = lambda :os.path.splitdrive(py3compat.getcwd())[1].replace('\\','/')
413 414 curpath = py3compat.getcwd
414 415 startdir = py3compat.getcwd()
415 416 ipdir = os.path.realpath(_ip.ipython_dir)
416 417 try:
417 418 _ip.magic('cd "%s"' % ipdir)
418 419 nt.assert_equal(curpath(), ipdir)
419 420 _ip.magic('cd -')
420 421 nt.assert_equal(curpath(), startdir)
421 422 _ip.magic('pushd "%s"' % ipdir)
422 423 nt.assert_equal(curpath(), ipdir)
423 424 _ip.magic('popd')
424 425 nt.assert_equal(curpath(), startdir)
425 426 finally:
426 427 os.chdir(startdir)
427 428
428 429
429 430 def test_xmode():
430 431 # Calling xmode three times should be a no-op
431 432 xmode = _ip.InteractiveTB.mode
432 433 for i in range(3):
433 434 _ip.magic("xmode")
434 435 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
435 436
436 437 def test_reset_hard():
437 438 monitor = []
438 439 class A(object):
439 440 def __del__(self):
440 441 monitor.append(1)
441 442 def __repr__(self):
442 443 return "<A instance>"
443 444
444 445 _ip.user_ns["a"] = A()
445 446 _ip.run_cell("a")
446 447
447 448 nt.assert_equal(monitor, [])
448 449 _ip.magic("reset -f")
449 450 nt.assert_equal(monitor, [1])
450 451
451 452 class TestXdel(tt.TempFileMixin):
452 453 def test_xdel(self):
453 454 """Test that references from %run are cleared by xdel."""
454 455 src = ("class A(object):\n"
455 456 " monitor = []\n"
456 457 " def __del__(self):\n"
457 458 " self.monitor.append(1)\n"
458 459 "a = A()\n")
459 460 self.mktmp(src)
460 461 # %run creates some hidden references...
461 462 _ip.magic("run %s" % self.fname)
462 463 # ... as does the displayhook.
463 464 _ip.run_cell("a")
464 465
465 466 monitor = _ip.user_ns["A"].monitor
466 467 nt.assert_equal(monitor, [])
467 468
468 469 _ip.magic("xdel a")
469 470
470 471 # Check that a's __del__ method has been called.
471 472 nt.assert_equal(monitor, [1])
472 473
473 474 def doctest_who():
474 475 """doctest for %who
475 476
476 477 In [1]: %reset -f
477 478
478 479 In [2]: alpha = 123
479 480
480 481 In [3]: beta = 'beta'
481 482
482 483 In [4]: %who int
483 484 alpha
484 485
485 486 In [5]: %who str
486 487 beta
487 488
488 489 In [6]: %whos
489 490 Variable Type Data/Info
490 491 ----------------------------
491 492 alpha int 123
492 493 beta str beta
493 494
494 495 In [7]: %who_ls
495 496 Out[7]: ['alpha', 'beta']
496 497 """
497 498
498 499 def test_whos():
499 500 """Check that whos is protected against objects where repr() fails."""
500 501 class A(object):
501 502 def __repr__(self):
502 503 raise Exception()
503 504 _ip.user_ns['a'] = A()
504 505 _ip.magic("whos")
505 506
506 507 @py3compat.u_format
507 508 def doctest_precision():
508 509 """doctest for %precision
509 510
510 511 In [1]: f = get_ipython().display_formatter.formatters['text/plain']
511 512
512 513 In [2]: %precision 5
513 514 Out[2]: {u}'%.5f'
514 515
515 516 In [3]: f.float_format
516 517 Out[3]: {u}'%.5f'
517 518
518 519 In [4]: %precision %e
519 520 Out[4]: {u}'%e'
520 521
521 522 In [5]: f(3.1415927)
522 523 Out[5]: {u}'3.141593e+00'
523 524 """
524 525
525 526 def test_psearch():
526 527 with tt.AssertPrints("dict.fromkeys"):
527 528 _ip.run_cell("dict.fr*?")
528 529
529 530 def test_timeit_shlex():
530 531 """test shlex issues with timeit (#1109)"""
531 532 _ip.ex("def f(*a,**kw): pass")
532 533 _ip.magic('timeit -n1 "this is a bug".count(" ")')
533 534 _ip.magic('timeit -r1 -n1 f(" ", 1)')
534 535 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
535 536 _ip.magic('timeit -r1 -n1 ("a " + "b")')
536 537 _ip.magic('timeit -r1 -n1 f("a " + "b")')
537 538 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
538 539
539 540
540 541 def test_timeit_arguments():
541 542 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
542 543 _ip.magic("timeit ('#')")
543 544
544 545
545 546 def test_timeit_special_syntax():
546 547 "Test %%timeit with IPython special syntax"
547 548 @register_line_magic
548 549 def lmagic(line):
549 550 ip = get_ipython()
550 551 ip.user_ns['lmagic_out'] = line
551 552
552 553 # line mode test
553 554 _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line')
554 555 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
555 556 # cell mode test
556 557 _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2')
557 558 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
558 559
559 560 def test_timeit_return():
560 561 """
561 562 test wether timeit -o return object
562 563 """
563 564
564 565 res = _ip.run_line_magic('timeit','-n10 -r10 -o 1')
565 566 assert(res is not None)
566 567
567 568 def test_timeit_quiet():
568 569 """
569 570 test quiet option of timeit magic
570 571 """
571 572 with tt.AssertNotPrints("loops"):
572 573 _ip.run_cell("%timeit -n1 -r1 -q 1")
573 574
574 575 @dec.skipif(sys.version_info[0] >= 3, "no differences with __future__ in py3")
575 576 def test_timeit_futures():
576 577 "Test %timeit with __future__ environments"
577 578 ip = get_ipython()
578 579 ip.run_cell("from __future__ import division")
579 580 with tt.AssertPrints('0.25'):
580 581 ip.run_line_magic('timeit', '-n1 -r1 print(1/4)')
581 582 ip.compile.reset_compiler_flags()
582 583 with tt.AssertNotPrints('0.25'):
583 584 ip.run_line_magic('timeit', '-n1 -r1 print(1/4)')
584 585
585 586 @dec.skipif(execution.profile is None)
586 587 def test_prun_special_syntax():
587 588 "Test %%prun with IPython special syntax"
588 589 @register_line_magic
589 590 def lmagic(line):
590 591 ip = get_ipython()
591 592 ip.user_ns['lmagic_out'] = line
592 593
593 594 # line mode test
594 595 _ip.run_line_magic('prun', '-q %lmagic my line')
595 596 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
596 597 # cell mode test
597 598 _ip.run_cell_magic('prun', '-q', '%lmagic my line2')
598 599 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
599 600
600 601 @dec.skipif(execution.profile is None)
601 602 def test_prun_quotes():
602 603 "Test that prun does not clobber string escapes (GH #1302)"
603 604 _ip.magic(r"prun -q x = '\t'")
604 605 nt.assert_equal(_ip.user_ns['x'], '\t')
605 606
606 607 def test_extension():
607 608 tmpdir = TemporaryDirectory()
608 609 orig_ipython_dir = _ip.ipython_dir
609 610 try:
610 611 _ip.ipython_dir = tmpdir.name
611 612 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
612 613 url = os.path.join(os.path.dirname(__file__), "daft_extension.py")
613 614 _ip.magic("install_ext %s" % url)
614 615 _ip.user_ns.pop('arq', None)
615 616 invalidate_caches() # Clear import caches
616 617 _ip.magic("load_ext daft_extension")
617 618 nt.assert_equal(_ip.user_ns['arq'], 185)
618 619 _ip.magic("unload_ext daft_extension")
619 620 assert 'arq' not in _ip.user_ns
620 621 finally:
621 622 _ip.ipython_dir = orig_ipython_dir
622 623 tmpdir.cleanup()
623 624
624 625
625 626 # The nose skip decorator doesn't work on classes, so this uses unittest's skipIf
626 627 @skipIf(dec.module_not_available('IPython.nbformat.current'), 'nbformat not importable')
627 628 class NotebookExportMagicTests(TestCase):
628 629 def test_notebook_export_json(self):
629 630 with TemporaryDirectory() as td:
630 631 outfile = os.path.join(td, "nb.ipynb")
631 632 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
632 633 _ip.magic("notebook -e %s" % outfile)
633 634
634 635 def test_notebook_export_py(self):
635 636 with TemporaryDirectory() as td:
636 637 outfile = os.path.join(td, "nb.py")
637 638 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
638 639 _ip.magic("notebook -e %s" % outfile)
639 640
640 641 def test_notebook_reformat_py(self):
641 642 from IPython.nbformat.v3.tests.nbexamples import nb0
642 643 from IPython.nbformat import current
643 644 with TemporaryDirectory() as td:
644 645 infile = os.path.join(td, "nb.ipynb")
645 646 with io.open(infile, 'w', encoding='utf-8') as f:
646 647 current.write(nb0, f, 'json')
647 648
648 649 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
649 650 _ip.magic("notebook -f py %s" % infile)
650 651
651 652 def test_notebook_reformat_json(self):
652 653 from IPython.nbformat.v3.tests.nbexamples import nb0
653 654 from IPython.nbformat import current
654 655 with TemporaryDirectory() as td:
655 656 infile = os.path.join(td, "nb.py")
656 657 with io.open(infile, 'w', encoding='utf-8') as f:
657 658 current.write(nb0, f, 'py')
658 659
659 660 _ip.ex(py3compat.u_format(u"u = {u}'hΓ©llo'"))
660 661 _ip.magic("notebook -f ipynb %s" % infile)
661 662 _ip.magic("notebook -f json %s" % infile)
662 663
663 664
664 665 def test_env():
665 666 env = _ip.magic("env")
666 667 assert isinstance(env, dict), type(env)
667 668
668 669
669 670 class CellMagicTestCase(TestCase):
670 671
671 672 def check_ident(self, magic):
672 673 # Manually called, we get the result
673 674 out = _ip.run_cell_magic(magic, 'a', 'b')
674 675 nt.assert_equal(out, ('a','b'))
675 676 # Via run_cell, it goes into the user's namespace via displayhook
676 677 _ip.run_cell('%%' + magic +' c\nd')
677 678 nt.assert_equal(_ip.user_ns['_'], ('c','d'))
678 679
679 680 def test_cell_magic_func_deco(self):
680 681 "Cell magic using simple decorator"
681 682 @register_cell_magic
682 683 def cellm(line, cell):
683 684 return line, cell
684 685
685 686 self.check_ident('cellm')
686 687
687 688 def test_cell_magic_reg(self):
688 689 "Cell magic manually registered"
689 690 def cellm(line, cell):
690 691 return line, cell
691 692
692 693 _ip.register_magic_function(cellm, 'cell', 'cellm2')
693 694 self.check_ident('cellm2')
694 695
695 696 def test_cell_magic_class(self):
696 697 "Cell magics declared via a class"
697 698 @magics_class
698 699 class MyMagics(Magics):
699 700
700 701 @cell_magic
701 702 def cellm3(self, line, cell):
702 703 return line, cell
703 704
704 705 _ip.register_magics(MyMagics)
705 706 self.check_ident('cellm3')
706 707
707 708 def test_cell_magic_class2(self):
708 709 "Cell magics declared via a class, #2"
709 710 @magics_class
710 711 class MyMagics2(Magics):
711 712
712 713 @cell_magic('cellm4')
713 714 def cellm33(self, line, cell):
714 715 return line, cell
715 716
716 717 _ip.register_magics(MyMagics2)
717 718 self.check_ident('cellm4')
718 719 # Check that nothing is registered as 'cellm33'
719 720 c33 = _ip.find_cell_magic('cellm33')
720 721 nt.assert_equal(c33, None)
721 722
722 723 def test_file():
723 724 """Basic %%file"""
724 725 ip = get_ipython()
725 726 with TemporaryDirectory() as td:
726 727 fname = os.path.join(td, 'file1')
727 728 ip.run_cell_magic("file", fname, u'\n'.join([
728 729 'line1',
729 730 'line2',
730 731 ]))
731 732 with open(fname) as f:
732 733 s = f.read()
733 734 nt.assert_in('line1\n', s)
734 735 nt.assert_in('line2', s)
735 736
736 737 def test_file_var_expand():
737 738 """%%file $filename"""
738 739 ip = get_ipython()
739 740 with TemporaryDirectory() as td:
740 741 fname = os.path.join(td, 'file1')
741 742 ip.user_ns['filename'] = fname
742 743 ip.run_cell_magic("file", '$filename', u'\n'.join([
743 744 'line1',
744 745 'line2',
745 746 ]))
746 747 with open(fname) as f:
747 748 s = f.read()
748 749 nt.assert_in('line1\n', s)
749 750 nt.assert_in('line2', s)
750 751
751 752 def test_file_unicode():
752 753 """%%file with unicode cell"""
753 754 ip = get_ipython()
754 755 with TemporaryDirectory() as td:
755 756 fname = os.path.join(td, 'file1')
756 757 ip.run_cell_magic("file", fname, u'\n'.join([
757 758 u'linΓ©1',
758 759 u'linΓ©2',
759 760 ]))
760 761 with io.open(fname, encoding='utf-8') as f:
761 762 s = f.read()
762 763 nt.assert_in(u'linΓ©1\n', s)
763 764 nt.assert_in(u'linΓ©2', s)
764 765
765 766 def test_file_amend():
766 767 """%%file -a amends files"""
767 768 ip = get_ipython()
768 769 with TemporaryDirectory() as td:
769 770 fname = os.path.join(td, 'file2')
770 771 ip.run_cell_magic("file", fname, u'\n'.join([
771 772 'line1',
772 773 'line2',
773 774 ]))
774 775 ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([
775 776 'line3',
776 777 'line4',
777 778 ]))
778 779 with open(fname) as f:
779 780 s = f.read()
780 781 nt.assert_in('line1\n', s)
781 782 nt.assert_in('line3\n', s)
782 783
783 784
784 785 def test_script_config():
785 786 ip = get_ipython()
786 787 ip.config.ScriptMagics.script_magics = ['whoda']
787 788 sm = script.ScriptMagics(shell=ip)
788 789 nt.assert_in('whoda', sm.magics['cell'])
789 790
790 791 @dec.skip_win32
791 792 def test_script_out():
792 793 ip = get_ipython()
793 794 ip.run_cell_magic("script", "--out output sh", "echo 'hi'")
794 795 nt.assert_equal(ip.user_ns['output'], 'hi\n')
795 796
796 797 @dec.skip_win32
797 798 def test_script_err():
798 799 ip = get_ipython()
799 800 ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2")
800 801 nt.assert_equal(ip.user_ns['error'], 'hello\n')
801 802
802 803 @dec.skip_win32
803 804 def test_script_out_err():
804 805 ip = get_ipython()
805 806 ip.run_cell_magic("script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2")
806 807 nt.assert_equal(ip.user_ns['output'], 'hi\n')
807 808 nt.assert_equal(ip.user_ns['error'], 'hello\n')
808 809
809 810 @dec.skip_win32
810 811 def test_script_bg_out():
811 812 ip = get_ipython()
812 813 ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'")
813 814 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
814 815
815 816 @dec.skip_win32
816 817 def test_script_bg_err():
817 818 ip = get_ipython()
818 819 ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2")
819 820 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
820 821
821 822 @dec.skip_win32
822 823 def test_script_bg_out_err():
823 824 ip = get_ipython()
824 825 ip.run_cell_magic("script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2")
825 826 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
826 827 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
827 828
828 829 def test_script_defaults():
829 830 ip = get_ipython()
830 831 for cmd in ['sh', 'bash', 'perl', 'ruby']:
831 832 try:
832 833 find_cmd(cmd)
833 834 except Exception:
834 835 pass
835 836 else:
836 837 nt.assert_in(cmd, ip.magics_manager.magics['cell'])
837 838
838 839
839 840 @magics_class
840 841 class FooFoo(Magics):
841 842 """class with both %foo and %%foo magics"""
842 843 @line_magic('foo')
843 844 def line_foo(self, line):
844 845 "I am line foo"
845 846 pass
846 847
847 848 @cell_magic("foo")
848 849 def cell_foo(self, line, cell):
849 850 "I am cell foo, not line foo"
850 851 pass
851 852
852 853 def test_line_cell_info():
853 854 """%%foo and %foo magics are distinguishable to inspect"""
854 855 ip = get_ipython()
855 856 ip.magics_manager.register(FooFoo)
856 857 oinfo = ip.object_inspect('foo')
857 858 nt.assert_true(oinfo['found'])
858 859 nt.assert_true(oinfo['ismagic'])
859 860
860 861 oinfo = ip.object_inspect('%%foo')
861 862 nt.assert_true(oinfo['found'])
862 863 nt.assert_true(oinfo['ismagic'])
863 864 nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
864 865
865 866 oinfo = ip.object_inspect('%foo')
866 867 nt.assert_true(oinfo['found'])
867 868 nt.assert_true(oinfo['ismagic'])
868 869 nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__)
869 870
870 871 def test_multiple_magics():
871 872 ip = get_ipython()
872 873 foo1 = FooFoo(ip)
873 874 foo2 = FooFoo(ip)
874 875 mm = ip.magics_manager
875 876 mm.register(foo1)
876 877 nt.assert_true(mm.magics['line']['foo'].__self__ is foo1)
877 878 mm.register(foo2)
878 879 nt.assert_true(mm.magics['line']['foo'].__self__ is foo2)
879 880
880 881 def test_alias_magic():
881 882 """Test %alias_magic."""
882 883 ip = get_ipython()
883 884 mm = ip.magics_manager
884 885
885 886 # Basic operation: both cell and line magics are created, if possible.
886 887 ip.run_line_magic('alias_magic', 'timeit_alias timeit')
887 888 nt.assert_in('timeit_alias', mm.magics['line'])
888 889 nt.assert_in('timeit_alias', mm.magics['cell'])
889 890
890 891 # --cell is specified, line magic not created.
891 892 ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
892 893 nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
893 894 nt.assert_in('timeit_cell_alias', mm.magics['cell'])
894 895
895 896 # Test that line alias is created successfully.
896 897 ip.run_line_magic('alias_magic', '--line env_alias env')
897 898 nt.assert_equal(ip.run_line_magic('env', ''),
898 899 ip.run_line_magic('env_alias', ''))
899 900
900 901 def test_save():
901 902 """Test %save."""
902 903 ip = get_ipython()
903 904 ip.history_manager.reset() # Clear any existing history.
904 905 cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"]
905 906 for i, cmd in enumerate(cmds, start=1):
906 907 ip.history_manager.store_inputs(i, cmd)
907 908 with TemporaryDirectory() as tmpdir:
908 909 file = os.path.join(tmpdir, "testsave.py")
909 910 ip.run_line_magic("save", "%s 1-10" % file)
910 911 with open(file) as f:
911 912 content = f.read()
912 913 nt.assert_equal(content.count(cmds[0]), 1)
913 914 nt.assert_in('coding: utf-8', content)
914 915 ip.run_line_magic("save", "-a %s 1-10" % file)
915 916 with open(file) as f:
916 917 content = f.read()
917 918 nt.assert_equal(content.count(cmds[0]), 2)
918 919 nt.assert_in('coding: utf-8', content)
919 920
920 921
921 922 def test_store():
922 923 """Test %store."""
923 924 ip = get_ipython()
924 925 ip.run_line_magic('load_ext', 'storemagic')
925 926
926 927 # make sure the storage is empty
927 928 ip.run_line_magic('store', '-z')
928 929 ip.user_ns['var'] = 42
929 930 ip.run_line_magic('store', 'var')
930 931 ip.user_ns['var'] = 39
931 932 ip.run_line_magic('store', '-r')
932 933 nt.assert_equal(ip.user_ns['var'], 42)
933 934
934 935 ip.run_line_magic('store', '-d var')
935 936 ip.user_ns['var'] = 39
936 937 ip.run_line_magic('store' , '-r')
937 938 nt.assert_equal(ip.user_ns['var'], 39)
938 939
939 940
940 941 def _run_edit_test(arg_s, exp_filename=None,
941 942 exp_lineno=-1,
942 943 exp_contents=None,
943 944 exp_is_temp=None):
944 945 ip = get_ipython()
945 946 M = code.CodeMagics(ip)
946 947 last_call = ['','']
947 948 opts,args = M.parse_options(arg_s,'prxn:')
948 949 filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call)
949 950
950 951 if exp_filename is not None:
951 952 nt.assert_equal(exp_filename, filename)
952 953 if exp_contents is not None:
953 954 with io.open(filename, 'r', encoding='utf-8') as f:
954 955 contents = f.read()
955 956 nt.assert_equal(exp_contents, contents)
956 957 if exp_lineno != -1:
957 958 nt.assert_equal(exp_lineno, lineno)
958 959 if exp_is_temp is not None:
959 960 nt.assert_equal(exp_is_temp, is_temp)
960 961
961 962
962 963 def test_edit_interactive():
963 964 """%edit on interactively defined objects"""
964 965 ip = get_ipython()
965 966 n = ip.execution_count
966 967 ip.run_cell(u"def foo(): return 1", store_history=True)
967 968
968 969 try:
969 970 _run_edit_test("foo")
970 971 except code.InteractivelyDefined as e:
971 972 nt.assert_equal(e.index, n)
972 973 else:
973 974 raise AssertionError("Should have raised InteractivelyDefined")
974 975
975 976
976 977 def test_edit_cell():
977 978 """%edit [cell id]"""
978 979 ip = get_ipython()
979 980
980 981 ip.run_cell(u"def foo(): return 1", store_history=True)
981 982
982 983 # test
983 984 _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True)
984 985
985 986 def test_bookmark():
986 987 ip = get_ipython()
987 988 ip.run_line_magic('bookmark', 'bmname')
988 989 with tt.AssertPrints('bmname'):
989 990 ip.run_line_magic('bookmark', '-l')
990 991 ip.run_line_magic('bookmark', '-d bmname')
General Comments 0
You need to be logged in to leave comments. Login now