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