##// END OF EJS Templates
Fixes #3664
Jarrod Janssen -
Show More
@@ -1,1386 +1,1401 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 sys
15 import sys
15 import time
16 import time
16 import timeit
17 import timeit
17 import math
18 import math
18 from pdb import Restart
19 from pdb import Restart
19
20
20 # cProfile was added in Python2.5
21 # cProfile was added in Python2.5
21 try:
22 try:
22 import cProfile as profile
23 import cProfile as profile
23 import pstats
24 import pstats
24 except ImportError:
25 except ImportError:
25 # profile isn't bundled by default in Debian for license reasons
26 # profile isn't bundled by default in Debian for license reasons
26 try:
27 try:
27 import profile, pstats
28 import profile, pstats
28 except ImportError:
29 except ImportError:
29 profile = pstats = None
30 profile = pstats = None
30
31
31 from IPython.core import oinspect
32 from IPython.core import oinspect
32 from IPython.core import magic_arguments
33 from IPython.core import magic_arguments
33 from IPython.core import page
34 from IPython.core import page
34 from IPython.core.error import UsageError
35 from IPython.core.error import UsageError
35 from IPython.core.macro import Macro
36 from IPython.core.macro import Macro
36 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,
37 line_cell_magic, on_off, needs_local_scope)
38 line_cell_magic, on_off, needs_local_scope)
38 from IPython.testing.skipdoctest import skip_doctest
39 from IPython.testing.skipdoctest import skip_doctest
39 from IPython.utils.contexts import preserve_keys
40 from IPython.utils.contexts import preserve_keys
40 from IPython.utils.capture import capture_output
41 from IPython.utils.capture import capture_output
41 from IPython.utils.ipstruct import Struct
42 from IPython.utils.ipstruct import Struct
42 from IPython.utils.module_paths import find_mod
43 from IPython.utils.module_paths import find_mod
43 from IPython.utils.path import get_py_filename, shellglob
44 from IPython.utils.path import get_py_filename, shellglob
44 from IPython.utils.timing import clock, clock2
45 from IPython.utils.timing import clock, clock2
45 from warnings import warn
46 from warnings import warn
46 from logging import error
47 from logging import error
47 from io import StringIO
48 from io import StringIO
48
49
49
50
50 #-----------------------------------------------------------------------------
51 #-----------------------------------------------------------------------------
51 # Magic implementation classes
52 # Magic implementation classes
52 #-----------------------------------------------------------------------------
53 #-----------------------------------------------------------------------------
53
54
54
55
55 class TimeitResult(object):
56 class TimeitResult(object):
56 """
57 """
57 Object returned by the timeit magic with info about the run.
58 Object returned by the timeit magic with info about the run.
58
59
59 Contains the following attributes :
60 Contains the following attributes :
60
61
61 loops: (int) number of loops done per measurement
62 loops: (int) number of loops done per measurement
62 repeat: (int) number of times the measurement has been repeated
63 repeat: (int) number of times the measurement has been repeated
63 best: (float) best execution time / number
64 best: (float) best execution time / number
64 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)
65 compile_time: (float) time of statement compilation (s)
66 compile_time: (float) time of statement compilation (s)
66
67
67 """
68 """
68 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):
69 self.loops = loops
70 self.loops = loops
70 self.repeat = repeat
71 self.repeat = repeat
71 self.best = best
72 self.best = best
72 self.worst = worst
73 self.worst = worst
73 self.all_runs = all_runs
74 self.all_runs = all_runs
74 self.compile_time = compile_time
75 self.compile_time = compile_time
75 self._precision = precision
76 self._precision = precision
76 self.timings = [ dt / self.loops for dt in all_runs]
77 self.timings = [ dt / self.loops for dt in all_runs]
77
78
78 @property
79 @property
79 def average(self):
80 def average(self):
80 return math.fsum(self.timings) / len(self.timings)
81 return math.fsum(self.timings) / len(self.timings)
81
82
82 @property
83 @property
83 def stdev(self):
84 def stdev(self):
84 mean = self.average
85 mean = self.average
85 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
86
87
87 def __str__(self):
88 def __str__(self):
88 pm = '+-'
89 pm = '+-'
89 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
90 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
90 try:
91 try:
91 u'\xb1'.encode(sys.stdout.encoding)
92 u'\xb1'.encode(sys.stdout.encoding)
92 pm = u'\xb1'
93 pm = u'\xb1'
93 except:
94 except:
94 pass
95 pass
95 return (
96 return (
96 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)"
97 .format(
98 .format(
98 pm = pm,
99 pm = pm,
99 runs = self.repeat,
100 runs = self.repeat,
100 loops = self.loops,
101 loops = self.loops,
101 loop_plural = "" if self.loops == 1 else "s",
102 loop_plural = "" if self.loops == 1 else "s",
102 run_plural = "" if self.repeat == 1 else "s",
103 run_plural = "" if self.repeat == 1 else "s",
103 mean = _format_time(self.average, self._precision),
104 mean = _format_time(self.average, self._precision),
104 std = _format_time(self.stdev, self._precision))
105 std = _format_time(self.stdev, self._precision))
105 )
106 )
106
107
107 def _repr_pretty_(self, p , cycle):
108 def _repr_pretty_(self, p , cycle):
108 unic = self.__str__()
109 unic = self.__str__()
109 p.text(u'<TimeitResult : '+unic+u'>')
110 p.text(u'<TimeitResult : '+unic+u'>')
110
111
111
112
112
113
113 class TimeitTemplateFiller(ast.NodeTransformer):
114 class TimeitTemplateFiller(ast.NodeTransformer):
114 """Fill in the AST template for timing execution.
115 """Fill in the AST template for timing execution.
115
116
116 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
117 :meth:`ExecutionMagics.timeit`.
118 :meth:`ExecutionMagics.timeit`.
118 """
119 """
119 def __init__(self, ast_setup, ast_stmt):
120 def __init__(self, ast_setup, ast_stmt):
120 self.ast_setup = ast_setup
121 self.ast_setup = ast_setup
121 self.ast_stmt = ast_stmt
122 self.ast_stmt = ast_stmt
122
123
123 def visit_FunctionDef(self, node):
124 def visit_FunctionDef(self, node):
124 "Fill in the setup statement"
125 "Fill in the setup statement"
125 self.generic_visit(node)
126 self.generic_visit(node)
126 if node.name == "inner":
127 if node.name == "inner":
127 node.body[:1] = self.ast_setup.body
128 node.body[:1] = self.ast_setup.body
128
129
129 return node
130 return node
130
131
131 def visit_For(self, node):
132 def visit_For(self, node):
132 "Fill in the statement to be timed"
133 "Fill in the statement to be timed"
133 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
134 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
134 node.body = self.ast_stmt.body
135 node.body = self.ast_stmt.body
135 return node
136 return node
136
137
137
138
138 class Timer(timeit.Timer):
139 class Timer(timeit.Timer):
139 """Timer class that explicitly uses self.inner
140 """Timer class that explicitly uses self.inner
140
141
141 which is an undocumented implementation detail of CPython,
142 which is an undocumented implementation detail of CPython,
142 not shared by PyPy.
143 not shared by PyPy.
143 """
144 """
144 # Timer.timeit copied from CPython 3.4.2
145 # Timer.timeit copied from CPython 3.4.2
145 def timeit(self, number=timeit.default_number):
146 def timeit(self, number=timeit.default_number):
146 """Time 'number' executions of the main statement.
147 """Time 'number' executions of the main statement.
147
148
148 To be precise, this executes the setup statement once, and
149 To be precise, this executes the setup statement once, and
149 then returns the time it takes to execute the main statement
150 then returns the time it takes to execute the main statement
150 a number of times, as a float measured in seconds. The
151 a number of times, as a float measured in seconds. The
151 argument is the number of times through the loop, defaulting
152 argument is the number of times through the loop, defaulting
152 to one million. The main statement, the setup statement and
153 to one million. The main statement, the setup statement and
153 the timer function to be used are passed to the constructor.
154 the timer function to be used are passed to the constructor.
154 """
155 """
155 it = itertools.repeat(None, number)
156 it = itertools.repeat(None, number)
156 gcold = gc.isenabled()
157 gcold = gc.isenabled()
157 gc.disable()
158 gc.disable()
158 try:
159 try:
159 timing = self.inner(it, self.timer)
160 timing = self.inner(it, self.timer)
160 finally:
161 finally:
161 if gcold:
162 if gcold:
162 gc.enable()
163 gc.enable()
163 return timing
164 return timing
164
165
165
166
166 @magics_class
167 @magics_class
167 class ExecutionMagics(Magics):
168 class ExecutionMagics(Magics):
168 """Magics related to code execution, debugging, profiling, etc.
169 """Magics related to code execution, debugging, profiling, etc.
169
170
170 """
171 """
171
172
172 def __init__(self, shell):
173 def __init__(self, shell):
173 super(ExecutionMagics, self).__init__(shell)
174 super(ExecutionMagics, self).__init__(shell)
174 if profile is None:
175 if profile is None:
175 self.prun = self.profile_missing_notice
176 self.prun = self.profile_missing_notice
176 # Default execution function used to actually run user code.
177 # Default execution function used to actually run user code.
177 self.default_runner = None
178 self.default_runner = None
178
179
179 def profile_missing_notice(self, *args, **kwargs):
180 def profile_missing_notice(self, *args, **kwargs):
180 error("""\
181 error("""\
181 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
182 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
183 python-profiler package from non-free.""")
184 python-profiler package from non-free.""")
184
185
185 @skip_doctest
186 @skip_doctest
186 @line_cell_magic
187 @line_cell_magic
187 def prun(self, parameter_s='', cell=None):
188 def prun(self, parameter_s='', cell=None):
188
189
189 """Run a statement through the python code profiler.
190 """Run a statement through the python code profiler.
190
191
191 Usage, in line mode:
192 Usage, in line mode:
192 %prun [options] statement
193 %prun [options] statement
193
194
194 Usage, in cell mode:
195 Usage, in cell mode:
195 %%prun [options] [statement]
196 %%prun [options] [statement]
196 code...
197 code...
197 code...
198 code...
198
199
199 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
200 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
201 profile multiline blocks without having to put them in a separate
202 profile multiline blocks without having to put them in a separate
202 function.
203 function.
203
204
204 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
205 python profiler in a manner similar to the profile.run() function.
206 python profiler in a manner similar to the profile.run() function.
206 Namespaces are internally managed to work correctly; profile.run
207 Namespaces are internally managed to work correctly; profile.run
207 cannot be used in IPython because it makes certain assumptions about
208 cannot be used in IPython because it makes certain assumptions about
208 namespaces which do not hold under IPython.
209 namespaces which do not hold under IPython.
209
210
210 Options:
211 Options:
211
212
212 -l <limit>
213 -l <limit>
213 you can place restrictions on what or how much of the
214 you can place restrictions on what or how much of the
214 profile gets printed. The limit value can be:
215 profile gets printed. The limit value can be:
215
216
216 * A string: only information for function names containing this string
217 * A string: only information for function names containing this string
217 is printed.
218 is printed.
218
219
219 * An integer: only these many lines are printed.
220 * An integer: only these many lines are printed.
220
221
221 * 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
222 (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).
223
224
224 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
225 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
226 information about class constructors.
227 information about class constructors.
227
228
228 -r
229 -r
229 return the pstats.Stats object generated by the profiling. This
230 return the pstats.Stats object generated by the profiling. This
230 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
231 later use it for further analysis or in other functions.
232 later use it for further analysis or in other functions.
232
233
233 -s <key>
234 -s <key>
234 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
235 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
236 default sorting key is 'time'.
237 default sorting key is 'time'.
237
238
238 The following is copied verbatim from the profile documentation
239 The following is copied verbatim from the profile documentation
239 referenced below:
240 referenced below:
240
241
241 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
242 secondary criteria when the there is equality in all keys selected
243 secondary criteria when the there is equality in all keys selected
243 before them.
244 before them.
244
245
245 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
246 abbreviation is unambiguous. The following are the keys currently
247 abbreviation is unambiguous. The following are the keys currently
247 defined:
248 defined:
248
249
249 ============ =====================
250 ============ =====================
250 Valid Arg Meaning
251 Valid Arg Meaning
251 ============ =====================
252 ============ =====================
252 "calls" call count
253 "calls" call count
253 "cumulative" cumulative time
254 "cumulative" cumulative time
254 "file" file name
255 "file" file name
255 "module" file name
256 "module" file name
256 "pcalls" primitive call count
257 "pcalls" primitive call count
257 "line" line number
258 "line" line number
258 "name" function name
259 "name" function name
259 "nfl" name/file/line
260 "nfl" name/file/line
260 "stdname" standard name
261 "stdname" standard name
261 "time" internal time
262 "time" internal time
262 ============ =====================
263 ============ =====================
263
264
264 Note that all sorts on statistics are in descending order (placing
265 Note that all sorts on statistics are in descending order (placing
265 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
266 searches are in ascending order (i.e., alphabetical). The subtle
267 searches are in ascending order (i.e., alphabetical). The subtle
267 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
268 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
269 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
270 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
271 "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
272 line numbers. In fact, sort_stats("nfl") is the same as
273 line numbers. In fact, sort_stats("nfl") is the same as
273 sort_stats("name", "file", "line").
274 sort_stats("name", "file", "line").
274
275
275 -T <filename>
276 -T <filename>
276 save profile results as shown on screen to a text
277 save profile results as shown on screen to a text
277 file. The profile is still shown on screen.
278 file. The profile is still shown on screen.
278
279
279 -D <filename>
280 -D <filename>
280 save (via dump_stats) profile statistics to given
281 save (via dump_stats) profile statistics to given
281 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
282 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
283 objects. The profile is still shown on screen.
284 objects. The profile is still shown on screen.
284
285
285 -q
286 -q
286 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.
287
288
288 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
289 ``%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
290 contains profiler specific options as described here.
291 contains profiler specific options as described here.
291
292
292 You can read the complete documentation for the profile module with::
293 You can read the complete documentation for the profile module with::
293
294
294 In [1]: import profile; profile.help()
295 In [1]: import profile; profile.help()
295 """
296 """
296 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',
297 list_all=True, posix=False)
298 list_all=True, posix=False)
298 if cell is not None:
299 if cell is not None:
299 arg_str += '\n' + cell
300 arg_str += '\n' + cell
300 arg_str = self.shell.input_splitter.transform_cell(arg_str)
301 arg_str = self.shell.input_splitter.transform_cell(arg_str)
301 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)
302
303
303 def _run_with_profiler(self, code, opts, namespace):
304 def _run_with_profiler(self, code, opts, namespace):
304 """
305 """
305 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
306 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
306
307
307 Parameters
308 Parameters
308 ----------
309 ----------
309 code : str
310 code : str
310 Code to be executed.
311 Code to be executed.
311 opts : Struct
312 opts : Struct
312 Options parsed by `self.parse_options`.
313 Options parsed by `self.parse_options`.
313 namespace : dict
314 namespace : dict
314 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
315 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
315
316
316 """
317 """
317
318
318 # Fill default values for unspecified options:
319 # Fill default values for unspecified options:
319 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
320 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
320
321
321 prof = profile.Profile()
322 prof = profile.Profile()
322 try:
323 try:
323 prof = prof.runctx(code, namespace, namespace)
324 prof = prof.runctx(code, namespace, namespace)
324 sys_exit = ''
325 sys_exit = ''
325 except SystemExit:
326 except SystemExit:
326 sys_exit = """*** SystemExit exception caught in code being profiled."""
327 sys_exit = """*** SystemExit exception caught in code being profiled."""
327
328
328 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
329 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
329
330
330 lims = opts.l
331 lims = opts.l
331 if lims:
332 if lims:
332 lims = [] # rebuild lims with ints/floats/strings
333 lims = [] # rebuild lims with ints/floats/strings
333 for lim in opts.l:
334 for lim in opts.l:
334 try:
335 try:
335 lims.append(int(lim))
336 lims.append(int(lim))
336 except ValueError:
337 except ValueError:
337 try:
338 try:
338 lims.append(float(lim))
339 lims.append(float(lim))
339 except ValueError:
340 except ValueError:
340 lims.append(lim)
341 lims.append(lim)
341
342
342 # Trap output.
343 # Trap output.
343 stdout_trap = StringIO()
344 stdout_trap = StringIO()
344 stats_stream = stats.stream
345 stats_stream = stats.stream
345 try:
346 try:
346 stats.stream = stdout_trap
347 stats.stream = stdout_trap
347 stats.print_stats(*lims)
348 stats.print_stats(*lims)
348 finally:
349 finally:
349 stats.stream = stats_stream
350 stats.stream = stats_stream
350
351
351 output = stdout_trap.getvalue()
352 output = stdout_trap.getvalue()
352 output = output.rstrip()
353 output = output.rstrip()
353
354
354 if 'q' not in opts:
355 if 'q' not in opts:
355 page.page(output)
356 page.page(output)
356 print(sys_exit, end=' ')
357 print(sys_exit, end=' ')
357
358
358 dump_file = opts.D[0]
359 dump_file = opts.D[0]
359 text_file = opts.T[0]
360 text_file = opts.T[0]
360 if dump_file:
361 if dump_file:
361 prof.dump_stats(dump_file)
362 prof.dump_stats(dump_file)
362 print('\n*** Profile stats marshalled to file',\
363 print('\n*** Profile stats marshalled to file',\
363 repr(dump_file)+'.',sys_exit)
364 repr(dump_file)+'.',sys_exit)
364 if text_file:
365 if text_file:
365 pfile = open(text_file,'w')
366 pfile = open(text_file,'w')
366 pfile.write(output)
367 pfile.write(output)
367 pfile.close()
368 pfile.close()
368 print('\n*** Profile printout saved to text file',\
369 print('\n*** Profile printout saved to text file',\
369 repr(text_file)+'.',sys_exit)
370 repr(text_file)+'.',sys_exit)
370
371
371 if 'r' in opts:
372 if 'r' in opts:
372 return stats
373 return stats
373 else:
374 else:
374 return None
375 return None
375
376
376 @line_magic
377 @line_magic
377 def pdb(self, parameter_s=''):
378 def pdb(self, parameter_s=''):
378 """Control the automatic calling of the pdb interactive debugger.
379 """Control the automatic calling of the pdb interactive debugger.
379
380
380 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
381 argument it works as a toggle.
382 argument it works as a toggle.
382
383
383 When an exception is triggered, IPython can optionally call the
384 When an exception is triggered, IPython can optionally call the
384 interactive pdb debugger after the traceback printout. %pdb toggles
385 interactive pdb debugger after the traceback printout. %pdb toggles
385 this feature on and off.
386 this feature on and off.
386
387
387 The initial state of this feature is set in your configuration
388 The initial state of this feature is set in your configuration
388 file (the option is ``InteractiveShell.pdb``).
389 file (the option is ``InteractiveShell.pdb``).
389
390
390 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,
391 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
392 the %debug magic."""
393 the %debug magic."""
393
394
394 par = parameter_s.strip().lower()
395 par = parameter_s.strip().lower()
395
396
396 if par:
397 if par:
397 try:
398 try:
398 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
399 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
399 except KeyError:
400 except KeyError:
400 print ('Incorrect argument. Use on/1, off/0, '
401 print ('Incorrect argument. Use on/1, off/0, '
401 'or nothing for a toggle.')
402 'or nothing for a toggle.')
402 return
403 return
403 else:
404 else:
404 # toggle
405 # toggle
405 new_pdb = not self.shell.call_pdb
406 new_pdb = not self.shell.call_pdb
406
407
407 # set on the shell
408 # set on the shell
408 self.shell.call_pdb = new_pdb
409 self.shell.call_pdb = new_pdb
409 print('Automatic pdb calling has been turned',on_off(new_pdb))
410 print('Automatic pdb calling has been turned',on_off(new_pdb))
410
411
411 @skip_doctest
412 @skip_doctest
412 @magic_arguments.magic_arguments()
413 @magic_arguments.magic_arguments()
413 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
414 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
414 help="""
415 help="""
415 Set break point at LINE in FILE.
416 Set break point at LINE in FILE.
416 """
417 """
417 )
418 )
418 @magic_arguments.argument('statement', nargs='*',
419 @magic_arguments.argument('statement', nargs='*',
419 help="""
420 help="""
420 Code to run in debugger.
421 Code to run in debugger.
421 You can omit this in cell magic mode.
422 You can omit this in cell magic mode.
422 """
423 """
423 )
424 )
424 @line_cell_magic
425 @line_cell_magic
425 def debug(self, line='', cell=None):
426 def debug(self, line='', cell=None):
426 """Activate the interactive debugger.
427 """Activate the interactive debugger.
427
428
428 This magic command support two ways of activating debugger.
429 This magic command support two ways of activating debugger.
429 One is to activate debugger before executing code. This way, you
430 One is to activate debugger before executing code. This way, you
430 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.
431 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
432 a breakpoint.
433 a breakpoint.
433
434
434 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
435 activate this mode simply running %debug without any argument.
436 activate this mode simply running %debug without any argument.
436 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
437 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
438 traceback that occurred, so you must call this quickly after an
439 traceback that occurred, so you must call this quickly after an
439 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
440 occurs, it clobbers the previous one.
441 occurs, it clobbers the previous one.
441
442
442 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
443 the %pdb magic for more details.
444 the %pdb magic for more details.
444 """
445 """
445 args = magic_arguments.parse_argstring(self.debug, line)
446 args = magic_arguments.parse_argstring(self.debug, line)
446
447
447 if not (args.breakpoint or args.statement or cell):
448 if not (args.breakpoint or args.statement or cell):
448 self._debug_post_mortem()
449 self._debug_post_mortem()
449 else:
450 else:
450 code = "\n".join(args.statement)
451 code = "\n".join(args.statement)
451 if cell:
452 if cell:
452 code += "\n" + cell
453 code += "\n" + cell
453 self._debug_exec(code, args.breakpoint)
454 self._debug_exec(code, args.breakpoint)
454
455
455 def _debug_post_mortem(self):
456 def _debug_post_mortem(self):
456 self.shell.debugger(force=True)
457 self.shell.debugger(force=True)
457
458
458 def _debug_exec(self, code, breakpoint):
459 def _debug_exec(self, code, breakpoint):
459 if breakpoint:
460 if breakpoint:
460 (filename, bp_line) = breakpoint.rsplit(':', 1)
461 (filename, bp_line) = breakpoint.rsplit(':', 1)
461 bp_line = int(bp_line)
462 bp_line = int(bp_line)
462 else:
463 else:
463 (filename, bp_line) = (None, None)
464 (filename, bp_line) = (None, None)
464 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)
465
466
466 @line_magic
467 @line_magic
467 def tb(self, s):
468 def tb(self, s):
468 """Print the last traceback with the currently active exception mode.
469 """Print the last traceback with the currently active exception mode.
469
470
470 See %xmode for changing exception reporting modes."""
471 See %xmode for changing exception reporting modes."""
471 self.shell.showtraceback()
472 self.shell.showtraceback()
472
473
473 @skip_doctest
474 @skip_doctest
474 @line_magic
475 @line_magic
475 def run(self, parameter_s='', runner=None,
476 def run(self, parameter_s='', runner=None,
476 file_finder=get_py_filename):
477 file_finder=get_py_filename):
477 """Run the named file inside IPython as a program.
478 """Run the named file inside IPython as a program.
478
479
479 Usage::
480 Usage::
480
481
481 %run [-n -i -e -G]
482 %run [-n -i -e -G]
482 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
483 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
483 ( -m mod | file ) [args]
484 ( -m mod | file ) [args]
484
485
485 Parameters after the filename are passed as command-line arguments to
486 Parameters after the filename are passed as command-line arguments to
486 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
487 prompt.
488 prompt.
488
489
489 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``,
490 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
491 loading all variables into your interactive namespace for further use
492 loading all variables into your interactive namespace for further use
492 (unless -p is used, see below).
493 (unless -p is used, see below).
493
494
494 The file is executed in a namespace initially consisting only of
495 The file is executed in a namespace initially consisting only of
495 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
496 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
496 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
497 (except for sharing global objects such as previously imported
498 (except for sharing global objects such as previously imported
498 modules). But after execution, the IPython interactive namespace gets
499 modules). But after execution, the IPython interactive namespace gets
499 updated with all variables defined in the program (except for __name__
500 updated with all variables defined in the program (except for __name__
500 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
501 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.
502
503
503 Arguments are expanded using shell-like glob match. Patterns
504 Arguments are expanded using shell-like glob match. Patterns
504 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
505 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
505 tilde '~' will be expanded into user's home directory. Unlike
506 tilde '~' will be expanded into user's home directory. Unlike
506 real shells, quotation does not suppress expansions. Use
507 real shells, quotation does not suppress expansions. Use
507 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
508 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
508 To completely disable these expansions, you can use -G flag.
509 To completely disable these expansions, you can use -G flag.
509
510
510 Options:
511 Options:
511
512
512 -n
513 -n
513 __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
514 without extension (as python does under import). This allows running
515 without extension (as python does under import). This allows running
515 scripts and reloading the definitions in them without calling code
516 scripts and reloading the definitions in them without calling code
516 protected by an ``if __name__ == "__main__"`` clause.
517 protected by an ``if __name__ == "__main__"`` clause.
517
518
518 -i
519 -i
519 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
520 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
521 which depends on variables defined interactively.
522 which depends on variables defined interactively.
522
523
523 -e
524 -e
524 ignore sys.exit() calls or SystemExit exceptions in the script
525 ignore sys.exit() calls or SystemExit exceptions in the script
525 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
526 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
527 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
528 seeing a traceback of the unittest module.
529 seeing a traceback of the unittest module.
529
530
530 -t
531 -t
531 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
532 you an estimated CPU time consumption for your script, which under
533 you an estimated CPU time consumption for your script, which under
533 Unix uses the resource module to avoid the wraparound problems of
534 Unix uses the resource module to avoid the wraparound problems of
534 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
535 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).
536
537
537 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>
538 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
539 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.
540
541
541 For example (testing the script uniq_stable.py)::
542 For example (testing the script uniq_stable.py)::
542
543
543 In [1]: run -t uniq_stable
544 In [1]: run -t uniq_stable
544
545
545 IPython CPU timings (estimated):
546 IPython CPU timings (estimated):
546 User : 0.19597 s.
547 User : 0.19597 s.
547 System: 0.0 s.
548 System: 0.0 s.
548
549
549 In [2]: run -t -N5 uniq_stable
550 In [2]: run -t -N5 uniq_stable
550
551
551 IPython CPU timings (estimated):
552 IPython CPU timings (estimated):
552 Total runs performed: 5
553 Total runs performed: 5
553 Times : Total Per run
554 Times : Total Per run
554 User : 0.910862 s, 0.1821724 s.
555 User : 0.910862 s, 0.1821724 s.
555 System: 0.0 s, 0.0 s.
556 System: 0.0 s, 0.0 s.
556
557
557 -d
558 -d
558 run your program under the control of pdb, the Python debugger.
559 run your program under the control of pdb, the Python debugger.
559 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,
560 etc. Internally, what IPython does is similar to calling::
561 etc. Internally, what IPython does is similar to calling::
561
562
562 pdb.run('execfile("YOURFILENAME")')
563 pdb.run('execfile("YOURFILENAME")')
563
564
564 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
565 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
566 (where N must be an integer). For example::
567 (where N must be an integer). For example::
567
568
568 %run -d -b40 myscript
569 %run -d -b40 myscript
569
570
570 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
571 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
572 something (not a comment or docstring) for it to stop execution.
573 something (not a comment or docstring) for it to stop execution.
573
574
574 Or you can specify a breakpoint in a different file::
575 Or you can specify a breakpoint in a different file::
575
576
576 %run -d -b myotherfile.py:20 myscript
577 %run -d -b myotherfile.py:20 myscript
577
578
578 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
579 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
580 breakpoint.
581 breakpoint.
581
582
582 Entering 'help' gives information about the use of the debugger. You
583 Entering 'help' gives information about the use of the debugger. You
583 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()"
584 at a prompt.
585 at a prompt.
585
586
586 -p
587 -p
587 run program under the control of the Python profiler module (which
588 run program under the control of the Python profiler module (which
588 prints a detailed report of execution times, function calls, etc).
589 prints a detailed report of execution times, function calls, etc).
589
590
590 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
591 profiler itself. See the docs for %prun for details.
592 profiler itself. See the docs for %prun for details.
592
593
593 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
594 IPython interactive namespace (because they remain in the namespace
595 IPython interactive namespace (because they remain in the namespace
595 where the profiler executes them).
596 where the profiler executes them).
596
597
597 Internally this triggers a call to %prun, see its documentation for
598 Internally this triggers a call to %prun, see its documentation for
598 details on the options available specifically for profiling.
599 details on the options available specifically for profiling.
599
600
600 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:
601 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,
602 just as if the commands were written on IPython prompt.
603 just as if the commands were written on IPython prompt.
603
604
604 -m
605 -m
605 specify module name to load instead of script path. Similar to
606 specify module name to load instead of script path. Similar to
606 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
607 want to combine with other %run options. Unlike the python interpreter
608 want to combine with other %run options. Unlike the python interpreter
608 only source modules are allowed no .pyc or .pyo files.
609 only source modules are allowed no .pyc or .pyo files.
609 For example::
610 For example::
610
611
611 %run -m example
612 %run -m example
612
613
613 will run the example module.
614 will run the example module.
614
615
615 -G
616 -G
616 disable shell-like glob expansion of arguments.
617 disable shell-like glob expansion of arguments.
617
618
618 """
619 """
619
620
621 # Logic to handle issue #3664
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:
624 argv = shlex.split(parameter_s, posix=(os.name == 'posix'))
625 for idx, arg in enumerate(argv):
626 if arg and arg.startswith('-') and arg != '-':
627 if arg == '-m':
628 argv.insert(idx + 2, '--')
629 break
630 else:
631 # Positional arg, break
632 break
633 parameter_s = ' '.join(shlex.quote(arg) for arg in argv)
634
620 # get arguments and set sys.argv for program to be run.
635 # get arguments and set sys.argv for program to be run.
621 opts, arg_lst = self.parse_options(parameter_s,
636 opts, arg_lst = self.parse_options(parameter_s,
622 'nidtN:b:pD:l:rs:T:em:G',
637 'nidtN:b:pD:l:rs:T:em:G',
623 mode='list', list_all=1)
638 mode='list', list_all=1)
624 if "m" in opts:
639 if "m" in opts:
625 modulename = opts["m"][0]
640 modulename = opts["m"][0]
626 modpath = find_mod(modulename)
641 modpath = find_mod(modulename)
627 if modpath is None:
642 if modpath is None:
628 warn('%r is not a valid modulename on sys.path'%modulename)
643 warn('%r is not a valid modulename on sys.path'%modulename)
629 return
644 return
630 arg_lst = [modpath] + arg_lst
645 arg_lst = [modpath] + arg_lst
631 try:
646 try:
632 filename = file_finder(arg_lst[0])
647 filename = file_finder(arg_lst[0])
633 except IndexError:
648 except IndexError:
634 warn('you must provide at least a filename.')
649 warn('you must provide at least a filename.')
635 print('\n%run:\n', oinspect.getdoc(self.run))
650 print('\n%run:\n', oinspect.getdoc(self.run))
636 return
651 return
637 except IOError as e:
652 except IOError as e:
638 try:
653 try:
639 msg = str(e)
654 msg = str(e)
640 except UnicodeError:
655 except UnicodeError:
641 msg = e.message
656 msg = e.message
642 error(msg)
657 error(msg)
643 return
658 return
644
659
645 if filename.lower().endswith(('.ipy', '.ipynb')):
660 if filename.lower().endswith(('.ipy', '.ipynb')):
646 with preserve_keys(self.shell.user_ns, '__file__'):
661 with preserve_keys(self.shell.user_ns, '__file__'):
647 self.shell.user_ns['__file__'] = filename
662 self.shell.user_ns['__file__'] = filename
648 self.shell.safe_execfile_ipy(filename)
663 self.shell.safe_execfile_ipy(filename)
649 return
664 return
650
665
651 # 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
652 exit_ignore = 'e' in opts
667 exit_ignore = 'e' in opts
653
668
654 # 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
655 # were run from a system shell.
670 # were run from a system shell.
656 save_argv = sys.argv # save it for later restoring
671 save_argv = sys.argv # save it for later restoring
657
672
658 if 'G' in opts:
673 if 'G' in opts:
659 args = arg_lst[1:]
674 args = arg_lst[1:]
660 else:
675 else:
661 # tilde and glob expansion
676 # tilde and glob expansion
662 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
677 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
663
678
664 sys.argv = [filename] + args # put in the proper filename
679 sys.argv = [filename] + args # put in the proper filename
665
680
666 if 'n' in opts:
681 if 'n' in opts:
667 name = os.path.splitext(os.path.basename(filename))[0]
682 name = os.path.splitext(os.path.basename(filename))[0]
668 else:
683 else:
669 name = '__main__'
684 name = '__main__'
670
685
671 if 'i' in opts:
686 if 'i' in opts:
672 # Run in user's interactive namespace
687 # Run in user's interactive namespace
673 prog_ns = self.shell.user_ns
688 prog_ns = self.shell.user_ns
674 __name__save = self.shell.user_ns['__name__']
689 __name__save = self.shell.user_ns['__name__']
675 prog_ns['__name__'] = name
690 prog_ns['__name__'] = name
676 main_mod = self.shell.user_module
691 main_mod = self.shell.user_module
677
692
678 # 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
679 # set the __file__ global in the script's namespace
694 # set the __file__ global in the script's namespace
680 # TK: Is this necessary in interactive mode?
695 # TK: Is this necessary in interactive mode?
681 prog_ns['__file__'] = filename
696 prog_ns['__file__'] = filename
682 else:
697 else:
683 # Run in a fresh, empty namespace
698 # Run in a fresh, empty namespace
684
699
685 # 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
686 # exits, the python deletion mechanism doesn't zero it out
701 # exits, the python deletion mechanism doesn't zero it out
687 # (leaving dangling references). See interactiveshell for details
702 # (leaving dangling references). See interactiveshell for details
688 main_mod = self.shell.new_main_mod(filename, name)
703 main_mod = self.shell.new_main_mod(filename, name)
689 prog_ns = main_mod.__dict__
704 prog_ns = main_mod.__dict__
690
705
691 # pickle fix. See interactiveshell for an explanation. But we need to
706 # pickle fix. See interactiveshell for an explanation. But we need to
692 # 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
693 main_mod_name = prog_ns['__name__']
708 main_mod_name = prog_ns['__name__']
694
709
695 if main_mod_name == '__main__':
710 if main_mod_name == '__main__':
696 restore_main = sys.modules['__main__']
711 restore_main = sys.modules['__main__']
697 else:
712 else:
698 restore_main = False
713 restore_main = False
699
714
700 # 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
701 # every single object ever created.
716 # every single object ever created.
702 sys.modules[main_mod_name] = main_mod
717 sys.modules[main_mod_name] = main_mod
703
718
704 if 'p' in opts or 'd' in opts:
719 if 'p' in opts or 'd' in opts:
705 if 'm' in opts:
720 if 'm' in opts:
706 code = 'run_module(modulename, prog_ns)'
721 code = 'run_module(modulename, prog_ns)'
707 code_ns = {
722 code_ns = {
708 'run_module': self.shell.safe_run_module,
723 'run_module': self.shell.safe_run_module,
709 'prog_ns': prog_ns,
724 'prog_ns': prog_ns,
710 'modulename': modulename,
725 'modulename': modulename,
711 }
726 }
712 else:
727 else:
713 if 'd' in opts:
728 if 'd' in opts:
714 # allow exceptions to raise in debug mode
729 # allow exceptions to raise in debug mode
715 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
730 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
716 else:
731 else:
717 code = 'execfile(filename, prog_ns)'
732 code = 'execfile(filename, prog_ns)'
718 code_ns = {
733 code_ns = {
719 'execfile': self.shell.safe_execfile,
734 'execfile': self.shell.safe_execfile,
720 'prog_ns': prog_ns,
735 'prog_ns': prog_ns,
721 'filename': get_py_filename(filename),
736 'filename': get_py_filename(filename),
722 }
737 }
723
738
724 try:
739 try:
725 stats = None
740 stats = None
726 if 'p' in opts:
741 if 'p' in opts:
727 stats = self._run_with_profiler(code, opts, code_ns)
742 stats = self._run_with_profiler(code, opts, code_ns)
728 else:
743 else:
729 if 'd' in opts:
744 if 'd' in opts:
730 bp_file, bp_line = parse_breakpoint(
745 bp_file, bp_line = parse_breakpoint(
731 opts.get('b', ['1'])[0], filename)
746 opts.get('b', ['1'])[0], filename)
732 self._run_with_debugger(
747 self._run_with_debugger(
733 code, code_ns, filename, bp_line, bp_file)
748 code, code_ns, filename, bp_line, bp_file)
734 else:
749 else:
735 if 'm' in opts:
750 if 'm' in opts:
736 def run():
751 def run():
737 self.shell.safe_run_module(modulename, prog_ns)
752 self.shell.safe_run_module(modulename, prog_ns)
738 else:
753 else:
739 if runner is None:
754 if runner is None:
740 runner = self.default_runner
755 runner = self.default_runner
741 if runner is None:
756 if runner is None:
742 runner = self.shell.safe_execfile
757 runner = self.shell.safe_execfile
743
758
744 def run():
759 def run():
745 runner(filename, prog_ns, prog_ns,
760 runner(filename, prog_ns, prog_ns,
746 exit_ignore=exit_ignore)
761 exit_ignore=exit_ignore)
747
762
748 if 't' in opts:
763 if 't' in opts:
749 # timed execution
764 # timed execution
750 try:
765 try:
751 nruns = int(opts['N'][0])
766 nruns = int(opts['N'][0])
752 if nruns < 1:
767 if nruns < 1:
753 error('Number of runs must be >=1')
768 error('Number of runs must be >=1')
754 return
769 return
755 except (KeyError):
770 except (KeyError):
756 nruns = 1
771 nruns = 1
757 self._run_with_timing(run, nruns)
772 self._run_with_timing(run, nruns)
758 else:
773 else:
759 # regular execution
774 # regular execution
760 run()
775 run()
761
776
762 if 'i' in opts:
777 if 'i' in opts:
763 self.shell.user_ns['__name__'] = __name__save
778 self.shell.user_ns['__name__'] = __name__save
764 else:
779 else:
765 # update IPython interactive namespace
780 # update IPython interactive namespace
766
781
767 # Some forms of read errors on the file may mean the
782 # Some forms of read errors on the file may mean the
768 # __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
769 # worry about a possible KeyError.
784 # worry about a possible KeyError.
770 prog_ns.pop('__name__', None)
785 prog_ns.pop('__name__', None)
771
786
772 with preserve_keys(self.shell.user_ns, '__file__'):
787 with preserve_keys(self.shell.user_ns, '__file__'):
773 self.shell.user_ns.update(prog_ns)
788 self.shell.user_ns.update(prog_ns)
774 finally:
789 finally:
775 # 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
776 # 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
777 # %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
778 # at all, and similar problems have been reported before:
793 # at all, and similar problems have been reported before:
779 # 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
780 # 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
781 # 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
782 # exit.
797 # exit.
783 self.shell.user_ns['__builtins__'] = builtin_mod
798 self.shell.user_ns['__builtins__'] = builtin_mod
784
799
785 # Ensure key global structures are restored
800 # Ensure key global structures are restored
786 sys.argv = save_argv
801 sys.argv = save_argv
787 if restore_main:
802 if restore_main:
788 sys.modules['__main__'] = restore_main
803 sys.modules['__main__'] = restore_main
789 else:
804 else:
790 # Remove from sys.modules the reference to main_mod we'd
805 # Remove from sys.modules the reference to main_mod we'd
791 # added. Otherwise it will trap references to objects
806 # added. Otherwise it will trap references to objects
792 # contained therein.
807 # contained therein.
793 del sys.modules[main_mod_name]
808 del sys.modules[main_mod_name]
794
809
795 return stats
810 return stats
796
811
797 def _run_with_debugger(self, code, code_ns, filename=None,
812 def _run_with_debugger(self, code, code_ns, filename=None,
798 bp_line=None, bp_file=None):
813 bp_line=None, bp_file=None):
799 """
814 """
800 Run `code` in debugger with a break point.
815 Run `code` in debugger with a break point.
801
816
802 Parameters
817 Parameters
803 ----------
818 ----------
804 code : str
819 code : str
805 Code to execute.
820 Code to execute.
806 code_ns : dict
821 code_ns : dict
807 A namespace in which `code` is executed.
822 A namespace in which `code` is executed.
808 filename : str
823 filename : str
809 `code` is ran as if it is in `filename`.
824 `code` is ran as if it is in `filename`.
810 bp_line : int, optional
825 bp_line : int, optional
811 Line number of the break point.
826 Line number of the break point.
812 bp_file : str, optional
827 bp_file : str, optional
813 Path to the file in which break point is specified.
828 Path to the file in which break point is specified.
814 `filename` is used if not given.
829 `filename` is used if not given.
815
830
816 Raises
831 Raises
817 ------
832 ------
818 UsageError
833 UsageError
819 If the break point given by `bp_line` is not valid.
834 If the break point given by `bp_line` is not valid.
820
835
821 """
836 """
822 deb = self.shell.InteractiveTB.pdb
837 deb = self.shell.InteractiveTB.pdb
823 if not deb:
838 if not deb:
824 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
839 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
825 deb = self.shell.InteractiveTB.pdb
840 deb = self.shell.InteractiveTB.pdb
826
841
827 # 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
828 # handle it not existing. https://github.com/ipython/ipython/issues/10028
843 # handle it not existing. https://github.com/ipython/ipython/issues/10028
829 if hasattr(deb, 'curframe'):
844 if hasattr(deb, 'curframe'):
830 del deb.curframe
845 del deb.curframe
831
846
832 # reset Breakpoint state, which is moronically kept
847 # reset Breakpoint state, which is moronically kept
833 # in a class
848 # in a class
834 bdb.Breakpoint.next = 1
849 bdb.Breakpoint.next = 1
835 bdb.Breakpoint.bplist = {}
850 bdb.Breakpoint.bplist = {}
836 bdb.Breakpoint.bpbynumber = [None]
851 bdb.Breakpoint.bpbynumber = [None]
837 if bp_line is not None:
852 if bp_line is not None:
838 # Set an initial breakpoint to stop execution
853 # Set an initial breakpoint to stop execution
839 maxtries = 10
854 maxtries = 10
840 bp_file = bp_file or filename
855 bp_file = bp_file or filename
841 checkline = deb.checkline(bp_file, bp_line)
856 checkline = deb.checkline(bp_file, bp_line)
842 if not checkline:
857 if not checkline:
843 for bp in range(bp_line + 1, bp_line + maxtries + 1):
858 for bp in range(bp_line + 1, bp_line + maxtries + 1):
844 if deb.checkline(bp_file, bp):
859 if deb.checkline(bp_file, bp):
845 break
860 break
846 else:
861 else:
847 msg = ("\nI failed to find a valid line to set "
862 msg = ("\nI failed to find a valid line to set "
848 "a breakpoint\n"
863 "a breakpoint\n"
849 "after trying up to line: %s.\n"
864 "after trying up to line: %s.\n"
850 "Please set a valid breakpoint manually "
865 "Please set a valid breakpoint manually "
851 "with the -b option." % bp)
866 "with the -b option." % bp)
852 raise UsageError(msg)
867 raise UsageError(msg)
853 # if we find a good linenumber, set the breakpoint
868 # if we find a good linenumber, set the breakpoint
854 deb.do_break('%s:%s' % (bp_file, bp_line))
869 deb.do_break('%s:%s' % (bp_file, bp_line))
855
870
856 if filename:
871 if filename:
857 # Mimic Pdb._runscript(...)
872 # Mimic Pdb._runscript(...)
858 deb._wait_for_mainpyfile = True
873 deb._wait_for_mainpyfile = True
859 deb.mainpyfile = deb.canonic(filename)
874 deb.mainpyfile = deb.canonic(filename)
860
875
861 # Start file run
876 # Start file run
862 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)
863 try:
878 try:
864 if filename:
879 if filename:
865 # 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
866 deb._exec_filename = filename
881 deb._exec_filename = filename
867 while True:
882 while True:
868 try:
883 try:
869 deb.run(code, code_ns)
884 deb.run(code, code_ns)
870 except Restart:
885 except Restart:
871 print("Restarting")
886 print("Restarting")
872 if filename:
887 if filename:
873 deb._wait_for_mainpyfile = True
888 deb._wait_for_mainpyfile = True
874 deb.mainpyfile = deb.canonic(filename)
889 deb.mainpyfile = deb.canonic(filename)
875 continue
890 continue
876 else:
891 else:
877 break
892 break
878
893
879
894
880 except:
895 except:
881 etype, value, tb = sys.exc_info()
896 etype, value, tb = sys.exc_info()
882 # Skip three frames in the traceback: the %run one,
897 # Skip three frames in the traceback: the %run one,
883 # one inside bdb.py, and the command-line typed by the
898 # one inside bdb.py, and the command-line typed by the
884 # user (run by exec in pdb itself).
899 # user (run by exec in pdb itself).
885 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
900 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
886
901
887 @staticmethod
902 @staticmethod
888 def _run_with_timing(run, nruns):
903 def _run_with_timing(run, nruns):
889 """
904 """
890 Run function `run` and print timing information.
905 Run function `run` and print timing information.
891
906
892 Parameters
907 Parameters
893 ----------
908 ----------
894 run : callable
909 run : callable
895 Any callable object which takes no argument.
910 Any callable object which takes no argument.
896 nruns : int
911 nruns : int
897 Number of times to execute `run`.
912 Number of times to execute `run`.
898
913
899 """
914 """
900 twall0 = time.time()
915 twall0 = time.time()
901 if nruns == 1:
916 if nruns == 1:
902 t0 = clock2()
917 t0 = clock2()
903 run()
918 run()
904 t1 = clock2()
919 t1 = clock2()
905 t_usr = t1[0] - t0[0]
920 t_usr = t1[0] - t0[0]
906 t_sys = t1[1] - t0[1]
921 t_sys = t1[1] - t0[1]
907 print("\nIPython CPU timings (estimated):")
922 print("\nIPython CPU timings (estimated):")
908 print(" User : %10.2f s." % t_usr)
923 print(" User : %10.2f s." % t_usr)
909 print(" System : %10.2f s." % t_sys)
924 print(" System : %10.2f s." % t_sys)
910 else:
925 else:
911 runs = range(nruns)
926 runs = range(nruns)
912 t0 = clock2()
927 t0 = clock2()
913 for nr in runs:
928 for nr in runs:
914 run()
929 run()
915 t1 = clock2()
930 t1 = clock2()
916 t_usr = t1[0] - t0[0]
931 t_usr = t1[0] - t0[0]
917 t_sys = t1[1] - t0[1]
932 t_sys = t1[1] - t0[1]
918 print("\nIPython CPU timings (estimated):")
933 print("\nIPython CPU timings (estimated):")
919 print("Total runs performed:", nruns)
934 print("Total runs performed:", nruns)
920 print(" Times : %10s %10s" % ('Total', 'Per run'))
935 print(" Times : %10s %10s" % ('Total', 'Per run'))
921 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))
922 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))
923 twall1 = time.time()
938 twall1 = time.time()
924 print("Wall time: %10.2f s." % (twall1 - twall0))
939 print("Wall time: %10.2f s." % (twall1 - twall0))
925
940
926 @skip_doctest
941 @skip_doctest
927 @line_cell_magic
942 @line_cell_magic
928 def timeit(self, line='', cell=None):
943 def timeit(self, line='', cell=None):
929 """Time execution of a Python statement or expression
944 """Time execution of a Python statement or expression
930
945
931 Usage, in line mode:
946 Usage, in line mode:
932 %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
933 or in cell mode:
948 or in cell mode:
934 %%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
935 code
950 code
936 code...
951 code...
937
952
938 Time execution of a Python statement or expression using the timeit
953 Time execution of a Python statement or expression using the timeit
939 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:
940
955
941 - 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
942 ones can be chained with using semicolons).
957 ones can be chained with using semicolons).
943
958
944 - 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
945 (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
946 body has access to any variables created in the setup code.
961 body has access to any variables created in the setup code.
947
962
948 Options:
963 Options:
949 -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
950 is not given, a fitting value is chosen.
965 is not given, a fitting value is chosen.
951
966
952 -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.
953 Default: 3
968 Default: 3
954
969
955 -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.
956 This function measures wall time.
971 This function measures wall time.
957
972
958 -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
959 Windows and measures wall time. On Unix, resource.getrusage is used
974 Windows and measures wall time. On Unix, resource.getrusage is used
960 instead and returns the CPU user time.
975 instead and returns the CPU user time.
961
976
962 -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.
963 Default: 3
978 Default: 3
964
979
965 -q: Quiet, do not print result.
980 -q: Quiet, do not print result.
966
981
967 -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
968 the result in more details.
983 the result in more details.
969
984
970
985
971 Examples
986 Examples
972 --------
987 --------
973 ::
988 ::
974
989
975 In [1]: %timeit pass
990 In [1]: %timeit pass
976 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)
977
992
978 In [2]: u = None
993 In [2]: u = None
979
994
980 In [3]: %timeit u is None
995 In [3]: %timeit u is None
981 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)
982
997
983 In [4]: %timeit -r 4 u == None
998 In [4]: %timeit -r 4 u == None
984
999
985 In [5]: import time
1000 In [5]: import time
986
1001
987 In [6]: %timeit -n1 time.sleep(2)
1002 In [6]: %timeit -n1 time.sleep(2)
988
1003
989
1004
990 The times reported by %timeit will be slightly higher than those
1005 The times reported by %timeit will be slightly higher than those
991 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
992 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
993 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
994 statement to import function or create variables. Generally, the bias
1009 statement to import function or create variables. Generally, the bias
995 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
996 those from %timeit."""
1011 those from %timeit."""
997
1012
998 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
1013 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
999 posix=False, strict=False)
1014 posix=False, strict=False)
1000 if stmt == "" and cell is None:
1015 if stmt == "" and cell is None:
1001 return
1016 return
1002
1017
1003 timefunc = timeit.default_timer
1018 timefunc = timeit.default_timer
1004 number = int(getattr(opts, "n", 0))
1019 number = int(getattr(opts, "n", 0))
1005 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
1006 repeat = int(getattr(opts, "r", default_repeat))
1021 repeat = int(getattr(opts, "r", default_repeat))
1007 precision = int(getattr(opts, "p", 3))
1022 precision = int(getattr(opts, "p", 3))
1008 quiet = 'q' in opts
1023 quiet = 'q' in opts
1009 return_result = 'o' in opts
1024 return_result = 'o' in opts
1010 if hasattr(opts, "t"):
1025 if hasattr(opts, "t"):
1011 timefunc = time.time
1026 timefunc = time.time
1012 if hasattr(opts, "c"):
1027 if hasattr(opts, "c"):
1013 timefunc = clock
1028 timefunc = clock
1014
1029
1015 timer = Timer(timer=timefunc)
1030 timer = Timer(timer=timefunc)
1016 # 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,
1017 # 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
1018 # to the shell namespace?
1033 # to the shell namespace?
1019 transform = self.shell.input_splitter.transform_cell
1034 transform = self.shell.input_splitter.transform_cell
1020
1035
1021 if cell is None:
1036 if cell is None:
1022 # called as line magic
1037 # called as line magic
1023 ast_setup = self.shell.compile.ast_parse("pass")
1038 ast_setup = self.shell.compile.ast_parse("pass")
1024 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1039 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1025 else:
1040 else:
1026 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1041 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1027 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1042 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1028
1043
1029 ast_setup = self.shell.transform_ast(ast_setup)
1044 ast_setup = self.shell.transform_ast(ast_setup)
1030 ast_stmt = self.shell.transform_ast(ast_stmt)
1045 ast_stmt = self.shell.transform_ast(ast_stmt)
1031
1046
1032 # This codestring is taken from timeit.template - we fill it in as an
1047 # This codestring is taken from timeit.template - we fill it in as an
1033 # AST, so that we can apply our AST transformations to the user code
1048 # AST, so that we can apply our AST transformations to the user code
1034 # without affecting the timing code.
1049 # without affecting the timing code.
1035 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1050 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1036 ' setup\n'
1051 ' setup\n'
1037 ' _t0 = _timer()\n'
1052 ' _t0 = _timer()\n'
1038 ' for _i in _it:\n'
1053 ' for _i in _it:\n'
1039 ' stmt\n'
1054 ' stmt\n'
1040 ' _t1 = _timer()\n'
1055 ' _t1 = _timer()\n'
1041 ' return _t1 - _t0\n')
1056 ' return _t1 - _t0\n')
1042
1057
1043 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1058 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1044 timeit_ast = ast.fix_missing_locations(timeit_ast)
1059 timeit_ast = ast.fix_missing_locations(timeit_ast)
1045
1060
1046 # Track compilation time so it can be reported if too long
1061 # Track compilation time so it can be reported if too long
1047 # Minimum time above which compilation time will be reported
1062 # Minimum time above which compilation time will be reported
1048 tc_min = 0.1
1063 tc_min = 0.1
1049
1064
1050 t0 = clock()
1065 t0 = clock()
1051 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1066 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1052 tc = clock()-t0
1067 tc = clock()-t0
1053
1068
1054 ns = {}
1069 ns = {}
1055 exec(code, self.shell.user_ns, ns)
1070 exec(code, self.shell.user_ns, ns)
1056 timer.inner = ns["inner"]
1071 timer.inner = ns["inner"]
1057
1072
1058 # This is used to check if there is a huge difference between the
1073 # This is used to check if there is a huge difference between the
1059 # best and worst timings.
1074 # best and worst timings.
1060 # Issue: https://github.com/ipython/ipython/issues/6471
1075 # Issue: https://github.com/ipython/ipython/issues/6471
1061 if number == 0:
1076 if number == 0:
1062 # determine number so that 0.2 <= total time < 2.0
1077 # determine number so that 0.2 <= total time < 2.0
1063 for index in range(0, 10):
1078 for index in range(0, 10):
1064 number = 10 ** index
1079 number = 10 ** index
1065 time_number = timer.timeit(number)
1080 time_number = timer.timeit(number)
1066 if time_number >= 0.2:
1081 if time_number >= 0.2:
1067 break
1082 break
1068
1083
1069 all_runs = timer.repeat(repeat, number)
1084 all_runs = timer.repeat(repeat, number)
1070 best = min(all_runs) / number
1085 best = min(all_runs) / number
1071 worst = max(all_runs) / number
1086 worst = max(all_runs) / number
1072 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1087 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1073
1088
1074 if not quiet :
1089 if not quiet :
1075 # Check best timing is greater than zero to avoid a
1090 # Check best timing is greater than zero to avoid a
1076 # ZeroDivisionError.
1091 # ZeroDivisionError.
1077 # In cases where the slowest timing is lesser than a micosecond
1092 # In cases where the slowest timing is lesser than a micosecond
1078 # we assume that it does not really matter if the fastest
1093 # we assume that it does not really matter if the fastest
1079 # timing is 4 times faster than the slowest timing or not.
1094 # timing is 4 times faster than the slowest timing or not.
1080 if worst > 4 * best and best > 0 and worst > 1e-6:
1095 if worst > 4 * best and best > 0 and worst > 1e-6:
1081 print("The slowest run took %0.2f times longer than the "
1096 print("The slowest run took %0.2f times longer than the "
1082 "fastest. This could mean that an intermediate result "
1097 "fastest. This could mean that an intermediate result "
1083 "is being cached." % (worst / best))
1098 "is being cached." % (worst / best))
1084
1099
1085 print( timeit_result )
1100 print( timeit_result )
1086
1101
1087 if tc > tc_min:
1102 if tc > tc_min:
1088 print("Compiler time: %.2f s" % tc)
1103 print("Compiler time: %.2f s" % tc)
1089 if return_result:
1104 if return_result:
1090 return timeit_result
1105 return timeit_result
1091
1106
1092 @skip_doctest
1107 @skip_doctest
1093 @needs_local_scope
1108 @needs_local_scope
1094 @line_cell_magic
1109 @line_cell_magic
1095 def time(self,line='', cell=None, local_ns=None):
1110 def time(self,line='', cell=None, local_ns=None):
1096 """Time execution of a Python statement or expression.
1111 """Time execution of a Python statement or expression.
1097
1112
1098 The CPU and wall clock times are printed, and the value of the
1113 The CPU and wall clock times are printed, and the value of the
1099 expression (if any) is returned. Note that under Win32, system time
1114 expression (if any) is returned. Note that under Win32, system time
1100 is always reported as 0, since it can not be measured.
1115 is always reported as 0, since it can not be measured.
1101
1116
1102 This function can be used both as a line and cell magic:
1117 This function can be used both as a line and cell magic:
1103
1118
1104 - In line mode you can time a single-line statement (though multiple
1119 - In line mode you can time a single-line statement (though multiple
1105 ones can be chained with using semicolons).
1120 ones can be chained with using semicolons).
1106
1121
1107 - In cell mode, you can time the cell body (a directly
1122 - In cell mode, you can time the cell body (a directly
1108 following statement raises an error).
1123 following statement raises an error).
1109
1124
1110 This function provides very basic timing functionality. Use the timeit
1125 This function provides very basic timing functionality. Use the timeit
1111 magic for more control over the measurement.
1126 magic for more control over the measurement.
1112
1127
1113 Examples
1128 Examples
1114 --------
1129 --------
1115 ::
1130 ::
1116
1131
1117 In [1]: %time 2**128
1132 In [1]: %time 2**128
1118 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1133 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1119 Wall time: 0.00
1134 Wall time: 0.00
1120 Out[1]: 340282366920938463463374607431768211456L
1135 Out[1]: 340282366920938463463374607431768211456L
1121
1136
1122 In [2]: n = 1000000
1137 In [2]: n = 1000000
1123
1138
1124 In [3]: %time sum(range(n))
1139 In [3]: %time sum(range(n))
1125 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1140 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1126 Wall time: 1.37
1141 Wall time: 1.37
1127 Out[3]: 499999500000L
1142 Out[3]: 499999500000L
1128
1143
1129 In [4]: %time print 'hello world'
1144 In [4]: %time print 'hello world'
1130 hello world
1145 hello world
1131 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1146 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1132 Wall time: 0.00
1147 Wall time: 0.00
1133
1148
1134 Note that the time needed by Python to compile the given expression
1149 Note that the time needed by Python to compile the given expression
1135 will be reported if it is more than 0.1s. In this example, the
1150 will be reported if it is more than 0.1s. In this example, the
1136 actual exponentiation is done by Python at compilation time, so while
1151 actual exponentiation is done by Python at compilation time, so while
1137 the expression can take a noticeable amount of time to compute, that
1152 the expression can take a noticeable amount of time to compute, that
1138 time is purely due to the compilation:
1153 time is purely due to the compilation:
1139
1154
1140 In [5]: %time 3**9999;
1155 In [5]: %time 3**9999;
1141 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1156 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1142 Wall time: 0.00 s
1157 Wall time: 0.00 s
1143
1158
1144 In [6]: %time 3**999999;
1159 In [6]: %time 3**999999;
1145 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1160 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1146 Wall time: 0.00 s
1161 Wall time: 0.00 s
1147 Compiler : 0.78 s
1162 Compiler : 0.78 s
1148 """
1163 """
1149
1164
1150 # fail immediately if the given expression can't be compiled
1165 # fail immediately if the given expression can't be compiled
1151
1166
1152 if line and cell:
1167 if line and cell:
1153 raise UsageError("Can't use statement directly after '%%time'!")
1168 raise UsageError("Can't use statement directly after '%%time'!")
1154
1169
1155 if cell:
1170 if cell:
1156 expr = self.shell.input_transformer_manager.transform_cell(cell)
1171 expr = self.shell.input_transformer_manager.transform_cell(cell)
1157 else:
1172 else:
1158 expr = self.shell.input_transformer_manager.transform_cell(line)
1173 expr = self.shell.input_transformer_manager.transform_cell(line)
1159
1174
1160 # Minimum time above which parse time will be reported
1175 # Minimum time above which parse time will be reported
1161 tp_min = 0.1
1176 tp_min = 0.1
1162
1177
1163 t0 = clock()
1178 t0 = clock()
1164 expr_ast = self.shell.compile.ast_parse(expr)
1179 expr_ast = self.shell.compile.ast_parse(expr)
1165 tp = clock()-t0
1180 tp = clock()-t0
1166
1181
1167 # Apply AST transformations
1182 # Apply AST transformations
1168 expr_ast = self.shell.transform_ast(expr_ast)
1183 expr_ast = self.shell.transform_ast(expr_ast)
1169
1184
1170 # Minimum time above which compilation time will be reported
1185 # Minimum time above which compilation time will be reported
1171 tc_min = 0.1
1186 tc_min = 0.1
1172
1187
1173 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1188 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1174 mode = 'eval'
1189 mode = 'eval'
1175 source = '<timed eval>'
1190 source = '<timed eval>'
1176 expr_ast = ast.Expression(expr_ast.body[0].value)
1191 expr_ast = ast.Expression(expr_ast.body[0].value)
1177 else:
1192 else:
1178 mode = 'exec'
1193 mode = 'exec'
1179 source = '<timed exec>'
1194 source = '<timed exec>'
1180 t0 = clock()
1195 t0 = clock()
1181 code = self.shell.compile(expr_ast, source, mode)
1196 code = self.shell.compile(expr_ast, source, mode)
1182 tc = clock()-t0
1197 tc = clock()-t0
1183
1198
1184 # skew measurement as little as possible
1199 # skew measurement as little as possible
1185 glob = self.shell.user_ns
1200 glob = self.shell.user_ns
1186 wtime = time.time
1201 wtime = time.time
1187 # time execution
1202 # time execution
1188 wall_st = wtime()
1203 wall_st = wtime()
1189 if mode=='eval':
1204 if mode=='eval':
1190 st = clock2()
1205 st = clock2()
1191 try:
1206 try:
1192 out = eval(code, glob, local_ns)
1207 out = eval(code, glob, local_ns)
1193 except:
1208 except:
1194 self.shell.showtraceback()
1209 self.shell.showtraceback()
1195 return
1210 return
1196 end = clock2()
1211 end = clock2()
1197 else:
1212 else:
1198 st = clock2()
1213 st = clock2()
1199 try:
1214 try:
1200 exec(code, glob, local_ns)
1215 exec(code, glob, local_ns)
1201 except:
1216 except:
1202 self.shell.showtraceback()
1217 self.shell.showtraceback()
1203 return
1218 return
1204 end = clock2()
1219 end = clock2()
1205 out = None
1220 out = None
1206 wall_end = wtime()
1221 wall_end = wtime()
1207 # Compute actual times and report
1222 # Compute actual times and report
1208 wall_time = wall_end-wall_st
1223 wall_time = wall_end-wall_st
1209 cpu_user = end[0]-st[0]
1224 cpu_user = end[0]-st[0]
1210 cpu_sys = end[1]-st[1]
1225 cpu_sys = end[1]-st[1]
1211 cpu_tot = cpu_user+cpu_sys
1226 cpu_tot = cpu_user+cpu_sys
1212 # On windows cpu_sys is always zero, so no new information to the next print
1227 # On windows cpu_sys is always zero, so no new information to the next print
1213 if sys.platform != 'win32':
1228 if sys.platform != 'win32':
1214 print("CPU times: user %s, sys: %s, total: %s" % \
1229 print("CPU times: user %s, sys: %s, total: %s" % \
1215 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1230 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1216 print("Wall time: %s" % _format_time(wall_time))
1231 print("Wall time: %s" % _format_time(wall_time))
1217 if tc > tc_min:
1232 if tc > tc_min:
1218 print("Compiler : %s" % _format_time(tc))
1233 print("Compiler : %s" % _format_time(tc))
1219 if tp > tp_min:
1234 if tp > tp_min:
1220 print("Parser : %s" % _format_time(tp))
1235 print("Parser : %s" % _format_time(tp))
1221 return out
1236 return out
1222
1237
1223 @skip_doctest
1238 @skip_doctest
1224 @line_magic
1239 @line_magic
1225 def macro(self, parameter_s=''):
1240 def macro(self, parameter_s=''):
1226 """Define a macro for future re-execution. It accepts ranges of history,
1241 """Define a macro for future re-execution. It accepts ranges of history,
1227 filenames or string objects.
1242 filenames or string objects.
1228
1243
1229 Usage:\\
1244 Usage:\\
1230 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1245 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1231
1246
1232 Options:
1247 Options:
1233
1248
1234 -r: use 'raw' input. By default, the 'processed' history is used,
1249 -r: use 'raw' input. By default, the 'processed' history is used,
1235 so that magics are loaded in their transformed version to valid
1250 so that magics are loaded in their transformed version to valid
1236 Python. If this option is given, the raw input as typed at the
1251 Python. If this option is given, the raw input as typed at the
1237 command line is used instead.
1252 command line is used instead.
1238
1253
1239 -q: quiet macro definition. By default, a tag line is printed
1254 -q: quiet macro definition. By default, a tag line is printed
1240 to indicate the macro has been created, and then the contents of
1255 to indicate the macro has been created, and then the contents of
1241 the macro are printed. If this option is given, then no printout
1256 the macro are printed. If this option is given, then no printout
1242 is produced once the macro is created.
1257 is produced once the macro is created.
1243
1258
1244 This will define a global variable called `name` which is a string
1259 This will define a global variable called `name` which is a string
1245 made of joining the slices and lines you specify (n1,n2,... numbers
1260 made of joining the slices and lines you specify (n1,n2,... numbers
1246 above) from your input history into a single string. This variable
1261 above) from your input history into a single string. This variable
1247 acts like an automatic function which re-executes those lines as if
1262 acts like an automatic function which re-executes those lines as if
1248 you had typed them. You just type 'name' at the prompt and the code
1263 you had typed them. You just type 'name' at the prompt and the code
1249 executes.
1264 executes.
1250
1265
1251 The syntax for indicating input ranges is described in %history.
1266 The syntax for indicating input ranges is described in %history.
1252
1267
1253 Note: as a 'hidden' feature, you can also use traditional python slice
1268 Note: as a 'hidden' feature, you can also use traditional python slice
1254 notation, where N:M means numbers N through M-1.
1269 notation, where N:M means numbers N through M-1.
1255
1270
1256 For example, if your history contains (print using %hist -n )::
1271 For example, if your history contains (print using %hist -n )::
1257
1272
1258 44: x=1
1273 44: x=1
1259 45: y=3
1274 45: y=3
1260 46: z=x+y
1275 46: z=x+y
1261 47: print x
1276 47: print x
1262 48: a=5
1277 48: a=5
1263 49: print 'x',x,'y',y
1278 49: print 'x',x,'y',y
1264
1279
1265 you can create a macro with lines 44 through 47 (included) and line 49
1280 you can create a macro with lines 44 through 47 (included) and line 49
1266 called my_macro with::
1281 called my_macro with::
1267
1282
1268 In [55]: %macro my_macro 44-47 49
1283 In [55]: %macro my_macro 44-47 49
1269
1284
1270 Now, typing `my_macro` (without quotes) will re-execute all this code
1285 Now, typing `my_macro` (without quotes) will re-execute all this code
1271 in one pass.
1286 in one pass.
1272
1287
1273 You don't need to give the line-numbers in order, and any given line
1288 You don't need to give the line-numbers in order, and any given line
1274 number can appear multiple times. You can assemble macros with any
1289 number can appear multiple times. You can assemble macros with any
1275 lines from your input history in any order.
1290 lines from your input history in any order.
1276
1291
1277 The macro is a simple object which holds its value in an attribute,
1292 The macro is a simple object which holds its value in an attribute,
1278 but IPython's display system checks for macros and executes them as
1293 but IPython's display system checks for macros and executes them as
1279 code instead of printing them when you type their name.
1294 code instead of printing them when you type their name.
1280
1295
1281 You can view a macro's contents by explicitly printing it with::
1296 You can view a macro's contents by explicitly printing it with::
1282
1297
1283 print macro_name
1298 print macro_name
1284
1299
1285 """
1300 """
1286 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1301 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1287 if not args: # List existing macros
1302 if not args: # List existing macros
1288 return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro))
1303 return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro))
1289 if len(args) == 1:
1304 if len(args) == 1:
1290 raise UsageError(
1305 raise UsageError(
1291 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1306 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1292 name, codefrom = args[0], " ".join(args[1:])
1307 name, codefrom = args[0], " ".join(args[1:])
1293
1308
1294 #print 'rng',ranges # dbg
1309 #print 'rng',ranges # dbg
1295 try:
1310 try:
1296 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1311 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1297 except (ValueError, TypeError) as e:
1312 except (ValueError, TypeError) as e:
1298 print(e.args[0])
1313 print(e.args[0])
1299 return
1314 return
1300 macro = Macro(lines)
1315 macro = Macro(lines)
1301 self.shell.define_macro(name, macro)
1316 self.shell.define_macro(name, macro)
1302 if not ( 'q' in opts) :
1317 if not ( 'q' in opts) :
1303 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1318 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1304 print('=== Macro contents: ===')
1319 print('=== Macro contents: ===')
1305 print(macro, end=' ')
1320 print(macro, end=' ')
1306
1321
1307 @magic_arguments.magic_arguments()
1322 @magic_arguments.magic_arguments()
1308 @magic_arguments.argument('output', type=str, default='', nargs='?',
1323 @magic_arguments.argument('output', type=str, default='', nargs='?',
1309 help="""The name of the variable in which to store output.
1324 help="""The name of the variable in which to store output.
1310 This is a utils.io.CapturedIO object with stdout/err attributes
1325 This is a utils.io.CapturedIO object with stdout/err attributes
1311 for the text of the captured output.
1326 for the text of the captured output.
1312
1327
1313 CapturedOutput also has a show() method for displaying the output,
1328 CapturedOutput also has a show() method for displaying the output,
1314 and __call__ as well, so you can use that to quickly display the
1329 and __call__ as well, so you can use that to quickly display the
1315 output.
1330 output.
1316
1331
1317 If unspecified, captured output is discarded.
1332 If unspecified, captured output is discarded.
1318 """
1333 """
1319 )
1334 )
1320 @magic_arguments.argument('--no-stderr', action="store_true",
1335 @magic_arguments.argument('--no-stderr', action="store_true",
1321 help="""Don't capture stderr."""
1336 help="""Don't capture stderr."""
1322 )
1337 )
1323 @magic_arguments.argument('--no-stdout', action="store_true",
1338 @magic_arguments.argument('--no-stdout', action="store_true",
1324 help="""Don't capture stdout."""
1339 help="""Don't capture stdout."""
1325 )
1340 )
1326 @magic_arguments.argument('--no-display', action="store_true",
1341 @magic_arguments.argument('--no-display', action="store_true",
1327 help="""Don't capture IPython's rich display."""
1342 help="""Don't capture IPython's rich display."""
1328 )
1343 )
1329 @cell_magic
1344 @cell_magic
1330 def capture(self, line, cell):
1345 def capture(self, line, cell):
1331 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1346 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1332 args = magic_arguments.parse_argstring(self.capture, line)
1347 args = magic_arguments.parse_argstring(self.capture, line)
1333 out = not args.no_stdout
1348 out = not args.no_stdout
1334 err = not args.no_stderr
1349 err = not args.no_stderr
1335 disp = not args.no_display
1350 disp = not args.no_display
1336 with capture_output(out, err, disp) as io:
1351 with capture_output(out, err, disp) as io:
1337 self.shell.run_cell(cell)
1352 self.shell.run_cell(cell)
1338 if args.output:
1353 if args.output:
1339 self.shell.user_ns[args.output] = io
1354 self.shell.user_ns[args.output] = io
1340
1355
1341 def parse_breakpoint(text, current_file):
1356 def parse_breakpoint(text, current_file):
1342 '''Returns (file, line) for file:line and (current_file, line) for line'''
1357 '''Returns (file, line) for file:line and (current_file, line) for line'''
1343 colon = text.find(':')
1358 colon = text.find(':')
1344 if colon == -1:
1359 if colon == -1:
1345 return current_file, int(text)
1360 return current_file, int(text)
1346 else:
1361 else:
1347 return text[:colon], int(text[colon+1:])
1362 return text[:colon], int(text[colon+1:])
1348
1363
1349 def _format_time(timespan, precision=3):
1364 def _format_time(timespan, precision=3):
1350 """Formats the timespan in a human readable form"""
1365 """Formats the timespan in a human readable form"""
1351
1366
1352 if timespan >= 60.0:
1367 if timespan >= 60.0:
1353 # we have more than a minute, format that in a human readable form
1368 # we have more than a minute, format that in a human readable form
1354 # Idea from http://snipplr.com/view/5713/
1369 # Idea from http://snipplr.com/view/5713/
1355 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1370 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1356 time = []
1371 time = []
1357 leftover = timespan
1372 leftover = timespan
1358 for suffix, length in parts:
1373 for suffix, length in parts:
1359 value = int(leftover / length)
1374 value = int(leftover / length)
1360 if value > 0:
1375 if value > 0:
1361 leftover = leftover % length
1376 leftover = leftover % length
1362 time.append(u'%s%s' % (str(value), suffix))
1377 time.append(u'%s%s' % (str(value), suffix))
1363 if leftover < 1:
1378 if leftover < 1:
1364 break
1379 break
1365 return " ".join(time)
1380 return " ".join(time)
1366
1381
1367
1382
1368 # Unfortunately the unicode 'micro' symbol can cause problems in
1383 # Unfortunately the unicode 'micro' symbol can cause problems in
1369 # certain terminals.
1384 # certain terminals.
1370 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1385 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1371 # Try to prevent crashes by being more secure than it needs to
1386 # Try to prevent crashes by being more secure than it needs to
1372 # E.g. eclipse is able to print a Β΅, but has no sys.stdout.encoding set.
1387 # E.g. eclipse is able to print a Β΅, but has no sys.stdout.encoding set.
1373 units = [u"s", u"ms",u'us',"ns"] # the save value
1388 units = [u"s", u"ms",u'us',"ns"] # the save value
1374 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1389 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1375 try:
1390 try:
1376 u'\xb5'.encode(sys.stdout.encoding)
1391 u'\xb5'.encode(sys.stdout.encoding)
1377 units = [u"s", u"ms",u'\xb5s',"ns"]
1392 units = [u"s", u"ms",u'\xb5s',"ns"]
1378 except:
1393 except:
1379 pass
1394 pass
1380 scaling = [1, 1e3, 1e6, 1e9]
1395 scaling = [1, 1e3, 1e6, 1e9]
1381
1396
1382 if timespan > 0.0:
1397 if timespan > 0.0:
1383 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1398 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1384 else:
1399 else:
1385 order = 3
1400 order = 3
1386 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
1401 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
@@ -1,514 +1,537 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Tests for code execution (%run and related), which is particularly tricky.
2 """Tests for code execution (%run and related), which is particularly tricky.
3
3
4 Because of how %run manages namespaces, and the fact that we are trying here to
4 Because of how %run manages namespaces, and the fact that we are trying here to
5 verify subtle object deletion and reference counting issues, the %run tests
5 verify subtle object deletion and reference counting issues, the %run tests
6 will be kept in this separate file. This makes it easier to aggregate in one
6 will be kept in this separate file. This makes it easier to aggregate in one
7 place the tricks needed to handle it; most other magics are much easier to test
7 place the tricks needed to handle it; most other magics are much easier to test
8 and we do so in a common test_magic file.
8 and we do so in a common test_magic file.
9 """
9 """
10
10
11 # Copyright (c) IPython Development Team.
11 # Copyright (c) IPython Development Team.
12 # Distributed under the terms of the Modified BSD License.
12 # Distributed under the terms of the Modified BSD License.
13
13
14
14
15
15
16 import functools
16 import functools
17 import os
17 import os
18 from os.path import join as pjoin
18 from os.path import join as pjoin
19 import random
19 import random
20 import sys
20 import sys
21 import textwrap
21 import textwrap
22 import unittest
22 import unittest
23 from unittest.mock import patch
23 from unittest.mock import patch
24
24
25 import nose.tools as nt
25 import nose.tools as nt
26 from nose import SkipTest
26 from nose import SkipTest
27
27
28 from IPython.testing import decorators as dec
28 from IPython.testing import decorators as dec
29 from IPython.testing import tools as tt
29 from IPython.testing import tools as tt
30 from IPython.utils import py3compat
30 from IPython.utils import py3compat
31 from IPython.utils.io import capture_output
31 from IPython.utils.io import capture_output
32 from IPython.utils.tempdir import TemporaryDirectory
32 from IPython.utils.tempdir import TemporaryDirectory
33 from IPython.core import debugger
33 from IPython.core import debugger
34
34
35
35
36 def doctest_refbug():
36 def doctest_refbug():
37 """Very nasty problem with references held by multiple runs of a script.
37 """Very nasty problem with references held by multiple runs of a script.
38 See: https://github.com/ipython/ipython/issues/141
38 See: https://github.com/ipython/ipython/issues/141
39
39
40 In [1]: _ip.clear_main_mod_cache()
40 In [1]: _ip.clear_main_mod_cache()
41 # random
41 # random
42
42
43 In [2]: %run refbug
43 In [2]: %run refbug
44
44
45 In [3]: call_f()
45 In [3]: call_f()
46 lowercased: hello
46 lowercased: hello
47
47
48 In [4]: %run refbug
48 In [4]: %run refbug
49
49
50 In [5]: call_f()
50 In [5]: call_f()
51 lowercased: hello
51 lowercased: hello
52 lowercased: hello
52 lowercased: hello
53 """
53 """
54
54
55
55
56 def doctest_run_builtins():
56 def doctest_run_builtins():
57 r"""Check that %run doesn't damage __builtins__.
57 r"""Check that %run doesn't damage __builtins__.
58
58
59 In [1]: import tempfile
59 In [1]: import tempfile
60
60
61 In [2]: bid1 = id(__builtins__)
61 In [2]: bid1 = id(__builtins__)
62
62
63 In [3]: fname = tempfile.mkstemp('.py')[1]
63 In [3]: fname = tempfile.mkstemp('.py')[1]
64
64
65 In [3]: f = open(fname,'w')
65 In [3]: f = open(fname,'w')
66
66
67 In [4]: dummy= f.write('pass\n')
67 In [4]: dummy= f.write('pass\n')
68
68
69 In [5]: f.flush()
69 In [5]: f.flush()
70
70
71 In [6]: t1 = type(__builtins__)
71 In [6]: t1 = type(__builtins__)
72
72
73 In [7]: %run $fname
73 In [7]: %run $fname
74
74
75 In [7]: f.close()
75 In [7]: f.close()
76
76
77 In [8]: bid2 = id(__builtins__)
77 In [8]: bid2 = id(__builtins__)
78
78
79 In [9]: t2 = type(__builtins__)
79 In [9]: t2 = type(__builtins__)
80
80
81 In [10]: t1 == t2
81 In [10]: t1 == t2
82 Out[10]: True
82 Out[10]: True
83
83
84 In [10]: bid1 == bid2
84 In [10]: bid1 == bid2
85 Out[10]: True
85 Out[10]: True
86
86
87 In [12]: try:
87 In [12]: try:
88 ....: os.unlink(fname)
88 ....: os.unlink(fname)
89 ....: except:
89 ....: except:
90 ....: pass
90 ....: pass
91 ....:
91 ....:
92 """
92 """
93
93
94
94
95 def doctest_run_option_parser():
95 def doctest_run_option_parser():
96 r"""Test option parser in %run.
96 r"""Test option parser in %run.
97
97
98 In [1]: %run print_argv.py
98 In [1]: %run print_argv.py
99 []
99 []
100
100
101 In [2]: %run print_argv.py print*.py
101 In [2]: %run print_argv.py print*.py
102 ['print_argv.py']
102 ['print_argv.py']
103
103
104 In [3]: %run -G print_argv.py print*.py
104 In [3]: %run -G print_argv.py print*.py
105 ['print*.py']
105 ['print*.py']
106
106
107 """
107 """
108
108
109
109
110 @dec.skip_win32
110 @dec.skip_win32
111 def doctest_run_option_parser_for_posix():
111 def doctest_run_option_parser_for_posix():
112 r"""Test option parser in %run (Linux/OSX specific).
112 r"""Test option parser in %run (Linux/OSX specific).
113
113
114 You need double quote to escape glob in POSIX systems:
114 You need double quote to escape glob in POSIX systems:
115
115
116 In [1]: %run print_argv.py print\\*.py
116 In [1]: %run print_argv.py print\\*.py
117 ['print*.py']
117 ['print*.py']
118
118
119 You can't use quote to escape glob in POSIX systems:
119 You can't use quote to escape glob in POSIX systems:
120
120
121 In [2]: %run print_argv.py 'print*.py'
121 In [2]: %run print_argv.py 'print*.py'
122 ['print_argv.py']
122 ['print_argv.py']
123
123
124 """
124 """
125
125
126
126
127 @dec.skip_if_not_win32
127 @dec.skip_if_not_win32
128 def doctest_run_option_parser_for_windows():
128 def doctest_run_option_parser_for_windows():
129 r"""Test option parser in %run (Windows specific).
129 r"""Test option parser in %run (Windows specific).
130
130
131 In Windows, you can't escape ``*` `by backslash:
131 In Windows, you can't escape ``*` `by backslash:
132
132
133 In [1]: %run print_argv.py print\\*.py
133 In [1]: %run print_argv.py print\\*.py
134 ['print\\*.py']
134 ['print\\*.py']
135
135
136 You can use quote to escape glob:
136 You can use quote to escape glob:
137
137
138 In [2]: %run print_argv.py 'print*.py'
138 In [2]: %run print_argv.py 'print*.py'
139 ['print*.py']
139 ['print*.py']
140
140
141 """
141 """
142
142
143
143
144 @py3compat.doctest_refactor_print
144 @py3compat.doctest_refactor_print
145 def doctest_reset_del():
145 def doctest_reset_del():
146 """Test that resetting doesn't cause errors in __del__ methods.
146 """Test that resetting doesn't cause errors in __del__ methods.
147
147
148 In [2]: class A(object):
148 In [2]: class A(object):
149 ...: def __del__(self):
149 ...: def __del__(self):
150 ...: print str("Hi")
150 ...: print str("Hi")
151 ...:
151 ...:
152
152
153 In [3]: a = A()
153 In [3]: a = A()
154
154
155 In [4]: get_ipython().reset()
155 In [4]: get_ipython().reset()
156 Hi
156 Hi
157
157
158 In [5]: 1+1
158 In [5]: 1+1
159 Out[5]: 2
159 Out[5]: 2
160 """
160 """
161
161
162 # For some tests, it will be handy to organize them in a class with a common
162 # For some tests, it will be handy to organize them in a class with a common
163 # setup that makes a temp file
163 # setup that makes a temp file
164
164
165 class TestMagicRunPass(tt.TempFileMixin):
165 class TestMagicRunPass(tt.TempFileMixin):
166
166
167 def setup(self):
167 def setup(self):
168 """Make a valid python temp file."""
168 """Make a valid python temp file."""
169 self.mktmp('pass\n')
169 self.mktmp('pass\n')
170
170
171 def run_tmpfile(self):
171 def run_tmpfile(self):
172 _ip = get_ipython()
172 _ip = get_ipython()
173 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
173 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
174 # See below and ticket https://bugs.launchpad.net/bugs/366353
174 # See below and ticket https://bugs.launchpad.net/bugs/366353
175 _ip.magic('run %s' % self.fname)
175 _ip.magic('run %s' % self.fname)
176
176
177 def run_tmpfile_p(self):
177 def run_tmpfile_p(self):
178 _ip = get_ipython()
178 _ip = get_ipython()
179 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
179 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
180 # See below and ticket https://bugs.launchpad.net/bugs/366353
180 # See below and ticket https://bugs.launchpad.net/bugs/366353
181 _ip.magic('run -p %s' % self.fname)
181 _ip.magic('run -p %s' % self.fname)
182
182
183 def test_builtins_id(self):
183 def test_builtins_id(self):
184 """Check that %run doesn't damage __builtins__ """
184 """Check that %run doesn't damage __builtins__ """
185 _ip = get_ipython()
185 _ip = get_ipython()
186 # Test that the id of __builtins__ is not modified by %run
186 # Test that the id of __builtins__ is not modified by %run
187 bid1 = id(_ip.user_ns['__builtins__'])
187 bid1 = id(_ip.user_ns['__builtins__'])
188 self.run_tmpfile()
188 self.run_tmpfile()
189 bid2 = id(_ip.user_ns['__builtins__'])
189 bid2 = id(_ip.user_ns['__builtins__'])
190 nt.assert_equal(bid1, bid2)
190 nt.assert_equal(bid1, bid2)
191
191
192 def test_builtins_type(self):
192 def test_builtins_type(self):
193 """Check that the type of __builtins__ doesn't change with %run.
193 """Check that the type of __builtins__ doesn't change with %run.
194
194
195 However, the above could pass if __builtins__ was already modified to
195 However, the above could pass if __builtins__ was already modified to
196 be a dict (it should be a module) by a previous use of %run. So we
196 be a dict (it should be a module) by a previous use of %run. So we
197 also check explicitly that it really is a module:
197 also check explicitly that it really is a module:
198 """
198 """
199 _ip = get_ipython()
199 _ip = get_ipython()
200 self.run_tmpfile()
200 self.run_tmpfile()
201 nt.assert_equal(type(_ip.user_ns['__builtins__']),type(sys))
201 nt.assert_equal(type(_ip.user_ns['__builtins__']),type(sys))
202
202
203 def test_run_profile( self ):
203 def test_run_profile( self ):
204 """Test that the option -p, which invokes the profiler, do not
204 """Test that the option -p, which invokes the profiler, do not
205 crash by invoking execfile"""
205 crash by invoking execfile"""
206 self.run_tmpfile_p()
206 self.run_tmpfile_p()
207
207
208 def test_run_debug_twice(self):
208 def test_run_debug_twice(self):
209 # https://github.com/ipython/ipython/issues/10028
209 # https://github.com/ipython/ipython/issues/10028
210 _ip = get_ipython()
210 _ip = get_ipython()
211 with tt.fake_input(['c']):
211 with tt.fake_input(['c']):
212 _ip.magic('run -d %s' % self.fname)
212 _ip.magic('run -d %s' % self.fname)
213 with tt.fake_input(['c']):
213 with tt.fake_input(['c']):
214 _ip.magic('run -d %s' % self.fname)
214 _ip.magic('run -d %s' % self.fname)
215
215
216
216
217 class TestMagicRunSimple(tt.TempFileMixin):
217 class TestMagicRunSimple(tt.TempFileMixin):
218
218
219 def test_simpledef(self):
219 def test_simpledef(self):
220 """Test that simple class definitions work."""
220 """Test that simple class definitions work."""
221 src = ("class foo: pass\n"
221 src = ("class foo: pass\n"
222 "def f(): return foo()")
222 "def f(): return foo()")
223 self.mktmp(src)
223 self.mktmp(src)
224 _ip.magic('run %s' % self.fname)
224 _ip.magic('run %s' % self.fname)
225 _ip.run_cell('t = isinstance(f(), foo)')
225 _ip.run_cell('t = isinstance(f(), foo)')
226 nt.assert_true(_ip.user_ns['t'])
226 nt.assert_true(_ip.user_ns['t'])
227
227
228 def test_obj_del(self):
228 def test_obj_del(self):
229 """Test that object's __del__ methods are called on exit."""
229 """Test that object's __del__ methods are called on exit."""
230 if sys.platform == 'win32':
230 if sys.platform == 'win32':
231 try:
231 try:
232 import win32api
232 import win32api
233 except ImportError:
233 except ImportError:
234 raise SkipTest("Test requires pywin32")
234 raise SkipTest("Test requires pywin32")
235 src = ("class A(object):\n"
235 src = ("class A(object):\n"
236 " def __del__(self):\n"
236 " def __del__(self):\n"
237 " print 'object A deleted'\n"
237 " print 'object A deleted'\n"
238 "a = A()\n")
238 "a = A()\n")
239 self.mktmp(py3compat.doctest_refactor_print(src))
239 self.mktmp(py3compat.doctest_refactor_print(src))
240 if dec.module_not_available('sqlite3'):
240 if dec.module_not_available('sqlite3'):
241 err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
241 err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
242 else:
242 else:
243 err = None
243 err = None
244 tt.ipexec_validate(self.fname, 'object A deleted', err)
244 tt.ipexec_validate(self.fname, 'object A deleted', err)
245
245
246 def test_aggressive_namespace_cleanup(self):
246 def test_aggressive_namespace_cleanup(self):
247 """Test that namespace cleanup is not too aggressive GH-238
247 """Test that namespace cleanup is not too aggressive GH-238
248
248
249 Returning from another run magic deletes the namespace"""
249 Returning from another run magic deletes the namespace"""
250 # see ticket https://github.com/ipython/ipython/issues/238
250 # see ticket https://github.com/ipython/ipython/issues/238
251
251
252 with tt.TempFileMixin() as empty:
252 with tt.TempFileMixin() as empty:
253 empty.mktmp('')
253 empty.mktmp('')
254 # On Windows, the filename will have \users in it, so we need to use the
254 # On Windows, the filename will have \users in it, so we need to use the
255 # repr so that the \u becomes \\u.
255 # repr so that the \u becomes \\u.
256 src = ("ip = get_ipython()\n"
256 src = ("ip = get_ipython()\n"
257 "for i in range(5):\n"
257 "for i in range(5):\n"
258 " try:\n"
258 " try:\n"
259 " ip.magic(%r)\n"
259 " ip.magic(%r)\n"
260 " except NameError as e:\n"
260 " except NameError as e:\n"
261 " print(i)\n"
261 " print(i)\n"
262 " break\n" % ('run ' + empty.fname))
262 " break\n" % ('run ' + empty.fname))
263 self.mktmp(src)
263 self.mktmp(src)
264 _ip.magic('run %s' % self.fname)
264 _ip.magic('run %s' % self.fname)
265 _ip.run_cell('ip == get_ipython()')
265 _ip.run_cell('ip == get_ipython()')
266 nt.assert_equal(_ip.user_ns['i'], 4)
266 nt.assert_equal(_ip.user_ns['i'], 4)
267
267
268 def test_run_second(self):
268 def test_run_second(self):
269 """Test that running a second file doesn't clobber the first, gh-3547
269 """Test that running a second file doesn't clobber the first, gh-3547
270 """
270 """
271 self.mktmp("avar = 1\n"
271 self.mktmp("avar = 1\n"
272 "def afunc():\n"
272 "def afunc():\n"
273 " return avar\n")
273 " return avar\n")
274
274
275 with tt.TempFileMixin() as empty:
275 with tt.TempFileMixin() as empty:
276 empty.mktmp("")
276 empty.mktmp("")
277
277
278 _ip.magic('run %s' % self.fname)
278 _ip.magic('run %s' % self.fname)
279 _ip.magic('run %s' % empty.fname)
279 _ip.magic('run %s' % empty.fname)
280 nt.assert_equal(_ip.user_ns['afunc'](), 1)
280 nt.assert_equal(_ip.user_ns['afunc'](), 1)
281
281
282 @dec.skip_win32
282 @dec.skip_win32
283 def test_tclass(self):
283 def test_tclass(self):
284 mydir = os.path.dirname(__file__)
284 mydir = os.path.dirname(__file__)
285 tc = os.path.join(mydir, 'tclass')
285 tc = os.path.join(mydir, 'tclass')
286 src = ("%%run '%s' C-first\n"
286 src = ("%%run '%s' C-first\n"
287 "%%run '%s' C-second\n"
287 "%%run '%s' C-second\n"
288 "%%run '%s' C-third\n") % (tc, tc, tc)
288 "%%run '%s' C-third\n") % (tc, tc, tc)
289 self.mktmp(src, '.ipy')
289 self.mktmp(src, '.ipy')
290 out = """\
290 out = """\
291 ARGV 1-: ['C-first']
291 ARGV 1-: ['C-first']
292 ARGV 1-: ['C-second']
292 ARGV 1-: ['C-second']
293 tclass.py: deleting object: C-first
293 tclass.py: deleting object: C-first
294 ARGV 1-: ['C-third']
294 ARGV 1-: ['C-third']
295 tclass.py: deleting object: C-second
295 tclass.py: deleting object: C-second
296 tclass.py: deleting object: C-third
296 tclass.py: deleting object: C-third
297 """
297 """
298 if dec.module_not_available('sqlite3'):
298 if dec.module_not_available('sqlite3'):
299 err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
299 err = 'WARNING: IPython History requires SQLite, your history will not be saved\n'
300 else:
300 else:
301 err = None
301 err = None
302 tt.ipexec_validate(self.fname, out, err)
302 tt.ipexec_validate(self.fname, out, err)
303
303
304 def test_run_i_after_reset(self):
304 def test_run_i_after_reset(self):
305 """Check that %run -i still works after %reset (gh-693)"""
305 """Check that %run -i still works after %reset (gh-693)"""
306 src = "yy = zz\n"
306 src = "yy = zz\n"
307 self.mktmp(src)
307 self.mktmp(src)
308 _ip.run_cell("zz = 23")
308 _ip.run_cell("zz = 23")
309 _ip.magic('run -i %s' % self.fname)
309 _ip.magic('run -i %s' % self.fname)
310 nt.assert_equal(_ip.user_ns['yy'], 23)
310 nt.assert_equal(_ip.user_ns['yy'], 23)
311 _ip.magic('reset -f')
311 _ip.magic('reset -f')
312 _ip.run_cell("zz = 23")
312 _ip.run_cell("zz = 23")
313 _ip.magic('run -i %s' % self.fname)
313 _ip.magic('run -i %s' % self.fname)
314 nt.assert_equal(_ip.user_ns['yy'], 23)
314 nt.assert_equal(_ip.user_ns['yy'], 23)
315
315
316 def test_unicode(self):
316 def test_unicode(self):
317 """Check that files in odd encodings are accepted."""
317 """Check that files in odd encodings are accepted."""
318 mydir = os.path.dirname(__file__)
318 mydir = os.path.dirname(__file__)
319 na = os.path.join(mydir, 'nonascii.py')
319 na = os.path.join(mydir, 'nonascii.py')
320 _ip.magic('run "%s"' % na)
320 _ip.magic('run "%s"' % na)
321 nt.assert_equal(_ip.user_ns['u'], u'ΠŽΡ‚β„–Π€')
321 nt.assert_equal(_ip.user_ns['u'], u'ΠŽΡ‚β„–Π€')
322
322
323 def test_run_py_file_attribute(self):
323 def test_run_py_file_attribute(self):
324 """Test handling of `__file__` attribute in `%run <file>.py`."""
324 """Test handling of `__file__` attribute in `%run <file>.py`."""
325 src = "t = __file__\n"
325 src = "t = __file__\n"
326 self.mktmp(src)
326 self.mktmp(src)
327 _missing = object()
327 _missing = object()
328 file1 = _ip.user_ns.get('__file__', _missing)
328 file1 = _ip.user_ns.get('__file__', _missing)
329 _ip.magic('run %s' % self.fname)
329 _ip.magic('run %s' % self.fname)
330 file2 = _ip.user_ns.get('__file__', _missing)
330 file2 = _ip.user_ns.get('__file__', _missing)
331
331
332 # Check that __file__ was equal to the filename in the script's
332 # Check that __file__ was equal to the filename in the script's
333 # namespace.
333 # namespace.
334 nt.assert_equal(_ip.user_ns['t'], self.fname)
334 nt.assert_equal(_ip.user_ns['t'], self.fname)
335
335
336 # Check that __file__ was not leaked back into user_ns.
336 # Check that __file__ was not leaked back into user_ns.
337 nt.assert_equal(file1, file2)
337 nt.assert_equal(file1, file2)
338
338
339 def test_run_ipy_file_attribute(self):
339 def test_run_ipy_file_attribute(self):
340 """Test handling of `__file__` attribute in `%run <file.ipy>`."""
340 """Test handling of `__file__` attribute in `%run <file.ipy>`."""
341 src = "t = __file__\n"
341 src = "t = __file__\n"
342 self.mktmp(src, ext='.ipy')
342 self.mktmp(src, ext='.ipy')
343 _missing = object()
343 _missing = object()
344 file1 = _ip.user_ns.get('__file__', _missing)
344 file1 = _ip.user_ns.get('__file__', _missing)
345 _ip.magic('run %s' % self.fname)
345 _ip.magic('run %s' % self.fname)
346 file2 = _ip.user_ns.get('__file__', _missing)
346 file2 = _ip.user_ns.get('__file__', _missing)
347
347
348 # Check that __file__ was equal to the filename in the script's
348 # Check that __file__ was equal to the filename in the script's
349 # namespace.
349 # namespace.
350 nt.assert_equal(_ip.user_ns['t'], self.fname)
350 nt.assert_equal(_ip.user_ns['t'], self.fname)
351
351
352 # Check that __file__ was not leaked back into user_ns.
352 # Check that __file__ was not leaked back into user_ns.
353 nt.assert_equal(file1, file2)
353 nt.assert_equal(file1, file2)
354
354
355 def test_run_formatting(self):
355 def test_run_formatting(self):
356 """ Test that %run -t -N<N> does not raise a TypeError for N > 1."""
356 """ Test that %run -t -N<N> does not raise a TypeError for N > 1."""
357 src = "pass"
357 src = "pass"
358 self.mktmp(src)
358 self.mktmp(src)
359 _ip.magic('run -t -N 1 %s' % self.fname)
359 _ip.magic('run -t -N 1 %s' % self.fname)
360 _ip.magic('run -t -N 10 %s' % self.fname)
360 _ip.magic('run -t -N 10 %s' % self.fname)
361
361
362 def test_ignore_sys_exit(self):
362 def test_ignore_sys_exit(self):
363 """Test the -e option to ignore sys.exit()"""
363 """Test the -e option to ignore sys.exit()"""
364 src = "import sys; sys.exit(1)"
364 src = "import sys; sys.exit(1)"
365 self.mktmp(src)
365 self.mktmp(src)
366 with tt.AssertPrints('SystemExit'):
366 with tt.AssertPrints('SystemExit'):
367 _ip.magic('run %s' % self.fname)
367 _ip.magic('run %s' % self.fname)
368
368
369 with tt.AssertNotPrints('SystemExit'):
369 with tt.AssertNotPrints('SystemExit'):
370 _ip.magic('run -e %s' % self.fname)
370 _ip.magic('run -e %s' % self.fname)
371
371
372 def test_run_nb(self):
372 def test_run_nb(self):
373 """Test %run notebook.ipynb"""
373 """Test %run notebook.ipynb"""
374 from nbformat import v4, writes
374 from nbformat import v4, writes
375 nb = v4.new_notebook(
375 nb = v4.new_notebook(
376 cells=[
376 cells=[
377 v4.new_markdown_cell("The Ultimate Question of Everything"),
377 v4.new_markdown_cell("The Ultimate Question of Everything"),
378 v4.new_code_cell("answer=42")
378 v4.new_code_cell("answer=42")
379 ]
379 ]
380 )
380 )
381 src = writes(nb, version=4)
381 src = writes(nb, version=4)
382 self.mktmp(src, ext='.ipynb')
382 self.mktmp(src, ext='.ipynb')
383
383
384 _ip.magic("run %s" % self.fname)
384 _ip.magic("run %s" % self.fname)
385
385
386 nt.assert_equal(_ip.user_ns['answer'], 42)
386 nt.assert_equal(_ip.user_ns['answer'], 42)
387
387
388 def test_file_options(self):
389 src = ('import sys\n'
390 'a = " ".join(sys.argv[1:])\n')
391 self.mktmp(src)
392 test_opts = '-x 3 --verbose'
393 _ip.run_line_magic("run", '{0} {1}'.format(self.fname, test_opts))
394 nt.assert_equal(_ip.user_ns['a'], test_opts)
388
395
389
396
390 class TestMagicRunWithPackage(unittest.TestCase):
397 class TestMagicRunWithPackage(unittest.TestCase):
391
398
392 def writefile(self, name, content):
399 def writefile(self, name, content):
393 path = os.path.join(self.tempdir.name, name)
400 path = os.path.join(self.tempdir.name, name)
394 d = os.path.dirname(path)
401 d = os.path.dirname(path)
395 if not os.path.isdir(d):
402 if not os.path.isdir(d):
396 os.makedirs(d)
403 os.makedirs(d)
397 with open(path, 'w') as f:
404 with open(path, 'w') as f:
398 f.write(textwrap.dedent(content))
405 f.write(textwrap.dedent(content))
399
406
400 def setUp(self):
407 def setUp(self):
401 self.package = package = 'tmp{0}'.format(repr(random.random())[2:])
408 self.package = package = 'tmp{0}'.format(repr(random.random())[2:])
402 """Temporary valid python package name."""
409 """Temporary valid python package name."""
403
410
404 self.value = int(random.random() * 10000)
411 self.value = int(random.random() * 10000)
405
412
406 self.tempdir = TemporaryDirectory()
413 self.tempdir = TemporaryDirectory()
407 self.__orig_cwd = os.getcwd()
414 self.__orig_cwd = os.getcwd()
408 sys.path.insert(0, self.tempdir.name)
415 sys.path.insert(0, self.tempdir.name)
409
416
410 self.writefile(os.path.join(package, '__init__.py'), '')
417 self.writefile(os.path.join(package, '__init__.py'), '')
411 self.writefile(os.path.join(package, 'sub.py'), """
418 self.writefile(os.path.join(package, 'sub.py'), """
412 x = {0!r}
419 x = {0!r}
413 """.format(self.value))
420 """.format(self.value))
414 self.writefile(os.path.join(package, 'relative.py'), """
421 self.writefile(os.path.join(package, 'relative.py'), """
415 from .sub import x
422 from .sub import x
416 """)
423 """)
417 self.writefile(os.path.join(package, 'absolute.py'), """
424 self.writefile(os.path.join(package, 'absolute.py'), """
418 from {0}.sub import x
425 from {0}.sub import x
419 """.format(package))
426 """.format(package))
427 self.writefile(os.path.join(package, 'args.py'), """
428 import sys
429 a = " ".join(sys.argv[1:])
430 """.format(package))
420
431
421 def tearDown(self):
432 def tearDown(self):
422 os.chdir(self.__orig_cwd)
433 os.chdir(self.__orig_cwd)
423 sys.path[:] = [p for p in sys.path if p != self.tempdir.name]
434 sys.path[:] = [p for p in sys.path if p != self.tempdir.name]
424 self.tempdir.cleanup()
435 self.tempdir.cleanup()
425
436
426 def check_run_submodule(self, submodule, opts=''):
437 def check_run_submodule(self, submodule, opts=''):
427 _ip.user_ns.pop('x', None)
438 _ip.user_ns.pop('x', None)
428 _ip.magic('run {2} -m {0}.{1}'.format(self.package, submodule, opts))
439 _ip.magic('run {2} -m {0}.{1}'.format(self.package, submodule, opts))
429 self.assertEqual(_ip.user_ns['x'], self.value,
440 self.assertEqual(_ip.user_ns['x'], self.value,
430 'Variable `x` is not loaded from module `{0}`.'
441 'Variable `x` is not loaded from module `{0}`.'
431 .format(submodule))
442 .format(submodule))
432
443
433 def test_run_submodule_with_absolute_import(self):
444 def test_run_submodule_with_absolute_import(self):
434 self.check_run_submodule('absolute')
445 self.check_run_submodule('absolute')
435
446
436 def test_run_submodule_with_relative_import(self):
447 def test_run_submodule_with_relative_import(self):
437 """Run submodule that has a relative import statement (#2727)."""
448 """Run submodule that has a relative import statement (#2727)."""
438 self.check_run_submodule('relative')
449 self.check_run_submodule('relative')
439
450
440 def test_prun_submodule_with_absolute_import(self):
451 def test_prun_submodule_with_absolute_import(self):
441 self.check_run_submodule('absolute', '-p')
452 self.check_run_submodule('absolute', '-p')
442
453
443 def test_prun_submodule_with_relative_import(self):
454 def test_prun_submodule_with_relative_import(self):
444 self.check_run_submodule('relative', '-p')
455 self.check_run_submodule('relative', '-p')
445
456
446 def with_fake_debugger(func):
457 def with_fake_debugger(func):
447 @functools.wraps(func)
458 @functools.wraps(func)
448 def wrapper(*args, **kwds):
459 def wrapper(*args, **kwds):
449 with patch.object(debugger.Pdb, 'run', staticmethod(eval)):
460 with patch.object(debugger.Pdb, 'run', staticmethod(eval)):
450 return func(*args, **kwds)
461 return func(*args, **kwds)
451 return wrapper
462 return wrapper
452
463
453 @with_fake_debugger
464 @with_fake_debugger
454 def test_debug_run_submodule_with_absolute_import(self):
465 def test_debug_run_submodule_with_absolute_import(self):
455 self.check_run_submodule('absolute', '-d')
466 self.check_run_submodule('absolute', '-d')
456
467
457 @with_fake_debugger
468 @with_fake_debugger
458 def test_debug_run_submodule_with_relative_import(self):
469 def test_debug_run_submodule_with_relative_import(self):
459 self.check_run_submodule('relative', '-d')
470 self.check_run_submodule('relative', '-d')
460
471
472 def test_module_options(self):
473 _ip.user_ns.pop('a', None)
474 test_opts = '-x abc -m test'
475 _ip.run_line_magic('run', '-m {0}.args {1}'.format(self.package, test_opts))
476 nt.assert_equal(_ip.user_ns['a'], test_opts)
477
478 def test_module_options_with_separator(self):
479 _ip.user_ns.pop('a', None)
480 test_opts = '-x abc -m test'
481 _ip.run_line_magic('run', '-m {0}.args -- {1}'.format(self.package, test_opts))
482 nt.assert_equal(_ip.user_ns['a'], test_opts)
483
461 def test_run__name__():
484 def test_run__name__():
462 with TemporaryDirectory() as td:
485 with TemporaryDirectory() as td:
463 path = pjoin(td, 'foo.py')
486 path = pjoin(td, 'foo.py')
464 with open(path, 'w') as f:
487 with open(path, 'w') as f:
465 f.write("q = __name__")
488 f.write("q = __name__")
466
489
467 _ip.user_ns.pop('q', None)
490 _ip.user_ns.pop('q', None)
468 _ip.magic('run {}'.format(path))
491 _ip.magic('run {}'.format(path))
469 nt.assert_equal(_ip.user_ns.pop('q'), '__main__')
492 nt.assert_equal(_ip.user_ns.pop('q'), '__main__')
470
493
471 _ip.magic('run -n {}'.format(path))
494 _ip.magic('run -n {}'.format(path))
472 nt.assert_equal(_ip.user_ns.pop('q'), 'foo')
495 nt.assert_equal(_ip.user_ns.pop('q'), 'foo')
473
496
474 _ip.magic('run -i -n {}'.format(path))
497 _ip.magic('run -i -n {}'.format(path))
475 nt.assert_equal(_ip.user_ns.pop('q'), 'foo')
498 nt.assert_equal(_ip.user_ns.pop('q'), 'foo')
476
499
477
500
478 def test_run_tb():
501 def test_run_tb():
479 """Test traceback offset in %run"""
502 """Test traceback offset in %run"""
480 with TemporaryDirectory() as td:
503 with TemporaryDirectory() as td:
481 path = pjoin(td, 'foo.py')
504 path = pjoin(td, 'foo.py')
482 with open(path, 'w') as f:
505 with open(path, 'w') as f:
483 f.write('\n'.join([
506 f.write('\n'.join([
484 "def foo():",
507 "def foo():",
485 " return bar()",
508 " return bar()",
486 "def bar():",
509 "def bar():",
487 " raise RuntimeError('hello!')",
510 " raise RuntimeError('hello!')",
488 "foo()",
511 "foo()",
489 ]))
512 ]))
490 with capture_output() as io:
513 with capture_output() as io:
491 _ip.magic('run {}'.format(path))
514 _ip.magic('run {}'.format(path))
492 out = io.stdout
515 out = io.stdout
493 nt.assert_not_in("execfile", out)
516 nt.assert_not_in("execfile", out)
494 nt.assert_in("RuntimeError", out)
517 nt.assert_in("RuntimeError", out)
495 nt.assert_equal(out.count("---->"), 3)
518 nt.assert_equal(out.count("---->"), 3)
496
519
497 @dec.knownfailureif(sys.platform == 'win32', "writes to io.stdout aren't captured on Windows")
520 @dec.knownfailureif(sys.platform == 'win32', "writes to io.stdout aren't captured on Windows")
498 def test_script_tb():
521 def test_script_tb():
499 """Test traceback offset in `ipython script.py`"""
522 """Test traceback offset in `ipython script.py`"""
500 with TemporaryDirectory() as td:
523 with TemporaryDirectory() as td:
501 path = pjoin(td, 'foo.py')
524 path = pjoin(td, 'foo.py')
502 with open(path, 'w') as f:
525 with open(path, 'w') as f:
503 f.write('\n'.join([
526 f.write('\n'.join([
504 "def foo():",
527 "def foo():",
505 " return bar()",
528 " return bar()",
506 "def bar():",
529 "def bar():",
507 " raise RuntimeError('hello!')",
530 " raise RuntimeError('hello!')",
508 "foo()",
531 "foo()",
509 ]))
532 ]))
510 out, err = tt.ipexec(path)
533 out, err = tt.ipexec(path)
511 nt.assert_not_in("execfile", out)
534 nt.assert_not_in("execfile", out)
512 nt.assert_in("RuntimeError", out)
535 nt.assert_in("RuntimeError", out)
513 nt.assert_equal(out.count("---->"), 3)
536 nt.assert_equal(out.count("---->"), 3)
514
537
General Comments 0
You need to be logged in to leave comments. Login now