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