##// END OF EJS Templates
remove magic-specific empty cell warnings
Robert Marchman -
Show More
@@ -1,1097 +1,1094 b''
1 """Implementation of execution-related magic functions.
1 """Implementation of execution-related magic functions.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
4 # Copyright (c) 2012 The IPython Development Team.
5 #
5 #
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7 #
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 # Stdlib
15 # Stdlib
16 import __builtin__ as builtin_mod
16 import __builtin__ as builtin_mod
17 import 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.contexts import preserve_keys
45 from IPython.utils.contexts import preserve_keys
46 from IPython.utils.io import capture_output
46 from IPython.utils.io import capture_output
47 from IPython.utils.ipstruct import Struct
47 from IPython.utils.ipstruct import Struct
48 from IPython.utils.module_paths import find_mod
48 from IPython.utils.module_paths import find_mod
49 from IPython.utils.path import get_py_filename, unquote_filename, shellglob
49 from IPython.utils.path import get_py_filename, unquote_filename, shellglob
50 from IPython.utils.timing import clock, clock2
50 from IPython.utils.timing import clock, clock2
51 from IPython.utils.warn import warn, error
51 from IPython.utils.warn import warn, error
52
52
53
53
54 #-----------------------------------------------------------------------------
54 #-----------------------------------------------------------------------------
55 # Magic implementation classes
55 # Magic implementation classes
56 #-----------------------------------------------------------------------------
56 #-----------------------------------------------------------------------------
57
57
58 @magics_class
58 @magics_class
59 class ExecutionMagics(Magics):
59 class ExecutionMagics(Magics):
60 """Magics related to code execution, debugging, profiling, etc.
60 """Magics related to code execution, debugging, profiling, etc.
61
61
62 """
62 """
63
63
64 def __init__(self, shell):
64 def __init__(self, shell):
65 super(ExecutionMagics, self).__init__(shell)
65 super(ExecutionMagics, self).__init__(shell)
66 if profile is None:
66 if profile is None:
67 self.prun = self.profile_missing_notice
67 self.prun = self.profile_missing_notice
68 # Default execution function used to actually run user code.
68 # Default execution function used to actually run user code.
69 self.default_runner = None
69 self.default_runner = None
70
70
71 def profile_missing_notice(self, *args, **kwargs):
71 def profile_missing_notice(self, *args, **kwargs):
72 error("""\
72 error("""\
73 The profile module could not be found. It has been removed from the standard
73 The profile module could not be found. It has been removed from the standard
74 python packages because of its non-free license. To use profiling, install the
74 python packages because of its non-free license. To use profiling, install the
75 python-profiler package from non-free.""")
75 python-profiler package from non-free.""")
76
76
77 @skip_doctest
77 @skip_doctest
78 @line_cell_magic
78 @line_cell_magic
79 def prun(self, parameter_s='', cell=None, user_mode=True,
79 def prun(self, parameter_s='', cell=None, user_mode=True,
80 opts=None,arg_lst=None,prog_ns=None):
80 opts=None,arg_lst=None,prog_ns=None):
81
81
82 """Run a statement through the python code profiler.
82 """Run a statement through the python code profiler.
83
83
84 Usage, in line mode:
84 Usage, in line mode:
85 %prun [options] statement
85 %prun [options] statement
86
86
87 Usage, in cell mode:
87 Usage, in cell mode:
88 %%prun [options] [statement]
88 %%prun [options] [statement]
89 code...
89 code...
90 code...
90 code...
91
91
92 In cell mode, the additional code lines are appended to the (possibly
92 In cell mode, the additional code lines are appended to the (possibly
93 empty) statement in the first line. Cell mode allows you to easily
93 empty) statement in the first line. Cell mode allows you to easily
94 profile multiline blocks without having to put them in a separate
94 profile multiline blocks without having to put them in a separate
95 function.
95 function.
96
96
97 The given statement (which doesn't require quote marks) is run via the
97 The given statement (which doesn't require quote marks) is run via the
98 python profiler in a manner similar to the profile.run() function.
98 python profiler in a manner similar to the profile.run() function.
99 Namespaces are internally managed to work correctly; profile.run
99 Namespaces are internally managed to work correctly; profile.run
100 cannot be used in IPython because it makes certain assumptions about
100 cannot be used in IPython because it makes certain assumptions about
101 namespaces which do not hold under IPython.
101 namespaces which do not hold under IPython.
102
102
103 Options:
103 Options:
104
104
105 -l <limit>: you can place restrictions on what or how much of the
105 -l <limit>: you can place restrictions on what or how much of the
106 profile gets printed. The limit value can be:
106 profile gets printed. The limit value can be:
107
107
108 * A string: only information for function names containing this string
108 * A string: only information for function names containing this string
109 is printed.
109 is printed.
110
110
111 * An integer: only these many lines are printed.
111 * An integer: only these many lines are printed.
112
112
113 * A float (between 0 and 1): this fraction of the report is printed
113 * A float (between 0 and 1): this fraction of the report is printed
114 (for example, use a limit of 0.4 to see the topmost 40% only).
114 (for example, use a limit of 0.4 to see the topmost 40% only).
115
115
116 You can combine several limits with repeated use of the option. For
116 You can combine several limits with repeated use of the option. For
117 example, '-l __init__ -l 5' will print only the topmost 5 lines of
117 example, '-l __init__ -l 5' will print only the topmost 5 lines of
118 information about class constructors.
118 information about class constructors.
119
119
120 -r: return the pstats.Stats object generated by the profiling. This
120 -r: return the pstats.Stats object generated by the profiling. This
121 object has all the information about the profile in it, and you can
121 object has all the information about the profile in it, and you can
122 later use it for further analysis or in other functions.
122 later use it for further analysis or in other functions.
123
123
124 -s <key>: sort profile by given key. You can provide more than one key
124 -s <key>: sort profile by given key. You can provide more than one key
125 by using the option several times: '-s key1 -s key2 -s key3...'. The
125 by using the option several times: '-s key1 -s key2 -s key3...'. The
126 default sorting key is 'time'.
126 default sorting key is 'time'.
127
127
128 The following is copied verbatim from the profile documentation
128 The following is copied verbatim from the profile documentation
129 referenced below:
129 referenced below:
130
130
131 When more than one key is provided, additional keys are used as
131 When more than one key is provided, additional keys are used as
132 secondary criteria when the there is equality in all keys selected
132 secondary criteria when the there is equality in all keys selected
133 before them.
133 before them.
134
134
135 Abbreviations can be used for any key names, as long as the
135 Abbreviations can be used for any key names, as long as the
136 abbreviation is unambiguous. The following are the keys currently
136 abbreviation is unambiguous. The following are the keys currently
137 defined:
137 defined:
138
138
139 Valid Arg Meaning
139 Valid Arg Meaning
140 "calls" call count
140 "calls" call count
141 "cumulative" cumulative time
141 "cumulative" cumulative time
142 "file" file name
142 "file" file name
143 "module" file name
143 "module" file name
144 "pcalls" primitive call count
144 "pcalls" primitive call count
145 "line" line number
145 "line" line number
146 "name" function name
146 "name" function name
147 "nfl" name/file/line
147 "nfl" name/file/line
148 "stdname" standard name
148 "stdname" standard name
149 "time" internal time
149 "time" internal time
150
150
151 Note that all sorts on statistics are in descending order (placing
151 Note that all sorts on statistics are in descending order (placing
152 most time consuming items first), where as name, file, and line number
152 most time consuming items first), where as name, file, and line number
153 searches are in ascending order (i.e., alphabetical). The subtle
153 searches are in ascending order (i.e., alphabetical). The subtle
154 distinction between "nfl" and "stdname" is that the standard name is a
154 distinction between "nfl" and "stdname" is that the standard name is a
155 sort of the name as printed, which means that the embedded line
155 sort of the name as printed, which means that the embedded line
156 numbers get compared in an odd way. For example, lines 3, 20, and 40
156 numbers get compared in an odd way. For example, lines 3, 20, and 40
157 would (if the file names were the same) appear in the string order
157 would (if the file names were the same) appear in the string order
158 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
158 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
159 line numbers. In fact, sort_stats("nfl") is the same as
159 line numbers. In fact, sort_stats("nfl") is the same as
160 sort_stats("name", "file", "line").
160 sort_stats("name", "file", "line").
161
161
162 -T <filename>: save profile results as shown on screen to a text
162 -T <filename>: save profile results as shown on screen to a text
163 file. The profile is still shown on screen.
163 file. The profile is still shown on screen.
164
164
165 -D <filename>: save (via dump_stats) profile statistics to given
165 -D <filename>: save (via dump_stats) profile statistics to given
166 filename. This data is in a format understood by the pstats module, and
166 filename. This data is in a format understood by the pstats module, and
167 is generated by a call to the dump_stats() method of profile
167 is generated by a call to the dump_stats() method of profile
168 objects. The profile is still shown on screen.
168 objects. The profile is still shown on screen.
169
169
170 -q: suppress output to the pager. Best used with -T and/or -D above.
170 -q: suppress output to the pager. Best used with -T and/or -D above.
171
171
172 If you want to run complete programs under the profiler's control, use
172 If you want to run complete programs under the profiler's control, use
173 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
173 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
174 contains profiler specific options as described here.
174 contains profiler specific options as described here.
175
175
176 You can read the complete documentation for the profile module with::
176 You can read the complete documentation for the profile module with::
177
177
178 In [1]: import profile; profile.help()
178 In [1]: import profile; profile.help()
179 """
179 """
180
180
181 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
181 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
182
182
183 if user_mode: # regular user call
183 if user_mode: # regular user call
184 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q',
184 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q',
185 list_all=True, posix=False)
185 list_all=True, posix=False)
186 namespace = self.shell.user_ns
186 namespace = self.shell.user_ns
187 if cell is not None:
187 if cell is not None:
188 arg_str += '\n' + cell
188 arg_str += '\n' + cell
189 else: # called to run a program by %run -p
189 else: # called to run a program by %run -p
190 try:
190 try:
191 filename = get_py_filename(arg_lst[0])
191 filename = get_py_filename(arg_lst[0])
192 except IOError as e:
192 except IOError as e:
193 try:
193 try:
194 msg = str(e)
194 msg = str(e)
195 except UnicodeError:
195 except UnicodeError:
196 msg = e.message
196 msg = e.message
197 error(msg)
197 error(msg)
198 return
198 return
199
199
200 arg_str = 'execfile(filename,prog_ns)'
200 arg_str = 'execfile(filename,prog_ns)'
201 namespace = {
201 namespace = {
202 'execfile': self.shell.safe_execfile,
202 'execfile': self.shell.safe_execfile,
203 'prog_ns': prog_ns,
203 'prog_ns': prog_ns,
204 'filename': filename
204 'filename': filename
205 }
205 }
206
206
207 opts.merge(opts_def)
207 opts.merge(opts_def)
208
208
209 prof = profile.Profile()
209 prof = profile.Profile()
210 try:
210 try:
211 prof = prof.runctx(arg_str,namespace,namespace)
211 prof = prof.runctx(arg_str,namespace,namespace)
212 sys_exit = ''
212 sys_exit = ''
213 except SystemExit:
213 except SystemExit:
214 sys_exit = """*** SystemExit exception caught in code being profiled."""
214 sys_exit = """*** SystemExit exception caught in code being profiled."""
215
215
216 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
216 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
217
217
218 lims = opts.l
218 lims = opts.l
219 if lims:
219 if lims:
220 lims = [] # rebuild lims with ints/floats/strings
220 lims = [] # rebuild lims with ints/floats/strings
221 for lim in opts.l:
221 for lim in opts.l:
222 try:
222 try:
223 lims.append(int(lim))
223 lims.append(int(lim))
224 except ValueError:
224 except ValueError:
225 try:
225 try:
226 lims.append(float(lim))
226 lims.append(float(lim))
227 except ValueError:
227 except ValueError:
228 lims.append(lim)
228 lims.append(lim)
229
229
230 # Trap output.
230 # Trap output.
231 stdout_trap = StringIO()
231 stdout_trap = StringIO()
232 stats_stream = stats.stream
232 stats_stream = stats.stream
233 try:
233 try:
234 stats.stream = stdout_trap
234 stats.stream = stdout_trap
235 stats.print_stats(*lims)
235 stats.print_stats(*lims)
236 finally:
236 finally:
237 stats.stream = stats_stream
237 stats.stream = stats_stream
238
238
239 output = stdout_trap.getvalue()
239 output = stdout_trap.getvalue()
240 output = output.rstrip()
240 output = output.rstrip()
241
241
242 if 'q' not in opts:
242 if 'q' not in opts:
243 page.page(output)
243 page.page(output)
244 print sys_exit,
244 print sys_exit,
245
245
246 dump_file = opts.D[0]
246 dump_file = opts.D[0]
247 text_file = opts.T[0]
247 text_file = opts.T[0]
248 if dump_file:
248 if dump_file:
249 dump_file = unquote_filename(dump_file)
249 dump_file = unquote_filename(dump_file)
250 prof.dump_stats(dump_file)
250 prof.dump_stats(dump_file)
251 print '\n*** Profile stats marshalled to file',\
251 print '\n*** Profile stats marshalled to file',\
252 repr(dump_file)+'.',sys_exit
252 repr(dump_file)+'.',sys_exit
253 if text_file:
253 if text_file:
254 text_file = unquote_filename(text_file)
254 text_file = unquote_filename(text_file)
255 pfile = open(text_file,'w')
255 pfile = open(text_file,'w')
256 pfile.write(output)
256 pfile.write(output)
257 pfile.close()
257 pfile.close()
258 print '\n*** Profile printout saved to text file',\
258 print '\n*** Profile printout saved to text file',\
259 repr(text_file)+'.',sys_exit
259 repr(text_file)+'.',sys_exit
260
260
261 if 'r' in opts:
261 if 'r' in opts:
262 return stats
262 return stats
263 else:
263 else:
264 return None
264 return None
265
265
266 @line_magic
266 @line_magic
267 def pdb(self, parameter_s=''):
267 def pdb(self, parameter_s=''):
268 """Control the automatic calling of the pdb interactive debugger.
268 """Control the automatic calling of the pdb interactive debugger.
269
269
270 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
270 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
271 argument it works as a toggle.
271 argument it works as a toggle.
272
272
273 When an exception is triggered, IPython can optionally call the
273 When an exception is triggered, IPython can optionally call the
274 interactive pdb debugger after the traceback printout. %pdb toggles
274 interactive pdb debugger after the traceback printout. %pdb toggles
275 this feature on and off.
275 this feature on and off.
276
276
277 The initial state of this feature is set in your configuration
277 The initial state of this feature is set in your configuration
278 file (the option is ``InteractiveShell.pdb``).
278 file (the option is ``InteractiveShell.pdb``).
279
279
280 If you want to just activate the debugger AFTER an exception has fired,
280 If you want to just activate the debugger AFTER an exception has fired,
281 without having to type '%pdb on' and rerunning your code, you can use
281 without having to type '%pdb on' and rerunning your code, you can use
282 the %debug magic."""
282 the %debug magic."""
283
283
284 par = parameter_s.strip().lower()
284 par = parameter_s.strip().lower()
285
285
286 if par:
286 if par:
287 try:
287 try:
288 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
288 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
289 except KeyError:
289 except KeyError:
290 print ('Incorrect argument. Use on/1, off/0, '
290 print ('Incorrect argument. Use on/1, off/0, '
291 'or nothing for a toggle.')
291 'or nothing for a toggle.')
292 return
292 return
293 else:
293 else:
294 # toggle
294 # toggle
295 new_pdb = not self.shell.call_pdb
295 new_pdb = not self.shell.call_pdb
296
296
297 # set on the shell
297 # set on the shell
298 self.shell.call_pdb = new_pdb
298 self.shell.call_pdb = new_pdb
299 print 'Automatic pdb calling has been turned',on_off(new_pdb)
299 print 'Automatic pdb calling has been turned',on_off(new_pdb)
300
300
301 @line_magic
301 @line_magic
302 def debug(self, parameter_s=''):
302 def debug(self, parameter_s=''):
303 """Activate the interactive debugger in post-mortem mode.
303 """Activate the interactive debugger in post-mortem mode.
304
304
305 If an exception has just occurred, this lets you inspect its stack
305 If an exception has just occurred, this lets you inspect its stack
306 frames interactively. Note that this will always work only on the last
306 frames interactively. Note that this will always work only on the last
307 traceback that occurred, so you must call this quickly after an
307 traceback that occurred, so you must call this quickly after an
308 exception that you wish to inspect has fired, because if another one
308 exception that you wish to inspect has fired, because if another one
309 occurs, it clobbers the previous one.
309 occurs, it clobbers the previous one.
310
310
311 If you want IPython to automatically do this on every exception, see
311 If you want IPython to automatically do this on every exception, see
312 the %pdb magic for more details.
312 the %pdb magic for more details.
313 """
313 """
314 self.shell.debugger(force=True)
314 self.shell.debugger(force=True)
315
315
316 @line_magic
316 @line_magic
317 def tb(self, s):
317 def tb(self, s):
318 """Print the last traceback with the currently active exception mode.
318 """Print the last traceback with the currently active exception mode.
319
319
320 See %xmode for changing exception reporting modes."""
320 See %xmode for changing exception reporting modes."""
321 self.shell.showtraceback()
321 self.shell.showtraceback()
322
322
323 @skip_doctest
323 @skip_doctest
324 @line_magic
324 @line_magic
325 def run(self, parameter_s='', runner=None,
325 def run(self, parameter_s='', runner=None,
326 file_finder=get_py_filename):
326 file_finder=get_py_filename):
327 """Run the named file inside IPython as a program.
327 """Run the named file inside IPython as a program.
328
328
329 Usage:\\
329 Usage:\\
330 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options] -G] file [args]
330 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options] -G] file [args]
331
331
332 Parameters after the filename are passed as command-line arguments to
332 Parameters after the filename are passed as command-line arguments to
333 the program (put in sys.argv). Then, control returns to IPython's
333 the program (put in sys.argv). Then, control returns to IPython's
334 prompt.
334 prompt.
335
335
336 This is similar to running at a system prompt:\\
336 This is similar to running at a system prompt:\\
337 $ python file args\\
337 $ python file args\\
338 but with the advantage of giving you IPython's tracebacks, and of
338 but with the advantage of giving you IPython's tracebacks, and of
339 loading all variables into your interactive namespace for further use
339 loading all variables into your interactive namespace for further use
340 (unless -p is used, see below).
340 (unless -p is used, see below).
341
341
342 The file is executed in a namespace initially consisting only of
342 The file is executed in a namespace initially consisting only of
343 __name__=='__main__' and sys.argv constructed as indicated. It thus
343 __name__=='__main__' and sys.argv constructed as indicated. It thus
344 sees its environment as if it were being run as a stand-alone program
344 sees its environment as if it were being run as a stand-alone program
345 (except for sharing global objects such as previously imported
345 (except for sharing global objects such as previously imported
346 modules). But after execution, the IPython interactive namespace gets
346 modules). But after execution, the IPython interactive namespace gets
347 updated with all variables defined in the program (except for __name__
347 updated with all variables defined in the program (except for __name__
348 and sys.argv). This allows for very convenient loading of code for
348 and sys.argv). This allows for very convenient loading of code for
349 interactive work, while giving each program a 'clean sheet' to run in.
349 interactive work, while giving each program a 'clean sheet' to run in.
350
350
351 Arguments are expanded using shell-like glob match. Patterns
351 Arguments are expanded using shell-like glob match. Patterns
352 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
352 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
353 tilde '~' will be expanded into user's home directory. Unlike
353 tilde '~' will be expanded into user's home directory. Unlike
354 real shells, quotation does not suppress expansions. Use
354 real shells, quotation does not suppress expansions. Use
355 *two* back slashes (e.g., '\\\\*') to suppress expansions.
355 *two* back slashes (e.g., '\\\\*') to suppress expansions.
356 To completely disable these expansions, you can use -G flag.
356 To completely disable these expansions, you can use -G flag.
357
357
358 Options:
358 Options:
359
359
360 -n: __name__ is NOT set to '__main__', but to the running file's name
360 -n: __name__ is NOT set to '__main__', but to the running file's name
361 without extension (as python does under import). This allows running
361 without extension (as python does under import). This allows running
362 scripts and reloading the definitions in them without calling code
362 scripts and reloading the definitions in them without calling code
363 protected by an ' if __name__ == "__main__" ' clause.
363 protected by an ' if __name__ == "__main__" ' clause.
364
364
365 -i: run the file in IPython's namespace instead of an empty one. This
365 -i: run the file in IPython's namespace instead of an empty one. This
366 is useful if you are experimenting with code written in a text editor
366 is useful if you are experimenting with code written in a text editor
367 which depends on variables defined interactively.
367 which depends on variables defined interactively.
368
368
369 -e: ignore sys.exit() calls or SystemExit exceptions in the script
369 -e: ignore sys.exit() calls or SystemExit exceptions in the script
370 being run. This is particularly useful if IPython is being used to
370 being run. This is particularly useful if IPython is being used to
371 run unittests, which always exit with a sys.exit() call. In such
371 run unittests, which always exit with a sys.exit() call. In such
372 cases you are interested in the output of the test results, not in
372 cases you are interested in the output of the test results, not in
373 seeing a traceback of the unittest module.
373 seeing a traceback of the unittest module.
374
374
375 -t: print timing information at the end of the run. IPython will give
375 -t: print timing information at the end of the run. IPython will give
376 you an estimated CPU time consumption for your script, which under
376 you an estimated CPU time consumption for your script, which under
377 Unix uses the resource module to avoid the wraparound problems of
377 Unix uses the resource module to avoid the wraparound problems of
378 time.clock(). Under Unix, an estimate of time spent on system tasks
378 time.clock(). Under Unix, an estimate of time spent on system tasks
379 is also given (for Windows platforms this is reported as 0.0).
379 is also given (for Windows platforms this is reported as 0.0).
380
380
381 If -t is given, an additional -N<N> option can be given, where <N>
381 If -t is given, an additional -N<N> option can be given, where <N>
382 must be an integer indicating how many times you want the script to
382 must be an integer indicating how many times you want the script to
383 run. The final timing report will include total and per run results.
383 run. The final timing report will include total and per run results.
384
384
385 For example (testing the script uniq_stable.py)::
385 For example (testing the script uniq_stable.py)::
386
386
387 In [1]: run -t uniq_stable
387 In [1]: run -t uniq_stable
388
388
389 IPython CPU timings (estimated):\\
389 IPython CPU timings (estimated):\\
390 User : 0.19597 s.\\
390 User : 0.19597 s.\\
391 System: 0.0 s.\\
391 System: 0.0 s.\\
392
392
393 In [2]: run -t -N5 uniq_stable
393 In [2]: run -t -N5 uniq_stable
394
394
395 IPython CPU timings (estimated):\\
395 IPython CPU timings (estimated):\\
396 Total runs performed: 5\\
396 Total runs performed: 5\\
397 Times : Total Per run\\
397 Times : Total Per run\\
398 User : 0.910862 s, 0.1821724 s.\\
398 User : 0.910862 s, 0.1821724 s.\\
399 System: 0.0 s, 0.0 s.
399 System: 0.0 s, 0.0 s.
400
400
401 -d: run your program under the control of pdb, the Python debugger.
401 -d: run your program under the control of pdb, the Python debugger.
402 This allows you to execute your program step by step, watch variables,
402 This allows you to execute your program step by step, watch variables,
403 etc. Internally, what IPython does is similar to calling:
403 etc. Internally, what IPython does is similar to calling:
404
404
405 pdb.run('execfile("YOURFILENAME")')
405 pdb.run('execfile("YOURFILENAME")')
406
406
407 with a breakpoint set on line 1 of your file. You can change the line
407 with a breakpoint set on line 1 of your file. You can change the line
408 number for this automatic breakpoint to be <N> by using the -bN option
408 number for this automatic breakpoint to be <N> by using the -bN option
409 (where N must be an integer). For example::
409 (where N must be an integer). For example::
410
410
411 %run -d -b40 myscript
411 %run -d -b40 myscript
412
412
413 will set the first breakpoint at line 40 in myscript.py. Note that
413 will set the first breakpoint at line 40 in myscript.py. Note that
414 the first breakpoint must be set on a line which actually does
414 the first breakpoint must be set on a line which actually does
415 something (not a comment or docstring) for it to stop execution.
415 something (not a comment or docstring) for it to stop execution.
416
416
417 Or you can specify a breakpoint in a different file::
417 Or you can specify a breakpoint in a different file::
418
418
419 %run -d -b myotherfile.py:20 myscript
419 %run -d -b myotherfile.py:20 myscript
420
420
421 When the pdb debugger starts, you will see a (Pdb) prompt. You must
421 When the pdb debugger starts, you will see a (Pdb) prompt. You must
422 first enter 'c' (without quotes) to start execution up to the first
422 first enter 'c' (without quotes) to start execution up to the first
423 breakpoint.
423 breakpoint.
424
424
425 Entering 'help' gives information about the use of the debugger. You
425 Entering 'help' gives information about the use of the debugger. You
426 can easily see pdb's full documentation with "import pdb;pdb.help()"
426 can easily see pdb's full documentation with "import pdb;pdb.help()"
427 at a prompt.
427 at a prompt.
428
428
429 -p: run program under the control of the Python profiler module (which
429 -p: run program under the control of the Python profiler module (which
430 prints a detailed report of execution times, function calls, etc).
430 prints a detailed report of execution times, function calls, etc).
431
431
432 You can pass other options after -p which affect the behavior of the
432 You can pass other options after -p which affect the behavior of the
433 profiler itself. See the docs for %prun for details.
433 profiler itself. See the docs for %prun for details.
434
434
435 In this mode, the program's variables do NOT propagate back to the
435 In this mode, the program's variables do NOT propagate back to the
436 IPython interactive namespace (because they remain in the namespace
436 IPython interactive namespace (because they remain in the namespace
437 where the profiler executes them).
437 where the profiler executes them).
438
438
439 Internally this triggers a call to %prun, see its documentation for
439 Internally this triggers a call to %prun, see its documentation for
440 details on the options available specifically for profiling.
440 details on the options available specifically for profiling.
441
441
442 There is one special usage for which the text above doesn't apply:
442 There is one special usage for which the text above doesn't apply:
443 if the filename ends with .ipy, the file is run as ipython script,
443 if the filename ends with .ipy, the file is run as ipython script,
444 just as if the commands were written on IPython prompt.
444 just as if the commands were written on IPython prompt.
445
445
446 -m: specify module name to load instead of script path. Similar to
446 -m: specify module name to load instead of script path. Similar to
447 the -m option for the python interpreter. Use this option last if you
447 the -m option for the python interpreter. Use this option last if you
448 want to combine with other %run options. Unlike the python interpreter
448 want to combine with other %run options. Unlike the python interpreter
449 only source modules are allowed no .pyc or .pyo files.
449 only source modules are allowed no .pyc or .pyo files.
450 For example::
450 For example::
451
451
452 %run -m example
452 %run -m example
453
453
454 will run the example module.
454 will run the example module.
455
455
456 -G: disable shell-like glob expansion of arguments.
456 -G: disable shell-like glob expansion of arguments.
457
457
458 """
458 """
459
459
460 # get arguments and set sys.argv for program to be run.
460 # get arguments and set sys.argv for program to be run.
461 opts, arg_lst = self.parse_options(parameter_s,
461 opts, arg_lst = self.parse_options(parameter_s,
462 'nidtN:b:pD:l:rs:T:em:G',
462 'nidtN:b:pD:l:rs:T:em:G',
463 mode='list', list_all=1)
463 mode='list', list_all=1)
464 if "m" in opts:
464 if "m" in opts:
465 modulename = opts["m"][0]
465 modulename = opts["m"][0]
466 modpath = find_mod(modulename)
466 modpath = find_mod(modulename)
467 if modpath is None:
467 if modpath is None:
468 warn('%r is not a valid modulename on sys.path'%modulename)
468 warn('%r is not a valid modulename on sys.path'%modulename)
469 return
469 return
470 arg_lst = [modpath] + arg_lst
470 arg_lst = [modpath] + arg_lst
471 try:
471 try:
472 filename = file_finder(arg_lst[0])
472 filename = file_finder(arg_lst[0])
473 except IndexError:
473 except IndexError:
474 warn('you must provide at least a filename.')
474 warn('you must provide at least a filename.')
475 print '\n%run:\n', oinspect.getdoc(self.run)
475 print '\n%run:\n', oinspect.getdoc(self.run)
476 return
476 return
477 except IOError as e:
477 except IOError as e:
478 try:
478 try:
479 msg = str(e)
479 msg = str(e)
480 except UnicodeError:
480 except UnicodeError:
481 msg = e.message
481 msg = e.message
482 error(msg)
482 error(msg)
483 return
483 return
484
484
485 if filename.lower().endswith('.ipy'):
485 if filename.lower().endswith('.ipy'):
486 with preserve_keys(self.shell.user_ns, '__file__'):
486 with preserve_keys(self.shell.user_ns, '__file__'):
487 self.shell.user_ns['__file__'] = filename
487 self.shell.user_ns['__file__'] = filename
488 self.shell.safe_execfile_ipy(filename)
488 self.shell.safe_execfile_ipy(filename)
489 return
489 return
490
490
491 # Control the response to exit() calls made by the script being run
491 # Control the response to exit() calls made by the script being run
492 exit_ignore = 'e' in opts
492 exit_ignore = 'e' in opts
493
493
494 # Make sure that the running script gets a proper sys.argv as if it
494 # Make sure that the running script gets a proper sys.argv as if it
495 # were run from a system shell.
495 # were run from a system shell.
496 save_argv = sys.argv # save it for later restoring
496 save_argv = sys.argv # save it for later restoring
497
497
498 if 'G' in opts:
498 if 'G' in opts:
499 args = arg_lst[1:]
499 args = arg_lst[1:]
500 else:
500 else:
501 # tilde and glob expansion
501 # tilde and glob expansion
502 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
502 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
503
503
504 sys.argv = [filename] + args # put in the proper filename
504 sys.argv = [filename] + args # put in the proper filename
505 # protect sys.argv from potential unicode strings on Python 2:
505 # protect sys.argv from potential unicode strings on Python 2:
506 if not py3compat.PY3:
506 if not py3compat.PY3:
507 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
507 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
508
508
509 if 'i' in opts:
509 if 'i' in opts:
510 # Run in user's interactive namespace
510 # Run in user's interactive namespace
511 prog_ns = self.shell.user_ns
511 prog_ns = self.shell.user_ns
512 __name__save = self.shell.user_ns['__name__']
512 __name__save = self.shell.user_ns['__name__']
513 prog_ns['__name__'] = '__main__'
513 prog_ns['__name__'] = '__main__'
514 main_mod = self.shell.new_main_mod(prog_ns)
514 main_mod = self.shell.new_main_mod(prog_ns)
515 else:
515 else:
516 # Run in a fresh, empty namespace
516 # Run in a fresh, empty namespace
517 if 'n' in opts:
517 if 'n' in opts:
518 name = os.path.splitext(os.path.basename(filename))[0]
518 name = os.path.splitext(os.path.basename(filename))[0]
519 else:
519 else:
520 name = '__main__'
520 name = '__main__'
521
521
522 main_mod = self.shell.new_main_mod()
522 main_mod = self.shell.new_main_mod()
523 prog_ns = main_mod.__dict__
523 prog_ns = main_mod.__dict__
524 prog_ns['__name__'] = name
524 prog_ns['__name__'] = name
525
525
526 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
526 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
527 # set the __file__ global in the script's namespace
527 # set the __file__ global in the script's namespace
528 prog_ns['__file__'] = filename
528 prog_ns['__file__'] = filename
529
529
530 # pickle fix. See interactiveshell for an explanation. But we need to
530 # pickle fix. See interactiveshell for an explanation. But we need to
531 # make sure that, if we overwrite __main__, we replace it at the end
531 # make sure that, if we overwrite __main__, we replace it at the end
532 main_mod_name = prog_ns['__name__']
532 main_mod_name = prog_ns['__name__']
533
533
534 if main_mod_name == '__main__':
534 if main_mod_name == '__main__':
535 restore_main = sys.modules['__main__']
535 restore_main = sys.modules['__main__']
536 else:
536 else:
537 restore_main = False
537 restore_main = False
538
538
539 # This needs to be undone at the end to prevent holding references to
539 # This needs to be undone at the end to prevent holding references to
540 # every single object ever created.
540 # every single object ever created.
541 sys.modules[main_mod_name] = main_mod
541 sys.modules[main_mod_name] = main_mod
542
542
543 try:
543 try:
544 stats = None
544 stats = None
545 with self.shell.readline_no_record:
545 with self.shell.readline_no_record:
546 if 'p' in opts:
546 if 'p' in opts:
547 stats = self.prun('', None, False, opts, arg_lst, prog_ns)
547 stats = self.prun('', None, False, opts, arg_lst, prog_ns)
548 else:
548 else:
549 if 'd' in opts:
549 if 'd' in opts:
550 deb = debugger.Pdb(self.shell.colors)
550 deb = debugger.Pdb(self.shell.colors)
551 # reset Breakpoint state, which is moronically kept
551 # reset Breakpoint state, which is moronically kept
552 # in a class
552 # in a class
553 bdb.Breakpoint.next = 1
553 bdb.Breakpoint.next = 1
554 bdb.Breakpoint.bplist = {}
554 bdb.Breakpoint.bplist = {}
555 bdb.Breakpoint.bpbynumber = [None]
555 bdb.Breakpoint.bpbynumber = [None]
556 # Set an initial breakpoint to stop execution
556 # Set an initial breakpoint to stop execution
557 maxtries = 10
557 maxtries = 10
558 bp_file, bp_line = parse_breakpoint(opts.get('b', ['1'])[0], filename)
558 bp_file, bp_line = parse_breakpoint(opts.get('b', ['1'])[0], filename)
559 checkline = deb.checkline(bp_file, bp_line)
559 checkline = deb.checkline(bp_file, bp_line)
560 if not checkline:
560 if not checkline:
561 for bp in range(bp_line + 1, bp_line + maxtries + 1):
561 for bp in range(bp_line + 1, bp_line + maxtries + 1):
562 if deb.checkline(bp_file, bp):
562 if deb.checkline(bp_file, bp):
563 break
563 break
564 else:
564 else:
565 msg = ("\nI failed to find a valid line to set "
565 msg = ("\nI failed to find a valid line to set "
566 "a breakpoint\n"
566 "a breakpoint\n"
567 "after trying up to line: %s.\n"
567 "after trying up to line: %s.\n"
568 "Please set a valid breakpoint manually "
568 "Please set a valid breakpoint manually "
569 "with the -b option." % bp)
569 "with the -b option." % bp)
570 error(msg)
570 error(msg)
571 return
571 return
572 # if we find a good linenumber, set the breakpoint
572 # if we find a good linenumber, set the breakpoint
573 deb.do_break('%s:%s' % (bp_file, bp_line))
573 deb.do_break('%s:%s' % (bp_file, bp_line))
574
574
575 # Mimic Pdb._runscript(...)
575 # Mimic Pdb._runscript(...)
576 deb._wait_for_mainpyfile = True
576 deb._wait_for_mainpyfile = True
577 deb.mainpyfile = deb.canonic(filename)
577 deb.mainpyfile = deb.canonic(filename)
578
578
579 # Start file run
579 # Start file run
580 print "NOTE: Enter 'c' at the",
580 print "NOTE: Enter 'c' at the",
581 print "%s prompt to start your script." % deb.prompt
581 print "%s prompt to start your script." % deb.prompt
582 ns = {'execfile': py3compat.execfile, 'prog_ns': prog_ns}
582 ns = {'execfile': py3compat.execfile, 'prog_ns': prog_ns}
583 try:
583 try:
584 #save filename so it can be used by methods on the deb object
584 #save filename so it can be used by methods on the deb object
585 deb._exec_filename = filename
585 deb._exec_filename = filename
586 deb.run('execfile("%s", prog_ns)' % filename, ns)
586 deb.run('execfile("%s", prog_ns)' % filename, ns)
587
587
588 except:
588 except:
589 etype, value, tb = sys.exc_info()
589 etype, value, tb = sys.exc_info()
590 # Skip three frames in the traceback: the %run one,
590 # Skip three frames in the traceback: the %run one,
591 # one inside bdb.py, and the command-line typed by the
591 # one inside bdb.py, and the command-line typed by the
592 # user (run by exec in pdb itself).
592 # user (run by exec in pdb itself).
593 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
593 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
594 else:
594 else:
595 if runner is None:
595 if runner is None:
596 runner = self.default_runner
596 runner = self.default_runner
597 if runner is None:
597 if runner is None:
598 runner = self.shell.safe_execfile
598 runner = self.shell.safe_execfile
599 if 't' in opts:
599 if 't' in opts:
600 # timed execution
600 # timed execution
601 try:
601 try:
602 nruns = int(opts['N'][0])
602 nruns = int(opts['N'][0])
603 if nruns < 1:
603 if nruns < 1:
604 error('Number of runs must be >=1')
604 error('Number of runs must be >=1')
605 return
605 return
606 except (KeyError):
606 except (KeyError):
607 nruns = 1
607 nruns = 1
608 twall0 = time.time()
608 twall0 = time.time()
609 if nruns == 1:
609 if nruns == 1:
610 t0 = clock2()
610 t0 = clock2()
611 runner(filename, prog_ns, prog_ns,
611 runner(filename, prog_ns, prog_ns,
612 exit_ignore=exit_ignore)
612 exit_ignore=exit_ignore)
613 t1 = clock2()
613 t1 = clock2()
614 t_usr = t1[0] - t0[0]
614 t_usr = t1[0] - t0[0]
615 t_sys = t1[1] - t0[1]
615 t_sys = t1[1] - t0[1]
616 print "\nIPython CPU timings (estimated):"
616 print "\nIPython CPU timings (estimated):"
617 print " User : %10.2f s." % t_usr
617 print " User : %10.2f s." % t_usr
618 print " System : %10.2f s." % t_sys
618 print " System : %10.2f s." % t_sys
619 else:
619 else:
620 runs = range(nruns)
620 runs = range(nruns)
621 t0 = clock2()
621 t0 = clock2()
622 for nr in runs:
622 for nr in runs:
623 runner(filename, prog_ns, prog_ns,
623 runner(filename, prog_ns, prog_ns,
624 exit_ignore=exit_ignore)
624 exit_ignore=exit_ignore)
625 t1 = clock2()
625 t1 = clock2()
626 t_usr = t1[0] - t0[0]
626 t_usr = t1[0] - t0[0]
627 t_sys = t1[1] - t0[1]
627 t_sys = t1[1] - t0[1]
628 print "\nIPython CPU timings (estimated):"
628 print "\nIPython CPU timings (estimated):"
629 print "Total runs performed:", nruns
629 print "Total runs performed:", nruns
630 print " Times : %10s %10s" % ('Total', 'Per run')
630 print " Times : %10s %10s" % ('Total', 'Per run')
631 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
631 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
632 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
632 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
633 twall1 = time.time()
633 twall1 = time.time()
634 print "Wall time: %10.2f s." % (twall1 - twall0)
634 print "Wall time: %10.2f s." % (twall1 - twall0)
635
635
636 else:
636 else:
637 # regular execution
637 # regular execution
638 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
638 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
639
639
640 if 'i' in opts:
640 if 'i' in opts:
641 self.shell.user_ns['__name__'] = __name__save
641 self.shell.user_ns['__name__'] = __name__save
642 else:
642 else:
643 # The shell MUST hold a reference to prog_ns so after %run
643 # The shell MUST hold a reference to prog_ns so after %run
644 # exits, the python deletion mechanism doesn't zero it out
644 # exits, the python deletion mechanism doesn't zero it out
645 # (leaving dangling references).
645 # (leaving dangling references).
646 self.shell.cache_main_mod(prog_ns, filename)
646 self.shell.cache_main_mod(prog_ns, filename)
647 # update IPython interactive namespace
647 # update IPython interactive namespace
648
648
649 # Some forms of read errors on the file may mean the
649 # Some forms of read errors on the file may mean the
650 # __name__ key was never set; using pop we don't have to
650 # __name__ key was never set; using pop we don't have to
651 # worry about a possible KeyError.
651 # worry about a possible KeyError.
652 prog_ns.pop('__name__', None)
652 prog_ns.pop('__name__', None)
653
653
654 with preserve_keys(self.shell.user_ns, '__file__'):
654 with preserve_keys(self.shell.user_ns, '__file__'):
655 self.shell.user_ns.update(prog_ns)
655 self.shell.user_ns.update(prog_ns)
656 finally:
656 finally:
657 # It's a bit of a mystery why, but __builtins__ can change from
657 # It's a bit of a mystery why, but __builtins__ can change from
658 # being a module to becoming a dict missing some key data after
658 # being a module to becoming a dict missing some key data after
659 # %run. As best I can see, this is NOT something IPython is doing
659 # %run. As best I can see, this is NOT something IPython is doing
660 # at all, and similar problems have been reported before:
660 # at all, and similar problems have been reported before:
661 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
661 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
662 # Since this seems to be done by the interpreter itself, the best
662 # Since this seems to be done by the interpreter itself, the best
663 # we can do is to at least restore __builtins__ for the user on
663 # we can do is to at least restore __builtins__ for the user on
664 # exit.
664 # exit.
665 self.shell.user_ns['__builtins__'] = builtin_mod
665 self.shell.user_ns['__builtins__'] = builtin_mod
666
666
667 # Ensure key global structures are restored
667 # Ensure key global structures are restored
668 sys.argv = save_argv
668 sys.argv = save_argv
669 if restore_main:
669 if restore_main:
670 sys.modules['__main__'] = restore_main
670 sys.modules['__main__'] = restore_main
671 else:
671 else:
672 # Remove from sys.modules the reference to main_mod we'd
672 # Remove from sys.modules the reference to main_mod we'd
673 # added. Otherwise it will trap references to objects
673 # added. Otherwise it will trap references to objects
674 # contained therein.
674 # contained therein.
675 del sys.modules[main_mod_name]
675 del sys.modules[main_mod_name]
676
676
677 return stats
677 return stats
678
678
679 @skip_doctest
679 @skip_doctest
680 @line_cell_magic
680 @line_cell_magic
681 def timeit(self, line='', cell=None):
681 def timeit(self, line='', cell=None):
682 """Time execution of a Python statement or expression
682 """Time execution of a Python statement or expression
683
683
684 Usage, in line mode:
684 Usage, in line mode:
685 %timeit [-n<N> -r<R> [-t|-c]] statement
685 %timeit [-n<N> -r<R> [-t|-c]] statement
686 or in cell mode:
686 or in cell mode:
687 %%timeit [-n<N> -r<R> [-t|-c]] setup_code
687 %%timeit [-n<N> -r<R> [-t|-c]] setup_code
688 code
688 code
689 code...
689 code...
690
690
691 Time execution of a Python statement or expression using the timeit
691 Time execution of a Python statement or expression using the timeit
692 module. This function can be used both as a line and cell magic:
692 module. This function can be used both as a line and cell magic:
693
693
694 - In line mode you can time a single-line statement (though multiple
694 - In line mode you can time a single-line statement (though multiple
695 ones can be chained with using semicolons).
695 ones can be chained with using semicolons).
696
696
697 - In cell mode, the statement in the first line is used as setup code
697 - In cell mode, the statement in the first line is used as setup code
698 (executed but not timed) and the body of the cell is timed. The cell
698 (executed but not timed) and the body of the cell is timed. The cell
699 body has access to any variables created in the setup code.
699 body has access to any variables created in the setup code.
700
700
701 Options:
701 Options:
702 -n<N>: execute the given statement <N> times in a loop. If this value
702 -n<N>: execute the given statement <N> times in a loop. If this value
703 is not given, a fitting value is chosen.
703 is not given, a fitting value is chosen.
704
704
705 -r<R>: repeat the loop iteration <R> times and take the best result.
705 -r<R>: repeat the loop iteration <R> times and take the best result.
706 Default: 3
706 Default: 3
707
707
708 -t: use time.time to measure the time, which is the default on Unix.
708 -t: use time.time to measure the time, which is the default on Unix.
709 This function measures wall time.
709 This function measures wall time.
710
710
711 -c: use time.clock to measure the time, which is the default on
711 -c: use time.clock to measure the time, which is the default on
712 Windows and measures wall time. On Unix, resource.getrusage is used
712 Windows and measures wall time. On Unix, resource.getrusage is used
713 instead and returns the CPU user time.
713 instead and returns the CPU user time.
714
714
715 -p<P>: use a precision of <P> digits to display the timing result.
715 -p<P>: use a precision of <P> digits to display the timing result.
716 Default: 3
716 Default: 3
717
717
718
718
719 Examples
719 Examples
720 --------
720 --------
721 ::
721 ::
722
722
723 In [1]: %timeit pass
723 In [1]: %timeit pass
724 10000000 loops, best of 3: 53.3 ns per loop
724 10000000 loops, best of 3: 53.3 ns per loop
725
725
726 In [2]: u = None
726 In [2]: u = None
727
727
728 In [3]: %timeit u is None
728 In [3]: %timeit u is None
729 10000000 loops, best of 3: 184 ns per loop
729 10000000 loops, best of 3: 184 ns per loop
730
730
731 In [4]: %timeit -r 4 u == None
731 In [4]: %timeit -r 4 u == None
732 1000000 loops, best of 4: 242 ns per loop
732 1000000 loops, best of 4: 242 ns per loop
733
733
734 In [5]: import time
734 In [5]: import time
735
735
736 In [6]: %timeit -n1 time.sleep(2)
736 In [6]: %timeit -n1 time.sleep(2)
737 1 loops, best of 3: 2 s per loop
737 1 loops, best of 3: 2 s per loop
738
738
739
739
740 The times reported by %timeit will be slightly higher than those
740 The times reported by %timeit will be slightly higher than those
741 reported by the timeit.py script when variables are accessed. This is
741 reported by the timeit.py script when variables are accessed. This is
742 due to the fact that %timeit executes the statement in the namespace
742 due to the fact that %timeit executes the statement in the namespace
743 of the shell, compared with timeit.py, which uses a single setup
743 of the shell, compared with timeit.py, which uses a single setup
744 statement to import function or create variables. Generally, the bias
744 statement to import function or create variables. Generally, the bias
745 does not matter as long as results from timeit.py are not mixed with
745 does not matter as long as results from timeit.py are not mixed with
746 those from %timeit."""
746 those from %timeit."""
747
747
748 import timeit
748 import timeit
749 import math
749 import math
750
750
751 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
751 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
752 # certain terminals. Until we figure out a robust way of
752 # certain terminals. Until we figure out a robust way of
753 # auto-detecting if the terminal can deal with it, use plain 'us' for
753 # auto-detecting if the terminal can deal with it, use plain 'us' for
754 # microseconds. I am really NOT happy about disabling the proper
754 # microseconds. I am really NOT happy about disabling the proper
755 # 'micro' prefix, but crashing is worse... If anyone knows what the
755 # 'micro' prefix, but crashing is worse... If anyone knows what the
756 # right solution for this is, I'm all ears...
756 # right solution for this is, I'm all ears...
757 #
757 #
758 # Note: using
758 # Note: using
759 #
759 #
760 # s = u'\xb5'
760 # s = u'\xb5'
761 # s.encode(sys.getdefaultencoding())
761 # s.encode(sys.getdefaultencoding())
762 #
762 #
763 # is not sufficient, as I've seen terminals where that fails but
763 # is not sufficient, as I've seen terminals where that fails but
764 # print s
764 # print s
765 #
765 #
766 # succeeds
766 # succeeds
767 #
767 #
768 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
768 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
769
769
770 #units = [u"s", u"ms",u'\xb5',"ns"]
770 #units = [u"s", u"ms",u'\xb5',"ns"]
771 units = [u"s", u"ms",u'us',"ns"]
771 units = [u"s", u"ms",u'us',"ns"]
772
772
773 scaling = [1, 1e3, 1e6, 1e9]
773 scaling = [1, 1e3, 1e6, 1e9]
774
774
775 opts, stmt = self.parse_options(line,'n:r:tcp:',
775 opts, stmt = self.parse_options(line,'n:r:tcp:',
776 posix=False, strict=False)
776 posix=False, strict=False)
777 if stmt == "" and cell is None:
777 if stmt == "" and cell is None:
778 return
778 return
779 elif cell == '':
780 warn("Empty cell. Did you mean to use %timeit?")
781 return
782
779
783 timefunc = timeit.default_timer
780 timefunc = timeit.default_timer
784 number = int(getattr(opts, "n", 0))
781 number = int(getattr(opts, "n", 0))
785 repeat = int(getattr(opts, "r", timeit.default_repeat))
782 repeat = int(getattr(opts, "r", timeit.default_repeat))
786 precision = int(getattr(opts, "p", 3))
783 precision = int(getattr(opts, "p", 3))
787 if hasattr(opts, "t"):
784 if hasattr(opts, "t"):
788 timefunc = time.time
785 timefunc = time.time
789 if hasattr(opts, "c"):
786 if hasattr(opts, "c"):
790 timefunc = clock
787 timefunc = clock
791
788
792 timer = timeit.Timer(timer=timefunc)
789 timer = timeit.Timer(timer=timefunc)
793 # this code has tight coupling to the inner workings of timeit.Timer,
790 # this code has tight coupling to the inner workings of timeit.Timer,
794 # but is there a better way to achieve that the code stmt has access
791 # but is there a better way to achieve that the code stmt has access
795 # to the shell namespace?
792 # to the shell namespace?
796 transform = self.shell.input_splitter.transform_cell
793 transform = self.shell.input_splitter.transform_cell
797
794
798 if cell is None:
795 if cell is None:
799 # called as line magic
796 # called as line magic
800 ast_setup = ast.parse("pass")
797 ast_setup = ast.parse("pass")
801 ast_stmt = ast.parse(transform(stmt))
798 ast_stmt = ast.parse(transform(stmt))
802 else:
799 else:
803 ast_setup = ast.parse(transform(stmt))
800 ast_setup = ast.parse(transform(stmt))
804 ast_stmt = ast.parse(transform(cell))
801 ast_stmt = ast.parse(transform(cell))
805
802
806 ast_setup = self.shell.transform_ast(ast_setup)
803 ast_setup = self.shell.transform_ast(ast_setup)
807 ast_stmt = self.shell.transform_ast(ast_stmt)
804 ast_stmt = self.shell.transform_ast(ast_stmt)
808
805
809 # This codestring is taken from timeit.template - we fill it in as an
806 # This codestring is taken from timeit.template - we fill it in as an
810 # AST, so that we can apply our AST transformations to the user code
807 # AST, so that we can apply our AST transformations to the user code
811 # without affecting the timing code.
808 # without affecting the timing code.
812 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
809 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
813 ' setup\n'
810 ' setup\n'
814 ' _t0 = _timer()\n'
811 ' _t0 = _timer()\n'
815 ' for _i in _it:\n'
812 ' for _i in _it:\n'
816 ' stmt\n'
813 ' stmt\n'
817 ' _t1 = _timer()\n'
814 ' _t1 = _timer()\n'
818 ' return _t1 - _t0\n')
815 ' return _t1 - _t0\n')
819
816
820 class TimeitTemplateFiller(ast.NodeTransformer):
817 class TimeitTemplateFiller(ast.NodeTransformer):
821 "This is quite tightly tied to the template definition above."
818 "This is quite tightly tied to the template definition above."
822 def visit_FunctionDef(self, node):
819 def visit_FunctionDef(self, node):
823 "Fill in the setup statement"
820 "Fill in the setup statement"
824 self.generic_visit(node)
821 self.generic_visit(node)
825 if node.name == "inner":
822 if node.name == "inner":
826 node.body[:1] = ast_setup.body
823 node.body[:1] = ast_setup.body
827
824
828 return node
825 return node
829
826
830 def visit_For(self, node):
827 def visit_For(self, node):
831 "Fill in the statement to be timed"
828 "Fill in the statement to be timed"
832 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
829 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
833 node.body = ast_stmt.body
830 node.body = ast_stmt.body
834 return node
831 return node
835
832
836 timeit_ast = TimeitTemplateFiller().visit(timeit_ast_template)
833 timeit_ast = TimeitTemplateFiller().visit(timeit_ast_template)
837 timeit_ast = ast.fix_missing_locations(timeit_ast)
834 timeit_ast = ast.fix_missing_locations(timeit_ast)
838
835
839 # Track compilation time so it can be reported if too long
836 # Track compilation time so it can be reported if too long
840 # Minimum time above which compilation time will be reported
837 # Minimum time above which compilation time will be reported
841 tc_min = 0.1
838 tc_min = 0.1
842
839
843 t0 = clock()
840 t0 = clock()
844 code = compile(timeit_ast, "<magic-timeit>", "exec")
841 code = compile(timeit_ast, "<magic-timeit>", "exec")
845 tc = clock()-t0
842 tc = clock()-t0
846
843
847 ns = {}
844 ns = {}
848 exec code in self.shell.user_ns, ns
845 exec code in self.shell.user_ns, ns
849 timer.inner = ns["inner"]
846 timer.inner = ns["inner"]
850
847
851 if number == 0:
848 if number == 0:
852 # determine number so that 0.2 <= total time < 2.0
849 # determine number so that 0.2 <= total time < 2.0
853 number = 1
850 number = 1
854 for i in range(1, 10):
851 for i in range(1, 10):
855 if timer.timeit(number) >= 0.2:
852 if timer.timeit(number) >= 0.2:
856 break
853 break
857 number *= 10
854 number *= 10
858
855
859 best = min(timer.repeat(repeat, number)) / number
856 best = min(timer.repeat(repeat, number)) / number
860
857
861 if best > 0.0 and best < 1000.0:
858 if best > 0.0 and best < 1000.0:
862 order = min(-int(math.floor(math.log10(best)) // 3), 3)
859 order = min(-int(math.floor(math.log10(best)) // 3), 3)
863 elif best >= 1000.0:
860 elif best >= 1000.0:
864 order = 0
861 order = 0
865 else:
862 else:
866 order = 3
863 order = 3
867 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
864 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
868 precision,
865 precision,
869 best * scaling[order],
866 best * scaling[order],
870 units[order])
867 units[order])
871 if tc > tc_min:
868 if tc > tc_min:
872 print "Compiler time: %.2f s" % tc
869 print "Compiler time: %.2f s" % tc
873
870
874 @skip_doctest
871 @skip_doctest
875 @needs_local_scope
872 @needs_local_scope
876 @line_magic
873 @line_magic
877 def time(self,parameter_s, local_ns=None):
874 def time(self,parameter_s, local_ns=None):
878 """Time execution of a Python statement or expression.
875 """Time execution of a Python statement or expression.
879
876
880 The CPU and wall clock times are printed, and the value of the
877 The CPU and wall clock times are printed, and the value of the
881 expression (if any) is returned. Note that under Win32, system time
878 expression (if any) is returned. Note that under Win32, system time
882 is always reported as 0, since it can not be measured.
879 is always reported as 0, since it can not be measured.
883
880
884 This function provides very basic timing functionality. In Python
881 This function provides very basic timing functionality. In Python
885 2.3, the timeit module offers more control and sophistication, so this
882 2.3, the timeit module offers more control and sophistication, so this
886 could be rewritten to use it (patches welcome).
883 could be rewritten to use it (patches welcome).
887
884
888 Examples
885 Examples
889 --------
886 --------
890 ::
887 ::
891
888
892 In [1]: time 2**128
889 In [1]: time 2**128
893 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
890 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
894 Wall time: 0.00
891 Wall time: 0.00
895 Out[1]: 340282366920938463463374607431768211456L
892 Out[1]: 340282366920938463463374607431768211456L
896
893
897 In [2]: n = 1000000
894 In [2]: n = 1000000
898
895
899 In [3]: time sum(range(n))
896 In [3]: time sum(range(n))
900 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
897 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
901 Wall time: 1.37
898 Wall time: 1.37
902 Out[3]: 499999500000L
899 Out[3]: 499999500000L
903
900
904 In [4]: time print 'hello world'
901 In [4]: time print 'hello world'
905 hello world
902 hello world
906 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
903 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
907 Wall time: 0.00
904 Wall time: 0.00
908
905
909 Note that the time needed by Python to compile the given expression
906 Note that the time needed by Python to compile the given expression
910 will be reported if it is more than 0.1s. In this example, the
907 will be reported if it is more than 0.1s. In this example, the
911 actual exponentiation is done by Python at compilation time, so while
908 actual exponentiation is done by Python at compilation time, so while
912 the expression can take a noticeable amount of time to compute, that
909 the expression can take a noticeable amount of time to compute, that
913 time is purely due to the compilation:
910 time is purely due to the compilation:
914
911
915 In [5]: time 3**9999;
912 In [5]: time 3**9999;
916 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
913 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
917 Wall time: 0.00 s
914 Wall time: 0.00 s
918
915
919 In [6]: time 3**999999;
916 In [6]: time 3**999999;
920 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
917 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
921 Wall time: 0.00 s
918 Wall time: 0.00 s
922 Compiler : 0.78 s
919 Compiler : 0.78 s
923 """
920 """
924
921
925 # fail immediately if the given expression can't be compiled
922 # fail immediately if the given expression can't be compiled
926
923
927 expr = self.shell.prefilter(parameter_s,False)
924 expr = self.shell.prefilter(parameter_s,False)
928
925
929 # Minimum time above which parse time will be reported
926 # Minimum time above which parse time will be reported
930 tp_min = 0.1
927 tp_min = 0.1
931
928
932 t0 = clock()
929 t0 = clock()
933 expr_ast = ast.parse(expr)
930 expr_ast = ast.parse(expr)
934 tp = clock()-t0
931 tp = clock()-t0
935
932
936 # Apply AST transformations
933 # Apply AST transformations
937 expr_ast = self.shell.transform_ast(expr_ast)
934 expr_ast = self.shell.transform_ast(expr_ast)
938
935
939 # Minimum time above which compilation time will be reported
936 # Minimum time above which compilation time will be reported
940 tc_min = 0.1
937 tc_min = 0.1
941
938
942 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
939 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
943 mode = 'eval'
940 mode = 'eval'
944 source = '<timed eval>'
941 source = '<timed eval>'
945 expr_ast = ast.Expression(expr_ast.body[0].value)
942 expr_ast = ast.Expression(expr_ast.body[0].value)
946 else:
943 else:
947 mode = 'exec'
944 mode = 'exec'
948 source = '<timed exec>'
945 source = '<timed exec>'
949 t0 = clock()
946 t0 = clock()
950 code = compile(expr_ast, source, mode)
947 code = compile(expr_ast, source, mode)
951 tc = clock()-t0
948 tc = clock()-t0
952
949
953 # skew measurement as little as possible
950 # skew measurement as little as possible
954 glob = self.shell.user_ns
951 glob = self.shell.user_ns
955 wtime = time.time
952 wtime = time.time
956 # time execution
953 # time execution
957 wall_st = wtime()
954 wall_st = wtime()
958 if mode=='eval':
955 if mode=='eval':
959 st = clock2()
956 st = clock2()
960 out = eval(code, glob, local_ns)
957 out = eval(code, glob, local_ns)
961 end = clock2()
958 end = clock2()
962 else:
959 else:
963 st = clock2()
960 st = clock2()
964 exec code in glob, local_ns
961 exec code in glob, local_ns
965 end = clock2()
962 end = clock2()
966 out = None
963 out = None
967 wall_end = wtime()
964 wall_end = wtime()
968 # Compute actual times and report
965 # Compute actual times and report
969 wall_time = wall_end-wall_st
966 wall_time = wall_end-wall_st
970 cpu_user = end[0]-st[0]
967 cpu_user = end[0]-st[0]
971 cpu_sys = end[1]-st[1]
968 cpu_sys = end[1]-st[1]
972 cpu_tot = cpu_user+cpu_sys
969 cpu_tot = cpu_user+cpu_sys
973 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
970 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
974 (cpu_user,cpu_sys,cpu_tot)
971 (cpu_user,cpu_sys,cpu_tot)
975 print "Wall time: %.2f s" % wall_time
972 print "Wall time: %.2f s" % wall_time
976 if tc > tc_min:
973 if tc > tc_min:
977 print "Compiler : %.2f s" % tc
974 print "Compiler : %.2f s" % tc
978 if tp > tp_min:
975 if tp > tp_min:
979 print "Parser : %.2f s" % tp
976 print "Parser : %.2f s" % tp
980 return out
977 return out
981
978
982 @skip_doctest
979 @skip_doctest
983 @line_magic
980 @line_magic
984 def macro(self, parameter_s=''):
981 def macro(self, parameter_s=''):
985 """Define a macro for future re-execution. It accepts ranges of history,
982 """Define a macro for future re-execution. It accepts ranges of history,
986 filenames or string objects.
983 filenames or string objects.
987
984
988 Usage:\\
985 Usage:\\
989 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
986 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
990
987
991 Options:
988 Options:
992
989
993 -r: use 'raw' input. By default, the 'processed' history is used,
990 -r: use 'raw' input. By default, the 'processed' history is used,
994 so that magics are loaded in their transformed version to valid
991 so that magics are loaded in their transformed version to valid
995 Python. If this option is given, the raw input as typed as the
992 Python. If this option is given, the raw input as typed as the
996 command line is used instead.
993 command line is used instead.
997
994
998 This will define a global variable called `name` which is a string
995 This will define a global variable called `name` which is a string
999 made of joining the slices and lines you specify (n1,n2,... numbers
996 made of joining the slices and lines you specify (n1,n2,... numbers
1000 above) from your input history into a single string. This variable
997 above) from your input history into a single string. This variable
1001 acts like an automatic function which re-executes those lines as if
998 acts like an automatic function which re-executes those lines as if
1002 you had typed them. You just type 'name' at the prompt and the code
999 you had typed them. You just type 'name' at the prompt and the code
1003 executes.
1000 executes.
1004
1001
1005 The syntax for indicating input ranges is described in %history.
1002 The syntax for indicating input ranges is described in %history.
1006
1003
1007 Note: as a 'hidden' feature, you can also use traditional python slice
1004 Note: as a 'hidden' feature, you can also use traditional python slice
1008 notation, where N:M means numbers N through M-1.
1005 notation, where N:M means numbers N through M-1.
1009
1006
1010 For example, if your history contains (%hist prints it)::
1007 For example, if your history contains (%hist prints it)::
1011
1008
1012 44: x=1
1009 44: x=1
1013 45: y=3
1010 45: y=3
1014 46: z=x+y
1011 46: z=x+y
1015 47: print x
1012 47: print x
1016 48: a=5
1013 48: a=5
1017 49: print 'x',x,'y',y
1014 49: print 'x',x,'y',y
1018
1015
1019 you can create a macro with lines 44 through 47 (included) and line 49
1016 you can create a macro with lines 44 through 47 (included) and line 49
1020 called my_macro with::
1017 called my_macro with::
1021
1018
1022 In [55]: %macro my_macro 44-47 49
1019 In [55]: %macro my_macro 44-47 49
1023
1020
1024 Now, typing `my_macro` (without quotes) will re-execute all this code
1021 Now, typing `my_macro` (without quotes) will re-execute all this code
1025 in one pass.
1022 in one pass.
1026
1023
1027 You don't need to give the line-numbers in order, and any given line
1024 You don't need to give the line-numbers in order, and any given line
1028 number can appear multiple times. You can assemble macros with any
1025 number can appear multiple times. You can assemble macros with any
1029 lines from your input history in any order.
1026 lines from your input history in any order.
1030
1027
1031 The macro is a simple object which holds its value in an attribute,
1028 The macro is a simple object which holds its value in an attribute,
1032 but IPython's display system checks for macros and executes them as
1029 but IPython's display system checks for macros and executes them as
1033 code instead of printing them when you type their name.
1030 code instead of printing them when you type their name.
1034
1031
1035 You can view a macro's contents by explicitly printing it with::
1032 You can view a macro's contents by explicitly printing it with::
1036
1033
1037 print macro_name
1034 print macro_name
1038
1035
1039 """
1036 """
1040 opts,args = self.parse_options(parameter_s,'r',mode='list')
1037 opts,args = self.parse_options(parameter_s,'r',mode='list')
1041 if not args: # List existing macros
1038 if not args: # List existing macros
1042 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
1039 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
1043 isinstance(v, Macro))
1040 isinstance(v, Macro))
1044 if len(args) == 1:
1041 if len(args) == 1:
1045 raise UsageError(
1042 raise UsageError(
1046 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1043 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1047 name, codefrom = args[0], " ".join(args[1:])
1044 name, codefrom = args[0], " ".join(args[1:])
1048
1045
1049 #print 'rng',ranges # dbg
1046 #print 'rng',ranges # dbg
1050 try:
1047 try:
1051 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1048 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1052 except (ValueError, TypeError) as e:
1049 except (ValueError, TypeError) as e:
1053 print e.args[0]
1050 print e.args[0]
1054 return
1051 return
1055 macro = Macro(lines)
1052 macro = Macro(lines)
1056 self.shell.define_macro(name, macro)
1053 self.shell.define_macro(name, macro)
1057 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1054 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1058 print '=== Macro contents: ==='
1055 print '=== Macro contents: ==='
1059 print macro,
1056 print macro,
1060
1057
1061 @magic_arguments.magic_arguments()
1058 @magic_arguments.magic_arguments()
1062 @magic_arguments.argument('output', type=str, default='', nargs='?',
1059 @magic_arguments.argument('output', type=str, default='', nargs='?',
1063 help="""The name of the variable in which to store output.
1060 help="""The name of the variable in which to store output.
1064 This is a utils.io.CapturedIO object with stdout/err attributes
1061 This is a utils.io.CapturedIO object with stdout/err attributes
1065 for the text of the captured output.
1062 for the text of the captured output.
1066
1063
1067 CapturedOutput also has a show() method for displaying the output,
1064 CapturedOutput also has a show() method for displaying the output,
1068 and __call__ as well, so you can use that to quickly display the
1065 and __call__ as well, so you can use that to quickly display the
1069 output.
1066 output.
1070
1067
1071 If unspecified, captured output is discarded.
1068 If unspecified, captured output is discarded.
1072 """
1069 """
1073 )
1070 )
1074 @magic_arguments.argument('--no-stderr', action="store_true",
1071 @magic_arguments.argument('--no-stderr', action="store_true",
1075 help="""Don't capture stderr."""
1072 help="""Don't capture stderr."""
1076 )
1073 )
1077 @magic_arguments.argument('--no-stdout', action="store_true",
1074 @magic_arguments.argument('--no-stdout', action="store_true",
1078 help="""Don't capture stdout."""
1075 help="""Don't capture stdout."""
1079 )
1076 )
1080 @cell_magic
1077 @cell_magic
1081 def capture(self, line, cell):
1078 def capture(self, line, cell):
1082 """run the cell, capturing stdout/err"""
1079 """run the cell, capturing stdout/err"""
1083 args = magic_arguments.parse_argstring(self.capture, line)
1080 args = magic_arguments.parse_argstring(self.capture, line)
1084 out = not args.no_stdout
1081 out = not args.no_stdout
1085 err = not args.no_stderr
1082 err = not args.no_stderr
1086 with capture_output(out, err) as io:
1083 with capture_output(out, err) as io:
1087 self.shell.run_cell(cell)
1084 self.shell.run_cell(cell)
1088 if args.output:
1085 if args.output:
1089 self.shell.user_ns[args.output] = io
1086 self.shell.user_ns[args.output] = io
1090
1087
1091 def parse_breakpoint(text, current_file):
1088 def parse_breakpoint(text, current_file):
1092 '''Returns (file, line) for file:line and (current_file, line) for line'''
1089 '''Returns (file, line) for file:line and (current_file, line) for line'''
1093 colon = text.find(':')
1090 colon = text.find(':')
1094 if colon == -1:
1091 if colon == -1:
1095 return current_file, int(text)
1092 return current_file, int(text)
1096 else:
1093 else:
1097 return text[:colon], int(text[colon+1:])
1094 return text[:colon], int(text[colon+1:])
@@ -1,729 +1,726 b''
1 """Implementation of magic functions for interaction with the OS.
1 """Implementation of magic functions for interaction with the OS.
2
2
3 Note: this module is named 'osm' instead of 'os' to avoid a collision with the
3 Note: this module is named 'osm' instead of 'os' to avoid a collision with the
4 builtin.
4 builtin.
5 """
5 """
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (c) 2012 The IPython Development Team.
7 # Copyright (c) 2012 The IPython Development Team.
8 #
8 #
9 # Distributed under the terms of the Modified BSD License.
9 # Distributed under the terms of the Modified BSD License.
10 #
10 #
11 # The full license is in the file COPYING.txt, distributed with this software.
11 # The full license is in the file COPYING.txt, distributed with this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 # Stdlib
18 # Stdlib
19 import io
19 import io
20 import os
20 import os
21 import re
21 import re
22 import sys
22 import sys
23 from pprint import pformat
23 from pprint import pformat
24
24
25 # Our own packages
25 # Our own packages
26 from IPython.core import magic_arguments
26 from IPython.core import magic_arguments
27 from IPython.core import oinspect
27 from IPython.core import oinspect
28 from IPython.core import page
28 from IPython.core import page
29 from IPython.core.error import UsageError, StdinNotImplementedError
29 from IPython.core.error import UsageError, StdinNotImplementedError
30 from IPython.core.magic import (
30 from IPython.core.magic import (
31 Magics, compress_dhist, magics_class, line_magic, cell_magic, line_cell_magic
31 Magics, compress_dhist, magics_class, line_magic, cell_magic, line_cell_magic
32 )
32 )
33 from IPython.testing.skipdoctest import skip_doctest
33 from IPython.testing.skipdoctest import skip_doctest
34 from IPython.utils.io import file_read, nlprint
34 from IPython.utils.io import file_read, nlprint
35 from IPython.utils.openpy import source_to_unicode
35 from IPython.utils.openpy import source_to_unicode
36 from IPython.utils.path import get_py_filename, unquote_filename
36 from IPython.utils.path import get_py_filename, unquote_filename
37 from IPython.utils.process import abbrev_cwd
37 from IPython.utils.process import abbrev_cwd
38 from IPython.utils.terminal import set_term_title
38 from IPython.utils.terminal import set_term_title
39 from IPython.utils.warn import warn
39
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41 # Magic implementation classes
41 # Magic implementation classes
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43 @magics_class
43 @magics_class
44 class OSMagics(Magics):
44 class OSMagics(Magics):
45 """Magics to interact with the underlying OS (shell-type functionality).
45 """Magics to interact with the underlying OS (shell-type functionality).
46 """
46 """
47
47
48 @skip_doctest
48 @skip_doctest
49 @line_magic
49 @line_magic
50 def alias(self, parameter_s=''):
50 def alias(self, parameter_s=''):
51 """Define an alias for a system command.
51 """Define an alias for a system command.
52
52
53 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
53 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
54
54
55 Then, typing 'alias_name params' will execute the system command 'cmd
55 Then, typing 'alias_name params' will execute the system command 'cmd
56 params' (from your underlying operating system).
56 params' (from your underlying operating system).
57
57
58 Aliases have lower precedence than magic functions and Python normal
58 Aliases have lower precedence than magic functions and Python normal
59 variables, so if 'foo' is both a Python variable and an alias, the
59 variables, so if 'foo' is both a Python variable and an alias, the
60 alias can not be executed until 'del foo' removes the Python variable.
60 alias can not be executed until 'del foo' removes the Python variable.
61
61
62 You can use the %l specifier in an alias definition to represent the
62 You can use the %l specifier in an alias definition to represent the
63 whole line when the alias is called. For example::
63 whole line when the alias is called. For example::
64
64
65 In [2]: alias bracket echo "Input in brackets: <%l>"
65 In [2]: alias bracket echo "Input in brackets: <%l>"
66 In [3]: bracket hello world
66 In [3]: bracket hello world
67 Input in brackets: <hello world>
67 Input in brackets: <hello world>
68
68
69 You can also define aliases with parameters using %s specifiers (one
69 You can also define aliases with parameters using %s specifiers (one
70 per parameter)::
70 per parameter)::
71
71
72 In [1]: alias parts echo first %s second %s
72 In [1]: alias parts echo first %s second %s
73 In [2]: %parts A B
73 In [2]: %parts A B
74 first A second B
74 first A second B
75 In [3]: %parts A
75 In [3]: %parts A
76 Incorrect number of arguments: 2 expected.
76 Incorrect number of arguments: 2 expected.
77 parts is an alias to: 'echo first %s second %s'
77 parts is an alias to: 'echo first %s second %s'
78
78
79 Note that %l and %s are mutually exclusive. You can only use one or
79 Note that %l and %s are mutually exclusive. You can only use one or
80 the other in your aliases.
80 the other in your aliases.
81
81
82 Aliases expand Python variables just like system calls using ! or !!
82 Aliases expand Python variables just like system calls using ! or !!
83 do: all expressions prefixed with '$' get expanded. For details of
83 do: all expressions prefixed with '$' get expanded. For details of
84 the semantic rules, see PEP-215:
84 the semantic rules, see PEP-215:
85 http://www.python.org/peps/pep-0215.html. This is the library used by
85 http://www.python.org/peps/pep-0215.html. This is the library used by
86 IPython for variable expansion. If you want to access a true shell
86 IPython for variable expansion. If you want to access a true shell
87 variable, an extra $ is necessary to prevent its expansion by
87 variable, an extra $ is necessary to prevent its expansion by
88 IPython::
88 IPython::
89
89
90 In [6]: alias show echo
90 In [6]: alias show echo
91 In [7]: PATH='A Python string'
91 In [7]: PATH='A Python string'
92 In [8]: show $PATH
92 In [8]: show $PATH
93 A Python string
93 A Python string
94 In [9]: show $$PATH
94 In [9]: show $$PATH
95 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
95 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
96
96
97 You can use the alias facility to acess all of $PATH. See the %rehash
97 You can use the alias facility to acess all of $PATH. See the %rehash
98 and %rehashx functions, which automatically create aliases for the
98 and %rehashx functions, which automatically create aliases for the
99 contents of your $PATH.
99 contents of your $PATH.
100
100
101 If called with no parameters, %alias prints the current alias table."""
101 If called with no parameters, %alias prints the current alias table."""
102
102
103 par = parameter_s.strip()
103 par = parameter_s.strip()
104 if not par:
104 if not par:
105 aliases = sorted(self.shell.alias_manager.aliases)
105 aliases = sorted(self.shell.alias_manager.aliases)
106 # stored = self.shell.db.get('stored_aliases', {} )
106 # stored = self.shell.db.get('stored_aliases', {} )
107 # for k, v in stored:
107 # for k, v in stored:
108 # atab.append(k, v[0])
108 # atab.append(k, v[0])
109
109
110 print "Total number of aliases:", len(aliases)
110 print "Total number of aliases:", len(aliases)
111 sys.stdout.flush()
111 sys.stdout.flush()
112 return aliases
112 return aliases
113
113
114 # Now try to define a new one
114 # Now try to define a new one
115 try:
115 try:
116 alias,cmd = par.split(None, 1)
116 alias,cmd = par.split(None, 1)
117 except:
117 except:
118 print oinspect.getdoc(self.alias)
118 print oinspect.getdoc(self.alias)
119 else:
119 else:
120 self.shell.alias_manager.soft_define_alias(alias, cmd)
120 self.shell.alias_manager.soft_define_alias(alias, cmd)
121 # end magic_alias
121 # end magic_alias
122
122
123 @line_magic
123 @line_magic
124 def unalias(self, parameter_s=''):
124 def unalias(self, parameter_s=''):
125 """Remove an alias"""
125 """Remove an alias"""
126
126
127 aname = parameter_s.strip()
127 aname = parameter_s.strip()
128 self.shell.alias_manager.undefine_alias(aname)
128 self.shell.alias_manager.undefine_alias(aname)
129 stored = self.shell.db.get('stored_aliases', {} )
129 stored = self.shell.db.get('stored_aliases', {} )
130 if aname in stored:
130 if aname in stored:
131 print "Removing %stored alias",aname
131 print "Removing %stored alias",aname
132 del stored[aname]
132 del stored[aname]
133 self.shell.db['stored_aliases'] = stored
133 self.shell.db['stored_aliases'] = stored
134
134
135 @line_magic
135 @line_magic
136 def rehashx(self, parameter_s=''):
136 def rehashx(self, parameter_s=''):
137 """Update the alias table with all executable files in $PATH.
137 """Update the alias table with all executable files in $PATH.
138
138
139 This version explicitly checks that every entry in $PATH is a file
139 This version explicitly checks that every entry in $PATH is a file
140 with execute access (os.X_OK), so it is much slower than %rehash.
140 with execute access (os.X_OK), so it is much slower than %rehash.
141
141
142 Under Windows, it checks executability as a match against a
142 Under Windows, it checks executability as a match against a
143 '|'-separated string of extensions, stored in the IPython config
143 '|'-separated string of extensions, stored in the IPython config
144 variable win_exec_ext. This defaults to 'exe|com|bat'.
144 variable win_exec_ext. This defaults to 'exe|com|bat'.
145
145
146 This function also resets the root module cache of module completer,
146 This function also resets the root module cache of module completer,
147 used on slow filesystems.
147 used on slow filesystems.
148 """
148 """
149 from IPython.core.alias import InvalidAliasError
149 from IPython.core.alias import InvalidAliasError
150
150
151 # for the benefit of module completer in ipy_completers.py
151 # for the benefit of module completer in ipy_completers.py
152 del self.shell.db['rootmodules']
152 del self.shell.db['rootmodules']
153
153
154 path = [os.path.abspath(os.path.expanduser(p)) for p in
154 path = [os.path.abspath(os.path.expanduser(p)) for p in
155 os.environ.get('PATH','').split(os.pathsep)]
155 os.environ.get('PATH','').split(os.pathsep)]
156 path = filter(os.path.isdir,path)
156 path = filter(os.path.isdir,path)
157
157
158 syscmdlist = []
158 syscmdlist = []
159 # Now define isexec in a cross platform manner.
159 # Now define isexec in a cross platform manner.
160 if os.name == 'posix':
160 if os.name == 'posix':
161 isexec = lambda fname:os.path.isfile(fname) and \
161 isexec = lambda fname:os.path.isfile(fname) and \
162 os.access(fname,os.X_OK)
162 os.access(fname,os.X_OK)
163 else:
163 else:
164 try:
164 try:
165 winext = os.environ['pathext'].replace(';','|').replace('.','')
165 winext = os.environ['pathext'].replace(';','|').replace('.','')
166 except KeyError:
166 except KeyError:
167 winext = 'exe|com|bat|py'
167 winext = 'exe|com|bat|py'
168 if 'py' not in winext:
168 if 'py' not in winext:
169 winext += '|py'
169 winext += '|py'
170 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
170 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
171 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
171 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
172 savedir = os.getcwdu()
172 savedir = os.getcwdu()
173
173
174 # Now walk the paths looking for executables to alias.
174 # Now walk the paths looking for executables to alias.
175 try:
175 try:
176 # write the whole loop for posix/Windows so we don't have an if in
176 # write the whole loop for posix/Windows so we don't have an if in
177 # the innermost part
177 # the innermost part
178 if os.name == 'posix':
178 if os.name == 'posix':
179 for pdir in path:
179 for pdir in path:
180 os.chdir(pdir)
180 os.chdir(pdir)
181 for ff in os.listdir(pdir):
181 for ff in os.listdir(pdir):
182 if isexec(ff):
182 if isexec(ff):
183 try:
183 try:
184 # Removes dots from the name since ipython
184 # Removes dots from the name since ipython
185 # will assume names with dots to be python.
185 # will assume names with dots to be python.
186 self.shell.alias_manager.define_alias(
186 self.shell.alias_manager.define_alias(
187 ff.replace('.',''), ff)
187 ff.replace('.',''), ff)
188 except InvalidAliasError:
188 except InvalidAliasError:
189 pass
189 pass
190 else:
190 else:
191 syscmdlist.append(ff)
191 syscmdlist.append(ff)
192 else:
192 else:
193 no_alias = self.shell.alias_manager.no_alias
193 no_alias = self.shell.alias_manager.no_alias
194 for pdir in path:
194 for pdir in path:
195 os.chdir(pdir)
195 os.chdir(pdir)
196 for ff in os.listdir(pdir):
196 for ff in os.listdir(pdir):
197 base, ext = os.path.splitext(ff)
197 base, ext = os.path.splitext(ff)
198 if isexec(ff) and base.lower() not in no_alias:
198 if isexec(ff) and base.lower() not in no_alias:
199 if ext.lower() == '.exe':
199 if ext.lower() == '.exe':
200 ff = base
200 ff = base
201 try:
201 try:
202 # Removes dots from the name since ipython
202 # Removes dots from the name since ipython
203 # will assume names with dots to be python.
203 # will assume names with dots to be python.
204 self.shell.alias_manager.define_alias(
204 self.shell.alias_manager.define_alias(
205 base.lower().replace('.',''), ff)
205 base.lower().replace('.',''), ff)
206 except InvalidAliasError:
206 except InvalidAliasError:
207 pass
207 pass
208 syscmdlist.append(ff)
208 syscmdlist.append(ff)
209 self.shell.db['syscmdlist'] = syscmdlist
209 self.shell.db['syscmdlist'] = syscmdlist
210 finally:
210 finally:
211 os.chdir(savedir)
211 os.chdir(savedir)
212
212
213 @skip_doctest
213 @skip_doctest
214 @line_magic
214 @line_magic
215 def pwd(self, parameter_s=''):
215 def pwd(self, parameter_s=''):
216 """Return the current working directory path.
216 """Return the current working directory path.
217
217
218 Examples
218 Examples
219 --------
219 --------
220 ::
220 ::
221
221
222 In [9]: pwd
222 In [9]: pwd
223 Out[9]: '/home/tsuser/sprint/ipython'
223 Out[9]: '/home/tsuser/sprint/ipython'
224 """
224 """
225 return os.getcwdu()
225 return os.getcwdu()
226
226
227 @skip_doctest
227 @skip_doctest
228 @line_magic
228 @line_magic
229 def cd(self, parameter_s=''):
229 def cd(self, parameter_s=''):
230 """Change the current working directory.
230 """Change the current working directory.
231
231
232 This command automatically maintains an internal list of directories
232 This command automatically maintains an internal list of directories
233 you visit during your IPython session, in the variable _dh. The
233 you visit during your IPython session, in the variable _dh. The
234 command %dhist shows this history nicely formatted. You can also
234 command %dhist shows this history nicely formatted. You can also
235 do 'cd -<tab>' to see directory history conveniently.
235 do 'cd -<tab>' to see directory history conveniently.
236
236
237 Usage:
237 Usage:
238
238
239 cd 'dir': changes to directory 'dir'.
239 cd 'dir': changes to directory 'dir'.
240
240
241 cd -: changes to the last visited directory.
241 cd -: changes to the last visited directory.
242
242
243 cd -<n>: changes to the n-th directory in the directory history.
243 cd -<n>: changes to the n-th directory in the directory history.
244
244
245 cd --foo: change to directory that matches 'foo' in history
245 cd --foo: change to directory that matches 'foo' in history
246
246
247 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
247 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
248 (note: cd <bookmark_name> is enough if there is no
248 (note: cd <bookmark_name> is enough if there is no
249 directory <bookmark_name>, but a bookmark with the name exists.)
249 directory <bookmark_name>, but a bookmark with the name exists.)
250 'cd -b <tab>' allows you to tab-complete bookmark names.
250 'cd -b <tab>' allows you to tab-complete bookmark names.
251
251
252 Options:
252 Options:
253
253
254 -q: quiet. Do not print the working directory after the cd command is
254 -q: quiet. Do not print the working directory after the cd command is
255 executed. By default IPython's cd command does print this directory,
255 executed. By default IPython's cd command does print this directory,
256 since the default prompts do not display path information.
256 since the default prompts do not display path information.
257
257
258 Note that !cd doesn't work for this purpose because the shell where
258 Note that !cd doesn't work for this purpose because the shell where
259 !command runs is immediately discarded after executing 'command'.
259 !command runs is immediately discarded after executing 'command'.
260
260
261 Examples
261 Examples
262 --------
262 --------
263 ::
263 ::
264
264
265 In [10]: cd parent/child
265 In [10]: cd parent/child
266 /home/tsuser/parent/child
266 /home/tsuser/parent/child
267 """
267 """
268
268
269 oldcwd = os.getcwdu()
269 oldcwd = os.getcwdu()
270 numcd = re.match(r'(-)(\d+)$',parameter_s)
270 numcd = re.match(r'(-)(\d+)$',parameter_s)
271 # jump in directory history by number
271 # jump in directory history by number
272 if numcd:
272 if numcd:
273 nn = int(numcd.group(2))
273 nn = int(numcd.group(2))
274 try:
274 try:
275 ps = self.shell.user_ns['_dh'][nn]
275 ps = self.shell.user_ns['_dh'][nn]
276 except IndexError:
276 except IndexError:
277 print 'The requested directory does not exist in history.'
277 print 'The requested directory does not exist in history.'
278 return
278 return
279 else:
279 else:
280 opts = {}
280 opts = {}
281 elif parameter_s.startswith('--'):
281 elif parameter_s.startswith('--'):
282 ps = None
282 ps = None
283 fallback = None
283 fallback = None
284 pat = parameter_s[2:]
284 pat = parameter_s[2:]
285 dh = self.shell.user_ns['_dh']
285 dh = self.shell.user_ns['_dh']
286 # first search only by basename (last component)
286 # first search only by basename (last component)
287 for ent in reversed(dh):
287 for ent in reversed(dh):
288 if pat in os.path.basename(ent) and os.path.isdir(ent):
288 if pat in os.path.basename(ent) and os.path.isdir(ent):
289 ps = ent
289 ps = ent
290 break
290 break
291
291
292 if fallback is None and pat in ent and os.path.isdir(ent):
292 if fallback is None and pat in ent and os.path.isdir(ent):
293 fallback = ent
293 fallback = ent
294
294
295 # if we have no last part match, pick the first full path match
295 # if we have no last part match, pick the first full path match
296 if ps is None:
296 if ps is None:
297 ps = fallback
297 ps = fallback
298
298
299 if ps is None:
299 if ps is None:
300 print "No matching entry in directory history"
300 print "No matching entry in directory history"
301 return
301 return
302 else:
302 else:
303 opts = {}
303 opts = {}
304
304
305
305
306 else:
306 else:
307 #turn all non-space-escaping backslashes to slashes,
307 #turn all non-space-escaping backslashes to slashes,
308 # for c:\windows\directory\names\
308 # for c:\windows\directory\names\
309 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
309 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
310 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
310 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
311 # jump to previous
311 # jump to previous
312 if ps == '-':
312 if ps == '-':
313 try:
313 try:
314 ps = self.shell.user_ns['_dh'][-2]
314 ps = self.shell.user_ns['_dh'][-2]
315 except IndexError:
315 except IndexError:
316 raise UsageError('%cd -: No previous directory to change to.')
316 raise UsageError('%cd -: No previous directory to change to.')
317 # jump to bookmark if needed
317 # jump to bookmark if needed
318 else:
318 else:
319 if not os.path.isdir(ps) or 'b' in opts:
319 if not os.path.isdir(ps) or 'b' in opts:
320 bkms = self.shell.db.get('bookmarks', {})
320 bkms = self.shell.db.get('bookmarks', {})
321
321
322 if ps in bkms:
322 if ps in bkms:
323 target = bkms[ps]
323 target = bkms[ps]
324 print '(bookmark:%s) -> %s' % (ps, target)
324 print '(bookmark:%s) -> %s' % (ps, target)
325 ps = target
325 ps = target
326 else:
326 else:
327 if 'b' in opts:
327 if 'b' in opts:
328 raise UsageError("Bookmark '%s' not found. "
328 raise UsageError("Bookmark '%s' not found. "
329 "Use '%%bookmark -l' to see your bookmarks." % ps)
329 "Use '%%bookmark -l' to see your bookmarks." % ps)
330
330
331 # strip extra quotes on Windows, because os.chdir doesn't like them
331 # strip extra quotes on Windows, because os.chdir doesn't like them
332 ps = unquote_filename(ps)
332 ps = unquote_filename(ps)
333 # at this point ps should point to the target dir
333 # at this point ps should point to the target dir
334 if ps:
334 if ps:
335 try:
335 try:
336 os.chdir(os.path.expanduser(ps))
336 os.chdir(os.path.expanduser(ps))
337 if hasattr(self.shell, 'term_title') and self.shell.term_title:
337 if hasattr(self.shell, 'term_title') and self.shell.term_title:
338 set_term_title('IPython: ' + abbrev_cwd())
338 set_term_title('IPython: ' + abbrev_cwd())
339 except OSError:
339 except OSError:
340 print sys.exc_info()[1]
340 print sys.exc_info()[1]
341 else:
341 else:
342 cwd = os.getcwdu()
342 cwd = os.getcwdu()
343 dhist = self.shell.user_ns['_dh']
343 dhist = self.shell.user_ns['_dh']
344 if oldcwd != cwd:
344 if oldcwd != cwd:
345 dhist.append(cwd)
345 dhist.append(cwd)
346 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
346 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
347
347
348 else:
348 else:
349 os.chdir(self.shell.home_dir)
349 os.chdir(self.shell.home_dir)
350 if hasattr(self.shell, 'term_title') and self.shell.term_title:
350 if hasattr(self.shell, 'term_title') and self.shell.term_title:
351 set_term_title('IPython: ' + '~')
351 set_term_title('IPython: ' + '~')
352 cwd = os.getcwdu()
352 cwd = os.getcwdu()
353 dhist = self.shell.user_ns['_dh']
353 dhist = self.shell.user_ns['_dh']
354
354
355 if oldcwd != cwd:
355 if oldcwd != cwd:
356 dhist.append(cwd)
356 dhist.append(cwd)
357 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
357 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
358 if not 'q' in opts and self.shell.user_ns['_dh']:
358 if not 'q' in opts and self.shell.user_ns['_dh']:
359 print self.shell.user_ns['_dh'][-1]
359 print self.shell.user_ns['_dh'][-1]
360
360
361
361
362 @line_magic
362 @line_magic
363 def env(self, parameter_s=''):
363 def env(self, parameter_s=''):
364 """List environment variables."""
364 """List environment variables."""
365
365
366 return dict(os.environ)
366 return dict(os.environ)
367
367
368 @line_magic
368 @line_magic
369 def pushd(self, parameter_s=''):
369 def pushd(self, parameter_s=''):
370 """Place the current dir on stack and change directory.
370 """Place the current dir on stack and change directory.
371
371
372 Usage:\\
372 Usage:\\
373 %pushd ['dirname']
373 %pushd ['dirname']
374 """
374 """
375
375
376 dir_s = self.shell.dir_stack
376 dir_s = self.shell.dir_stack
377 tgt = os.path.expanduser(unquote_filename(parameter_s))
377 tgt = os.path.expanduser(unquote_filename(parameter_s))
378 cwd = os.getcwdu().replace(self.shell.home_dir,'~')
378 cwd = os.getcwdu().replace(self.shell.home_dir,'~')
379 if tgt:
379 if tgt:
380 self.cd(parameter_s)
380 self.cd(parameter_s)
381 dir_s.insert(0,cwd)
381 dir_s.insert(0,cwd)
382 return self.shell.magic('dirs')
382 return self.shell.magic('dirs')
383
383
384 @line_magic
384 @line_magic
385 def popd(self, parameter_s=''):
385 def popd(self, parameter_s=''):
386 """Change to directory popped off the top of the stack.
386 """Change to directory popped off the top of the stack.
387 """
387 """
388 if not self.shell.dir_stack:
388 if not self.shell.dir_stack:
389 raise UsageError("%popd on empty stack")
389 raise UsageError("%popd on empty stack")
390 top = self.shell.dir_stack.pop(0)
390 top = self.shell.dir_stack.pop(0)
391 self.cd(top)
391 self.cd(top)
392 print "popd ->",top
392 print "popd ->",top
393
393
394 @line_magic
394 @line_magic
395 def dirs(self, parameter_s=''):
395 def dirs(self, parameter_s=''):
396 """Return the current directory stack."""
396 """Return the current directory stack."""
397
397
398 return self.shell.dir_stack
398 return self.shell.dir_stack
399
399
400 @line_magic
400 @line_magic
401 def dhist(self, parameter_s=''):
401 def dhist(self, parameter_s=''):
402 """Print your history of visited directories.
402 """Print your history of visited directories.
403
403
404 %dhist -> print full history\\
404 %dhist -> print full history\\
405 %dhist n -> print last n entries only\\
405 %dhist n -> print last n entries only\\
406 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
406 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
407
407
408 This history is automatically maintained by the %cd command, and
408 This history is automatically maintained by the %cd command, and
409 always available as the global list variable _dh. You can use %cd -<n>
409 always available as the global list variable _dh. You can use %cd -<n>
410 to go to directory number <n>.
410 to go to directory number <n>.
411
411
412 Note that most of time, you should view directory history by entering
412 Note that most of time, you should view directory history by entering
413 cd -<TAB>.
413 cd -<TAB>.
414
414
415 """
415 """
416
416
417 dh = self.shell.user_ns['_dh']
417 dh = self.shell.user_ns['_dh']
418 if parameter_s:
418 if parameter_s:
419 try:
419 try:
420 args = map(int,parameter_s.split())
420 args = map(int,parameter_s.split())
421 except:
421 except:
422 self.arg_err(self.dhist)
422 self.arg_err(self.dhist)
423 return
423 return
424 if len(args) == 1:
424 if len(args) == 1:
425 ini,fin = max(len(dh)-(args[0]),0),len(dh)
425 ini,fin = max(len(dh)-(args[0]),0),len(dh)
426 elif len(args) == 2:
426 elif len(args) == 2:
427 ini,fin = args
427 ini,fin = args
428 else:
428 else:
429 self.arg_err(self.dhist)
429 self.arg_err(self.dhist)
430 return
430 return
431 else:
431 else:
432 ini,fin = 0,len(dh)
432 ini,fin = 0,len(dh)
433 nlprint(dh,
433 nlprint(dh,
434 header = 'Directory history (kept in _dh)',
434 header = 'Directory history (kept in _dh)',
435 start=ini,stop=fin)
435 start=ini,stop=fin)
436
436
437 @skip_doctest
437 @skip_doctest
438 @line_magic
438 @line_magic
439 def sc(self, parameter_s=''):
439 def sc(self, parameter_s=''):
440 """Shell capture - run shell command and capture output (DEPRECATED use !).
440 """Shell capture - run shell command and capture output (DEPRECATED use !).
441
441
442 DEPRECATED. Suboptimal, retained for backwards compatibility.
442 DEPRECATED. Suboptimal, retained for backwards compatibility.
443
443
444 You should use the form 'var = !command' instead. Example:
444 You should use the form 'var = !command' instead. Example:
445
445
446 "%sc -l myfiles = ls ~" should now be written as
446 "%sc -l myfiles = ls ~" should now be written as
447
447
448 "myfiles = !ls ~"
448 "myfiles = !ls ~"
449
449
450 myfiles.s, myfiles.l and myfiles.n still apply as documented
450 myfiles.s, myfiles.l and myfiles.n still apply as documented
451 below.
451 below.
452
452
453 --
453 --
454 %sc [options] varname=command
454 %sc [options] varname=command
455
455
456 IPython will run the given command using commands.getoutput(), and
456 IPython will run the given command using commands.getoutput(), and
457 will then update the user's interactive namespace with a variable
457 will then update the user's interactive namespace with a variable
458 called varname, containing the value of the call. Your command can
458 called varname, containing the value of the call. Your command can
459 contain shell wildcards, pipes, etc.
459 contain shell wildcards, pipes, etc.
460
460
461 The '=' sign in the syntax is mandatory, and the variable name you
461 The '=' sign in the syntax is mandatory, and the variable name you
462 supply must follow Python's standard conventions for valid names.
462 supply must follow Python's standard conventions for valid names.
463
463
464 (A special format without variable name exists for internal use)
464 (A special format without variable name exists for internal use)
465
465
466 Options:
466 Options:
467
467
468 -l: list output. Split the output on newlines into a list before
468 -l: list output. Split the output on newlines into a list before
469 assigning it to the given variable. By default the output is stored
469 assigning it to the given variable. By default the output is stored
470 as a single string.
470 as a single string.
471
471
472 -v: verbose. Print the contents of the variable.
472 -v: verbose. Print the contents of the variable.
473
473
474 In most cases you should not need to split as a list, because the
474 In most cases you should not need to split as a list, because the
475 returned value is a special type of string which can automatically
475 returned value is a special type of string which can automatically
476 provide its contents either as a list (split on newlines) or as a
476 provide its contents either as a list (split on newlines) or as a
477 space-separated string. These are convenient, respectively, either
477 space-separated string. These are convenient, respectively, either
478 for sequential processing or to be passed to a shell command.
478 for sequential processing or to be passed to a shell command.
479
479
480 For example::
480 For example::
481
481
482 # Capture into variable a
482 # Capture into variable a
483 In [1]: sc a=ls *py
483 In [1]: sc a=ls *py
484
484
485 # a is a string with embedded newlines
485 # a is a string with embedded newlines
486 In [2]: a
486 In [2]: a
487 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
487 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
488
488
489 # which can be seen as a list:
489 # which can be seen as a list:
490 In [3]: a.l
490 In [3]: a.l
491 Out[3]: ['setup.py', 'win32_manual_post_install.py']
491 Out[3]: ['setup.py', 'win32_manual_post_install.py']
492
492
493 # or as a whitespace-separated string:
493 # or as a whitespace-separated string:
494 In [4]: a.s
494 In [4]: a.s
495 Out[4]: 'setup.py win32_manual_post_install.py'
495 Out[4]: 'setup.py win32_manual_post_install.py'
496
496
497 # a.s is useful to pass as a single command line:
497 # a.s is useful to pass as a single command line:
498 In [5]: !wc -l $a.s
498 In [5]: !wc -l $a.s
499 146 setup.py
499 146 setup.py
500 130 win32_manual_post_install.py
500 130 win32_manual_post_install.py
501 276 total
501 276 total
502
502
503 # while the list form is useful to loop over:
503 # while the list form is useful to loop over:
504 In [6]: for f in a.l:
504 In [6]: for f in a.l:
505 ...: !wc -l $f
505 ...: !wc -l $f
506 ...:
506 ...:
507 146 setup.py
507 146 setup.py
508 130 win32_manual_post_install.py
508 130 win32_manual_post_install.py
509
509
510 Similarly, the lists returned by the -l option are also special, in
510 Similarly, the lists returned by the -l option are also special, in
511 the sense that you can equally invoke the .s attribute on them to
511 the sense that you can equally invoke the .s attribute on them to
512 automatically get a whitespace-separated string from their contents::
512 automatically get a whitespace-separated string from their contents::
513
513
514 In [7]: sc -l b=ls *py
514 In [7]: sc -l b=ls *py
515
515
516 In [8]: b
516 In [8]: b
517 Out[8]: ['setup.py', 'win32_manual_post_install.py']
517 Out[8]: ['setup.py', 'win32_manual_post_install.py']
518
518
519 In [9]: b.s
519 In [9]: b.s
520 Out[9]: 'setup.py win32_manual_post_install.py'
520 Out[9]: 'setup.py win32_manual_post_install.py'
521
521
522 In summary, both the lists and strings used for output capture have
522 In summary, both the lists and strings used for output capture have
523 the following special attributes::
523 the following special attributes::
524
524
525 .l (or .list) : value as list.
525 .l (or .list) : value as list.
526 .n (or .nlstr): value as newline-separated string.
526 .n (or .nlstr): value as newline-separated string.
527 .s (or .spstr): value as space-separated string.
527 .s (or .spstr): value as space-separated string.
528 """
528 """
529
529
530 opts,args = self.parse_options(parameter_s, 'lv')
530 opts,args = self.parse_options(parameter_s, 'lv')
531 # Try to get a variable name and command to run
531 # Try to get a variable name and command to run
532 try:
532 try:
533 # the variable name must be obtained from the parse_options
533 # the variable name must be obtained from the parse_options
534 # output, which uses shlex.split to strip options out.
534 # output, which uses shlex.split to strip options out.
535 var,_ = args.split('=', 1)
535 var,_ = args.split('=', 1)
536 var = var.strip()
536 var = var.strip()
537 # But the command has to be extracted from the original input
537 # But the command has to be extracted from the original input
538 # parameter_s, not on what parse_options returns, to avoid the
538 # parameter_s, not on what parse_options returns, to avoid the
539 # quote stripping which shlex.split performs on it.
539 # quote stripping which shlex.split performs on it.
540 _,cmd = parameter_s.split('=', 1)
540 _,cmd = parameter_s.split('=', 1)
541 except ValueError:
541 except ValueError:
542 var,cmd = '',''
542 var,cmd = '',''
543 # If all looks ok, proceed
543 # If all looks ok, proceed
544 split = 'l' in opts
544 split = 'l' in opts
545 out = self.shell.getoutput(cmd, split=split)
545 out = self.shell.getoutput(cmd, split=split)
546 if 'v' in opts:
546 if 'v' in opts:
547 print '%s ==\n%s' % (var, pformat(out))
547 print '%s ==\n%s' % (var, pformat(out))
548 if var:
548 if var:
549 self.shell.user_ns.update({var:out})
549 self.shell.user_ns.update({var:out})
550 else:
550 else:
551 return out
551 return out
552
552
553 @line_cell_magic
553 @line_cell_magic
554 def sx(self, line='', cell=None):
554 def sx(self, line='', cell=None):
555 """Shell execute - run shell command and capture output (!! is short-hand).
555 """Shell execute - run shell command and capture output (!! is short-hand).
556
556
557 %sx command
557 %sx command
558
558
559 IPython will run the given command using commands.getoutput(), and
559 IPython will run the given command using commands.getoutput(), and
560 return the result formatted as a list (split on '\\n'). Since the
560 return the result formatted as a list (split on '\\n'). Since the
561 output is _returned_, it will be stored in ipython's regular output
561 output is _returned_, it will be stored in ipython's regular output
562 cache Out[N] and in the '_N' automatic variables.
562 cache Out[N] and in the '_N' automatic variables.
563
563
564 Notes:
564 Notes:
565
565
566 1) If an input line begins with '!!', then %sx is automatically
566 1) If an input line begins with '!!', then %sx is automatically
567 invoked. That is, while::
567 invoked. That is, while::
568
568
569 !ls
569 !ls
570
570
571 causes ipython to simply issue system('ls'), typing::
571 causes ipython to simply issue system('ls'), typing::
572
572
573 !!ls
573 !!ls
574
574
575 is a shorthand equivalent to::
575 is a shorthand equivalent to::
576
576
577 %sx ls
577 %sx ls
578
578
579 2) %sx differs from %sc in that %sx automatically splits into a list,
579 2) %sx differs from %sc in that %sx automatically splits into a list,
580 like '%sc -l'. The reason for this is to make it as easy as possible
580 like '%sc -l'. The reason for this is to make it as easy as possible
581 to process line-oriented shell output via further python commands.
581 to process line-oriented shell output via further python commands.
582 %sc is meant to provide much finer control, but requires more
582 %sc is meant to provide much finer control, but requires more
583 typing.
583 typing.
584
584
585 3) Just like %sc -l, this is a list with special attributes:
585 3) Just like %sc -l, this is a list with special attributes:
586 ::
586 ::
587
587
588 .l (or .list) : value as list.
588 .l (or .list) : value as list.
589 .n (or .nlstr): value as newline-separated string.
589 .n (or .nlstr): value as newline-separated string.
590 .s (or .spstr): value as whitespace-separated string.
590 .s (or .spstr): value as whitespace-separated string.
591
591
592 This is very useful when trying to use such lists as arguments to
592 This is very useful when trying to use such lists as arguments to
593 system commands."""
593 system commands."""
594
594
595 if cell is None:
595 if cell is None:
596 # line magic
596 # line magic
597 return self.shell.getoutput(line)
597 return self.shell.getoutput(line)
598 elif cell == '':
599 warn("Empty cell. Did you mean to use %!, %sx, or %system?")
600 return
601 else:
598 else:
602 opts,args = self.parse_options(line, '', 'out=')
599 opts,args = self.parse_options(line, '', 'out=')
603 output = self.shell.getoutput(cell)
600 output = self.shell.getoutput(cell)
604 out_name = opts.get('out', opts.get('o'))
601 out_name = opts.get('out', opts.get('o'))
605 if out_name:
602 if out_name:
606 self.shell.user_ns[out_name] = output
603 self.shell.user_ns[out_name] = output
607 else:
604 else:
608 return output
605 return output
609
606
610 system = line_cell_magic('system')(sx)
607 system = line_cell_magic('system')(sx)
611 bang = cell_magic('!')(sx)
608 bang = cell_magic('!')(sx)
612
609
613 @line_magic
610 @line_magic
614 def bookmark(self, parameter_s=''):
611 def bookmark(self, parameter_s=''):
615 """Manage IPython's bookmark system.
612 """Manage IPython's bookmark system.
616
613
617 %bookmark <name> - set bookmark to current dir
614 %bookmark <name> - set bookmark to current dir
618 %bookmark <name> <dir> - set bookmark to <dir>
615 %bookmark <name> <dir> - set bookmark to <dir>
619 %bookmark -l - list all bookmarks
616 %bookmark -l - list all bookmarks
620 %bookmark -d <name> - remove bookmark
617 %bookmark -d <name> - remove bookmark
621 %bookmark -r - remove all bookmarks
618 %bookmark -r - remove all bookmarks
622
619
623 You can later on access a bookmarked folder with::
620 You can later on access a bookmarked folder with::
624
621
625 %cd -b <name>
622 %cd -b <name>
626
623
627 or simply '%cd <name>' if there is no directory called <name> AND
624 or simply '%cd <name>' if there is no directory called <name> AND
628 there is such a bookmark defined.
625 there is such a bookmark defined.
629
626
630 Your bookmarks persist through IPython sessions, but they are
627 Your bookmarks persist through IPython sessions, but they are
631 associated with each profile."""
628 associated with each profile."""
632
629
633 opts,args = self.parse_options(parameter_s,'drl',mode='list')
630 opts,args = self.parse_options(parameter_s,'drl',mode='list')
634 if len(args) > 2:
631 if len(args) > 2:
635 raise UsageError("%bookmark: too many arguments")
632 raise UsageError("%bookmark: too many arguments")
636
633
637 bkms = self.shell.db.get('bookmarks',{})
634 bkms = self.shell.db.get('bookmarks',{})
638
635
639 if 'd' in opts:
636 if 'd' in opts:
640 try:
637 try:
641 todel = args[0]
638 todel = args[0]
642 except IndexError:
639 except IndexError:
643 raise UsageError(
640 raise UsageError(
644 "%bookmark -d: must provide a bookmark to delete")
641 "%bookmark -d: must provide a bookmark to delete")
645 else:
642 else:
646 try:
643 try:
647 del bkms[todel]
644 del bkms[todel]
648 except KeyError:
645 except KeyError:
649 raise UsageError(
646 raise UsageError(
650 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
647 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
651
648
652 elif 'r' in opts:
649 elif 'r' in opts:
653 bkms = {}
650 bkms = {}
654 elif 'l' in opts:
651 elif 'l' in opts:
655 bks = bkms.keys()
652 bks = bkms.keys()
656 bks.sort()
653 bks.sort()
657 if bks:
654 if bks:
658 size = max(map(len, bks))
655 size = max(map(len, bks))
659 else:
656 else:
660 size = 0
657 size = 0
661 fmt = '%-'+str(size)+'s -> %s'
658 fmt = '%-'+str(size)+'s -> %s'
662 print 'Current bookmarks:'
659 print 'Current bookmarks:'
663 for bk in bks:
660 for bk in bks:
664 print fmt % (bk, bkms[bk])
661 print fmt % (bk, bkms[bk])
665 else:
662 else:
666 if not args:
663 if not args:
667 raise UsageError("%bookmark: You must specify the bookmark name")
664 raise UsageError("%bookmark: You must specify the bookmark name")
668 elif len(args)==1:
665 elif len(args)==1:
669 bkms[args[0]] = os.getcwdu()
666 bkms[args[0]] = os.getcwdu()
670 elif len(args)==2:
667 elif len(args)==2:
671 bkms[args[0]] = args[1]
668 bkms[args[0]] = args[1]
672 self.shell.db['bookmarks'] = bkms
669 self.shell.db['bookmarks'] = bkms
673
670
674 @line_magic
671 @line_magic
675 def pycat(self, parameter_s=''):
672 def pycat(self, parameter_s=''):
676 """Show a syntax-highlighted file through a pager.
673 """Show a syntax-highlighted file through a pager.
677
674
678 This magic is similar to the cat utility, but it will assume the file
675 This magic is similar to the cat utility, but it will assume the file
679 to be Python source and will show it with syntax highlighting.
676 to be Python source and will show it with syntax highlighting.
680
677
681 This magic command can either take a local filename, an url,
678 This magic command can either take a local filename, an url,
682 an history range (see %history) or a macro as argument ::
679 an history range (see %history) or a macro as argument ::
683
680
684 %pycat myscript.py
681 %pycat myscript.py
685 %pycat 7-27
682 %pycat 7-27
686 %pycat myMacro
683 %pycat myMacro
687 %pycat http://www.example.com/myscript.py
684 %pycat http://www.example.com/myscript.py
688 """
685 """
689 if not parameter_s:
686 if not parameter_s:
690 raise UsageError('Missing filename, URL, input history range, '
687 raise UsageError('Missing filename, URL, input history range, '
691 'or macro.')
688 'or macro.')
692
689
693 try :
690 try :
694 cont = self.shell.find_user_code(parameter_s, skip_encoding_cookie=False)
691 cont = self.shell.find_user_code(parameter_s, skip_encoding_cookie=False)
695 except (ValueError, IOError):
692 except (ValueError, IOError):
696 print "Error: no such file, variable, URL, history range or macro"
693 print "Error: no such file, variable, URL, history range or macro"
697 return
694 return
698
695
699 page.page(self.shell.pycolorize(source_to_unicode(cont)))
696 page.page(self.shell.pycolorize(source_to_unicode(cont)))
700
697
701 @magic_arguments.magic_arguments()
698 @magic_arguments.magic_arguments()
702 @magic_arguments.argument(
699 @magic_arguments.argument(
703 '-a', '--amend', action='store_true', default=False,
700 '-a', '--amend', action='store_true', default=False,
704 help='Open file for amending if it exists'
701 help='Open file for amending if it exists'
705 )
702 )
706 @magic_arguments.argument(
703 @magic_arguments.argument(
707 'filename', type=unicode,
704 'filename', type=unicode,
708 help='file to write'
705 help='file to write'
709 )
706 )
710 @cell_magic
707 @cell_magic
711 def file(self, line, cell):
708 def file(self, line, cell):
712 """Write the contents of the cell to a file.
709 """Write the contents of the cell to a file.
713
710
714 For frontends that do not support stdin (Notebook), -f is implied.
711 For frontends that do not support stdin (Notebook), -f is implied.
715 """
712 """
716 args = magic_arguments.parse_argstring(self.file, line)
713 args = magic_arguments.parse_argstring(self.file, line)
717 filename = unquote_filename(args.filename)
714 filename = unquote_filename(args.filename)
718
715
719 if os.path.exists(filename):
716 if os.path.exists(filename):
720 if args.amend:
717 if args.amend:
721 print "Amending to %s" % filename
718 print "Amending to %s" % filename
722 else:
719 else:
723 print "Overwriting %s" % filename
720 print "Overwriting %s" % filename
724 else:
721 else:
725 print "Writing %s" % filename
722 print "Writing %s" % filename
726
723
727 mode = 'a' if args.amend else 'w'
724 mode = 'a' if args.amend else 'w'
728 with io.open(filename, mode, encoding='utf-8') as f:
725 with io.open(filename, mode, encoding='utf-8') as f:
729 f.write(cell)
726 f.write(cell)
General Comments 0
You need to be logged in to leave comments. Login now