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