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