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