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