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