##// END OF EJS Templates
Use str.format in core magics.
Thomas Kluyver -
Show More
@@ -1,3504 +1,3502 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2008-2009 The IPython Development Team
8 # Copyright (C) 2008-2009 The IPython Development Team
9
9
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17
17
18 import __builtin__
18 import __builtin__
19 import __future__
19 import __future__
20 import bdb
20 import bdb
21 import inspect
21 import inspect
22 import os
22 import os
23 import sys
23 import sys
24 import shutil
24 import shutil
25 import re
25 import re
26 import time
26 import time
27 import textwrap
27 import textwrap
28 from cStringIO import StringIO
28 from cStringIO import StringIO
29 from getopt import getopt,GetoptError
29 from getopt import getopt,GetoptError
30 from pprint import pformat
30 from pprint import pformat
31 from xmlrpclib import ServerProxy
31 from xmlrpclib import ServerProxy
32
32
33 # cProfile was added in Python2.5
33 # cProfile was added in Python2.5
34 try:
34 try:
35 import cProfile as profile
35 import cProfile as profile
36 import pstats
36 import pstats
37 except ImportError:
37 except ImportError:
38 # profile isn't bundled by default in Debian for license reasons
38 # profile isn't bundled by default in Debian for license reasons
39 try:
39 try:
40 import profile,pstats
40 import profile,pstats
41 except ImportError:
41 except ImportError:
42 profile = pstats = None
42 profile = pstats = None
43
43
44 import IPython
44 import IPython
45 from IPython.core import debugger, oinspect
45 from IPython.core import debugger, oinspect
46 from IPython.core.error import TryNext
46 from IPython.core.error import TryNext
47 from IPython.core.error import UsageError
47 from IPython.core.error import UsageError
48 from IPython.core.fakemodule import FakeModule
48 from IPython.core.fakemodule import FakeModule
49 from IPython.core.profiledir import ProfileDir
49 from IPython.core.profiledir import ProfileDir
50 from IPython.core.macro import Macro
50 from IPython.core.macro import Macro
51 from IPython.core import page
51 from IPython.core import page
52 from IPython.core.prefilter import ESC_MAGIC
52 from IPython.core.prefilter import ESC_MAGIC
53 from IPython.lib.pylabtools import mpl_runner
53 from IPython.lib.pylabtools import mpl_runner
54 from IPython.external.Itpl import itpl, printpl
55 from IPython.testing.skipdoctest import skip_doctest
54 from IPython.testing.skipdoctest import skip_doctest
56 from IPython.utils.io import file_read, nlprint
55 from IPython.utils.io import file_read, nlprint
57 from IPython.utils.path import get_py_filename
56 from IPython.utils.path import get_py_filename
58 from IPython.utils.process import arg_split, abbrev_cwd
57 from IPython.utils.process import arg_split, abbrev_cwd
59 from IPython.utils.terminal import set_term_title
58 from IPython.utils.terminal import set_term_title
60 from IPython.utils.text import LSString, SList, format_screen
59 from IPython.utils.text import LSString, SList, format_screen
61 from IPython.utils.timing import clock, clock2
60 from IPython.utils.timing import clock, clock2
62 from IPython.utils.warn import warn, error
61 from IPython.utils.warn import warn, error
63 from IPython.utils.ipstruct import Struct
62 from IPython.utils.ipstruct import Struct
64 import IPython.utils.generics
63 import IPython.utils.generics
65
64
66 #-----------------------------------------------------------------------------
65 #-----------------------------------------------------------------------------
67 # Utility functions
66 # Utility functions
68 #-----------------------------------------------------------------------------
67 #-----------------------------------------------------------------------------
69
68
70 def on_off(tag):
69 def on_off(tag):
71 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
70 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
72 return ['OFF','ON'][tag]
71 return ['OFF','ON'][tag]
73
72
74 class Bunch: pass
73 class Bunch: pass
75
74
76 def compress_dhist(dh):
75 def compress_dhist(dh):
77 head, tail = dh[:-10], dh[-10:]
76 head, tail = dh[:-10], dh[-10:]
78
77
79 newhead = []
78 newhead = []
80 done = set()
79 done = set()
81 for h in head:
80 for h in head:
82 if h in done:
81 if h in done:
83 continue
82 continue
84 newhead.append(h)
83 newhead.append(h)
85 done.add(h)
84 done.add(h)
86
85
87 return newhead + tail
86 return newhead + tail
88
87
89 def needs_local_scope(func):
88 def needs_local_scope(func):
90 """Decorator to mark magic functions which need to local scope to run."""
89 """Decorator to mark magic functions which need to local scope to run."""
91 func.needs_local_scope = True
90 func.needs_local_scope = True
92 return func
91 return func
93
92
94 # Used for exception handling in magic_edit
93 # Used for exception handling in magic_edit
95 class MacroToEdit(ValueError): pass
94 class MacroToEdit(ValueError): pass
96
95
97 #***************************************************************************
96 #***************************************************************************
98 # Main class implementing Magic functionality
97 # Main class implementing Magic functionality
99
98
100 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
99 # XXX - for some odd reason, if Magic is made a new-style class, we get errors
101 # on construction of the main InteractiveShell object. Something odd is going
100 # on construction of the main InteractiveShell object. Something odd is going
102 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
101 # on with super() calls, Configurable and the MRO... For now leave it as-is, but
103 # eventually this needs to be clarified.
102 # eventually this needs to be clarified.
104 # BG: This is because InteractiveShell inherits from this, but is itself a
103 # BG: This is because InteractiveShell inherits from this, but is itself a
105 # Configurable. This messes up the MRO in some way. The fix is that we need to
104 # Configurable. This messes up the MRO in some way. The fix is that we need to
106 # make Magic a configurable that InteractiveShell does not subclass.
105 # make Magic a configurable that InteractiveShell does not subclass.
107
106
108 class Magic:
107 class Magic:
109 """Magic functions for InteractiveShell.
108 """Magic functions for InteractiveShell.
110
109
111 Shell functions which can be reached as %function_name. All magic
110 Shell functions which can be reached as %function_name. All magic
112 functions should accept a string, which they can parse for their own
111 functions should accept a string, which they can parse for their own
113 needs. This can make some functions easier to type, eg `%cd ../`
112 needs. This can make some functions easier to type, eg `%cd ../`
114 vs. `%cd("../")`
113 vs. `%cd("../")`
115
114
116 ALL definitions MUST begin with the prefix magic_. The user won't need it
115 ALL definitions MUST begin with the prefix magic_. The user won't need it
117 at the command line, but it is is needed in the definition. """
116 at the command line, but it is is needed in the definition. """
118
117
119 # class globals
118 # class globals
120 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
119 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
121 'Automagic is ON, % prefix NOT needed for magic functions.']
120 'Automagic is ON, % prefix NOT needed for magic functions.']
122
121
123 #......................................................................
122 #......................................................................
124 # some utility functions
123 # some utility functions
125
124
126 def __init__(self,shell):
125 def __init__(self,shell):
127
126
128 self.options_table = {}
127 self.options_table = {}
129 if profile is None:
128 if profile is None:
130 self.magic_prun = self.profile_missing_notice
129 self.magic_prun = self.profile_missing_notice
131 self.shell = shell
130 self.shell = shell
132
131
133 # namespace for holding state we may need
132 # namespace for holding state we may need
134 self._magic_state = Bunch()
133 self._magic_state = Bunch()
135
134
136 def profile_missing_notice(self, *args, **kwargs):
135 def profile_missing_notice(self, *args, **kwargs):
137 error("""\
136 error("""\
138 The profile module could not be found. It has been removed from the standard
137 The profile module could not be found. It has been removed from the standard
139 python packages because of its non-free license. To use profiling, install the
138 python packages because of its non-free license. To use profiling, install the
140 python-profiler package from non-free.""")
139 python-profiler package from non-free.""")
141
140
142 def default_option(self,fn,optstr):
141 def default_option(self,fn,optstr):
143 """Make an entry in the options_table for fn, with value optstr"""
142 """Make an entry in the options_table for fn, with value optstr"""
144
143
145 if fn not in self.lsmagic():
144 if fn not in self.lsmagic():
146 error("%s is not a magic function" % fn)
145 error("%s is not a magic function" % fn)
147 self.options_table[fn] = optstr
146 self.options_table[fn] = optstr
148
147
149 def lsmagic(self):
148 def lsmagic(self):
150 """Return a list of currently available magic functions.
149 """Return a list of currently available magic functions.
151
150
152 Gives a list of the bare names after mangling (['ls','cd', ...], not
151 Gives a list of the bare names after mangling (['ls','cd', ...], not
153 ['magic_ls','magic_cd',...]"""
152 ['magic_ls','magic_cd',...]"""
154
153
155 # FIXME. This needs a cleanup, in the way the magics list is built.
154 # FIXME. This needs a cleanup, in the way the magics list is built.
156
155
157 # magics in class definition
156 # magics in class definition
158 class_magic = lambda fn: fn.startswith('magic_') and \
157 class_magic = lambda fn: fn.startswith('magic_') and \
159 callable(Magic.__dict__[fn])
158 callable(Magic.__dict__[fn])
160 # in instance namespace (run-time user additions)
159 # in instance namespace (run-time user additions)
161 inst_magic = lambda fn: fn.startswith('magic_') and \
160 inst_magic = lambda fn: fn.startswith('magic_') and \
162 callable(self.__dict__[fn])
161 callable(self.__dict__[fn])
163 # and bound magics by user (so they can access self):
162 # and bound magics by user (so they can access self):
164 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
163 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
165 callable(self.__class__.__dict__[fn])
164 callable(self.__class__.__dict__[fn])
166 magics = filter(class_magic,Magic.__dict__.keys()) + \
165 magics = filter(class_magic,Magic.__dict__.keys()) + \
167 filter(inst_magic,self.__dict__.keys()) + \
166 filter(inst_magic,self.__dict__.keys()) + \
168 filter(inst_bound_magic,self.__class__.__dict__.keys())
167 filter(inst_bound_magic,self.__class__.__dict__.keys())
169 out = []
168 out = []
170 for fn in set(magics):
169 for fn in set(magics):
171 out.append(fn.replace('magic_','',1))
170 out.append(fn.replace('magic_','',1))
172 out.sort()
171 out.sort()
173 return out
172 return out
174
173
175 def extract_input_lines(self, range_str, raw=False):
174 def extract_input_lines(self, range_str, raw=False):
176 """Return as a string a set of input history slices.
175 """Return as a string a set of input history slices.
177
176
178 Inputs:
177 Inputs:
179
178
180 - range_str: the set of slices is given as a string, like
179 - range_str: the set of slices is given as a string, like
181 "~5/6-~4/2 4:8 9", since this function is for use by magic functions
180 "~5/6-~4/2 4:8 9", since this function is for use by magic functions
182 which get their arguments as strings. The number before the / is the
181 which get their arguments as strings. The number before the / is the
183 session number: ~n goes n back from the current session.
182 session number: ~n goes n back from the current session.
184
183
185 Optional inputs:
184 Optional inputs:
186
185
187 - raw(False): by default, the processed input is used. If this is
186 - raw(False): by default, the processed input is used. If this is
188 true, the raw input history is used instead.
187 true, the raw input history is used instead.
189
188
190 Note that slices can be called with two notations:
189 Note that slices can be called with two notations:
191
190
192 N:M -> standard python form, means including items N...(M-1).
191 N:M -> standard python form, means including items N...(M-1).
193
192
194 N-M -> include items N..M (closed endpoint)."""
193 N-M -> include items N..M (closed endpoint)."""
195 lines = self.shell.history_manager.\
194 lines = self.shell.history_manager.\
196 get_range_by_str(range_str, raw=raw)
195 get_range_by_str(range_str, raw=raw)
197 return "\n".join(x for _, _, x in lines)
196 return "\n".join(x for _, _, x in lines)
198
197
199 def arg_err(self,func):
198 def arg_err(self,func):
200 """Print docstring if incorrect arguments were passed"""
199 """Print docstring if incorrect arguments were passed"""
201 print 'Error in arguments:'
200 print 'Error in arguments:'
202 print oinspect.getdoc(func)
201 print oinspect.getdoc(func)
203
202
204 def format_latex(self,strng):
203 def format_latex(self,strng):
205 """Format a string for latex inclusion."""
204 """Format a string for latex inclusion."""
206
205
207 # Characters that need to be escaped for latex:
206 # Characters that need to be escaped for latex:
208 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
207 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
209 # Magic command names as headers:
208 # Magic command names as headers:
210 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
209 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
211 re.MULTILINE)
210 re.MULTILINE)
212 # Magic commands
211 # Magic commands
213 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
212 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
214 re.MULTILINE)
213 re.MULTILINE)
215 # Paragraph continue
214 # Paragraph continue
216 par_re = re.compile(r'\\$',re.MULTILINE)
215 par_re = re.compile(r'\\$',re.MULTILINE)
217
216
218 # The "\n" symbol
217 # The "\n" symbol
219 newline_re = re.compile(r'\\n')
218 newline_re = re.compile(r'\\n')
220
219
221 # Now build the string for output:
220 # Now build the string for output:
222 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
221 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
223 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
222 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
224 strng)
223 strng)
225 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
224 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
226 strng = par_re.sub(r'\\\\',strng)
225 strng = par_re.sub(r'\\\\',strng)
227 strng = escape_re.sub(r'\\\1',strng)
226 strng = escape_re.sub(r'\\\1',strng)
228 strng = newline_re.sub(r'\\textbackslash{}n',strng)
227 strng = newline_re.sub(r'\\textbackslash{}n',strng)
229 return strng
228 return strng
230
229
231 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
230 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
232 """Parse options passed to an argument string.
231 """Parse options passed to an argument string.
233
232
234 The interface is similar to that of getopt(), but it returns back a
233 The interface is similar to that of getopt(), but it returns back a
235 Struct with the options as keys and the stripped argument string still
234 Struct with the options as keys and the stripped argument string still
236 as a string.
235 as a string.
237
236
238 arg_str is quoted as a true sys.argv vector by using shlex.split.
237 arg_str is quoted as a true sys.argv vector by using shlex.split.
239 This allows us to easily expand variables, glob files, quote
238 This allows us to easily expand variables, glob files, quote
240 arguments, etc.
239 arguments, etc.
241
240
242 Options:
241 Options:
243 -mode: default 'string'. If given as 'list', the argument string is
242 -mode: default 'string'. If given as 'list', the argument string is
244 returned as a list (split on whitespace) instead of a string.
243 returned as a list (split on whitespace) instead of a string.
245
244
246 -list_all: put all option values in lists. Normally only options
245 -list_all: put all option values in lists. Normally only options
247 appearing more than once are put in a list.
246 appearing more than once are put in a list.
248
247
249 -posix (True): whether to split the input line in POSIX mode or not,
248 -posix (True): whether to split the input line in POSIX mode or not,
250 as per the conventions outlined in the shlex module from the
249 as per the conventions outlined in the shlex module from the
251 standard library."""
250 standard library."""
252
251
253 # inject default options at the beginning of the input line
252 # inject default options at the beginning of the input line
254 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
253 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
255 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
254 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
256
255
257 mode = kw.get('mode','string')
256 mode = kw.get('mode','string')
258 if mode not in ['string','list']:
257 if mode not in ['string','list']:
259 raise ValueError,'incorrect mode given: %s' % mode
258 raise ValueError,'incorrect mode given: %s' % mode
260 # Get options
259 # Get options
261 list_all = kw.get('list_all',0)
260 list_all = kw.get('list_all',0)
262 posix = kw.get('posix', os.name == 'posix')
261 posix = kw.get('posix', os.name == 'posix')
263
262
264 # Check if we have more than one argument to warrant extra processing:
263 # Check if we have more than one argument to warrant extra processing:
265 odict = {} # Dictionary with options
264 odict = {} # Dictionary with options
266 args = arg_str.split()
265 args = arg_str.split()
267 if len(args) >= 1:
266 if len(args) >= 1:
268 # If the list of inputs only has 0 or 1 thing in it, there's no
267 # If the list of inputs only has 0 or 1 thing in it, there's no
269 # need to look for options
268 # need to look for options
270 argv = arg_split(arg_str,posix)
269 argv = arg_split(arg_str,posix)
271 # Do regular option processing
270 # Do regular option processing
272 try:
271 try:
273 opts,args = getopt(argv,opt_str,*long_opts)
272 opts,args = getopt(argv,opt_str,*long_opts)
274 except GetoptError,e:
273 except GetoptError,e:
275 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
274 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
276 " ".join(long_opts)))
275 " ".join(long_opts)))
277 for o,a in opts:
276 for o,a in opts:
278 if o.startswith('--'):
277 if o.startswith('--'):
279 o = o[2:]
278 o = o[2:]
280 else:
279 else:
281 o = o[1:]
280 o = o[1:]
282 try:
281 try:
283 odict[o].append(a)
282 odict[o].append(a)
284 except AttributeError:
283 except AttributeError:
285 odict[o] = [odict[o],a]
284 odict[o] = [odict[o],a]
286 except KeyError:
285 except KeyError:
287 if list_all:
286 if list_all:
288 odict[o] = [a]
287 odict[o] = [a]
289 else:
288 else:
290 odict[o] = a
289 odict[o] = a
291
290
292 # Prepare opts,args for return
291 # Prepare opts,args for return
293 opts = Struct(odict)
292 opts = Struct(odict)
294 if mode == 'string':
293 if mode == 'string':
295 args = ' '.join(args)
294 args = ' '.join(args)
296
295
297 return opts,args
296 return opts,args
298
297
299 #......................................................................
298 #......................................................................
300 # And now the actual magic functions
299 # And now the actual magic functions
301
300
302 # Functions for IPython shell work (vars,funcs, config, etc)
301 # Functions for IPython shell work (vars,funcs, config, etc)
303 def magic_lsmagic(self, parameter_s = ''):
302 def magic_lsmagic(self, parameter_s = ''):
304 """List currently available magic functions."""
303 """List currently available magic functions."""
305 mesc = ESC_MAGIC
304 mesc = ESC_MAGIC
306 print 'Available magic functions:\n'+mesc+\
305 print 'Available magic functions:\n'+mesc+\
307 (' '+mesc).join(self.lsmagic())
306 (' '+mesc).join(self.lsmagic())
308 print '\n' + Magic.auto_status[self.shell.automagic]
307 print '\n' + Magic.auto_status[self.shell.automagic]
309 return None
308 return None
310
309
311 def magic_magic(self, parameter_s = ''):
310 def magic_magic(self, parameter_s = ''):
312 """Print information about the magic function system.
311 """Print information about the magic function system.
313
312
314 Supported formats: -latex, -brief, -rest
313 Supported formats: -latex, -brief, -rest
315 """
314 """
316
315
317 mode = ''
316 mode = ''
318 try:
317 try:
319 if parameter_s.split()[0] == '-latex':
318 if parameter_s.split()[0] == '-latex':
320 mode = 'latex'
319 mode = 'latex'
321 if parameter_s.split()[0] == '-brief':
320 if parameter_s.split()[0] == '-brief':
322 mode = 'brief'
321 mode = 'brief'
323 if parameter_s.split()[0] == '-rest':
322 if parameter_s.split()[0] == '-rest':
324 mode = 'rest'
323 mode = 'rest'
325 rest_docs = []
324 rest_docs = []
326 except:
325 except:
327 pass
326 pass
328
327
329 magic_docs = []
328 magic_docs = []
330 for fname in self.lsmagic():
329 for fname in self.lsmagic():
331 mname = 'magic_' + fname
330 mname = 'magic_' + fname
332 for space in (Magic,self,self.__class__):
331 for space in (Magic,self,self.__class__):
333 try:
332 try:
334 fn = space.__dict__[mname]
333 fn = space.__dict__[mname]
335 except KeyError:
334 except KeyError:
336 pass
335 pass
337 else:
336 else:
338 break
337 break
339 if mode == 'brief':
338 if mode == 'brief':
340 # only first line
339 # only first line
341 if fn.__doc__:
340 if fn.__doc__:
342 fndoc = fn.__doc__.split('\n',1)[0]
341 fndoc = fn.__doc__.split('\n',1)[0]
343 else:
342 else:
344 fndoc = 'No documentation'
343 fndoc = 'No documentation'
345 else:
344 else:
346 if fn.__doc__:
345 if fn.__doc__:
347 fndoc = fn.__doc__.rstrip()
346 fndoc = fn.__doc__.rstrip()
348 else:
347 else:
349 fndoc = 'No documentation'
348 fndoc = 'No documentation'
350
349
351
350
352 if mode == 'rest':
351 if mode == 'rest':
353 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
352 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC,
354 fname,fndoc))
353 fname,fndoc))
355
354
356 else:
355 else:
357 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
356 magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC,
358 fname,fndoc))
357 fname,fndoc))
359
358
360 magic_docs = ''.join(magic_docs)
359 magic_docs = ''.join(magic_docs)
361
360
362 if mode == 'rest':
361 if mode == 'rest':
363 return "".join(rest_docs)
362 return "".join(rest_docs)
364
363
365 if mode == 'latex':
364 if mode == 'latex':
366 print self.format_latex(magic_docs)
365 print self.format_latex(magic_docs)
367 return
366 return
368 else:
367 else:
369 magic_docs = format_screen(magic_docs)
368 magic_docs = format_screen(magic_docs)
370 if mode == 'brief':
369 if mode == 'brief':
371 return magic_docs
370 return magic_docs
372
371
373 outmsg = """
372 outmsg = """
374 IPython's 'magic' functions
373 IPython's 'magic' functions
375 ===========================
374 ===========================
376
375
377 The magic function system provides a series of functions which allow you to
376 The magic function system provides a series of functions which allow you to
378 control the behavior of IPython itself, plus a lot of system-type
377 control the behavior of IPython itself, plus a lot of system-type
379 features. All these functions are prefixed with a % character, but parameters
378 features. All these functions are prefixed with a % character, but parameters
380 are given without parentheses or quotes.
379 are given without parentheses or quotes.
381
380
382 NOTE: If you have 'automagic' enabled (via the command line option or with the
381 NOTE: If you have 'automagic' enabled (via the command line option or with the
383 %automagic function), you don't need to type in the % explicitly. By default,
382 %automagic function), you don't need to type in the % explicitly. By default,
384 IPython ships with automagic on, so you should only rarely need the % escape.
383 IPython ships with automagic on, so you should only rarely need the % escape.
385
384
386 Example: typing '%cd mydir' (without the quotes) changes you working directory
385 Example: typing '%cd mydir' (without the quotes) changes you working directory
387 to 'mydir', if it exists.
386 to 'mydir', if it exists.
388
387
389 You can define your own magic functions to extend the system. See the supplied
388 You can define your own magic functions to extend the system. See the supplied
390 ipythonrc and example-magic.py files for details (in your ipython
389 ipythonrc and example-magic.py files for details (in your ipython
391 configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere).
390 configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere).
392
391
393 You can also define your own aliased names for magic functions. In your
392 You can also define your own aliased names for magic functions. In your
394 ipythonrc file, placing a line like:
393 ipythonrc file, placing a line like:
395
394
396 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
395 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
397
396
398 will define %pf as a new name for %profile.
397 will define %pf as a new name for %profile.
399
398
400 You can also call magics in code using the magic() function, which IPython
399 You can also call magics in code using the magic() function, which IPython
401 automatically adds to the builtin namespace. Type 'magic?' for details.
400 automatically adds to the builtin namespace. Type 'magic?' for details.
402
401
403 For a list of the available magic functions, use %lsmagic. For a description
402 For a list of the available magic functions, use %lsmagic. For a description
404 of any of them, type %magic_name?, e.g. '%cd?'.
403 of any of them, type %magic_name?, e.g. '%cd?'.
405
404
406 Currently the magic system has the following functions:\n"""
405 Currently the magic system has the following functions:\n"""
407
406
408 mesc = ESC_MAGIC
407 mesc = ESC_MAGIC
409 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
408 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
410 "\n\n%s%s\n\n%s" % (outmsg,
409 "\n\n%s%s\n\n%s" % (outmsg,
411 magic_docs,mesc,mesc,
410 magic_docs,mesc,mesc,
412 (' '+mesc).join(self.lsmagic()),
411 (' '+mesc).join(self.lsmagic()),
413 Magic.auto_status[self.shell.automagic] ) )
412 Magic.auto_status[self.shell.automagic] ) )
414 page.page(outmsg)
413 page.page(outmsg)
415
414
416 def magic_automagic(self, parameter_s = ''):
415 def magic_automagic(self, parameter_s = ''):
417 """Make magic functions callable without having to type the initial %.
416 """Make magic functions callable without having to type the initial %.
418
417
419 Without argumentsl toggles on/off (when off, you must call it as
418 Without argumentsl toggles on/off (when off, you must call it as
420 %automagic, of course). With arguments it sets the value, and you can
419 %automagic, of course). With arguments it sets the value, and you can
421 use any of (case insensitive):
420 use any of (case insensitive):
422
421
423 - on,1,True: to activate
422 - on,1,True: to activate
424
423
425 - off,0,False: to deactivate.
424 - off,0,False: to deactivate.
426
425
427 Note that magic functions have lowest priority, so if there's a
426 Note that magic functions have lowest priority, so if there's a
428 variable whose name collides with that of a magic fn, automagic won't
427 variable whose name collides with that of a magic fn, automagic won't
429 work for that function (you get the variable instead). However, if you
428 work for that function (you get the variable instead). However, if you
430 delete the variable (del var), the previously shadowed magic function
429 delete the variable (del var), the previously shadowed magic function
431 becomes visible to automagic again."""
430 becomes visible to automagic again."""
432
431
433 arg = parameter_s.lower()
432 arg = parameter_s.lower()
434 if parameter_s in ('on','1','true'):
433 if parameter_s in ('on','1','true'):
435 self.shell.automagic = True
434 self.shell.automagic = True
436 elif parameter_s in ('off','0','false'):
435 elif parameter_s in ('off','0','false'):
437 self.shell.automagic = False
436 self.shell.automagic = False
438 else:
437 else:
439 self.shell.automagic = not self.shell.automagic
438 self.shell.automagic = not self.shell.automagic
440 print '\n' + Magic.auto_status[self.shell.automagic]
439 print '\n' + Magic.auto_status[self.shell.automagic]
441
440
442 @skip_doctest
441 @skip_doctest
443 def magic_autocall(self, parameter_s = ''):
442 def magic_autocall(self, parameter_s = ''):
444 """Make functions callable without having to type parentheses.
443 """Make functions callable without having to type parentheses.
445
444
446 Usage:
445 Usage:
447
446
448 %autocall [mode]
447 %autocall [mode]
449
448
450 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
449 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
451 value is toggled on and off (remembering the previous state).
450 value is toggled on and off (remembering the previous state).
452
451
453 In more detail, these values mean:
452 In more detail, these values mean:
454
453
455 0 -> fully disabled
454 0 -> fully disabled
456
455
457 1 -> active, but do not apply if there are no arguments on the line.
456 1 -> active, but do not apply if there are no arguments on the line.
458
457
459 In this mode, you get:
458 In this mode, you get:
460
459
461 In [1]: callable
460 In [1]: callable
462 Out[1]: <built-in function callable>
461 Out[1]: <built-in function callable>
463
462
464 In [2]: callable 'hello'
463 In [2]: callable 'hello'
465 ------> callable('hello')
464 ------> callable('hello')
466 Out[2]: False
465 Out[2]: False
467
466
468 2 -> Active always. Even if no arguments are present, the callable
467 2 -> Active always. Even if no arguments are present, the callable
469 object is called:
468 object is called:
470
469
471 In [2]: float
470 In [2]: float
472 ------> float()
471 ------> float()
473 Out[2]: 0.0
472 Out[2]: 0.0
474
473
475 Note that even with autocall off, you can still use '/' at the start of
474 Note that even with autocall off, you can still use '/' at the start of
476 a line to treat the first argument on the command line as a function
475 a line to treat the first argument on the command line as a function
477 and add parentheses to it:
476 and add parentheses to it:
478
477
479 In [8]: /str 43
478 In [8]: /str 43
480 ------> str(43)
479 ------> str(43)
481 Out[8]: '43'
480 Out[8]: '43'
482
481
483 # all-random (note for auto-testing)
482 # all-random (note for auto-testing)
484 """
483 """
485
484
486 if parameter_s:
485 if parameter_s:
487 arg = int(parameter_s)
486 arg = int(parameter_s)
488 else:
487 else:
489 arg = 'toggle'
488 arg = 'toggle'
490
489
491 if not arg in (0,1,2,'toggle'):
490 if not arg in (0,1,2,'toggle'):
492 error('Valid modes: (0->Off, 1->Smart, 2->Full')
491 error('Valid modes: (0->Off, 1->Smart, 2->Full')
493 return
492 return
494
493
495 if arg in (0,1,2):
494 if arg in (0,1,2):
496 self.shell.autocall = arg
495 self.shell.autocall = arg
497 else: # toggle
496 else: # toggle
498 if self.shell.autocall:
497 if self.shell.autocall:
499 self._magic_state.autocall_save = self.shell.autocall
498 self._magic_state.autocall_save = self.shell.autocall
500 self.shell.autocall = 0
499 self.shell.autocall = 0
501 else:
500 else:
502 try:
501 try:
503 self.shell.autocall = self._magic_state.autocall_save
502 self.shell.autocall = self._magic_state.autocall_save
504 except AttributeError:
503 except AttributeError:
505 self.shell.autocall = self._magic_state.autocall_save = 1
504 self.shell.autocall = self._magic_state.autocall_save = 1
506
505
507 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
506 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
508
507
509
508
510 def magic_page(self, parameter_s=''):
509 def magic_page(self, parameter_s=''):
511 """Pretty print the object and display it through a pager.
510 """Pretty print the object and display it through a pager.
512
511
513 %page [options] OBJECT
512 %page [options] OBJECT
514
513
515 If no object is given, use _ (last output).
514 If no object is given, use _ (last output).
516
515
517 Options:
516 Options:
518
517
519 -r: page str(object), don't pretty-print it."""
518 -r: page str(object), don't pretty-print it."""
520
519
521 # After a function contributed by Olivier Aubert, slightly modified.
520 # After a function contributed by Olivier Aubert, slightly modified.
522
521
523 # Process options/args
522 # Process options/args
524 opts,args = self.parse_options(parameter_s,'r')
523 opts,args = self.parse_options(parameter_s,'r')
525 raw = 'r' in opts
524 raw = 'r' in opts
526
525
527 oname = args and args or '_'
526 oname = args and args or '_'
528 info = self._ofind(oname)
527 info = self._ofind(oname)
529 if info['found']:
528 if info['found']:
530 txt = (raw and str or pformat)( info['obj'] )
529 txt = (raw and str or pformat)( info['obj'] )
531 page.page(txt)
530 page.page(txt)
532 else:
531 else:
533 print 'Object `%s` not found' % oname
532 print 'Object `%s` not found' % oname
534
533
535 def magic_profile(self, parameter_s=''):
534 def magic_profile(self, parameter_s=''):
536 """Print your currently active IPython profile."""
535 """Print your currently active IPython profile."""
537 print self.shell.profile
536 print self.shell.profile
538
537
539 def magic_pinfo(self, parameter_s='', namespaces=None):
538 def magic_pinfo(self, parameter_s='', namespaces=None):
540 """Provide detailed information about an object.
539 """Provide detailed information about an object.
541
540
542 '%pinfo object' is just a synonym for object? or ?object."""
541 '%pinfo object' is just a synonym for object? or ?object."""
543
542
544 #print 'pinfo par: <%s>' % parameter_s # dbg
543 #print 'pinfo par: <%s>' % parameter_s # dbg
545
544
546
545
547 # detail_level: 0 -> obj? , 1 -> obj??
546 # detail_level: 0 -> obj? , 1 -> obj??
548 detail_level = 0
547 detail_level = 0
549 # We need to detect if we got called as 'pinfo pinfo foo', which can
548 # We need to detect if we got called as 'pinfo pinfo foo', which can
550 # happen if the user types 'pinfo foo?' at the cmd line.
549 # happen if the user types 'pinfo foo?' at the cmd line.
551 pinfo,qmark1,oname,qmark2 = \
550 pinfo,qmark1,oname,qmark2 = \
552 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
551 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
553 if pinfo or qmark1 or qmark2:
552 if pinfo or qmark1 or qmark2:
554 detail_level = 1
553 detail_level = 1
555 if "*" in oname:
554 if "*" in oname:
556 self.magic_psearch(oname)
555 self.magic_psearch(oname)
557 else:
556 else:
558 self.shell._inspect('pinfo', oname, detail_level=detail_level,
557 self.shell._inspect('pinfo', oname, detail_level=detail_level,
559 namespaces=namespaces)
558 namespaces=namespaces)
560
559
561 def magic_pinfo2(self, parameter_s='', namespaces=None):
560 def magic_pinfo2(self, parameter_s='', namespaces=None):
562 """Provide extra detailed information about an object.
561 """Provide extra detailed information about an object.
563
562
564 '%pinfo2 object' is just a synonym for object?? or ??object."""
563 '%pinfo2 object' is just a synonym for object?? or ??object."""
565 self.shell._inspect('pinfo', parameter_s, detail_level=1,
564 self.shell._inspect('pinfo', parameter_s, detail_level=1,
566 namespaces=namespaces)
565 namespaces=namespaces)
567
566
568 @skip_doctest
567 @skip_doctest
569 def magic_pdef(self, parameter_s='', namespaces=None):
568 def magic_pdef(self, parameter_s='', namespaces=None):
570 """Print the definition header for any callable object.
569 """Print the definition header for any callable object.
571
570
572 If the object is a class, print the constructor information.
571 If the object is a class, print the constructor information.
573
572
574 Examples
573 Examples
575 --------
574 --------
576 ::
575 ::
577
576
578 In [3]: %pdef urllib.urlopen
577 In [3]: %pdef urllib.urlopen
579 urllib.urlopen(url, data=None, proxies=None)
578 urllib.urlopen(url, data=None, proxies=None)
580 """
579 """
581 self._inspect('pdef',parameter_s, namespaces)
580 self._inspect('pdef',parameter_s, namespaces)
582
581
583 def magic_pdoc(self, parameter_s='', namespaces=None):
582 def magic_pdoc(self, parameter_s='', namespaces=None):
584 """Print the docstring for an object.
583 """Print the docstring for an object.
585
584
586 If the given object is a class, it will print both the class and the
585 If the given object is a class, it will print both the class and the
587 constructor docstrings."""
586 constructor docstrings."""
588 self._inspect('pdoc',parameter_s, namespaces)
587 self._inspect('pdoc',parameter_s, namespaces)
589
588
590 def magic_psource(self, parameter_s='', namespaces=None):
589 def magic_psource(self, parameter_s='', namespaces=None):
591 """Print (or run through pager) the source code for an object."""
590 """Print (or run through pager) the source code for an object."""
592 self._inspect('psource',parameter_s, namespaces)
591 self._inspect('psource',parameter_s, namespaces)
593
592
594 def magic_pfile(self, parameter_s=''):
593 def magic_pfile(self, parameter_s=''):
595 """Print (or run through pager) the file where an object is defined.
594 """Print (or run through pager) the file where an object is defined.
596
595
597 The file opens at the line where the object definition begins. IPython
596 The file opens at the line where the object definition begins. IPython
598 will honor the environment variable PAGER if set, and otherwise will
597 will honor the environment variable PAGER if set, and otherwise will
599 do its best to print the file in a convenient form.
598 do its best to print the file in a convenient form.
600
599
601 If the given argument is not an object currently defined, IPython will
600 If the given argument is not an object currently defined, IPython will
602 try to interpret it as a filename (automatically adding a .py extension
601 try to interpret it as a filename (automatically adding a .py extension
603 if needed). You can thus use %pfile as a syntax highlighting code
602 if needed). You can thus use %pfile as a syntax highlighting code
604 viewer."""
603 viewer."""
605
604
606 # first interpret argument as an object name
605 # first interpret argument as an object name
607 out = self._inspect('pfile',parameter_s)
606 out = self._inspect('pfile',parameter_s)
608 # if not, try the input as a filename
607 # if not, try the input as a filename
609 if out == 'not found':
608 if out == 'not found':
610 try:
609 try:
611 filename = get_py_filename(parameter_s)
610 filename = get_py_filename(parameter_s)
612 except IOError,msg:
611 except IOError,msg:
613 print msg
612 print msg
614 return
613 return
615 page.page(self.shell.inspector.format(file(filename).read()))
614 page.page(self.shell.inspector.format(file(filename).read()))
616
615
617 def magic_psearch(self, parameter_s=''):
616 def magic_psearch(self, parameter_s=''):
618 """Search for object in namespaces by wildcard.
617 """Search for object in namespaces by wildcard.
619
618
620 %psearch [options] PATTERN [OBJECT TYPE]
619 %psearch [options] PATTERN [OBJECT TYPE]
621
620
622 Note: ? can be used as a synonym for %psearch, at the beginning or at
621 Note: ? can be used as a synonym for %psearch, at the beginning or at
623 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
622 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
624 rest of the command line must be unchanged (options come first), so
623 rest of the command line must be unchanged (options come first), so
625 for example the following forms are equivalent
624 for example the following forms are equivalent
626
625
627 %psearch -i a* function
626 %psearch -i a* function
628 -i a* function?
627 -i a* function?
629 ?-i a* function
628 ?-i a* function
630
629
631 Arguments:
630 Arguments:
632
631
633 PATTERN
632 PATTERN
634
633
635 where PATTERN is a string containing * as a wildcard similar to its
634 where PATTERN is a string containing * as a wildcard similar to its
636 use in a shell. The pattern is matched in all namespaces on the
635 use in a shell. The pattern is matched in all namespaces on the
637 search path. By default objects starting with a single _ are not
636 search path. By default objects starting with a single _ are not
638 matched, many IPython generated objects have a single
637 matched, many IPython generated objects have a single
639 underscore. The default is case insensitive matching. Matching is
638 underscore. The default is case insensitive matching. Matching is
640 also done on the attributes of objects and not only on the objects
639 also done on the attributes of objects and not only on the objects
641 in a module.
640 in a module.
642
641
643 [OBJECT TYPE]
642 [OBJECT TYPE]
644
643
645 Is the name of a python type from the types module. The name is
644 Is the name of a python type from the types module. The name is
646 given in lowercase without the ending type, ex. StringType is
645 given in lowercase without the ending type, ex. StringType is
647 written string. By adding a type here only objects matching the
646 written string. By adding a type here only objects matching the
648 given type are matched. Using all here makes the pattern match all
647 given type are matched. Using all here makes the pattern match all
649 types (this is the default).
648 types (this is the default).
650
649
651 Options:
650 Options:
652
651
653 -a: makes the pattern match even objects whose names start with a
652 -a: makes the pattern match even objects whose names start with a
654 single underscore. These names are normally ommitted from the
653 single underscore. These names are normally ommitted from the
655 search.
654 search.
656
655
657 -i/-c: make the pattern case insensitive/sensitive. If neither of
656 -i/-c: make the pattern case insensitive/sensitive. If neither of
658 these options is given, the default is read from your ipythonrc
657 these options is given, the default is read from your ipythonrc
659 file. The option name which sets this value is
658 file. The option name which sets this value is
660 'wildcards_case_sensitive'. If this option is not specified in your
659 'wildcards_case_sensitive'. If this option is not specified in your
661 ipythonrc file, IPython's internal default is to do a case sensitive
660 ipythonrc file, IPython's internal default is to do a case sensitive
662 search.
661 search.
663
662
664 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
663 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
665 specifiy can be searched in any of the following namespaces:
664 specifiy can be searched in any of the following namespaces:
666 'builtin', 'user', 'user_global','internal', 'alias', where
665 'builtin', 'user', 'user_global','internal', 'alias', where
667 'builtin' and 'user' are the search defaults. Note that you should
666 'builtin' and 'user' are the search defaults. Note that you should
668 not use quotes when specifying namespaces.
667 not use quotes when specifying namespaces.
669
668
670 'Builtin' contains the python module builtin, 'user' contains all
669 'Builtin' contains the python module builtin, 'user' contains all
671 user data, 'alias' only contain the shell aliases and no python
670 user data, 'alias' only contain the shell aliases and no python
672 objects, 'internal' contains objects used by IPython. The
671 objects, 'internal' contains objects used by IPython. The
673 'user_global' namespace is only used by embedded IPython instances,
672 'user_global' namespace is only used by embedded IPython instances,
674 and it contains module-level globals. You can add namespaces to the
673 and it contains module-level globals. You can add namespaces to the
675 search with -s or exclude them with -e (these options can be given
674 search with -s or exclude them with -e (these options can be given
676 more than once).
675 more than once).
677
676
678 Examples:
677 Examples:
679
678
680 %psearch a* -> objects beginning with an a
679 %psearch a* -> objects beginning with an a
681 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
680 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
682 %psearch a* function -> all functions beginning with an a
681 %psearch a* function -> all functions beginning with an a
683 %psearch re.e* -> objects beginning with an e in module re
682 %psearch re.e* -> objects beginning with an e in module re
684 %psearch r*.e* -> objects that start with e in modules starting in r
683 %psearch r*.e* -> objects that start with e in modules starting in r
685 %psearch r*.* string -> all strings in modules beginning with r
684 %psearch r*.* string -> all strings in modules beginning with r
686
685
687 Case sensitve search:
686 Case sensitve search:
688
687
689 %psearch -c a* list all object beginning with lower case a
688 %psearch -c a* list all object beginning with lower case a
690
689
691 Show objects beginning with a single _:
690 Show objects beginning with a single _:
692
691
693 %psearch -a _* list objects beginning with a single underscore"""
692 %psearch -a _* list objects beginning with a single underscore"""
694 try:
693 try:
695 parameter_s = parameter_s.encode('ascii')
694 parameter_s = parameter_s.encode('ascii')
696 except UnicodeEncodeError:
695 except UnicodeEncodeError:
697 print 'Python identifiers can only contain ascii characters.'
696 print 'Python identifiers can only contain ascii characters.'
698 return
697 return
699
698
700 # default namespaces to be searched
699 # default namespaces to be searched
701 def_search = ['user','builtin']
700 def_search = ['user','builtin']
702
701
703 # Process options/args
702 # Process options/args
704 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
703 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
705 opt = opts.get
704 opt = opts.get
706 shell = self.shell
705 shell = self.shell
707 psearch = shell.inspector.psearch
706 psearch = shell.inspector.psearch
708
707
709 # select case options
708 # select case options
710 if opts.has_key('i'):
709 if opts.has_key('i'):
711 ignore_case = True
710 ignore_case = True
712 elif opts.has_key('c'):
711 elif opts.has_key('c'):
713 ignore_case = False
712 ignore_case = False
714 else:
713 else:
715 ignore_case = not shell.wildcards_case_sensitive
714 ignore_case = not shell.wildcards_case_sensitive
716
715
717 # Build list of namespaces to search from user options
716 # Build list of namespaces to search from user options
718 def_search.extend(opt('s',[]))
717 def_search.extend(opt('s',[]))
719 ns_exclude = ns_exclude=opt('e',[])
718 ns_exclude = ns_exclude=opt('e',[])
720 ns_search = [nm for nm in def_search if nm not in ns_exclude]
719 ns_search = [nm for nm in def_search if nm not in ns_exclude]
721
720
722 # Call the actual search
721 # Call the actual search
723 try:
722 try:
724 psearch(args,shell.ns_table,ns_search,
723 psearch(args,shell.ns_table,ns_search,
725 show_all=opt('a'),ignore_case=ignore_case)
724 show_all=opt('a'),ignore_case=ignore_case)
726 except:
725 except:
727 shell.showtraceback()
726 shell.showtraceback()
728
727
729 @skip_doctest
728 @skip_doctest
730 def magic_who_ls(self, parameter_s=''):
729 def magic_who_ls(self, parameter_s=''):
731 """Return a sorted list of all interactive variables.
730 """Return a sorted list of all interactive variables.
732
731
733 If arguments are given, only variables of types matching these
732 If arguments are given, only variables of types matching these
734 arguments are returned.
733 arguments are returned.
735
734
736 Examples
735 Examples
737 --------
736 --------
738
737
739 Define two variables and list them with who_ls::
738 Define two variables and list them with who_ls::
740
739
741 In [1]: alpha = 123
740 In [1]: alpha = 123
742
741
743 In [2]: beta = 'test'
742 In [2]: beta = 'test'
744
743
745 In [3]: %who_ls
744 In [3]: %who_ls
746 Out[3]: ['alpha', 'beta']
745 Out[3]: ['alpha', 'beta']
747
746
748 In [4]: %who_ls int
747 In [4]: %who_ls int
749 Out[4]: ['alpha']
748 Out[4]: ['alpha']
750
749
751 In [5]: %who_ls str
750 In [5]: %who_ls str
752 Out[5]: ['beta']
751 Out[5]: ['beta']
753 """
752 """
754
753
755 user_ns = self.shell.user_ns
754 user_ns = self.shell.user_ns
756 internal_ns = self.shell.internal_ns
755 internal_ns = self.shell.internal_ns
757 user_ns_hidden = self.shell.user_ns_hidden
756 user_ns_hidden = self.shell.user_ns_hidden
758 out = [ i for i in user_ns
757 out = [ i for i in user_ns
759 if not i.startswith('_') \
758 if not i.startswith('_') \
760 and not (i in internal_ns or i in user_ns_hidden) ]
759 and not (i in internal_ns or i in user_ns_hidden) ]
761
760
762 typelist = parameter_s.split()
761 typelist = parameter_s.split()
763 if typelist:
762 if typelist:
764 typeset = set(typelist)
763 typeset = set(typelist)
765 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
764 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
766
765
767 out.sort()
766 out.sort()
768 return out
767 return out
769
768
770 @skip_doctest
769 @skip_doctest
771 def magic_who(self, parameter_s=''):
770 def magic_who(self, parameter_s=''):
772 """Print all interactive variables, with some minimal formatting.
771 """Print all interactive variables, with some minimal formatting.
773
772
774 If any arguments are given, only variables whose type matches one of
773 If any arguments are given, only variables whose type matches one of
775 these are printed. For example:
774 these are printed. For example:
776
775
777 %who function str
776 %who function str
778
777
779 will only list functions and strings, excluding all other types of
778 will only list functions and strings, excluding all other types of
780 variables. To find the proper type names, simply use type(var) at a
779 variables. To find the proper type names, simply use type(var) at a
781 command line to see how python prints type names. For example:
780 command line to see how python prints type names. For example:
782
781
783 In [1]: type('hello')\\
782 In [1]: type('hello')\\
784 Out[1]: <type 'str'>
783 Out[1]: <type 'str'>
785
784
786 indicates that the type name for strings is 'str'.
785 indicates that the type name for strings is 'str'.
787
786
788 %who always excludes executed names loaded through your configuration
787 %who always excludes executed names loaded through your configuration
789 file and things which are internal to IPython.
788 file and things which are internal to IPython.
790
789
791 This is deliberate, as typically you may load many modules and the
790 This is deliberate, as typically you may load many modules and the
792 purpose of %who is to show you only what you've manually defined.
791 purpose of %who is to show you only what you've manually defined.
793
792
794 Examples
793 Examples
795 --------
794 --------
796
795
797 Define two variables and list them with who::
796 Define two variables and list them with who::
798
797
799 In [1]: alpha = 123
798 In [1]: alpha = 123
800
799
801 In [2]: beta = 'test'
800 In [2]: beta = 'test'
802
801
803 In [3]: %who
802 In [3]: %who
804 alpha beta
803 alpha beta
805
804
806 In [4]: %who int
805 In [4]: %who int
807 alpha
806 alpha
808
807
809 In [5]: %who str
808 In [5]: %who str
810 beta
809 beta
811 """
810 """
812
811
813 varlist = self.magic_who_ls(parameter_s)
812 varlist = self.magic_who_ls(parameter_s)
814 if not varlist:
813 if not varlist:
815 if parameter_s:
814 if parameter_s:
816 print 'No variables match your requested type.'
815 print 'No variables match your requested type.'
817 else:
816 else:
818 print 'Interactive namespace is empty.'
817 print 'Interactive namespace is empty.'
819 return
818 return
820
819
821 # if we have variables, move on...
820 # if we have variables, move on...
822 count = 0
821 count = 0
823 for i in varlist:
822 for i in varlist:
824 print i+'\t',
823 print i+'\t',
825 count += 1
824 count += 1
826 if count > 8:
825 if count > 8:
827 count = 0
826 count = 0
828 print
827 print
829 print
828 print
830
829
831 @skip_doctest
830 @skip_doctest
832 def magic_whos(self, parameter_s=''):
831 def magic_whos(self, parameter_s=''):
833 """Like %who, but gives some extra information about each variable.
832 """Like %who, but gives some extra information about each variable.
834
833
835 The same type filtering of %who can be applied here.
834 The same type filtering of %who can be applied here.
836
835
837 For all variables, the type is printed. Additionally it prints:
836 For all variables, the type is printed. Additionally it prints:
838
837
839 - For {},[],(): their length.
838 - For {},[],(): their length.
840
839
841 - For numpy arrays, a summary with shape, number of
840 - For numpy arrays, a summary with shape, number of
842 elements, typecode and size in memory.
841 elements, typecode and size in memory.
843
842
844 - Everything else: a string representation, snipping their middle if
843 - Everything else: a string representation, snipping their middle if
845 too long.
844 too long.
846
845
847 Examples
846 Examples
848 --------
847 --------
849
848
850 Define two variables and list them with whos::
849 Define two variables and list them with whos::
851
850
852 In [1]: alpha = 123
851 In [1]: alpha = 123
853
852
854 In [2]: beta = 'test'
853 In [2]: beta = 'test'
855
854
856 In [3]: %whos
855 In [3]: %whos
857 Variable Type Data/Info
856 Variable Type Data/Info
858 --------------------------------
857 --------------------------------
859 alpha int 123
858 alpha int 123
860 beta str test
859 beta str test
861 """
860 """
862
861
863 varnames = self.magic_who_ls(parameter_s)
862 varnames = self.magic_who_ls(parameter_s)
864 if not varnames:
863 if not varnames:
865 if parameter_s:
864 if parameter_s:
866 print 'No variables match your requested type.'
865 print 'No variables match your requested type.'
867 else:
866 else:
868 print 'Interactive namespace is empty.'
867 print 'Interactive namespace is empty.'
869 return
868 return
870
869
871 # if we have variables, move on...
870 # if we have variables, move on...
872
871
873 # for these types, show len() instead of data:
872 # for these types, show len() instead of data:
874 seq_types = ['dict', 'list', 'tuple']
873 seq_types = ['dict', 'list', 'tuple']
875
874
876 # for numpy/Numeric arrays, display summary info
875 # for numpy/Numeric arrays, display summary info
877 try:
876 try:
878 import numpy
877 import numpy
879 except ImportError:
878 except ImportError:
880 ndarray_type = None
879 ndarray_type = None
881 else:
880 else:
882 ndarray_type = numpy.ndarray.__name__
881 ndarray_type = numpy.ndarray.__name__
883 try:
882 try:
884 import Numeric
883 import Numeric
885 except ImportError:
884 except ImportError:
886 array_type = None
885 array_type = None
887 else:
886 else:
888 array_type = Numeric.ArrayType.__name__
887 array_type = Numeric.ArrayType.__name__
889
888
890 # Find all variable names and types so we can figure out column sizes
889 # Find all variable names and types so we can figure out column sizes
891 def get_vars(i):
890 def get_vars(i):
892 return self.shell.user_ns[i]
891 return self.shell.user_ns[i]
893
892
894 # some types are well known and can be shorter
893 # some types are well known and can be shorter
895 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
894 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
896 def type_name(v):
895 def type_name(v):
897 tn = type(v).__name__
896 tn = type(v).__name__
898 return abbrevs.get(tn,tn)
897 return abbrevs.get(tn,tn)
899
898
900 varlist = map(get_vars,varnames)
899 varlist = map(get_vars,varnames)
901
900
902 typelist = []
901 typelist = []
903 for vv in varlist:
902 for vv in varlist:
904 tt = type_name(vv)
903 tt = type_name(vv)
905
904
906 if tt=='instance':
905 if tt=='instance':
907 typelist.append( abbrevs.get(str(vv.__class__),
906 typelist.append( abbrevs.get(str(vv.__class__),
908 str(vv.__class__)))
907 str(vv.__class__)))
909 else:
908 else:
910 typelist.append(tt)
909 typelist.append(tt)
911
910
912 # column labels and # of spaces as separator
911 # column labels and # of spaces as separator
913 varlabel = 'Variable'
912 varlabel = 'Variable'
914 typelabel = 'Type'
913 typelabel = 'Type'
915 datalabel = 'Data/Info'
914 datalabel = 'Data/Info'
916 colsep = 3
915 colsep = 3
917 # variable format strings
916 # variable format strings
918 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
917 vformat = "{0:<{varwidth}}{1:<{typewidth}}"
919 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
920 aformat = "%s: %s elems, type `%s`, %s bytes"
918 aformat = "%s: %s elems, type `%s`, %s bytes"
921 # find the size of the columns to format the output nicely
919 # find the size of the columns to format the output nicely
922 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
920 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
923 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
921 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
924 # table header
922 # table header
925 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
923 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
926 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
924 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
927 # and the table itself
925 # and the table itself
928 kb = 1024
926 kb = 1024
929 Mb = 1048576 # kb**2
927 Mb = 1048576 # kb**2
930 for vname,var,vtype in zip(varnames,varlist,typelist):
928 for vname,var,vtype in zip(varnames,varlist,typelist):
931 print itpl(vformat),
929 print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth),
932 if vtype in seq_types:
930 if vtype in seq_types:
933 print "n="+str(len(var))
931 print "n="+str(len(var))
934 elif vtype in [array_type,ndarray_type]:
932 elif vtype in [array_type,ndarray_type]:
935 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
933 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
936 if vtype==ndarray_type:
934 if vtype==ndarray_type:
937 # numpy
935 # numpy
938 vsize = var.size
936 vsize = var.size
939 vbytes = vsize*var.itemsize
937 vbytes = vsize*var.itemsize
940 vdtype = var.dtype
938 vdtype = var.dtype
941 else:
939 else:
942 # Numeric
940 # Numeric
943 vsize = Numeric.size(var)
941 vsize = Numeric.size(var)
944 vbytes = vsize*var.itemsize()
942 vbytes = vsize*var.itemsize()
945 vdtype = var.typecode()
943 vdtype = var.typecode()
946
944
947 if vbytes < 100000:
945 if vbytes < 100000:
948 print aformat % (vshape,vsize,vdtype,vbytes)
946 print aformat % (vshape,vsize,vdtype,vbytes)
949 else:
947 else:
950 print aformat % (vshape,vsize,vdtype,vbytes),
948 print aformat % (vshape,vsize,vdtype,vbytes),
951 if vbytes < Mb:
949 if vbytes < Mb:
952 print '(%s kb)' % (vbytes/kb,)
950 print '(%s kb)' % (vbytes/kb,)
953 else:
951 else:
954 print '(%s Mb)' % (vbytes/Mb,)
952 print '(%s Mb)' % (vbytes/Mb,)
955 else:
953 else:
956 try:
954 try:
957 vstr = str(var)
955 vstr = str(var)
958 except UnicodeEncodeError:
956 except UnicodeEncodeError:
959 vstr = unicode(var).encode(sys.getdefaultencoding(),
957 vstr = unicode(var).encode(sys.getdefaultencoding(),
960 'backslashreplace')
958 'backslashreplace')
961 vstr = vstr.replace('\n','\\n')
959 vstr = vstr.replace('\n','\\n')
962 if len(vstr) < 50:
960 if len(vstr) < 50:
963 print vstr
961 print vstr
964 else:
962 else:
965 printpl(vfmt_short)
963 print vstr[:25] + "<...>" + vstr[-25:]
966
964
967 def magic_reset(self, parameter_s=''):
965 def magic_reset(self, parameter_s=''):
968 """Resets the namespace by removing all names defined by the user.
966 """Resets the namespace by removing all names defined by the user.
969
967
970 Parameters
968 Parameters
971 ----------
969 ----------
972 -f : force reset without asking for confirmation.
970 -f : force reset without asking for confirmation.
973
971
974 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
972 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
975 References to objects may be kept. By default (without this option),
973 References to objects may be kept. By default (without this option),
976 we do a 'hard' reset, giving you a new session and removing all
974 we do a 'hard' reset, giving you a new session and removing all
977 references to objects from the current session.
975 references to objects from the current session.
978
976
979 Examples
977 Examples
980 --------
978 --------
981 In [6]: a = 1
979 In [6]: a = 1
982
980
983 In [7]: a
981 In [7]: a
984 Out[7]: 1
982 Out[7]: 1
985
983
986 In [8]: 'a' in _ip.user_ns
984 In [8]: 'a' in _ip.user_ns
987 Out[8]: True
985 Out[8]: True
988
986
989 In [9]: %reset -f
987 In [9]: %reset -f
990
988
991 In [1]: 'a' in _ip.user_ns
989 In [1]: 'a' in _ip.user_ns
992 Out[1]: False
990 Out[1]: False
993 """
991 """
994 opts, args = self.parse_options(parameter_s,'sf')
992 opts, args = self.parse_options(parameter_s,'sf')
995 if 'f' in opts:
993 if 'f' in opts:
996 ans = True
994 ans = True
997 else:
995 else:
998 ans = self.shell.ask_yes_no(
996 ans = self.shell.ask_yes_no(
999 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
997 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1000 if not ans:
998 if not ans:
1001 print 'Nothing done.'
999 print 'Nothing done.'
1002 return
1000 return
1003
1001
1004 if 's' in opts: # Soft reset
1002 if 's' in opts: # Soft reset
1005 user_ns = self.shell.user_ns
1003 user_ns = self.shell.user_ns
1006 for i in self.magic_who_ls():
1004 for i in self.magic_who_ls():
1007 del(user_ns[i])
1005 del(user_ns[i])
1008
1006
1009 else: # Hard reset
1007 else: # Hard reset
1010 self.shell.reset(new_session = False)
1008 self.shell.reset(new_session = False)
1011
1009
1012
1010
1013
1011
1014 def magic_reset_selective(self, parameter_s=''):
1012 def magic_reset_selective(self, parameter_s=''):
1015 """Resets the namespace by removing names defined by the user.
1013 """Resets the namespace by removing names defined by the user.
1016
1014
1017 Input/Output history are left around in case you need them.
1015 Input/Output history are left around in case you need them.
1018
1016
1019 %reset_selective [-f] regex
1017 %reset_selective [-f] regex
1020
1018
1021 No action is taken if regex is not included
1019 No action is taken if regex is not included
1022
1020
1023 Options
1021 Options
1024 -f : force reset without asking for confirmation.
1022 -f : force reset without asking for confirmation.
1025
1023
1026 Examples
1024 Examples
1027 --------
1025 --------
1028
1026
1029 We first fully reset the namespace so your output looks identical to
1027 We first fully reset the namespace so your output looks identical to
1030 this example for pedagogical reasons; in practice you do not need a
1028 this example for pedagogical reasons; in practice you do not need a
1031 full reset.
1029 full reset.
1032
1030
1033 In [1]: %reset -f
1031 In [1]: %reset -f
1034
1032
1035 Now, with a clean namespace we can make a few variables and use
1033 Now, with a clean namespace we can make a few variables and use
1036 %reset_selective to only delete names that match our regexp:
1034 %reset_selective to only delete names that match our regexp:
1037
1035
1038 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1036 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1039
1037
1040 In [3]: who_ls
1038 In [3]: who_ls
1041 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1039 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1042
1040
1043 In [4]: %reset_selective -f b[2-3]m
1041 In [4]: %reset_selective -f b[2-3]m
1044
1042
1045 In [5]: who_ls
1043 In [5]: who_ls
1046 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1044 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1047
1045
1048 In [6]: %reset_selective -f d
1046 In [6]: %reset_selective -f d
1049
1047
1050 In [7]: who_ls
1048 In [7]: who_ls
1051 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1049 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1052
1050
1053 In [8]: %reset_selective -f c
1051 In [8]: %reset_selective -f c
1054
1052
1055 In [9]: who_ls
1053 In [9]: who_ls
1056 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1054 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1057
1055
1058 In [10]: %reset_selective -f b
1056 In [10]: %reset_selective -f b
1059
1057
1060 In [11]: who_ls
1058 In [11]: who_ls
1061 Out[11]: ['a']
1059 Out[11]: ['a']
1062 """
1060 """
1063
1061
1064 opts, regex = self.parse_options(parameter_s,'f')
1062 opts, regex = self.parse_options(parameter_s,'f')
1065
1063
1066 if opts.has_key('f'):
1064 if opts.has_key('f'):
1067 ans = True
1065 ans = True
1068 else:
1066 else:
1069 ans = self.shell.ask_yes_no(
1067 ans = self.shell.ask_yes_no(
1070 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1068 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ")
1071 if not ans:
1069 if not ans:
1072 print 'Nothing done.'
1070 print 'Nothing done.'
1073 return
1071 return
1074 user_ns = self.shell.user_ns
1072 user_ns = self.shell.user_ns
1075 if not regex:
1073 if not regex:
1076 print 'No regex pattern specified. Nothing done.'
1074 print 'No regex pattern specified. Nothing done.'
1077 return
1075 return
1078 else:
1076 else:
1079 try:
1077 try:
1080 m = re.compile(regex)
1078 m = re.compile(regex)
1081 except TypeError:
1079 except TypeError:
1082 raise TypeError('regex must be a string or compiled pattern')
1080 raise TypeError('regex must be a string or compiled pattern')
1083 for i in self.magic_who_ls():
1081 for i in self.magic_who_ls():
1084 if m.search(i):
1082 if m.search(i):
1085 del(user_ns[i])
1083 del(user_ns[i])
1086
1084
1087 def magic_xdel(self, parameter_s=''):
1085 def magic_xdel(self, parameter_s=''):
1088 """Delete a variable, trying to clear it from anywhere that
1086 """Delete a variable, trying to clear it from anywhere that
1089 IPython's machinery has references to it. By default, this uses
1087 IPython's machinery has references to it. By default, this uses
1090 the identity of the named object in the user namespace to remove
1088 the identity of the named object in the user namespace to remove
1091 references held under other names. The object is also removed
1089 references held under other names. The object is also removed
1092 from the output history.
1090 from the output history.
1093
1091
1094 Options
1092 Options
1095 -n : Delete the specified name from all namespaces, without
1093 -n : Delete the specified name from all namespaces, without
1096 checking their identity.
1094 checking their identity.
1097 """
1095 """
1098 opts, varname = self.parse_options(parameter_s,'n')
1096 opts, varname = self.parse_options(parameter_s,'n')
1099 try:
1097 try:
1100 self.shell.del_var(varname, ('n' in opts))
1098 self.shell.del_var(varname, ('n' in opts))
1101 except (NameError, ValueError) as e:
1099 except (NameError, ValueError) as e:
1102 print type(e).__name__ +": "+ str(e)
1100 print type(e).__name__ +": "+ str(e)
1103
1101
1104 def magic_logstart(self,parameter_s=''):
1102 def magic_logstart(self,parameter_s=''):
1105 """Start logging anywhere in a session.
1103 """Start logging anywhere in a session.
1106
1104
1107 %logstart [-o|-r|-t] [log_name [log_mode]]
1105 %logstart [-o|-r|-t] [log_name [log_mode]]
1108
1106
1109 If no name is given, it defaults to a file named 'ipython_log.py' in your
1107 If no name is given, it defaults to a file named 'ipython_log.py' in your
1110 current directory, in 'rotate' mode (see below).
1108 current directory, in 'rotate' mode (see below).
1111
1109
1112 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1110 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
1113 history up to that point and then continues logging.
1111 history up to that point and then continues logging.
1114
1112
1115 %logstart takes a second optional parameter: logging mode. This can be one
1113 %logstart takes a second optional parameter: logging mode. This can be one
1116 of (note that the modes are given unquoted):\\
1114 of (note that the modes are given unquoted):\\
1117 append: well, that says it.\\
1115 append: well, that says it.\\
1118 backup: rename (if exists) to name~ and start name.\\
1116 backup: rename (if exists) to name~ and start name.\\
1119 global: single logfile in your home dir, appended to.\\
1117 global: single logfile in your home dir, appended to.\\
1120 over : overwrite existing log.\\
1118 over : overwrite existing log.\\
1121 rotate: create rotating logs name.1~, name.2~, etc.
1119 rotate: create rotating logs name.1~, name.2~, etc.
1122
1120
1123 Options:
1121 Options:
1124
1122
1125 -o: log also IPython's output. In this mode, all commands which
1123 -o: log also IPython's output. In this mode, all commands which
1126 generate an Out[NN] prompt are recorded to the logfile, right after
1124 generate an Out[NN] prompt are recorded to the logfile, right after
1127 their corresponding input line. The output lines are always
1125 their corresponding input line. The output lines are always
1128 prepended with a '#[Out]# ' marker, so that the log remains valid
1126 prepended with a '#[Out]# ' marker, so that the log remains valid
1129 Python code.
1127 Python code.
1130
1128
1131 Since this marker is always the same, filtering only the output from
1129 Since this marker is always the same, filtering only the output from
1132 a log is very easy, using for example a simple awk call:
1130 a log is very easy, using for example a simple awk call:
1133
1131
1134 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1132 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
1135
1133
1136 -r: log 'raw' input. Normally, IPython's logs contain the processed
1134 -r: log 'raw' input. Normally, IPython's logs contain the processed
1137 input, so that user lines are logged in their final form, converted
1135 input, so that user lines are logged in their final form, converted
1138 into valid Python. For example, %Exit is logged as
1136 into valid Python. For example, %Exit is logged as
1139 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1137 '_ip.magic("Exit"). If the -r flag is given, all input is logged
1140 exactly as typed, with no transformations applied.
1138 exactly as typed, with no transformations applied.
1141
1139
1142 -t: put timestamps before each input line logged (these are put in
1140 -t: put timestamps before each input line logged (these are put in
1143 comments)."""
1141 comments)."""
1144
1142
1145 opts,par = self.parse_options(parameter_s,'ort')
1143 opts,par = self.parse_options(parameter_s,'ort')
1146 log_output = 'o' in opts
1144 log_output = 'o' in opts
1147 log_raw_input = 'r' in opts
1145 log_raw_input = 'r' in opts
1148 timestamp = 't' in opts
1146 timestamp = 't' in opts
1149
1147
1150 logger = self.shell.logger
1148 logger = self.shell.logger
1151
1149
1152 # if no args are given, the defaults set in the logger constructor by
1150 # if no args are given, the defaults set in the logger constructor by
1153 # ipytohn remain valid
1151 # ipytohn remain valid
1154 if par:
1152 if par:
1155 try:
1153 try:
1156 logfname,logmode = par.split()
1154 logfname,logmode = par.split()
1157 except:
1155 except:
1158 logfname = par
1156 logfname = par
1159 logmode = 'backup'
1157 logmode = 'backup'
1160 else:
1158 else:
1161 logfname = logger.logfname
1159 logfname = logger.logfname
1162 logmode = logger.logmode
1160 logmode = logger.logmode
1163 # put logfname into rc struct as if it had been called on the command
1161 # put logfname into rc struct as if it had been called on the command
1164 # line, so it ends up saved in the log header Save it in case we need
1162 # line, so it ends up saved in the log header Save it in case we need
1165 # to restore it...
1163 # to restore it...
1166 old_logfile = self.shell.logfile
1164 old_logfile = self.shell.logfile
1167 if logfname:
1165 if logfname:
1168 logfname = os.path.expanduser(logfname)
1166 logfname = os.path.expanduser(logfname)
1169 self.shell.logfile = logfname
1167 self.shell.logfile = logfname
1170
1168
1171 loghead = '# IPython log file\n\n'
1169 loghead = '# IPython log file\n\n'
1172 try:
1170 try:
1173 started = logger.logstart(logfname,loghead,logmode,
1171 started = logger.logstart(logfname,loghead,logmode,
1174 log_output,timestamp,log_raw_input)
1172 log_output,timestamp,log_raw_input)
1175 except:
1173 except:
1176 self.shell.logfile = old_logfile
1174 self.shell.logfile = old_logfile
1177 warn("Couldn't start log: %s" % sys.exc_info()[1])
1175 warn("Couldn't start log: %s" % sys.exc_info()[1])
1178 else:
1176 else:
1179 # log input history up to this point, optionally interleaving
1177 # log input history up to this point, optionally interleaving
1180 # output if requested
1178 # output if requested
1181
1179
1182 if timestamp:
1180 if timestamp:
1183 # disable timestamping for the previous history, since we've
1181 # disable timestamping for the previous history, since we've
1184 # lost those already (no time machine here).
1182 # lost those already (no time machine here).
1185 logger.timestamp = False
1183 logger.timestamp = False
1186
1184
1187 if log_raw_input:
1185 if log_raw_input:
1188 input_hist = self.shell.history_manager.input_hist_raw
1186 input_hist = self.shell.history_manager.input_hist_raw
1189 else:
1187 else:
1190 input_hist = self.shell.history_manager.input_hist_parsed
1188 input_hist = self.shell.history_manager.input_hist_parsed
1191
1189
1192 if log_output:
1190 if log_output:
1193 log_write = logger.log_write
1191 log_write = logger.log_write
1194 output_hist = self.shell.history_manager.output_hist
1192 output_hist = self.shell.history_manager.output_hist
1195 for n in range(1,len(input_hist)-1):
1193 for n in range(1,len(input_hist)-1):
1196 log_write(input_hist[n].rstrip() + '\n')
1194 log_write(input_hist[n].rstrip() + '\n')
1197 if n in output_hist:
1195 if n in output_hist:
1198 log_write(repr(output_hist[n]),'output')
1196 log_write(repr(output_hist[n]),'output')
1199 else:
1197 else:
1200 logger.log_write('\n'.join(input_hist[1:]))
1198 logger.log_write('\n'.join(input_hist[1:]))
1201 logger.log_write('\n')
1199 logger.log_write('\n')
1202 if timestamp:
1200 if timestamp:
1203 # re-enable timestamping
1201 # re-enable timestamping
1204 logger.timestamp = True
1202 logger.timestamp = True
1205
1203
1206 print ('Activating auto-logging. '
1204 print ('Activating auto-logging. '
1207 'Current session state plus future input saved.')
1205 'Current session state plus future input saved.')
1208 logger.logstate()
1206 logger.logstate()
1209
1207
1210 def magic_logstop(self,parameter_s=''):
1208 def magic_logstop(self,parameter_s=''):
1211 """Fully stop logging and close log file.
1209 """Fully stop logging and close log file.
1212
1210
1213 In order to start logging again, a new %logstart call needs to be made,
1211 In order to start logging again, a new %logstart call needs to be made,
1214 possibly (though not necessarily) with a new filename, mode and other
1212 possibly (though not necessarily) with a new filename, mode and other
1215 options."""
1213 options."""
1216 self.logger.logstop()
1214 self.logger.logstop()
1217
1215
1218 def magic_logoff(self,parameter_s=''):
1216 def magic_logoff(self,parameter_s=''):
1219 """Temporarily stop logging.
1217 """Temporarily stop logging.
1220
1218
1221 You must have previously started logging."""
1219 You must have previously started logging."""
1222 self.shell.logger.switch_log(0)
1220 self.shell.logger.switch_log(0)
1223
1221
1224 def magic_logon(self,parameter_s=''):
1222 def magic_logon(self,parameter_s=''):
1225 """Restart logging.
1223 """Restart logging.
1226
1224
1227 This function is for restarting logging which you've temporarily
1225 This function is for restarting logging which you've temporarily
1228 stopped with %logoff. For starting logging for the first time, you
1226 stopped with %logoff. For starting logging for the first time, you
1229 must use the %logstart function, which allows you to specify an
1227 must use the %logstart function, which allows you to specify an
1230 optional log filename."""
1228 optional log filename."""
1231
1229
1232 self.shell.logger.switch_log(1)
1230 self.shell.logger.switch_log(1)
1233
1231
1234 def magic_logstate(self,parameter_s=''):
1232 def magic_logstate(self,parameter_s=''):
1235 """Print the status of the logging system."""
1233 """Print the status of the logging system."""
1236
1234
1237 self.shell.logger.logstate()
1235 self.shell.logger.logstate()
1238
1236
1239 def magic_pdb(self, parameter_s=''):
1237 def magic_pdb(self, parameter_s=''):
1240 """Control the automatic calling of the pdb interactive debugger.
1238 """Control the automatic calling of the pdb interactive debugger.
1241
1239
1242 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1240 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1243 argument it works as a toggle.
1241 argument it works as a toggle.
1244
1242
1245 When an exception is triggered, IPython can optionally call the
1243 When an exception is triggered, IPython can optionally call the
1246 interactive pdb debugger after the traceback printout. %pdb toggles
1244 interactive pdb debugger after the traceback printout. %pdb toggles
1247 this feature on and off.
1245 this feature on and off.
1248
1246
1249 The initial state of this feature is set in your ipythonrc
1247 The initial state of this feature is set in your ipythonrc
1250 configuration file (the variable is called 'pdb').
1248 configuration file (the variable is called 'pdb').
1251
1249
1252 If you want to just activate the debugger AFTER an exception has fired,
1250 If you want to just activate the debugger AFTER an exception has fired,
1253 without having to type '%pdb on' and rerunning your code, you can use
1251 without having to type '%pdb on' and rerunning your code, you can use
1254 the %debug magic."""
1252 the %debug magic."""
1255
1253
1256 par = parameter_s.strip().lower()
1254 par = parameter_s.strip().lower()
1257
1255
1258 if par:
1256 if par:
1259 try:
1257 try:
1260 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1258 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1261 except KeyError:
1259 except KeyError:
1262 print ('Incorrect argument. Use on/1, off/0, '
1260 print ('Incorrect argument. Use on/1, off/0, '
1263 'or nothing for a toggle.')
1261 'or nothing for a toggle.')
1264 return
1262 return
1265 else:
1263 else:
1266 # toggle
1264 # toggle
1267 new_pdb = not self.shell.call_pdb
1265 new_pdb = not self.shell.call_pdb
1268
1266
1269 # set on the shell
1267 # set on the shell
1270 self.shell.call_pdb = new_pdb
1268 self.shell.call_pdb = new_pdb
1271 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1269 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1272
1270
1273 def magic_debug(self, parameter_s=''):
1271 def magic_debug(self, parameter_s=''):
1274 """Activate the interactive debugger in post-mortem mode.
1272 """Activate the interactive debugger in post-mortem mode.
1275
1273
1276 If an exception has just occurred, this lets you inspect its stack
1274 If an exception has just occurred, this lets you inspect its stack
1277 frames interactively. Note that this will always work only on the last
1275 frames interactively. Note that this will always work only on the last
1278 traceback that occurred, so you must call this quickly after an
1276 traceback that occurred, so you must call this quickly after an
1279 exception that you wish to inspect has fired, because if another one
1277 exception that you wish to inspect has fired, because if another one
1280 occurs, it clobbers the previous one.
1278 occurs, it clobbers the previous one.
1281
1279
1282 If you want IPython to automatically do this on every exception, see
1280 If you want IPython to automatically do this on every exception, see
1283 the %pdb magic for more details.
1281 the %pdb magic for more details.
1284 """
1282 """
1285 self.shell.debugger(force=True)
1283 self.shell.debugger(force=True)
1286
1284
1287 @skip_doctest
1285 @skip_doctest
1288 def magic_prun(self, parameter_s ='',user_mode=1,
1286 def magic_prun(self, parameter_s ='',user_mode=1,
1289 opts=None,arg_lst=None,prog_ns=None):
1287 opts=None,arg_lst=None,prog_ns=None):
1290
1288
1291 """Run a statement through the python code profiler.
1289 """Run a statement through the python code profiler.
1292
1290
1293 Usage:
1291 Usage:
1294 %prun [options] statement
1292 %prun [options] statement
1295
1293
1296 The given statement (which doesn't require quote marks) is run via the
1294 The given statement (which doesn't require quote marks) is run via the
1297 python profiler in a manner similar to the profile.run() function.
1295 python profiler in a manner similar to the profile.run() function.
1298 Namespaces are internally managed to work correctly; profile.run
1296 Namespaces are internally managed to work correctly; profile.run
1299 cannot be used in IPython because it makes certain assumptions about
1297 cannot be used in IPython because it makes certain assumptions about
1300 namespaces which do not hold under IPython.
1298 namespaces which do not hold under IPython.
1301
1299
1302 Options:
1300 Options:
1303
1301
1304 -l <limit>: you can place restrictions on what or how much of the
1302 -l <limit>: you can place restrictions on what or how much of the
1305 profile gets printed. The limit value can be:
1303 profile gets printed. The limit value can be:
1306
1304
1307 * A string: only information for function names containing this string
1305 * A string: only information for function names containing this string
1308 is printed.
1306 is printed.
1309
1307
1310 * An integer: only these many lines are printed.
1308 * An integer: only these many lines are printed.
1311
1309
1312 * A float (between 0 and 1): this fraction of the report is printed
1310 * A float (between 0 and 1): this fraction of the report is printed
1313 (for example, use a limit of 0.4 to see the topmost 40% only).
1311 (for example, use a limit of 0.4 to see the topmost 40% only).
1314
1312
1315 You can combine several limits with repeated use of the option. For
1313 You can combine several limits with repeated use of the option. For
1316 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1314 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1317 information about class constructors.
1315 information about class constructors.
1318
1316
1319 -r: return the pstats.Stats object generated by the profiling. This
1317 -r: return the pstats.Stats object generated by the profiling. This
1320 object has all the information about the profile in it, and you can
1318 object has all the information about the profile in it, and you can
1321 later use it for further analysis or in other functions.
1319 later use it for further analysis or in other functions.
1322
1320
1323 -s <key>: sort profile by given key. You can provide more than one key
1321 -s <key>: sort profile by given key. You can provide more than one key
1324 by using the option several times: '-s key1 -s key2 -s key3...'. The
1322 by using the option several times: '-s key1 -s key2 -s key3...'. The
1325 default sorting key is 'time'.
1323 default sorting key is 'time'.
1326
1324
1327 The following is copied verbatim from the profile documentation
1325 The following is copied verbatim from the profile documentation
1328 referenced below:
1326 referenced below:
1329
1327
1330 When more than one key is provided, additional keys are used as
1328 When more than one key is provided, additional keys are used as
1331 secondary criteria when the there is equality in all keys selected
1329 secondary criteria when the there is equality in all keys selected
1332 before them.
1330 before them.
1333
1331
1334 Abbreviations can be used for any key names, as long as the
1332 Abbreviations can be used for any key names, as long as the
1335 abbreviation is unambiguous. The following are the keys currently
1333 abbreviation is unambiguous. The following are the keys currently
1336 defined:
1334 defined:
1337
1335
1338 Valid Arg Meaning
1336 Valid Arg Meaning
1339 "calls" call count
1337 "calls" call count
1340 "cumulative" cumulative time
1338 "cumulative" cumulative time
1341 "file" file name
1339 "file" file name
1342 "module" file name
1340 "module" file name
1343 "pcalls" primitive call count
1341 "pcalls" primitive call count
1344 "line" line number
1342 "line" line number
1345 "name" function name
1343 "name" function name
1346 "nfl" name/file/line
1344 "nfl" name/file/line
1347 "stdname" standard name
1345 "stdname" standard name
1348 "time" internal time
1346 "time" internal time
1349
1347
1350 Note that all sorts on statistics are in descending order (placing
1348 Note that all sorts on statistics are in descending order (placing
1351 most time consuming items first), where as name, file, and line number
1349 most time consuming items first), where as name, file, and line number
1352 searches are in ascending order (i.e., alphabetical). The subtle
1350 searches are in ascending order (i.e., alphabetical). The subtle
1353 distinction between "nfl" and "stdname" is that the standard name is a
1351 distinction between "nfl" and "stdname" is that the standard name is a
1354 sort of the name as printed, which means that the embedded line
1352 sort of the name as printed, which means that the embedded line
1355 numbers get compared in an odd way. For example, lines 3, 20, and 40
1353 numbers get compared in an odd way. For example, lines 3, 20, and 40
1356 would (if the file names were the same) appear in the string order
1354 would (if the file names were the same) appear in the string order
1357 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1355 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1358 line numbers. In fact, sort_stats("nfl") is the same as
1356 line numbers. In fact, sort_stats("nfl") is the same as
1359 sort_stats("name", "file", "line").
1357 sort_stats("name", "file", "line").
1360
1358
1361 -T <filename>: save profile results as shown on screen to a text
1359 -T <filename>: save profile results as shown on screen to a text
1362 file. The profile is still shown on screen.
1360 file. The profile is still shown on screen.
1363
1361
1364 -D <filename>: save (via dump_stats) profile statistics to given
1362 -D <filename>: save (via dump_stats) profile statistics to given
1365 filename. This data is in a format understod by the pstats module, and
1363 filename. This data is in a format understod by the pstats module, and
1366 is generated by a call to the dump_stats() method of profile
1364 is generated by a call to the dump_stats() method of profile
1367 objects. The profile is still shown on screen.
1365 objects. The profile is still shown on screen.
1368
1366
1369 If you want to run complete programs under the profiler's control, use
1367 If you want to run complete programs under the profiler's control, use
1370 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1368 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1371 contains profiler specific options as described here.
1369 contains profiler specific options as described here.
1372
1370
1373 You can read the complete documentation for the profile module with::
1371 You can read the complete documentation for the profile module with::
1374
1372
1375 In [1]: import profile; profile.help()
1373 In [1]: import profile; profile.help()
1376 """
1374 """
1377
1375
1378 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1376 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1379 # protect user quote marks
1377 # protect user quote marks
1380 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1378 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1381
1379
1382 if user_mode: # regular user call
1380 if user_mode: # regular user call
1383 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1381 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1384 list_all=1)
1382 list_all=1)
1385 namespace = self.shell.user_ns
1383 namespace = self.shell.user_ns
1386 else: # called to run a program by %run -p
1384 else: # called to run a program by %run -p
1387 try:
1385 try:
1388 filename = get_py_filename(arg_lst[0])
1386 filename = get_py_filename(arg_lst[0])
1389 except IOError,msg:
1387 except IOError,msg:
1390 error(msg)
1388 error(msg)
1391 return
1389 return
1392
1390
1393 arg_str = 'execfile(filename,prog_ns)'
1391 arg_str = 'execfile(filename,prog_ns)'
1394 namespace = locals()
1392 namespace = locals()
1395
1393
1396 opts.merge(opts_def)
1394 opts.merge(opts_def)
1397
1395
1398 prof = profile.Profile()
1396 prof = profile.Profile()
1399 try:
1397 try:
1400 prof = prof.runctx(arg_str,namespace,namespace)
1398 prof = prof.runctx(arg_str,namespace,namespace)
1401 sys_exit = ''
1399 sys_exit = ''
1402 except SystemExit:
1400 except SystemExit:
1403 sys_exit = """*** SystemExit exception caught in code being profiled."""
1401 sys_exit = """*** SystemExit exception caught in code being profiled."""
1404
1402
1405 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1403 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1406
1404
1407 lims = opts.l
1405 lims = opts.l
1408 if lims:
1406 if lims:
1409 lims = [] # rebuild lims with ints/floats/strings
1407 lims = [] # rebuild lims with ints/floats/strings
1410 for lim in opts.l:
1408 for lim in opts.l:
1411 try:
1409 try:
1412 lims.append(int(lim))
1410 lims.append(int(lim))
1413 except ValueError:
1411 except ValueError:
1414 try:
1412 try:
1415 lims.append(float(lim))
1413 lims.append(float(lim))
1416 except ValueError:
1414 except ValueError:
1417 lims.append(lim)
1415 lims.append(lim)
1418
1416
1419 # Trap output.
1417 # Trap output.
1420 stdout_trap = StringIO()
1418 stdout_trap = StringIO()
1421
1419
1422 if hasattr(stats,'stream'):
1420 if hasattr(stats,'stream'):
1423 # In newer versions of python, the stats object has a 'stream'
1421 # In newer versions of python, the stats object has a 'stream'
1424 # attribute to write into.
1422 # attribute to write into.
1425 stats.stream = stdout_trap
1423 stats.stream = stdout_trap
1426 stats.print_stats(*lims)
1424 stats.print_stats(*lims)
1427 else:
1425 else:
1428 # For older versions, we manually redirect stdout during printing
1426 # For older versions, we manually redirect stdout during printing
1429 sys_stdout = sys.stdout
1427 sys_stdout = sys.stdout
1430 try:
1428 try:
1431 sys.stdout = stdout_trap
1429 sys.stdout = stdout_trap
1432 stats.print_stats(*lims)
1430 stats.print_stats(*lims)
1433 finally:
1431 finally:
1434 sys.stdout = sys_stdout
1432 sys.stdout = sys_stdout
1435
1433
1436 output = stdout_trap.getvalue()
1434 output = stdout_trap.getvalue()
1437 output = output.rstrip()
1435 output = output.rstrip()
1438
1436
1439 page.page(output)
1437 page.page(output)
1440 print sys_exit,
1438 print sys_exit,
1441
1439
1442 dump_file = opts.D[0]
1440 dump_file = opts.D[0]
1443 text_file = opts.T[0]
1441 text_file = opts.T[0]
1444 if dump_file:
1442 if dump_file:
1445 prof.dump_stats(dump_file)
1443 prof.dump_stats(dump_file)
1446 print '\n*** Profile stats marshalled to file',\
1444 print '\n*** Profile stats marshalled to file',\
1447 `dump_file`+'.',sys_exit
1445 `dump_file`+'.',sys_exit
1448 if text_file:
1446 if text_file:
1449 pfile = file(text_file,'w')
1447 pfile = file(text_file,'w')
1450 pfile.write(output)
1448 pfile.write(output)
1451 pfile.close()
1449 pfile.close()
1452 print '\n*** Profile printout saved to text file',\
1450 print '\n*** Profile printout saved to text file',\
1453 `text_file`+'.',sys_exit
1451 `text_file`+'.',sys_exit
1454
1452
1455 if opts.has_key('r'):
1453 if opts.has_key('r'):
1456 return stats
1454 return stats
1457 else:
1455 else:
1458 return None
1456 return None
1459
1457
1460 @skip_doctest
1458 @skip_doctest
1461 def magic_run(self, parameter_s ='',runner=None,
1459 def magic_run(self, parameter_s ='',runner=None,
1462 file_finder=get_py_filename):
1460 file_finder=get_py_filename):
1463 """Run the named file inside IPython as a program.
1461 """Run the named file inside IPython as a program.
1464
1462
1465 Usage:\\
1463 Usage:\\
1466 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1464 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1467
1465
1468 Parameters after the filename are passed as command-line arguments to
1466 Parameters after the filename are passed as command-line arguments to
1469 the program (put in sys.argv). Then, control returns to IPython's
1467 the program (put in sys.argv). Then, control returns to IPython's
1470 prompt.
1468 prompt.
1471
1469
1472 This is similar to running at a system prompt:\\
1470 This is similar to running at a system prompt:\\
1473 $ python file args\\
1471 $ python file args\\
1474 but with the advantage of giving you IPython's tracebacks, and of
1472 but with the advantage of giving you IPython's tracebacks, and of
1475 loading all variables into your interactive namespace for further use
1473 loading all variables into your interactive namespace for further use
1476 (unless -p is used, see below).
1474 (unless -p is used, see below).
1477
1475
1478 The file is executed in a namespace initially consisting only of
1476 The file is executed in a namespace initially consisting only of
1479 __name__=='__main__' and sys.argv constructed as indicated. It thus
1477 __name__=='__main__' and sys.argv constructed as indicated. It thus
1480 sees its environment as if it were being run as a stand-alone program
1478 sees its environment as if it were being run as a stand-alone program
1481 (except for sharing global objects such as previously imported
1479 (except for sharing global objects such as previously imported
1482 modules). But after execution, the IPython interactive namespace gets
1480 modules). But after execution, the IPython interactive namespace gets
1483 updated with all variables defined in the program (except for __name__
1481 updated with all variables defined in the program (except for __name__
1484 and sys.argv). This allows for very convenient loading of code for
1482 and sys.argv). This allows for very convenient loading of code for
1485 interactive work, while giving each program a 'clean sheet' to run in.
1483 interactive work, while giving each program a 'clean sheet' to run in.
1486
1484
1487 Options:
1485 Options:
1488
1486
1489 -n: __name__ is NOT set to '__main__', but to the running file's name
1487 -n: __name__ is NOT set to '__main__', but to the running file's name
1490 without extension (as python does under import). This allows running
1488 without extension (as python does under import). This allows running
1491 scripts and reloading the definitions in them without calling code
1489 scripts and reloading the definitions in them without calling code
1492 protected by an ' if __name__ == "__main__" ' clause.
1490 protected by an ' if __name__ == "__main__" ' clause.
1493
1491
1494 -i: run the file in IPython's namespace instead of an empty one. This
1492 -i: run the file in IPython's namespace instead of an empty one. This
1495 is useful if you are experimenting with code written in a text editor
1493 is useful if you are experimenting with code written in a text editor
1496 which depends on variables defined interactively.
1494 which depends on variables defined interactively.
1497
1495
1498 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1496 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1499 being run. This is particularly useful if IPython is being used to
1497 being run. This is particularly useful if IPython is being used to
1500 run unittests, which always exit with a sys.exit() call. In such
1498 run unittests, which always exit with a sys.exit() call. In such
1501 cases you are interested in the output of the test results, not in
1499 cases you are interested in the output of the test results, not in
1502 seeing a traceback of the unittest module.
1500 seeing a traceback of the unittest module.
1503
1501
1504 -t: print timing information at the end of the run. IPython will give
1502 -t: print timing information at the end of the run. IPython will give
1505 you an estimated CPU time consumption for your script, which under
1503 you an estimated CPU time consumption for your script, which under
1506 Unix uses the resource module to avoid the wraparound problems of
1504 Unix uses the resource module to avoid the wraparound problems of
1507 time.clock(). Under Unix, an estimate of time spent on system tasks
1505 time.clock(). Under Unix, an estimate of time spent on system tasks
1508 is also given (for Windows platforms this is reported as 0.0).
1506 is also given (for Windows platforms this is reported as 0.0).
1509
1507
1510 If -t is given, an additional -N<N> option can be given, where <N>
1508 If -t is given, an additional -N<N> option can be given, where <N>
1511 must be an integer indicating how many times you want the script to
1509 must be an integer indicating how many times you want the script to
1512 run. The final timing report will include total and per run results.
1510 run. The final timing report will include total and per run results.
1513
1511
1514 For example (testing the script uniq_stable.py):
1512 For example (testing the script uniq_stable.py):
1515
1513
1516 In [1]: run -t uniq_stable
1514 In [1]: run -t uniq_stable
1517
1515
1518 IPython CPU timings (estimated):\\
1516 IPython CPU timings (estimated):\\
1519 User : 0.19597 s.\\
1517 User : 0.19597 s.\\
1520 System: 0.0 s.\\
1518 System: 0.0 s.\\
1521
1519
1522 In [2]: run -t -N5 uniq_stable
1520 In [2]: run -t -N5 uniq_stable
1523
1521
1524 IPython CPU timings (estimated):\\
1522 IPython CPU timings (estimated):\\
1525 Total runs performed: 5\\
1523 Total runs performed: 5\\
1526 Times : Total Per run\\
1524 Times : Total Per run\\
1527 User : 0.910862 s, 0.1821724 s.\\
1525 User : 0.910862 s, 0.1821724 s.\\
1528 System: 0.0 s, 0.0 s.
1526 System: 0.0 s, 0.0 s.
1529
1527
1530 -d: run your program under the control of pdb, the Python debugger.
1528 -d: run your program under the control of pdb, the Python debugger.
1531 This allows you to execute your program step by step, watch variables,
1529 This allows you to execute your program step by step, watch variables,
1532 etc. Internally, what IPython does is similar to calling:
1530 etc. Internally, what IPython does is similar to calling:
1533
1531
1534 pdb.run('execfile("YOURFILENAME")')
1532 pdb.run('execfile("YOURFILENAME")')
1535
1533
1536 with a breakpoint set on line 1 of your file. You can change the line
1534 with a breakpoint set on line 1 of your file. You can change the line
1537 number for this automatic breakpoint to be <N> by using the -bN option
1535 number for this automatic breakpoint to be <N> by using the -bN option
1538 (where N must be an integer). For example:
1536 (where N must be an integer). For example:
1539
1537
1540 %run -d -b40 myscript
1538 %run -d -b40 myscript
1541
1539
1542 will set the first breakpoint at line 40 in myscript.py. Note that
1540 will set the first breakpoint at line 40 in myscript.py. Note that
1543 the first breakpoint must be set on a line which actually does
1541 the first breakpoint must be set on a line which actually does
1544 something (not a comment or docstring) for it to stop execution.
1542 something (not a comment or docstring) for it to stop execution.
1545
1543
1546 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1544 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1547 first enter 'c' (without qoutes) to start execution up to the first
1545 first enter 'c' (without qoutes) to start execution up to the first
1548 breakpoint.
1546 breakpoint.
1549
1547
1550 Entering 'help' gives information about the use of the debugger. You
1548 Entering 'help' gives information about the use of the debugger. You
1551 can easily see pdb's full documentation with "import pdb;pdb.help()"
1549 can easily see pdb's full documentation with "import pdb;pdb.help()"
1552 at a prompt.
1550 at a prompt.
1553
1551
1554 -p: run program under the control of the Python profiler module (which
1552 -p: run program under the control of the Python profiler module (which
1555 prints a detailed report of execution times, function calls, etc).
1553 prints a detailed report of execution times, function calls, etc).
1556
1554
1557 You can pass other options after -p which affect the behavior of the
1555 You can pass other options after -p which affect the behavior of the
1558 profiler itself. See the docs for %prun for details.
1556 profiler itself. See the docs for %prun for details.
1559
1557
1560 In this mode, the program's variables do NOT propagate back to the
1558 In this mode, the program's variables do NOT propagate back to the
1561 IPython interactive namespace (because they remain in the namespace
1559 IPython interactive namespace (because they remain in the namespace
1562 where the profiler executes them).
1560 where the profiler executes them).
1563
1561
1564 Internally this triggers a call to %prun, see its documentation for
1562 Internally this triggers a call to %prun, see its documentation for
1565 details on the options available specifically for profiling.
1563 details on the options available specifically for profiling.
1566
1564
1567 There is one special usage for which the text above doesn't apply:
1565 There is one special usage for which the text above doesn't apply:
1568 if the filename ends with .ipy, the file is run as ipython script,
1566 if the filename ends with .ipy, the file is run as ipython script,
1569 just as if the commands were written on IPython prompt.
1567 just as if the commands were written on IPython prompt.
1570 """
1568 """
1571
1569
1572 # get arguments and set sys.argv for program to be run.
1570 # get arguments and set sys.argv for program to be run.
1573 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1571 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1574 mode='list',list_all=1)
1572 mode='list',list_all=1)
1575
1573
1576 try:
1574 try:
1577 filename = file_finder(arg_lst[0])
1575 filename = file_finder(arg_lst[0])
1578 except IndexError:
1576 except IndexError:
1579 warn('you must provide at least a filename.')
1577 warn('you must provide at least a filename.')
1580 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1578 print '\n%run:\n',oinspect.getdoc(self.magic_run)
1581 return
1579 return
1582 except IOError,msg:
1580 except IOError,msg:
1583 error(msg)
1581 error(msg)
1584 return
1582 return
1585
1583
1586 if filename.lower().endswith('.ipy'):
1584 if filename.lower().endswith('.ipy'):
1587 self.shell.safe_execfile_ipy(filename)
1585 self.shell.safe_execfile_ipy(filename)
1588 return
1586 return
1589
1587
1590 # Control the response to exit() calls made by the script being run
1588 # Control the response to exit() calls made by the script being run
1591 exit_ignore = opts.has_key('e')
1589 exit_ignore = opts.has_key('e')
1592
1590
1593 # Make sure that the running script gets a proper sys.argv as if it
1591 # Make sure that the running script gets a proper sys.argv as if it
1594 # were run from a system shell.
1592 # were run from a system shell.
1595 save_argv = sys.argv # save it for later restoring
1593 save_argv = sys.argv # save it for later restoring
1596 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1594 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1597
1595
1598 if opts.has_key('i'):
1596 if opts.has_key('i'):
1599 # Run in user's interactive namespace
1597 # Run in user's interactive namespace
1600 prog_ns = self.shell.user_ns
1598 prog_ns = self.shell.user_ns
1601 __name__save = self.shell.user_ns['__name__']
1599 __name__save = self.shell.user_ns['__name__']
1602 prog_ns['__name__'] = '__main__'
1600 prog_ns['__name__'] = '__main__'
1603 main_mod = self.shell.new_main_mod(prog_ns)
1601 main_mod = self.shell.new_main_mod(prog_ns)
1604 else:
1602 else:
1605 # Run in a fresh, empty namespace
1603 # Run in a fresh, empty namespace
1606 if opts.has_key('n'):
1604 if opts.has_key('n'):
1607 name = os.path.splitext(os.path.basename(filename))[0]
1605 name = os.path.splitext(os.path.basename(filename))[0]
1608 else:
1606 else:
1609 name = '__main__'
1607 name = '__main__'
1610
1608
1611 main_mod = self.shell.new_main_mod()
1609 main_mod = self.shell.new_main_mod()
1612 prog_ns = main_mod.__dict__
1610 prog_ns = main_mod.__dict__
1613 prog_ns['__name__'] = name
1611 prog_ns['__name__'] = name
1614
1612
1615 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1613 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1616 # set the __file__ global in the script's namespace
1614 # set the __file__ global in the script's namespace
1617 prog_ns['__file__'] = filename
1615 prog_ns['__file__'] = filename
1618
1616
1619 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1617 # pickle fix. See interactiveshell for an explanation. But we need to make sure
1620 # that, if we overwrite __main__, we replace it at the end
1618 # that, if we overwrite __main__, we replace it at the end
1621 main_mod_name = prog_ns['__name__']
1619 main_mod_name = prog_ns['__name__']
1622
1620
1623 if main_mod_name == '__main__':
1621 if main_mod_name == '__main__':
1624 restore_main = sys.modules['__main__']
1622 restore_main = sys.modules['__main__']
1625 else:
1623 else:
1626 restore_main = False
1624 restore_main = False
1627
1625
1628 # This needs to be undone at the end to prevent holding references to
1626 # This needs to be undone at the end to prevent holding references to
1629 # every single object ever created.
1627 # every single object ever created.
1630 sys.modules[main_mod_name] = main_mod
1628 sys.modules[main_mod_name] = main_mod
1631
1629
1632 try:
1630 try:
1633 stats = None
1631 stats = None
1634 with self.readline_no_record:
1632 with self.readline_no_record:
1635 if opts.has_key('p'):
1633 if opts.has_key('p'):
1636 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1634 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1637 else:
1635 else:
1638 if opts.has_key('d'):
1636 if opts.has_key('d'):
1639 deb = debugger.Pdb(self.shell.colors)
1637 deb = debugger.Pdb(self.shell.colors)
1640 # reset Breakpoint state, which is moronically kept
1638 # reset Breakpoint state, which is moronically kept
1641 # in a class
1639 # in a class
1642 bdb.Breakpoint.next = 1
1640 bdb.Breakpoint.next = 1
1643 bdb.Breakpoint.bplist = {}
1641 bdb.Breakpoint.bplist = {}
1644 bdb.Breakpoint.bpbynumber = [None]
1642 bdb.Breakpoint.bpbynumber = [None]
1645 # Set an initial breakpoint to stop execution
1643 # Set an initial breakpoint to stop execution
1646 maxtries = 10
1644 maxtries = 10
1647 bp = int(opts.get('b',[1])[0])
1645 bp = int(opts.get('b',[1])[0])
1648 checkline = deb.checkline(filename,bp)
1646 checkline = deb.checkline(filename,bp)
1649 if not checkline:
1647 if not checkline:
1650 for bp in range(bp+1,bp+maxtries+1):
1648 for bp in range(bp+1,bp+maxtries+1):
1651 if deb.checkline(filename,bp):
1649 if deb.checkline(filename,bp):
1652 break
1650 break
1653 else:
1651 else:
1654 msg = ("\nI failed to find a valid line to set "
1652 msg = ("\nI failed to find a valid line to set "
1655 "a breakpoint\n"
1653 "a breakpoint\n"
1656 "after trying up to line: %s.\n"
1654 "after trying up to line: %s.\n"
1657 "Please set a valid breakpoint manually "
1655 "Please set a valid breakpoint manually "
1658 "with the -b option." % bp)
1656 "with the -b option." % bp)
1659 error(msg)
1657 error(msg)
1660 return
1658 return
1661 # if we find a good linenumber, set the breakpoint
1659 # if we find a good linenumber, set the breakpoint
1662 deb.do_break('%s:%s' % (filename,bp))
1660 deb.do_break('%s:%s' % (filename,bp))
1663 # Start file run
1661 # Start file run
1664 print "NOTE: Enter 'c' at the",
1662 print "NOTE: Enter 'c' at the",
1665 print "%s prompt to start your script." % deb.prompt
1663 print "%s prompt to start your script." % deb.prompt
1666 try:
1664 try:
1667 deb.run('execfile("%s")' % filename,prog_ns)
1665 deb.run('execfile("%s")' % filename,prog_ns)
1668
1666
1669 except:
1667 except:
1670 etype, value, tb = sys.exc_info()
1668 etype, value, tb = sys.exc_info()
1671 # Skip three frames in the traceback: the %run one,
1669 # Skip three frames in the traceback: the %run one,
1672 # one inside bdb.py, and the command-line typed by the
1670 # one inside bdb.py, and the command-line typed by the
1673 # user (run by exec in pdb itself).
1671 # user (run by exec in pdb itself).
1674 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1672 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1675 else:
1673 else:
1676 if runner is None:
1674 if runner is None:
1677 runner = self.shell.safe_execfile
1675 runner = self.shell.safe_execfile
1678 if opts.has_key('t'):
1676 if opts.has_key('t'):
1679 # timed execution
1677 # timed execution
1680 try:
1678 try:
1681 nruns = int(opts['N'][0])
1679 nruns = int(opts['N'][0])
1682 if nruns < 1:
1680 if nruns < 1:
1683 error('Number of runs must be >=1')
1681 error('Number of runs must be >=1')
1684 return
1682 return
1685 except (KeyError):
1683 except (KeyError):
1686 nruns = 1
1684 nruns = 1
1687 if nruns == 1:
1685 if nruns == 1:
1688 t0 = clock2()
1686 t0 = clock2()
1689 runner(filename,prog_ns,prog_ns,
1687 runner(filename,prog_ns,prog_ns,
1690 exit_ignore=exit_ignore)
1688 exit_ignore=exit_ignore)
1691 t1 = clock2()
1689 t1 = clock2()
1692 t_usr = t1[0]-t0[0]
1690 t_usr = t1[0]-t0[0]
1693 t_sys = t1[1]-t0[1]
1691 t_sys = t1[1]-t0[1]
1694 print "\nIPython CPU timings (estimated):"
1692 print "\nIPython CPU timings (estimated):"
1695 print " User : %10s s." % t_usr
1693 print " User : %10s s." % t_usr
1696 print " System: %10s s." % t_sys
1694 print " System: %10s s." % t_sys
1697 else:
1695 else:
1698 runs = range(nruns)
1696 runs = range(nruns)
1699 t0 = clock2()
1697 t0 = clock2()
1700 for nr in runs:
1698 for nr in runs:
1701 runner(filename,prog_ns,prog_ns,
1699 runner(filename,prog_ns,prog_ns,
1702 exit_ignore=exit_ignore)
1700 exit_ignore=exit_ignore)
1703 t1 = clock2()
1701 t1 = clock2()
1704 t_usr = t1[0]-t0[0]
1702 t_usr = t1[0]-t0[0]
1705 t_sys = t1[1]-t0[1]
1703 t_sys = t1[1]-t0[1]
1706 print "\nIPython CPU timings (estimated):"
1704 print "\nIPython CPU timings (estimated):"
1707 print "Total runs performed:",nruns
1705 print "Total runs performed:",nruns
1708 print " Times : %10s %10s" % ('Total','Per run')
1706 print " Times : %10s %10s" % ('Total','Per run')
1709 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1707 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1710 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1708 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1711
1709
1712 else:
1710 else:
1713 # regular execution
1711 # regular execution
1714 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1712 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1715
1713
1716 if opts.has_key('i'):
1714 if opts.has_key('i'):
1717 self.shell.user_ns['__name__'] = __name__save
1715 self.shell.user_ns['__name__'] = __name__save
1718 else:
1716 else:
1719 # The shell MUST hold a reference to prog_ns so after %run
1717 # The shell MUST hold a reference to prog_ns so after %run
1720 # exits, the python deletion mechanism doesn't zero it out
1718 # exits, the python deletion mechanism doesn't zero it out
1721 # (leaving dangling references).
1719 # (leaving dangling references).
1722 self.shell.cache_main_mod(prog_ns,filename)
1720 self.shell.cache_main_mod(prog_ns,filename)
1723 # update IPython interactive namespace
1721 # update IPython interactive namespace
1724
1722
1725 # Some forms of read errors on the file may mean the
1723 # Some forms of read errors on the file may mean the
1726 # __name__ key was never set; using pop we don't have to
1724 # __name__ key was never set; using pop we don't have to
1727 # worry about a possible KeyError.
1725 # worry about a possible KeyError.
1728 prog_ns.pop('__name__', None)
1726 prog_ns.pop('__name__', None)
1729
1727
1730 self.shell.user_ns.update(prog_ns)
1728 self.shell.user_ns.update(prog_ns)
1731 finally:
1729 finally:
1732 # It's a bit of a mystery why, but __builtins__ can change from
1730 # It's a bit of a mystery why, but __builtins__ can change from
1733 # being a module to becoming a dict missing some key data after
1731 # being a module to becoming a dict missing some key data after
1734 # %run. As best I can see, this is NOT something IPython is doing
1732 # %run. As best I can see, this is NOT something IPython is doing
1735 # at all, and similar problems have been reported before:
1733 # at all, and similar problems have been reported before:
1736 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1734 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
1737 # Since this seems to be done by the interpreter itself, the best
1735 # Since this seems to be done by the interpreter itself, the best
1738 # we can do is to at least restore __builtins__ for the user on
1736 # we can do is to at least restore __builtins__ for the user on
1739 # exit.
1737 # exit.
1740 self.shell.user_ns['__builtins__'] = __builtin__
1738 self.shell.user_ns['__builtins__'] = __builtin__
1741
1739
1742 # Ensure key global structures are restored
1740 # Ensure key global structures are restored
1743 sys.argv = save_argv
1741 sys.argv = save_argv
1744 if restore_main:
1742 if restore_main:
1745 sys.modules['__main__'] = restore_main
1743 sys.modules['__main__'] = restore_main
1746 else:
1744 else:
1747 # Remove from sys.modules the reference to main_mod we'd
1745 # Remove from sys.modules the reference to main_mod we'd
1748 # added. Otherwise it will trap references to objects
1746 # added. Otherwise it will trap references to objects
1749 # contained therein.
1747 # contained therein.
1750 del sys.modules[main_mod_name]
1748 del sys.modules[main_mod_name]
1751
1749
1752 return stats
1750 return stats
1753
1751
1754 @skip_doctest
1752 @skip_doctest
1755 def magic_timeit(self, parameter_s =''):
1753 def magic_timeit(self, parameter_s =''):
1756 """Time execution of a Python statement or expression
1754 """Time execution of a Python statement or expression
1757
1755
1758 Usage:\\
1756 Usage:\\
1759 %timeit [-n<N> -r<R> [-t|-c]] statement
1757 %timeit [-n<N> -r<R> [-t|-c]] statement
1760
1758
1761 Time execution of a Python statement or expression using the timeit
1759 Time execution of a Python statement or expression using the timeit
1762 module.
1760 module.
1763
1761
1764 Options:
1762 Options:
1765 -n<N>: execute the given statement <N> times in a loop. If this value
1763 -n<N>: execute the given statement <N> times in a loop. If this value
1766 is not given, a fitting value is chosen.
1764 is not given, a fitting value is chosen.
1767
1765
1768 -r<R>: repeat the loop iteration <R> times and take the best result.
1766 -r<R>: repeat the loop iteration <R> times and take the best result.
1769 Default: 3
1767 Default: 3
1770
1768
1771 -t: use time.time to measure the time, which is the default on Unix.
1769 -t: use time.time to measure the time, which is the default on Unix.
1772 This function measures wall time.
1770 This function measures wall time.
1773
1771
1774 -c: use time.clock to measure the time, which is the default on
1772 -c: use time.clock to measure the time, which is the default on
1775 Windows and measures wall time. On Unix, resource.getrusage is used
1773 Windows and measures wall time. On Unix, resource.getrusage is used
1776 instead and returns the CPU user time.
1774 instead and returns the CPU user time.
1777
1775
1778 -p<P>: use a precision of <P> digits to display the timing result.
1776 -p<P>: use a precision of <P> digits to display the timing result.
1779 Default: 3
1777 Default: 3
1780
1778
1781
1779
1782 Examples:
1780 Examples:
1783
1781
1784 In [1]: %timeit pass
1782 In [1]: %timeit pass
1785 10000000 loops, best of 3: 53.3 ns per loop
1783 10000000 loops, best of 3: 53.3 ns per loop
1786
1784
1787 In [2]: u = None
1785 In [2]: u = None
1788
1786
1789 In [3]: %timeit u is None
1787 In [3]: %timeit u is None
1790 10000000 loops, best of 3: 184 ns per loop
1788 10000000 loops, best of 3: 184 ns per loop
1791
1789
1792 In [4]: %timeit -r 4 u == None
1790 In [4]: %timeit -r 4 u == None
1793 1000000 loops, best of 4: 242 ns per loop
1791 1000000 loops, best of 4: 242 ns per loop
1794
1792
1795 In [5]: import time
1793 In [5]: import time
1796
1794
1797 In [6]: %timeit -n1 time.sleep(2)
1795 In [6]: %timeit -n1 time.sleep(2)
1798 1 loops, best of 3: 2 s per loop
1796 1 loops, best of 3: 2 s per loop
1799
1797
1800
1798
1801 The times reported by %timeit will be slightly higher than those
1799 The times reported by %timeit will be slightly higher than those
1802 reported by the timeit.py script when variables are accessed. This is
1800 reported by the timeit.py script when variables are accessed. This is
1803 due to the fact that %timeit executes the statement in the namespace
1801 due to the fact that %timeit executes the statement in the namespace
1804 of the shell, compared with timeit.py, which uses a single setup
1802 of the shell, compared with timeit.py, which uses a single setup
1805 statement to import function or create variables. Generally, the bias
1803 statement to import function or create variables. Generally, the bias
1806 does not matter as long as results from timeit.py are not mixed with
1804 does not matter as long as results from timeit.py are not mixed with
1807 those from %timeit."""
1805 those from %timeit."""
1808
1806
1809 import timeit
1807 import timeit
1810 import math
1808 import math
1811
1809
1812 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1810 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
1813 # certain terminals. Until we figure out a robust way of
1811 # certain terminals. Until we figure out a robust way of
1814 # auto-detecting if the terminal can deal with it, use plain 'us' for
1812 # auto-detecting if the terminal can deal with it, use plain 'us' for
1815 # microseconds. I am really NOT happy about disabling the proper
1813 # microseconds. I am really NOT happy about disabling the proper
1816 # 'micro' prefix, but crashing is worse... If anyone knows what the
1814 # 'micro' prefix, but crashing is worse... If anyone knows what the
1817 # right solution for this is, I'm all ears...
1815 # right solution for this is, I'm all ears...
1818 #
1816 #
1819 # Note: using
1817 # Note: using
1820 #
1818 #
1821 # s = u'\xb5'
1819 # s = u'\xb5'
1822 # s.encode(sys.getdefaultencoding())
1820 # s.encode(sys.getdefaultencoding())
1823 #
1821 #
1824 # is not sufficient, as I've seen terminals where that fails but
1822 # is not sufficient, as I've seen terminals where that fails but
1825 # print s
1823 # print s
1826 #
1824 #
1827 # succeeds
1825 # succeeds
1828 #
1826 #
1829 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1827 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1830
1828
1831 #units = [u"s", u"ms",u'\xb5',"ns"]
1829 #units = [u"s", u"ms",u'\xb5',"ns"]
1832 units = [u"s", u"ms",u'us',"ns"]
1830 units = [u"s", u"ms",u'us',"ns"]
1833
1831
1834 scaling = [1, 1e3, 1e6, 1e9]
1832 scaling = [1, 1e3, 1e6, 1e9]
1835
1833
1836 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1834 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
1837 posix=False)
1835 posix=False)
1838 if stmt == "":
1836 if stmt == "":
1839 return
1837 return
1840 timefunc = timeit.default_timer
1838 timefunc = timeit.default_timer
1841 number = int(getattr(opts, "n", 0))
1839 number = int(getattr(opts, "n", 0))
1842 repeat = int(getattr(opts, "r", timeit.default_repeat))
1840 repeat = int(getattr(opts, "r", timeit.default_repeat))
1843 precision = int(getattr(opts, "p", 3))
1841 precision = int(getattr(opts, "p", 3))
1844 if hasattr(opts, "t"):
1842 if hasattr(opts, "t"):
1845 timefunc = time.time
1843 timefunc = time.time
1846 if hasattr(opts, "c"):
1844 if hasattr(opts, "c"):
1847 timefunc = clock
1845 timefunc = clock
1848
1846
1849 timer = timeit.Timer(timer=timefunc)
1847 timer = timeit.Timer(timer=timefunc)
1850 # this code has tight coupling to the inner workings of timeit.Timer,
1848 # this code has tight coupling to the inner workings of timeit.Timer,
1851 # but is there a better way to achieve that the code stmt has access
1849 # but is there a better way to achieve that the code stmt has access
1852 # to the shell namespace?
1850 # to the shell namespace?
1853
1851
1854 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1852 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
1855 'setup': "pass"}
1853 'setup': "pass"}
1856 # Track compilation time so it can be reported if too long
1854 # Track compilation time so it can be reported if too long
1857 # Minimum time above which compilation time will be reported
1855 # Minimum time above which compilation time will be reported
1858 tc_min = 0.1
1856 tc_min = 0.1
1859
1857
1860 t0 = clock()
1858 t0 = clock()
1861 code = compile(src, "<magic-timeit>", "exec")
1859 code = compile(src, "<magic-timeit>", "exec")
1862 tc = clock()-t0
1860 tc = clock()-t0
1863
1861
1864 ns = {}
1862 ns = {}
1865 exec code in self.shell.user_ns, ns
1863 exec code in self.shell.user_ns, ns
1866 timer.inner = ns["inner"]
1864 timer.inner = ns["inner"]
1867
1865
1868 if number == 0:
1866 if number == 0:
1869 # determine number so that 0.2 <= total time < 2.0
1867 # determine number so that 0.2 <= total time < 2.0
1870 number = 1
1868 number = 1
1871 for i in range(1, 10):
1869 for i in range(1, 10):
1872 if timer.timeit(number) >= 0.2:
1870 if timer.timeit(number) >= 0.2:
1873 break
1871 break
1874 number *= 10
1872 number *= 10
1875
1873
1876 best = min(timer.repeat(repeat, number)) / number
1874 best = min(timer.repeat(repeat, number)) / number
1877
1875
1878 if best > 0.0 and best < 1000.0:
1876 if best > 0.0 and best < 1000.0:
1879 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1877 order = min(-int(math.floor(math.log10(best)) // 3), 3)
1880 elif best >= 1000.0:
1878 elif best >= 1000.0:
1881 order = 0
1879 order = 0
1882 else:
1880 else:
1883 order = 3
1881 order = 3
1884 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1882 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
1885 precision,
1883 precision,
1886 best * scaling[order],
1884 best * scaling[order],
1887 units[order])
1885 units[order])
1888 if tc > tc_min:
1886 if tc > tc_min:
1889 print "Compiler time: %.2f s" % tc
1887 print "Compiler time: %.2f s" % tc
1890
1888
1891 @skip_doctest
1889 @skip_doctest
1892 @needs_local_scope
1890 @needs_local_scope
1893 def magic_time(self,parameter_s = ''):
1891 def magic_time(self,parameter_s = ''):
1894 """Time execution of a Python statement or expression.
1892 """Time execution of a Python statement or expression.
1895
1893
1896 The CPU and wall clock times are printed, and the value of the
1894 The CPU and wall clock times are printed, and the value of the
1897 expression (if any) is returned. Note that under Win32, system time
1895 expression (if any) is returned. Note that under Win32, system time
1898 is always reported as 0, since it can not be measured.
1896 is always reported as 0, since it can not be measured.
1899
1897
1900 This function provides very basic timing functionality. In Python
1898 This function provides very basic timing functionality. In Python
1901 2.3, the timeit module offers more control and sophistication, so this
1899 2.3, the timeit module offers more control and sophistication, so this
1902 could be rewritten to use it (patches welcome).
1900 could be rewritten to use it (patches welcome).
1903
1901
1904 Some examples:
1902 Some examples:
1905
1903
1906 In [1]: time 2**128
1904 In [1]: time 2**128
1907 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1905 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1908 Wall time: 0.00
1906 Wall time: 0.00
1909 Out[1]: 340282366920938463463374607431768211456L
1907 Out[1]: 340282366920938463463374607431768211456L
1910
1908
1911 In [2]: n = 1000000
1909 In [2]: n = 1000000
1912
1910
1913 In [3]: time sum(range(n))
1911 In [3]: time sum(range(n))
1914 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1912 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1915 Wall time: 1.37
1913 Wall time: 1.37
1916 Out[3]: 499999500000L
1914 Out[3]: 499999500000L
1917
1915
1918 In [4]: time print 'hello world'
1916 In [4]: time print 'hello world'
1919 hello world
1917 hello world
1920 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1918 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1921 Wall time: 0.00
1919 Wall time: 0.00
1922
1920
1923 Note that the time needed by Python to compile the given expression
1921 Note that the time needed by Python to compile the given expression
1924 will be reported if it is more than 0.1s. In this example, the
1922 will be reported if it is more than 0.1s. In this example, the
1925 actual exponentiation is done by Python at compilation time, so while
1923 actual exponentiation is done by Python at compilation time, so while
1926 the expression can take a noticeable amount of time to compute, that
1924 the expression can take a noticeable amount of time to compute, that
1927 time is purely due to the compilation:
1925 time is purely due to the compilation:
1928
1926
1929 In [5]: time 3**9999;
1927 In [5]: time 3**9999;
1930 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1928 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1931 Wall time: 0.00 s
1929 Wall time: 0.00 s
1932
1930
1933 In [6]: time 3**999999;
1931 In [6]: time 3**999999;
1934 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1932 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1935 Wall time: 0.00 s
1933 Wall time: 0.00 s
1936 Compiler : 0.78 s
1934 Compiler : 0.78 s
1937 """
1935 """
1938
1936
1939 # fail immediately if the given expression can't be compiled
1937 # fail immediately if the given expression can't be compiled
1940
1938
1941 expr = self.shell.prefilter(parameter_s,False)
1939 expr = self.shell.prefilter(parameter_s,False)
1942
1940
1943 # Minimum time above which compilation time will be reported
1941 # Minimum time above which compilation time will be reported
1944 tc_min = 0.1
1942 tc_min = 0.1
1945
1943
1946 try:
1944 try:
1947 mode = 'eval'
1945 mode = 'eval'
1948 t0 = clock()
1946 t0 = clock()
1949 code = compile(expr,'<timed eval>',mode)
1947 code = compile(expr,'<timed eval>',mode)
1950 tc = clock()-t0
1948 tc = clock()-t0
1951 except SyntaxError:
1949 except SyntaxError:
1952 mode = 'exec'
1950 mode = 'exec'
1953 t0 = clock()
1951 t0 = clock()
1954 code = compile(expr,'<timed exec>',mode)
1952 code = compile(expr,'<timed exec>',mode)
1955 tc = clock()-t0
1953 tc = clock()-t0
1956 # skew measurement as little as possible
1954 # skew measurement as little as possible
1957 glob = self.shell.user_ns
1955 glob = self.shell.user_ns
1958 locs = self._magic_locals
1956 locs = self._magic_locals
1959 clk = clock2
1957 clk = clock2
1960 wtime = time.time
1958 wtime = time.time
1961 # time execution
1959 # time execution
1962 wall_st = wtime()
1960 wall_st = wtime()
1963 if mode=='eval':
1961 if mode=='eval':
1964 st = clk()
1962 st = clk()
1965 out = eval(code, glob, locs)
1963 out = eval(code, glob, locs)
1966 end = clk()
1964 end = clk()
1967 else:
1965 else:
1968 st = clk()
1966 st = clk()
1969 exec code in glob, locs
1967 exec code in glob, locs
1970 end = clk()
1968 end = clk()
1971 out = None
1969 out = None
1972 wall_end = wtime()
1970 wall_end = wtime()
1973 # Compute actual times and report
1971 # Compute actual times and report
1974 wall_time = wall_end-wall_st
1972 wall_time = wall_end-wall_st
1975 cpu_user = end[0]-st[0]
1973 cpu_user = end[0]-st[0]
1976 cpu_sys = end[1]-st[1]
1974 cpu_sys = end[1]-st[1]
1977 cpu_tot = cpu_user+cpu_sys
1975 cpu_tot = cpu_user+cpu_sys
1978 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1976 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1979 (cpu_user,cpu_sys,cpu_tot)
1977 (cpu_user,cpu_sys,cpu_tot)
1980 print "Wall time: %.2f s" % wall_time
1978 print "Wall time: %.2f s" % wall_time
1981 if tc > tc_min:
1979 if tc > tc_min:
1982 print "Compiler : %.2f s" % tc
1980 print "Compiler : %.2f s" % tc
1983 return out
1981 return out
1984
1982
1985 @skip_doctest
1983 @skip_doctest
1986 def magic_macro(self,parameter_s = ''):
1984 def magic_macro(self,parameter_s = ''):
1987 """Define a macro for future re-execution. It accepts ranges of history,
1985 """Define a macro for future re-execution. It accepts ranges of history,
1988 filenames or string objects.
1986 filenames or string objects.
1989
1987
1990 Usage:\\
1988 Usage:\\
1991 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1989 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1992
1990
1993 Options:
1991 Options:
1994
1992
1995 -r: use 'raw' input. By default, the 'processed' history is used,
1993 -r: use 'raw' input. By default, the 'processed' history is used,
1996 so that magics are loaded in their transformed version to valid
1994 so that magics are loaded in their transformed version to valid
1997 Python. If this option is given, the raw input as typed as the
1995 Python. If this option is given, the raw input as typed as the
1998 command line is used instead.
1996 command line is used instead.
1999
1997
2000 This will define a global variable called `name` which is a string
1998 This will define a global variable called `name` which is a string
2001 made of joining the slices and lines you specify (n1,n2,... numbers
1999 made of joining the slices and lines you specify (n1,n2,... numbers
2002 above) from your input history into a single string. This variable
2000 above) from your input history into a single string. This variable
2003 acts like an automatic function which re-executes those lines as if
2001 acts like an automatic function which re-executes those lines as if
2004 you had typed them. You just type 'name' at the prompt and the code
2002 you had typed them. You just type 'name' at the prompt and the code
2005 executes.
2003 executes.
2006
2004
2007 The syntax for indicating input ranges is described in %history.
2005 The syntax for indicating input ranges is described in %history.
2008
2006
2009 Note: as a 'hidden' feature, you can also use traditional python slice
2007 Note: as a 'hidden' feature, you can also use traditional python slice
2010 notation, where N:M means numbers N through M-1.
2008 notation, where N:M means numbers N through M-1.
2011
2009
2012 For example, if your history contains (%hist prints it):
2010 For example, if your history contains (%hist prints it):
2013
2011
2014 44: x=1
2012 44: x=1
2015 45: y=3
2013 45: y=3
2016 46: z=x+y
2014 46: z=x+y
2017 47: print x
2015 47: print x
2018 48: a=5
2016 48: a=5
2019 49: print 'x',x,'y',y
2017 49: print 'x',x,'y',y
2020
2018
2021 you can create a macro with lines 44 through 47 (included) and line 49
2019 you can create a macro with lines 44 through 47 (included) and line 49
2022 called my_macro with:
2020 called my_macro with:
2023
2021
2024 In [55]: %macro my_macro 44-47 49
2022 In [55]: %macro my_macro 44-47 49
2025
2023
2026 Now, typing `my_macro` (without quotes) will re-execute all this code
2024 Now, typing `my_macro` (without quotes) will re-execute all this code
2027 in one pass.
2025 in one pass.
2028
2026
2029 You don't need to give the line-numbers in order, and any given line
2027 You don't need to give the line-numbers in order, and any given line
2030 number can appear multiple times. You can assemble macros with any
2028 number can appear multiple times. You can assemble macros with any
2031 lines from your input history in any order.
2029 lines from your input history in any order.
2032
2030
2033 The macro is a simple object which holds its value in an attribute,
2031 The macro is a simple object which holds its value in an attribute,
2034 but IPython's display system checks for macros and executes them as
2032 but IPython's display system checks for macros and executes them as
2035 code instead of printing them when you type their name.
2033 code instead of printing them when you type their name.
2036
2034
2037 You can view a macro's contents by explicitly printing it with:
2035 You can view a macro's contents by explicitly printing it with:
2038
2036
2039 'print macro_name'.
2037 'print macro_name'.
2040
2038
2041 """
2039 """
2042 opts,args = self.parse_options(parameter_s,'r',mode='list')
2040 opts,args = self.parse_options(parameter_s,'r',mode='list')
2043 if not args: # List existing macros
2041 if not args: # List existing macros
2044 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2042 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2045 isinstance(v, Macro))
2043 isinstance(v, Macro))
2046 if len(args) == 1:
2044 if len(args) == 1:
2047 raise UsageError(
2045 raise UsageError(
2048 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2046 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2049 name, codefrom = args[0], " ".join(args[1:])
2047 name, codefrom = args[0], " ".join(args[1:])
2050
2048
2051 #print 'rng',ranges # dbg
2049 #print 'rng',ranges # dbg
2052 try:
2050 try:
2053 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2051 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2054 except (ValueError, TypeError) as e:
2052 except (ValueError, TypeError) as e:
2055 print e.args[0]
2053 print e.args[0]
2056 return
2054 return
2057 macro = Macro(lines)
2055 macro = Macro(lines)
2058 self.shell.define_macro(name, macro)
2056 self.shell.define_macro(name, macro)
2059 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2057 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2060 print '=== Macro contents: ==='
2058 print '=== Macro contents: ==='
2061 print macro,
2059 print macro,
2062
2060
2063 def magic_save(self,parameter_s = ''):
2061 def magic_save(self,parameter_s = ''):
2064 """Save a set of lines or a macro to a given filename.
2062 """Save a set of lines or a macro to a given filename.
2065
2063
2066 Usage:\\
2064 Usage:\\
2067 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2065 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
2068
2066
2069 Options:
2067 Options:
2070
2068
2071 -r: use 'raw' input. By default, the 'processed' history is used,
2069 -r: use 'raw' input. By default, the 'processed' history is used,
2072 so that magics are loaded in their transformed version to valid
2070 so that magics are loaded in their transformed version to valid
2073 Python. If this option is given, the raw input as typed as the
2071 Python. If this option is given, the raw input as typed as the
2074 command line is used instead.
2072 command line is used instead.
2075
2073
2076 This function uses the same syntax as %history for input ranges,
2074 This function uses the same syntax as %history for input ranges,
2077 then saves the lines to the filename you specify.
2075 then saves the lines to the filename you specify.
2078
2076
2079 It adds a '.py' extension to the file if you don't do so yourself, and
2077 It adds a '.py' extension to the file if you don't do so yourself, and
2080 it asks for confirmation before overwriting existing files."""
2078 it asks for confirmation before overwriting existing files."""
2081
2079
2082 opts,args = self.parse_options(parameter_s,'r',mode='list')
2080 opts,args = self.parse_options(parameter_s,'r',mode='list')
2083 fname, codefrom = args[0], " ".join(args[1:])
2081 fname, codefrom = args[0], " ".join(args[1:])
2084 if not fname.endswith('.py'):
2082 if not fname.endswith('.py'):
2085 fname += '.py'
2083 fname += '.py'
2086 if os.path.isfile(fname):
2084 if os.path.isfile(fname):
2087 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2085 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
2088 if ans.lower() not in ['y','yes']:
2086 if ans.lower() not in ['y','yes']:
2089 print 'Operation cancelled.'
2087 print 'Operation cancelled.'
2090 return
2088 return
2091 try:
2089 try:
2092 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2090 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
2093 except (TypeError, ValueError) as e:
2091 except (TypeError, ValueError) as e:
2094 print e.args[0]
2092 print e.args[0]
2095 return
2093 return
2096 if isinstance(cmds, unicode):
2094 if isinstance(cmds, unicode):
2097 cmds = cmds.encode("utf-8")
2095 cmds = cmds.encode("utf-8")
2098 with open(fname,'w') as f:
2096 with open(fname,'w') as f:
2099 f.write("# coding: utf-8\n")
2097 f.write("# coding: utf-8\n")
2100 f.write(cmds)
2098 f.write(cmds)
2101 print 'The following commands were written to file `%s`:' % fname
2099 print 'The following commands were written to file `%s`:' % fname
2102 print cmds
2100 print cmds
2103
2101
2104 def magic_pastebin(self, parameter_s = ''):
2102 def magic_pastebin(self, parameter_s = ''):
2105 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2103 """Upload code to the 'Lodge it' paste bin, returning the URL."""
2106 try:
2104 try:
2107 code = self.shell.find_user_code(parameter_s)
2105 code = self.shell.find_user_code(parameter_s)
2108 except (ValueError, TypeError) as e:
2106 except (ValueError, TypeError) as e:
2109 print e.args[0]
2107 print e.args[0]
2110 return
2108 return
2111 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2109 pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/')
2112 id = pbserver.pastes.newPaste("python", code)
2110 id = pbserver.pastes.newPaste("python", code)
2113 return "http://paste.pocoo.org/show/" + id
2111 return "http://paste.pocoo.org/show/" + id
2114
2112
2115 def magic_loadpy(self, arg_s):
2113 def magic_loadpy(self, arg_s):
2116 """Load a .py python script into the GUI console.
2114 """Load a .py python script into the GUI console.
2117
2115
2118 This magic command can either take a local filename or a url::
2116 This magic command can either take a local filename or a url::
2119
2117
2120 %loadpy myscript.py
2118 %loadpy myscript.py
2121 %loadpy http://www.example.com/myscript.py
2119 %loadpy http://www.example.com/myscript.py
2122 """
2120 """
2123 if not arg_s.endswith('.py'):
2121 if not arg_s.endswith('.py'):
2124 raise ValueError('%%load only works with .py files: %s' % arg_s)
2122 raise ValueError('%%load only works with .py files: %s' % arg_s)
2125 if arg_s.startswith('http'):
2123 if arg_s.startswith('http'):
2126 import urllib2
2124 import urllib2
2127 response = urllib2.urlopen(arg_s)
2125 response = urllib2.urlopen(arg_s)
2128 content = response.read()
2126 content = response.read()
2129 else:
2127 else:
2130 content = open(arg_s).read()
2128 content = open(arg_s).read()
2131 self.set_next_input(content)
2129 self.set_next_input(content)
2132
2130
2133 def _find_edit_target(self, args, opts, last_call):
2131 def _find_edit_target(self, args, opts, last_call):
2134 """Utility method used by magic_edit to find what to edit."""
2132 """Utility method used by magic_edit to find what to edit."""
2135
2133
2136 def make_filename(arg):
2134 def make_filename(arg):
2137 "Make a filename from the given args"
2135 "Make a filename from the given args"
2138 try:
2136 try:
2139 filename = get_py_filename(arg)
2137 filename = get_py_filename(arg)
2140 except IOError:
2138 except IOError:
2141 # If it ends with .py but doesn't already exist, assume we want
2139 # If it ends with .py but doesn't already exist, assume we want
2142 # a new file.
2140 # a new file.
2143 if args.endswith('.py'):
2141 if args.endswith('.py'):
2144 filename = arg
2142 filename = arg
2145 else:
2143 else:
2146 filename = None
2144 filename = None
2147 return filename
2145 return filename
2148
2146
2149 # Set a few locals from the options for convenience:
2147 # Set a few locals from the options for convenience:
2150 opts_prev = 'p' in opts
2148 opts_prev = 'p' in opts
2151 opts_raw = 'r' in opts
2149 opts_raw = 'r' in opts
2152
2150
2153 # custom exceptions
2151 # custom exceptions
2154 class DataIsObject(Exception): pass
2152 class DataIsObject(Exception): pass
2155
2153
2156 # Default line number value
2154 # Default line number value
2157 lineno = opts.get('n',None)
2155 lineno = opts.get('n',None)
2158
2156
2159 if opts_prev:
2157 if opts_prev:
2160 args = '_%s' % last_call[0]
2158 args = '_%s' % last_call[0]
2161 if not self.shell.user_ns.has_key(args):
2159 if not self.shell.user_ns.has_key(args):
2162 args = last_call[1]
2160 args = last_call[1]
2163
2161
2164 # use last_call to remember the state of the previous call, but don't
2162 # use last_call to remember the state of the previous call, but don't
2165 # let it be clobbered by successive '-p' calls.
2163 # let it be clobbered by successive '-p' calls.
2166 try:
2164 try:
2167 last_call[0] = self.shell.displayhook.prompt_count
2165 last_call[0] = self.shell.displayhook.prompt_count
2168 if not opts_prev:
2166 if not opts_prev:
2169 last_call[1] = parameter_s
2167 last_call[1] = parameter_s
2170 except:
2168 except:
2171 pass
2169 pass
2172
2170
2173 # by default this is done with temp files, except when the given
2171 # by default this is done with temp files, except when the given
2174 # arg is a filename
2172 # arg is a filename
2175 use_temp = True
2173 use_temp = True
2176
2174
2177 data = ''
2175 data = ''
2178
2176
2179 # First, see if the arguments should be a filename.
2177 # First, see if the arguments should be a filename.
2180 filename = make_filename(args)
2178 filename = make_filename(args)
2181 if filename:
2179 if filename:
2182 use_temp = False
2180 use_temp = False
2183 elif args:
2181 elif args:
2184 # Mode where user specifies ranges of lines, like in %macro.
2182 # Mode where user specifies ranges of lines, like in %macro.
2185 data = self.extract_input_lines(args, opts_raw)
2183 data = self.extract_input_lines(args, opts_raw)
2186 if not data:
2184 if not data:
2187 try:
2185 try:
2188 # Load the parameter given as a variable. If not a string,
2186 # Load the parameter given as a variable. If not a string,
2189 # process it as an object instead (below)
2187 # process it as an object instead (below)
2190
2188
2191 #print '*** args',args,'type',type(args) # dbg
2189 #print '*** args',args,'type',type(args) # dbg
2192 data = eval(args, self.shell.user_ns)
2190 data = eval(args, self.shell.user_ns)
2193 if not isinstance(data, basestring):
2191 if not isinstance(data, basestring):
2194 raise DataIsObject
2192 raise DataIsObject
2195
2193
2196 except (NameError,SyntaxError):
2194 except (NameError,SyntaxError):
2197 # given argument is not a variable, try as a filename
2195 # given argument is not a variable, try as a filename
2198 filename = make_filename(args)
2196 filename = make_filename(args)
2199 if filename is None:
2197 if filename is None:
2200 warn("Argument given (%s) can't be found as a variable "
2198 warn("Argument given (%s) can't be found as a variable "
2201 "or as a filename." % args)
2199 "or as a filename." % args)
2202 return
2200 return
2203 use_temp = False
2201 use_temp = False
2204
2202
2205 except DataIsObject:
2203 except DataIsObject:
2206 # macros have a special edit function
2204 # macros have a special edit function
2207 if isinstance(data, Macro):
2205 if isinstance(data, Macro):
2208 raise MacroToEdit(data)
2206 raise MacroToEdit(data)
2209
2207
2210 # For objects, try to edit the file where they are defined
2208 # For objects, try to edit the file where they are defined
2211 try:
2209 try:
2212 filename = inspect.getabsfile(data)
2210 filename = inspect.getabsfile(data)
2213 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2211 if 'fakemodule' in filename.lower() and inspect.isclass(data):
2214 # class created by %edit? Try to find source
2212 # class created by %edit? Try to find source
2215 # by looking for method definitions instead, the
2213 # by looking for method definitions instead, the
2216 # __module__ in those classes is FakeModule.
2214 # __module__ in those classes is FakeModule.
2217 attrs = [getattr(data, aname) for aname in dir(data)]
2215 attrs = [getattr(data, aname) for aname in dir(data)]
2218 for attr in attrs:
2216 for attr in attrs:
2219 if not inspect.ismethod(attr):
2217 if not inspect.ismethod(attr):
2220 continue
2218 continue
2221 filename = inspect.getabsfile(attr)
2219 filename = inspect.getabsfile(attr)
2222 if filename and 'fakemodule' not in filename.lower():
2220 if filename and 'fakemodule' not in filename.lower():
2223 # change the attribute to be the edit target instead
2221 # change the attribute to be the edit target instead
2224 data = attr
2222 data = attr
2225 break
2223 break
2226
2224
2227 datafile = 1
2225 datafile = 1
2228 except TypeError:
2226 except TypeError:
2229 filename = make_filename(args)
2227 filename = make_filename(args)
2230 datafile = 1
2228 datafile = 1
2231 warn('Could not find file where `%s` is defined.\n'
2229 warn('Could not find file where `%s` is defined.\n'
2232 'Opening a file named `%s`' % (args,filename))
2230 'Opening a file named `%s`' % (args,filename))
2233 # Now, make sure we can actually read the source (if it was in
2231 # Now, make sure we can actually read the source (if it was in
2234 # a temp file it's gone by now).
2232 # a temp file it's gone by now).
2235 if datafile:
2233 if datafile:
2236 try:
2234 try:
2237 if lineno is None:
2235 if lineno is None:
2238 lineno = inspect.getsourcelines(data)[1]
2236 lineno = inspect.getsourcelines(data)[1]
2239 except IOError:
2237 except IOError:
2240 filename = make_filename(args)
2238 filename = make_filename(args)
2241 if filename is None:
2239 if filename is None:
2242 warn('The file `%s` where `%s` was defined cannot '
2240 warn('The file `%s` where `%s` was defined cannot '
2243 'be read.' % (filename,data))
2241 'be read.' % (filename,data))
2244 return
2242 return
2245 use_temp = False
2243 use_temp = False
2246
2244
2247 if use_temp:
2245 if use_temp:
2248 filename = self.shell.mktempfile(data)
2246 filename = self.shell.mktempfile(data)
2249 print 'IPython will make a temporary file named:',filename
2247 print 'IPython will make a temporary file named:',filename
2250
2248
2251 return filename, lineno, use_temp
2249 return filename, lineno, use_temp
2252
2250
2253 def _edit_macro(self,mname,macro):
2251 def _edit_macro(self,mname,macro):
2254 """open an editor with the macro data in a file"""
2252 """open an editor with the macro data in a file"""
2255 filename = self.shell.mktempfile(macro.value)
2253 filename = self.shell.mktempfile(macro.value)
2256 self.shell.hooks.editor(filename)
2254 self.shell.hooks.editor(filename)
2257
2255
2258 # and make a new macro object, to replace the old one
2256 # and make a new macro object, to replace the old one
2259 mfile = open(filename)
2257 mfile = open(filename)
2260 mvalue = mfile.read()
2258 mvalue = mfile.read()
2261 mfile.close()
2259 mfile.close()
2262 self.shell.user_ns[mname] = Macro(mvalue)
2260 self.shell.user_ns[mname] = Macro(mvalue)
2263
2261
2264 def magic_ed(self,parameter_s=''):
2262 def magic_ed(self,parameter_s=''):
2265 """Alias to %edit."""
2263 """Alias to %edit."""
2266 return self.magic_edit(parameter_s)
2264 return self.magic_edit(parameter_s)
2267
2265
2268 @skip_doctest
2266 @skip_doctest
2269 def magic_edit(self,parameter_s='',last_call=['','']):
2267 def magic_edit(self,parameter_s='',last_call=['','']):
2270 """Bring up an editor and execute the resulting code.
2268 """Bring up an editor and execute the resulting code.
2271
2269
2272 Usage:
2270 Usage:
2273 %edit [options] [args]
2271 %edit [options] [args]
2274
2272
2275 %edit runs IPython's editor hook. The default version of this hook is
2273 %edit runs IPython's editor hook. The default version of this hook is
2276 set to call the __IPYTHON__.rc.editor command. This is read from your
2274 set to call the __IPYTHON__.rc.editor command. This is read from your
2277 environment variable $EDITOR. If this isn't found, it will default to
2275 environment variable $EDITOR. If this isn't found, it will default to
2278 vi under Linux/Unix and to notepad under Windows. See the end of this
2276 vi under Linux/Unix and to notepad under Windows. See the end of this
2279 docstring for how to change the editor hook.
2277 docstring for how to change the editor hook.
2280
2278
2281 You can also set the value of this editor via the command line option
2279 You can also set the value of this editor via the command line option
2282 '-editor' or in your ipythonrc file. This is useful if you wish to use
2280 '-editor' or in your ipythonrc file. This is useful if you wish to use
2283 specifically for IPython an editor different from your typical default
2281 specifically for IPython an editor different from your typical default
2284 (and for Windows users who typically don't set environment variables).
2282 (and for Windows users who typically don't set environment variables).
2285
2283
2286 This command allows you to conveniently edit multi-line code right in
2284 This command allows you to conveniently edit multi-line code right in
2287 your IPython session.
2285 your IPython session.
2288
2286
2289 If called without arguments, %edit opens up an empty editor with a
2287 If called without arguments, %edit opens up an empty editor with a
2290 temporary file and will execute the contents of this file when you
2288 temporary file and will execute the contents of this file when you
2291 close it (don't forget to save it!).
2289 close it (don't forget to save it!).
2292
2290
2293
2291
2294 Options:
2292 Options:
2295
2293
2296 -n <number>: open the editor at a specified line number. By default,
2294 -n <number>: open the editor at a specified line number. By default,
2297 the IPython editor hook uses the unix syntax 'editor +N filename', but
2295 the IPython editor hook uses the unix syntax 'editor +N filename', but
2298 you can configure this by providing your own modified hook if your
2296 you can configure this by providing your own modified hook if your
2299 favorite editor supports line-number specifications with a different
2297 favorite editor supports line-number specifications with a different
2300 syntax.
2298 syntax.
2301
2299
2302 -p: this will call the editor with the same data as the previous time
2300 -p: this will call the editor with the same data as the previous time
2303 it was used, regardless of how long ago (in your current session) it
2301 it was used, regardless of how long ago (in your current session) it
2304 was.
2302 was.
2305
2303
2306 -r: use 'raw' input. This option only applies to input taken from the
2304 -r: use 'raw' input. This option only applies to input taken from the
2307 user's history. By default, the 'processed' history is used, so that
2305 user's history. By default, the 'processed' history is used, so that
2308 magics are loaded in their transformed version to valid Python. If
2306 magics are loaded in their transformed version to valid Python. If
2309 this option is given, the raw input as typed as the command line is
2307 this option is given, the raw input as typed as the command line is
2310 used instead. When you exit the editor, it will be executed by
2308 used instead. When you exit the editor, it will be executed by
2311 IPython's own processor.
2309 IPython's own processor.
2312
2310
2313 -x: do not execute the edited code immediately upon exit. This is
2311 -x: do not execute the edited code immediately upon exit. This is
2314 mainly useful if you are editing programs which need to be called with
2312 mainly useful if you are editing programs which need to be called with
2315 command line arguments, which you can then do using %run.
2313 command line arguments, which you can then do using %run.
2316
2314
2317
2315
2318 Arguments:
2316 Arguments:
2319
2317
2320 If arguments are given, the following possibilites exist:
2318 If arguments are given, the following possibilites exist:
2321
2319
2322 - If the argument is a filename, IPython will load that into the
2320 - If the argument is a filename, IPython will load that into the
2323 editor. It will execute its contents with execfile() when you exit,
2321 editor. It will execute its contents with execfile() when you exit,
2324 loading any code in the file into your interactive namespace.
2322 loading any code in the file into your interactive namespace.
2325
2323
2326 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2324 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
2327 The syntax is the same as in the %history magic.
2325 The syntax is the same as in the %history magic.
2328
2326
2329 - If the argument is a string variable, its contents are loaded
2327 - If the argument is a string variable, its contents are loaded
2330 into the editor. You can thus edit any string which contains
2328 into the editor. You can thus edit any string which contains
2331 python code (including the result of previous edits).
2329 python code (including the result of previous edits).
2332
2330
2333 - If the argument is the name of an object (other than a string),
2331 - If the argument is the name of an object (other than a string),
2334 IPython will try to locate the file where it was defined and open the
2332 IPython will try to locate the file where it was defined and open the
2335 editor at the point where it is defined. You can use `%edit function`
2333 editor at the point where it is defined. You can use `%edit function`
2336 to load an editor exactly at the point where 'function' is defined,
2334 to load an editor exactly at the point where 'function' is defined,
2337 edit it and have the file be executed automatically.
2335 edit it and have the file be executed automatically.
2338
2336
2339 If the object is a macro (see %macro for details), this opens up your
2337 If the object is a macro (see %macro for details), this opens up your
2340 specified editor with a temporary file containing the macro's data.
2338 specified editor with a temporary file containing the macro's data.
2341 Upon exit, the macro is reloaded with the contents of the file.
2339 Upon exit, the macro is reloaded with the contents of the file.
2342
2340
2343 Note: opening at an exact line is only supported under Unix, and some
2341 Note: opening at an exact line is only supported under Unix, and some
2344 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2342 editors (like kedit and gedit up to Gnome 2.8) do not understand the
2345 '+NUMBER' parameter necessary for this feature. Good editors like
2343 '+NUMBER' parameter necessary for this feature. Good editors like
2346 (X)Emacs, vi, jed, pico and joe all do.
2344 (X)Emacs, vi, jed, pico and joe all do.
2347
2345
2348 After executing your code, %edit will return as output the code you
2346 After executing your code, %edit will return as output the code you
2349 typed in the editor (except when it was an existing file). This way
2347 typed in the editor (except when it was an existing file). This way
2350 you can reload the code in further invocations of %edit as a variable,
2348 you can reload the code in further invocations of %edit as a variable,
2351 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2349 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
2352 the output.
2350 the output.
2353
2351
2354 Note that %edit is also available through the alias %ed.
2352 Note that %edit is also available through the alias %ed.
2355
2353
2356 This is an example of creating a simple function inside the editor and
2354 This is an example of creating a simple function inside the editor and
2357 then modifying it. First, start up the editor:
2355 then modifying it. First, start up the editor:
2358
2356
2359 In [1]: ed
2357 In [1]: ed
2360 Editing... done. Executing edited code...
2358 Editing... done. Executing edited code...
2361 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2359 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
2362
2360
2363 We can then call the function foo():
2361 We can then call the function foo():
2364
2362
2365 In [2]: foo()
2363 In [2]: foo()
2366 foo() was defined in an editing session
2364 foo() was defined in an editing session
2367
2365
2368 Now we edit foo. IPython automatically loads the editor with the
2366 Now we edit foo. IPython automatically loads the editor with the
2369 (temporary) file where foo() was previously defined:
2367 (temporary) file where foo() was previously defined:
2370
2368
2371 In [3]: ed foo
2369 In [3]: ed foo
2372 Editing... done. Executing edited code...
2370 Editing... done. Executing edited code...
2373
2371
2374 And if we call foo() again we get the modified version:
2372 And if we call foo() again we get the modified version:
2375
2373
2376 In [4]: foo()
2374 In [4]: foo()
2377 foo() has now been changed!
2375 foo() has now been changed!
2378
2376
2379 Here is an example of how to edit a code snippet successive
2377 Here is an example of how to edit a code snippet successive
2380 times. First we call the editor:
2378 times. First we call the editor:
2381
2379
2382 In [5]: ed
2380 In [5]: ed
2383 Editing... done. Executing edited code...
2381 Editing... done. Executing edited code...
2384 hello
2382 hello
2385 Out[5]: "print 'hello'n"
2383 Out[5]: "print 'hello'n"
2386
2384
2387 Now we call it again with the previous output (stored in _):
2385 Now we call it again with the previous output (stored in _):
2388
2386
2389 In [6]: ed _
2387 In [6]: ed _
2390 Editing... done. Executing edited code...
2388 Editing... done. Executing edited code...
2391 hello world
2389 hello world
2392 Out[6]: "print 'hello world'n"
2390 Out[6]: "print 'hello world'n"
2393
2391
2394 Now we call it with the output #8 (stored in _8, also as Out[8]):
2392 Now we call it with the output #8 (stored in _8, also as Out[8]):
2395
2393
2396 In [7]: ed _8
2394 In [7]: ed _8
2397 Editing... done. Executing edited code...
2395 Editing... done. Executing edited code...
2398 hello again
2396 hello again
2399 Out[7]: "print 'hello again'n"
2397 Out[7]: "print 'hello again'n"
2400
2398
2401
2399
2402 Changing the default editor hook:
2400 Changing the default editor hook:
2403
2401
2404 If you wish to write your own editor hook, you can put it in a
2402 If you wish to write your own editor hook, you can put it in a
2405 configuration file which you load at startup time. The default hook
2403 configuration file which you load at startup time. The default hook
2406 is defined in the IPython.core.hooks module, and you can use that as a
2404 is defined in the IPython.core.hooks module, and you can use that as a
2407 starting example for further modifications. That file also has
2405 starting example for further modifications. That file also has
2408 general instructions on how to set a new hook for use once you've
2406 general instructions on how to set a new hook for use once you've
2409 defined it."""
2407 defined it."""
2410 opts,args = self.parse_options(parameter_s,'prxn:')
2408 opts,args = self.parse_options(parameter_s,'prxn:')
2411
2409
2412 try:
2410 try:
2413 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
2411 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
2414 except MacroToEdit as e:
2412 except MacroToEdit as e:
2415 self._edit_macro(args, e.args[0])
2413 self._edit_macro(args, e.args[0])
2416 return
2414 return
2417
2415
2418 # do actual editing here
2416 # do actual editing here
2419 print 'Editing...',
2417 print 'Editing...',
2420 sys.stdout.flush()
2418 sys.stdout.flush()
2421 try:
2419 try:
2422 # Quote filenames that may have spaces in them
2420 # Quote filenames that may have spaces in them
2423 if ' ' in filename:
2421 if ' ' in filename:
2424 filename = "'%s'" % filename
2422 filename = "'%s'" % filename
2425 self.shell.hooks.editor(filename,lineno)
2423 self.shell.hooks.editor(filename,lineno)
2426 except TryNext:
2424 except TryNext:
2427 warn('Could not open editor')
2425 warn('Could not open editor')
2428 return
2426 return
2429
2427
2430 # XXX TODO: should this be generalized for all string vars?
2428 # XXX TODO: should this be generalized for all string vars?
2431 # For now, this is special-cased to blocks created by cpaste
2429 # For now, this is special-cased to blocks created by cpaste
2432 if args.strip() == 'pasted_block':
2430 if args.strip() == 'pasted_block':
2433 self.shell.user_ns['pasted_block'] = file_read(filename)
2431 self.shell.user_ns['pasted_block'] = file_read(filename)
2434
2432
2435 if 'x' in opts: # -x prevents actual execution
2433 if 'x' in opts: # -x prevents actual execution
2436 print
2434 print
2437 else:
2435 else:
2438 print 'done. Executing edited code...'
2436 print 'done. Executing edited code...'
2439 if 'r' in opts: # Untranslated IPython code
2437 if 'r' in opts: # Untranslated IPython code
2440 self.shell.run_cell(file_read(filename),
2438 self.shell.run_cell(file_read(filename),
2441 store_history=False)
2439 store_history=False)
2442 else:
2440 else:
2443 self.shell.safe_execfile(filename,self.shell.user_ns,
2441 self.shell.safe_execfile(filename,self.shell.user_ns,
2444 self.shell.user_ns)
2442 self.shell.user_ns)
2445
2443
2446 if is_temp:
2444 if is_temp:
2447 try:
2445 try:
2448 return open(filename).read()
2446 return open(filename).read()
2449 except IOError,msg:
2447 except IOError,msg:
2450 if msg.filename == filename:
2448 if msg.filename == filename:
2451 warn('File not found. Did you forget to save?')
2449 warn('File not found. Did you forget to save?')
2452 return
2450 return
2453 else:
2451 else:
2454 self.shell.showtraceback()
2452 self.shell.showtraceback()
2455
2453
2456 def magic_xmode(self,parameter_s = ''):
2454 def magic_xmode(self,parameter_s = ''):
2457 """Switch modes for the exception handlers.
2455 """Switch modes for the exception handlers.
2458
2456
2459 Valid modes: Plain, Context and Verbose.
2457 Valid modes: Plain, Context and Verbose.
2460
2458
2461 If called without arguments, acts as a toggle."""
2459 If called without arguments, acts as a toggle."""
2462
2460
2463 def xmode_switch_err(name):
2461 def xmode_switch_err(name):
2464 warn('Error changing %s exception modes.\n%s' %
2462 warn('Error changing %s exception modes.\n%s' %
2465 (name,sys.exc_info()[1]))
2463 (name,sys.exc_info()[1]))
2466
2464
2467 shell = self.shell
2465 shell = self.shell
2468 new_mode = parameter_s.strip().capitalize()
2466 new_mode = parameter_s.strip().capitalize()
2469 try:
2467 try:
2470 shell.InteractiveTB.set_mode(mode=new_mode)
2468 shell.InteractiveTB.set_mode(mode=new_mode)
2471 print 'Exception reporting mode:',shell.InteractiveTB.mode
2469 print 'Exception reporting mode:',shell.InteractiveTB.mode
2472 except:
2470 except:
2473 xmode_switch_err('user')
2471 xmode_switch_err('user')
2474
2472
2475 def magic_colors(self,parameter_s = ''):
2473 def magic_colors(self,parameter_s = ''):
2476 """Switch color scheme for prompts, info system and exception handlers.
2474 """Switch color scheme for prompts, info system and exception handlers.
2477
2475
2478 Currently implemented schemes: NoColor, Linux, LightBG.
2476 Currently implemented schemes: NoColor, Linux, LightBG.
2479
2477
2480 Color scheme names are not case-sensitive.
2478 Color scheme names are not case-sensitive.
2481
2479
2482 Examples
2480 Examples
2483 --------
2481 --------
2484 To get a plain black and white terminal::
2482 To get a plain black and white terminal::
2485
2483
2486 %colors nocolor
2484 %colors nocolor
2487 """
2485 """
2488
2486
2489 def color_switch_err(name):
2487 def color_switch_err(name):
2490 warn('Error changing %s color schemes.\n%s' %
2488 warn('Error changing %s color schemes.\n%s' %
2491 (name,sys.exc_info()[1]))
2489 (name,sys.exc_info()[1]))
2492
2490
2493
2491
2494 new_scheme = parameter_s.strip()
2492 new_scheme = parameter_s.strip()
2495 if not new_scheme:
2493 if not new_scheme:
2496 raise UsageError(
2494 raise UsageError(
2497 "%colors: you must specify a color scheme. See '%colors?'")
2495 "%colors: you must specify a color scheme. See '%colors?'")
2498 return
2496 return
2499 # local shortcut
2497 # local shortcut
2500 shell = self.shell
2498 shell = self.shell
2501
2499
2502 import IPython.utils.rlineimpl as readline
2500 import IPython.utils.rlineimpl as readline
2503
2501
2504 if not readline.have_readline and sys.platform == "win32":
2502 if not readline.have_readline and sys.platform == "win32":
2505 msg = """\
2503 msg = """\
2506 Proper color support under MS Windows requires the pyreadline library.
2504 Proper color support under MS Windows requires the pyreadline library.
2507 You can find it at:
2505 You can find it at:
2508 http://ipython.scipy.org/moin/PyReadline/Intro
2506 http://ipython.scipy.org/moin/PyReadline/Intro
2509 Gary's readline needs the ctypes module, from:
2507 Gary's readline needs the ctypes module, from:
2510 http://starship.python.net/crew/theller/ctypes
2508 http://starship.python.net/crew/theller/ctypes
2511 (Note that ctypes is already part of Python versions 2.5 and newer).
2509 (Note that ctypes is already part of Python versions 2.5 and newer).
2512
2510
2513 Defaulting color scheme to 'NoColor'"""
2511 Defaulting color scheme to 'NoColor'"""
2514 new_scheme = 'NoColor'
2512 new_scheme = 'NoColor'
2515 warn(msg)
2513 warn(msg)
2516
2514
2517 # readline option is 0
2515 # readline option is 0
2518 if not shell.has_readline:
2516 if not shell.has_readline:
2519 new_scheme = 'NoColor'
2517 new_scheme = 'NoColor'
2520
2518
2521 # Set prompt colors
2519 # Set prompt colors
2522 try:
2520 try:
2523 shell.displayhook.set_colors(new_scheme)
2521 shell.displayhook.set_colors(new_scheme)
2524 except:
2522 except:
2525 color_switch_err('prompt')
2523 color_switch_err('prompt')
2526 else:
2524 else:
2527 shell.colors = \
2525 shell.colors = \
2528 shell.displayhook.color_table.active_scheme_name
2526 shell.displayhook.color_table.active_scheme_name
2529 # Set exception colors
2527 # Set exception colors
2530 try:
2528 try:
2531 shell.InteractiveTB.set_colors(scheme = new_scheme)
2529 shell.InteractiveTB.set_colors(scheme = new_scheme)
2532 shell.SyntaxTB.set_colors(scheme = new_scheme)
2530 shell.SyntaxTB.set_colors(scheme = new_scheme)
2533 except:
2531 except:
2534 color_switch_err('exception')
2532 color_switch_err('exception')
2535
2533
2536 # Set info (for 'object?') colors
2534 # Set info (for 'object?') colors
2537 if shell.color_info:
2535 if shell.color_info:
2538 try:
2536 try:
2539 shell.inspector.set_active_scheme(new_scheme)
2537 shell.inspector.set_active_scheme(new_scheme)
2540 except:
2538 except:
2541 color_switch_err('object inspector')
2539 color_switch_err('object inspector')
2542 else:
2540 else:
2543 shell.inspector.set_active_scheme('NoColor')
2541 shell.inspector.set_active_scheme('NoColor')
2544
2542
2545 def magic_pprint(self, parameter_s=''):
2543 def magic_pprint(self, parameter_s=''):
2546 """Toggle pretty printing on/off."""
2544 """Toggle pretty printing on/off."""
2547 ptformatter = self.shell.display_formatter.formatters['text/plain']
2545 ptformatter = self.shell.display_formatter.formatters['text/plain']
2548 ptformatter.pprint = bool(1 - ptformatter.pprint)
2546 ptformatter.pprint = bool(1 - ptformatter.pprint)
2549 print 'Pretty printing has been turned', \
2547 print 'Pretty printing has been turned', \
2550 ['OFF','ON'][ptformatter.pprint]
2548 ['OFF','ON'][ptformatter.pprint]
2551
2549
2552 #......................................................................
2550 #......................................................................
2553 # Functions to implement unix shell-type things
2551 # Functions to implement unix shell-type things
2554
2552
2555 @skip_doctest
2553 @skip_doctest
2556 def magic_alias(self, parameter_s = ''):
2554 def magic_alias(self, parameter_s = ''):
2557 """Define an alias for a system command.
2555 """Define an alias for a system command.
2558
2556
2559 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2557 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2560
2558
2561 Then, typing 'alias_name params' will execute the system command 'cmd
2559 Then, typing 'alias_name params' will execute the system command 'cmd
2562 params' (from your underlying operating system).
2560 params' (from your underlying operating system).
2563
2561
2564 Aliases have lower precedence than magic functions and Python normal
2562 Aliases have lower precedence than magic functions and Python normal
2565 variables, so if 'foo' is both a Python variable and an alias, the
2563 variables, so if 'foo' is both a Python variable and an alias, the
2566 alias can not be executed until 'del foo' removes the Python variable.
2564 alias can not be executed until 'del foo' removes the Python variable.
2567
2565
2568 You can use the %l specifier in an alias definition to represent the
2566 You can use the %l specifier in an alias definition to represent the
2569 whole line when the alias is called. For example:
2567 whole line when the alias is called. For example:
2570
2568
2571 In [2]: alias bracket echo "Input in brackets: <%l>"
2569 In [2]: alias bracket echo "Input in brackets: <%l>"
2572 In [3]: bracket hello world
2570 In [3]: bracket hello world
2573 Input in brackets: <hello world>
2571 Input in brackets: <hello world>
2574
2572
2575 You can also define aliases with parameters using %s specifiers (one
2573 You can also define aliases with parameters using %s specifiers (one
2576 per parameter):
2574 per parameter):
2577
2575
2578 In [1]: alias parts echo first %s second %s
2576 In [1]: alias parts echo first %s second %s
2579 In [2]: %parts A B
2577 In [2]: %parts A B
2580 first A second B
2578 first A second B
2581 In [3]: %parts A
2579 In [3]: %parts A
2582 Incorrect number of arguments: 2 expected.
2580 Incorrect number of arguments: 2 expected.
2583 parts is an alias to: 'echo first %s second %s'
2581 parts is an alias to: 'echo first %s second %s'
2584
2582
2585 Note that %l and %s are mutually exclusive. You can only use one or
2583 Note that %l and %s are mutually exclusive. You can only use one or
2586 the other in your aliases.
2584 the other in your aliases.
2587
2585
2588 Aliases expand Python variables just like system calls using ! or !!
2586 Aliases expand Python variables just like system calls using ! or !!
2589 do: all expressions prefixed with '$' get expanded. For details of
2587 do: all expressions prefixed with '$' get expanded. For details of
2590 the semantic rules, see PEP-215:
2588 the semantic rules, see PEP-215:
2591 http://www.python.org/peps/pep-0215.html. This is the library used by
2589 http://www.python.org/peps/pep-0215.html. This is the library used by
2592 IPython for variable expansion. If you want to access a true shell
2590 IPython for variable expansion. If you want to access a true shell
2593 variable, an extra $ is necessary to prevent its expansion by IPython:
2591 variable, an extra $ is necessary to prevent its expansion by IPython:
2594
2592
2595 In [6]: alias show echo
2593 In [6]: alias show echo
2596 In [7]: PATH='A Python string'
2594 In [7]: PATH='A Python string'
2597 In [8]: show $PATH
2595 In [8]: show $PATH
2598 A Python string
2596 A Python string
2599 In [9]: show $$PATH
2597 In [9]: show $$PATH
2600 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2598 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2601
2599
2602 You can use the alias facility to acess all of $PATH. See the %rehash
2600 You can use the alias facility to acess all of $PATH. See the %rehash
2603 and %rehashx functions, which automatically create aliases for the
2601 and %rehashx functions, which automatically create aliases for the
2604 contents of your $PATH.
2602 contents of your $PATH.
2605
2603
2606 If called with no parameters, %alias prints the current alias table."""
2604 If called with no parameters, %alias prints the current alias table."""
2607
2605
2608 par = parameter_s.strip()
2606 par = parameter_s.strip()
2609 if not par:
2607 if not par:
2610 stored = self.db.get('stored_aliases', {} )
2608 stored = self.db.get('stored_aliases', {} )
2611 aliases = sorted(self.shell.alias_manager.aliases)
2609 aliases = sorted(self.shell.alias_manager.aliases)
2612 # for k, v in stored:
2610 # for k, v in stored:
2613 # atab.append(k, v[0])
2611 # atab.append(k, v[0])
2614
2612
2615 print "Total number of aliases:", len(aliases)
2613 print "Total number of aliases:", len(aliases)
2616 sys.stdout.flush()
2614 sys.stdout.flush()
2617 return aliases
2615 return aliases
2618
2616
2619 # Now try to define a new one
2617 # Now try to define a new one
2620 try:
2618 try:
2621 alias,cmd = par.split(None, 1)
2619 alias,cmd = par.split(None, 1)
2622 except:
2620 except:
2623 print oinspect.getdoc(self.magic_alias)
2621 print oinspect.getdoc(self.magic_alias)
2624 else:
2622 else:
2625 self.shell.alias_manager.soft_define_alias(alias, cmd)
2623 self.shell.alias_manager.soft_define_alias(alias, cmd)
2626 # end magic_alias
2624 # end magic_alias
2627
2625
2628 def magic_unalias(self, parameter_s = ''):
2626 def magic_unalias(self, parameter_s = ''):
2629 """Remove an alias"""
2627 """Remove an alias"""
2630
2628
2631 aname = parameter_s.strip()
2629 aname = parameter_s.strip()
2632 self.shell.alias_manager.undefine_alias(aname)
2630 self.shell.alias_manager.undefine_alias(aname)
2633 stored = self.db.get('stored_aliases', {} )
2631 stored = self.db.get('stored_aliases', {} )
2634 if aname in stored:
2632 if aname in stored:
2635 print "Removing %stored alias",aname
2633 print "Removing %stored alias",aname
2636 del stored[aname]
2634 del stored[aname]
2637 self.db['stored_aliases'] = stored
2635 self.db['stored_aliases'] = stored
2638
2636
2639 def magic_rehashx(self, parameter_s = ''):
2637 def magic_rehashx(self, parameter_s = ''):
2640 """Update the alias table with all executable files in $PATH.
2638 """Update the alias table with all executable files in $PATH.
2641
2639
2642 This version explicitly checks that every entry in $PATH is a file
2640 This version explicitly checks that every entry in $PATH is a file
2643 with execute access (os.X_OK), so it is much slower than %rehash.
2641 with execute access (os.X_OK), so it is much slower than %rehash.
2644
2642
2645 Under Windows, it checks executability as a match agains a
2643 Under Windows, it checks executability as a match agains a
2646 '|'-separated string of extensions, stored in the IPython config
2644 '|'-separated string of extensions, stored in the IPython config
2647 variable win_exec_ext. This defaults to 'exe|com|bat'.
2645 variable win_exec_ext. This defaults to 'exe|com|bat'.
2648
2646
2649 This function also resets the root module cache of module completer,
2647 This function also resets the root module cache of module completer,
2650 used on slow filesystems.
2648 used on slow filesystems.
2651 """
2649 """
2652 from IPython.core.alias import InvalidAliasError
2650 from IPython.core.alias import InvalidAliasError
2653
2651
2654 # for the benefit of module completer in ipy_completers.py
2652 # for the benefit of module completer in ipy_completers.py
2655 del self.db['rootmodules']
2653 del self.db['rootmodules']
2656
2654
2657 path = [os.path.abspath(os.path.expanduser(p)) for p in
2655 path = [os.path.abspath(os.path.expanduser(p)) for p in
2658 os.environ.get('PATH','').split(os.pathsep)]
2656 os.environ.get('PATH','').split(os.pathsep)]
2659 path = filter(os.path.isdir,path)
2657 path = filter(os.path.isdir,path)
2660
2658
2661 syscmdlist = []
2659 syscmdlist = []
2662 # Now define isexec in a cross platform manner.
2660 # Now define isexec in a cross platform manner.
2663 if os.name == 'posix':
2661 if os.name == 'posix':
2664 isexec = lambda fname:os.path.isfile(fname) and \
2662 isexec = lambda fname:os.path.isfile(fname) and \
2665 os.access(fname,os.X_OK)
2663 os.access(fname,os.X_OK)
2666 else:
2664 else:
2667 try:
2665 try:
2668 winext = os.environ['pathext'].replace(';','|').replace('.','')
2666 winext = os.environ['pathext'].replace(';','|').replace('.','')
2669 except KeyError:
2667 except KeyError:
2670 winext = 'exe|com|bat|py'
2668 winext = 'exe|com|bat|py'
2671 if 'py' not in winext:
2669 if 'py' not in winext:
2672 winext += '|py'
2670 winext += '|py'
2673 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2671 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2674 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2672 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2675 savedir = os.getcwd()
2673 savedir = os.getcwd()
2676
2674
2677 # Now walk the paths looking for executables to alias.
2675 # Now walk the paths looking for executables to alias.
2678 try:
2676 try:
2679 # write the whole loop for posix/Windows so we don't have an if in
2677 # write the whole loop for posix/Windows so we don't have an if in
2680 # the innermost part
2678 # the innermost part
2681 if os.name == 'posix':
2679 if os.name == 'posix':
2682 for pdir in path:
2680 for pdir in path:
2683 os.chdir(pdir)
2681 os.chdir(pdir)
2684 for ff in os.listdir(pdir):
2682 for ff in os.listdir(pdir):
2685 if isexec(ff):
2683 if isexec(ff):
2686 try:
2684 try:
2687 # Removes dots from the name since ipython
2685 # Removes dots from the name since ipython
2688 # will assume names with dots to be python.
2686 # will assume names with dots to be python.
2689 self.shell.alias_manager.define_alias(
2687 self.shell.alias_manager.define_alias(
2690 ff.replace('.',''), ff)
2688 ff.replace('.',''), ff)
2691 except InvalidAliasError:
2689 except InvalidAliasError:
2692 pass
2690 pass
2693 else:
2691 else:
2694 syscmdlist.append(ff)
2692 syscmdlist.append(ff)
2695 else:
2693 else:
2696 no_alias = self.shell.alias_manager.no_alias
2694 no_alias = self.shell.alias_manager.no_alias
2697 for pdir in path:
2695 for pdir in path:
2698 os.chdir(pdir)
2696 os.chdir(pdir)
2699 for ff in os.listdir(pdir):
2697 for ff in os.listdir(pdir):
2700 base, ext = os.path.splitext(ff)
2698 base, ext = os.path.splitext(ff)
2701 if isexec(ff) and base.lower() not in no_alias:
2699 if isexec(ff) and base.lower() not in no_alias:
2702 if ext.lower() == '.exe':
2700 if ext.lower() == '.exe':
2703 ff = base
2701 ff = base
2704 try:
2702 try:
2705 # Removes dots from the name since ipython
2703 # Removes dots from the name since ipython
2706 # will assume names with dots to be python.
2704 # will assume names with dots to be python.
2707 self.shell.alias_manager.define_alias(
2705 self.shell.alias_manager.define_alias(
2708 base.lower().replace('.',''), ff)
2706 base.lower().replace('.',''), ff)
2709 except InvalidAliasError:
2707 except InvalidAliasError:
2710 pass
2708 pass
2711 syscmdlist.append(ff)
2709 syscmdlist.append(ff)
2712 db = self.db
2710 db = self.db
2713 db['syscmdlist'] = syscmdlist
2711 db['syscmdlist'] = syscmdlist
2714 finally:
2712 finally:
2715 os.chdir(savedir)
2713 os.chdir(savedir)
2716
2714
2717 @skip_doctest
2715 @skip_doctest
2718 def magic_pwd(self, parameter_s = ''):
2716 def magic_pwd(self, parameter_s = ''):
2719 """Return the current working directory path.
2717 """Return the current working directory path.
2720
2718
2721 Examples
2719 Examples
2722 --------
2720 --------
2723 ::
2721 ::
2724
2722
2725 In [9]: pwd
2723 In [9]: pwd
2726 Out[9]: '/home/tsuser/sprint/ipython'
2724 Out[9]: '/home/tsuser/sprint/ipython'
2727 """
2725 """
2728 return os.getcwd()
2726 return os.getcwd()
2729
2727
2730 @skip_doctest
2728 @skip_doctest
2731 def magic_cd(self, parameter_s=''):
2729 def magic_cd(self, parameter_s=''):
2732 """Change the current working directory.
2730 """Change the current working directory.
2733
2731
2734 This command automatically maintains an internal list of directories
2732 This command automatically maintains an internal list of directories
2735 you visit during your IPython session, in the variable _dh. The
2733 you visit during your IPython session, in the variable _dh. The
2736 command %dhist shows this history nicely formatted. You can also
2734 command %dhist shows this history nicely formatted. You can also
2737 do 'cd -<tab>' to see directory history conveniently.
2735 do 'cd -<tab>' to see directory history conveniently.
2738
2736
2739 Usage:
2737 Usage:
2740
2738
2741 cd 'dir': changes to directory 'dir'.
2739 cd 'dir': changes to directory 'dir'.
2742
2740
2743 cd -: changes to the last visited directory.
2741 cd -: changes to the last visited directory.
2744
2742
2745 cd -<n>: changes to the n-th directory in the directory history.
2743 cd -<n>: changes to the n-th directory in the directory history.
2746
2744
2747 cd --foo: change to directory that matches 'foo' in history
2745 cd --foo: change to directory that matches 'foo' in history
2748
2746
2749 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2747 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2750 (note: cd <bookmark_name> is enough if there is no
2748 (note: cd <bookmark_name> is enough if there is no
2751 directory <bookmark_name>, but a bookmark with the name exists.)
2749 directory <bookmark_name>, but a bookmark with the name exists.)
2752 'cd -b <tab>' allows you to tab-complete bookmark names.
2750 'cd -b <tab>' allows you to tab-complete bookmark names.
2753
2751
2754 Options:
2752 Options:
2755
2753
2756 -q: quiet. Do not print the working directory after the cd command is
2754 -q: quiet. Do not print the working directory after the cd command is
2757 executed. By default IPython's cd command does print this directory,
2755 executed. By default IPython's cd command does print this directory,
2758 since the default prompts do not display path information.
2756 since the default prompts do not display path information.
2759
2757
2760 Note that !cd doesn't work for this purpose because the shell where
2758 Note that !cd doesn't work for this purpose because the shell where
2761 !command runs is immediately discarded after executing 'command'.
2759 !command runs is immediately discarded after executing 'command'.
2762
2760
2763 Examples
2761 Examples
2764 --------
2762 --------
2765 ::
2763 ::
2766
2764
2767 In [10]: cd parent/child
2765 In [10]: cd parent/child
2768 /home/tsuser/parent/child
2766 /home/tsuser/parent/child
2769 """
2767 """
2770
2768
2771 parameter_s = parameter_s.strip()
2769 parameter_s = parameter_s.strip()
2772 #bkms = self.shell.persist.get("bookmarks",{})
2770 #bkms = self.shell.persist.get("bookmarks",{})
2773
2771
2774 oldcwd = os.getcwd()
2772 oldcwd = os.getcwd()
2775 numcd = re.match(r'(-)(\d+)$',parameter_s)
2773 numcd = re.match(r'(-)(\d+)$',parameter_s)
2776 # jump in directory history by number
2774 # jump in directory history by number
2777 if numcd:
2775 if numcd:
2778 nn = int(numcd.group(2))
2776 nn = int(numcd.group(2))
2779 try:
2777 try:
2780 ps = self.shell.user_ns['_dh'][nn]
2778 ps = self.shell.user_ns['_dh'][nn]
2781 except IndexError:
2779 except IndexError:
2782 print 'The requested directory does not exist in history.'
2780 print 'The requested directory does not exist in history.'
2783 return
2781 return
2784 else:
2782 else:
2785 opts = {}
2783 opts = {}
2786 elif parameter_s.startswith('--'):
2784 elif parameter_s.startswith('--'):
2787 ps = None
2785 ps = None
2788 fallback = None
2786 fallback = None
2789 pat = parameter_s[2:]
2787 pat = parameter_s[2:]
2790 dh = self.shell.user_ns['_dh']
2788 dh = self.shell.user_ns['_dh']
2791 # first search only by basename (last component)
2789 # first search only by basename (last component)
2792 for ent in reversed(dh):
2790 for ent in reversed(dh):
2793 if pat in os.path.basename(ent) and os.path.isdir(ent):
2791 if pat in os.path.basename(ent) and os.path.isdir(ent):
2794 ps = ent
2792 ps = ent
2795 break
2793 break
2796
2794
2797 if fallback is None and pat in ent and os.path.isdir(ent):
2795 if fallback is None and pat in ent and os.path.isdir(ent):
2798 fallback = ent
2796 fallback = ent
2799
2797
2800 # if we have no last part match, pick the first full path match
2798 # if we have no last part match, pick the first full path match
2801 if ps is None:
2799 if ps is None:
2802 ps = fallback
2800 ps = fallback
2803
2801
2804 if ps is None:
2802 if ps is None:
2805 print "No matching entry in directory history"
2803 print "No matching entry in directory history"
2806 return
2804 return
2807 else:
2805 else:
2808 opts = {}
2806 opts = {}
2809
2807
2810
2808
2811 else:
2809 else:
2812 #turn all non-space-escaping backslashes to slashes,
2810 #turn all non-space-escaping backslashes to slashes,
2813 # for c:\windows\directory\names\
2811 # for c:\windows\directory\names\
2814 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2812 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2815 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2813 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2816 # jump to previous
2814 # jump to previous
2817 if ps == '-':
2815 if ps == '-':
2818 try:
2816 try:
2819 ps = self.shell.user_ns['_dh'][-2]
2817 ps = self.shell.user_ns['_dh'][-2]
2820 except IndexError:
2818 except IndexError:
2821 raise UsageError('%cd -: No previous directory to change to.')
2819 raise UsageError('%cd -: No previous directory to change to.')
2822 # jump to bookmark if needed
2820 # jump to bookmark if needed
2823 else:
2821 else:
2824 if not os.path.isdir(ps) or opts.has_key('b'):
2822 if not os.path.isdir(ps) or opts.has_key('b'):
2825 bkms = self.db.get('bookmarks', {})
2823 bkms = self.db.get('bookmarks', {})
2826
2824
2827 if bkms.has_key(ps):
2825 if bkms.has_key(ps):
2828 target = bkms[ps]
2826 target = bkms[ps]
2829 print '(bookmark:%s) -> %s' % (ps,target)
2827 print '(bookmark:%s) -> %s' % (ps,target)
2830 ps = target
2828 ps = target
2831 else:
2829 else:
2832 if opts.has_key('b'):
2830 if opts.has_key('b'):
2833 raise UsageError("Bookmark '%s' not found. "
2831 raise UsageError("Bookmark '%s' not found. "
2834 "Use '%%bookmark -l' to see your bookmarks." % ps)
2832 "Use '%%bookmark -l' to see your bookmarks." % ps)
2835
2833
2836 # at this point ps should point to the target dir
2834 # at this point ps should point to the target dir
2837 if ps:
2835 if ps:
2838 try:
2836 try:
2839 os.chdir(os.path.expanduser(ps))
2837 os.chdir(os.path.expanduser(ps))
2840 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2838 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2841 set_term_title('IPython: ' + abbrev_cwd())
2839 set_term_title('IPython: ' + abbrev_cwd())
2842 except OSError:
2840 except OSError:
2843 print sys.exc_info()[1]
2841 print sys.exc_info()[1]
2844 else:
2842 else:
2845 cwd = os.getcwd()
2843 cwd = os.getcwd()
2846 dhist = self.shell.user_ns['_dh']
2844 dhist = self.shell.user_ns['_dh']
2847 if oldcwd != cwd:
2845 if oldcwd != cwd:
2848 dhist.append(cwd)
2846 dhist.append(cwd)
2849 self.db['dhist'] = compress_dhist(dhist)[-100:]
2847 self.db['dhist'] = compress_dhist(dhist)[-100:]
2850
2848
2851 else:
2849 else:
2852 os.chdir(self.shell.home_dir)
2850 os.chdir(self.shell.home_dir)
2853 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2851 if hasattr(self.shell, 'term_title') and self.shell.term_title:
2854 set_term_title('IPython: ' + '~')
2852 set_term_title('IPython: ' + '~')
2855 cwd = os.getcwd()
2853 cwd = os.getcwd()
2856 dhist = self.shell.user_ns['_dh']
2854 dhist = self.shell.user_ns['_dh']
2857
2855
2858 if oldcwd != cwd:
2856 if oldcwd != cwd:
2859 dhist.append(cwd)
2857 dhist.append(cwd)
2860 self.db['dhist'] = compress_dhist(dhist)[-100:]
2858 self.db['dhist'] = compress_dhist(dhist)[-100:]
2861 if not 'q' in opts and self.shell.user_ns['_dh']:
2859 if not 'q' in opts and self.shell.user_ns['_dh']:
2862 print self.shell.user_ns['_dh'][-1]
2860 print self.shell.user_ns['_dh'][-1]
2863
2861
2864
2862
2865 def magic_env(self, parameter_s=''):
2863 def magic_env(self, parameter_s=''):
2866 """List environment variables."""
2864 """List environment variables."""
2867
2865
2868 return os.environ.data
2866 return os.environ.data
2869
2867
2870 def magic_pushd(self, parameter_s=''):
2868 def magic_pushd(self, parameter_s=''):
2871 """Place the current dir on stack and change directory.
2869 """Place the current dir on stack and change directory.
2872
2870
2873 Usage:\\
2871 Usage:\\
2874 %pushd ['dirname']
2872 %pushd ['dirname']
2875 """
2873 """
2876
2874
2877 dir_s = self.shell.dir_stack
2875 dir_s = self.shell.dir_stack
2878 tgt = os.path.expanduser(parameter_s)
2876 tgt = os.path.expanduser(parameter_s)
2879 cwd = os.getcwd().replace(self.home_dir,'~')
2877 cwd = os.getcwd().replace(self.home_dir,'~')
2880 if tgt:
2878 if tgt:
2881 self.magic_cd(parameter_s)
2879 self.magic_cd(parameter_s)
2882 dir_s.insert(0,cwd)
2880 dir_s.insert(0,cwd)
2883 return self.magic_dirs()
2881 return self.magic_dirs()
2884
2882
2885 def magic_popd(self, parameter_s=''):
2883 def magic_popd(self, parameter_s=''):
2886 """Change to directory popped off the top of the stack.
2884 """Change to directory popped off the top of the stack.
2887 """
2885 """
2888 if not self.shell.dir_stack:
2886 if not self.shell.dir_stack:
2889 raise UsageError("%popd on empty stack")
2887 raise UsageError("%popd on empty stack")
2890 top = self.shell.dir_stack.pop(0)
2888 top = self.shell.dir_stack.pop(0)
2891 self.magic_cd(top)
2889 self.magic_cd(top)
2892 print "popd ->",top
2890 print "popd ->",top
2893
2891
2894 def magic_dirs(self, parameter_s=''):
2892 def magic_dirs(self, parameter_s=''):
2895 """Return the current directory stack."""
2893 """Return the current directory stack."""
2896
2894
2897 return self.shell.dir_stack
2895 return self.shell.dir_stack
2898
2896
2899 def magic_dhist(self, parameter_s=''):
2897 def magic_dhist(self, parameter_s=''):
2900 """Print your history of visited directories.
2898 """Print your history of visited directories.
2901
2899
2902 %dhist -> print full history\\
2900 %dhist -> print full history\\
2903 %dhist n -> print last n entries only\\
2901 %dhist n -> print last n entries only\\
2904 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2902 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2905
2903
2906 This history is automatically maintained by the %cd command, and
2904 This history is automatically maintained by the %cd command, and
2907 always available as the global list variable _dh. You can use %cd -<n>
2905 always available as the global list variable _dh. You can use %cd -<n>
2908 to go to directory number <n>.
2906 to go to directory number <n>.
2909
2907
2910 Note that most of time, you should view directory history by entering
2908 Note that most of time, you should view directory history by entering
2911 cd -<TAB>.
2909 cd -<TAB>.
2912
2910
2913 """
2911 """
2914
2912
2915 dh = self.shell.user_ns['_dh']
2913 dh = self.shell.user_ns['_dh']
2916 if parameter_s:
2914 if parameter_s:
2917 try:
2915 try:
2918 args = map(int,parameter_s.split())
2916 args = map(int,parameter_s.split())
2919 except:
2917 except:
2920 self.arg_err(Magic.magic_dhist)
2918 self.arg_err(Magic.magic_dhist)
2921 return
2919 return
2922 if len(args) == 1:
2920 if len(args) == 1:
2923 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2921 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2924 elif len(args) == 2:
2922 elif len(args) == 2:
2925 ini,fin = args
2923 ini,fin = args
2926 else:
2924 else:
2927 self.arg_err(Magic.magic_dhist)
2925 self.arg_err(Magic.magic_dhist)
2928 return
2926 return
2929 else:
2927 else:
2930 ini,fin = 0,len(dh)
2928 ini,fin = 0,len(dh)
2931 nlprint(dh,
2929 nlprint(dh,
2932 header = 'Directory history (kept in _dh)',
2930 header = 'Directory history (kept in _dh)',
2933 start=ini,stop=fin)
2931 start=ini,stop=fin)
2934
2932
2935 @skip_doctest
2933 @skip_doctest
2936 def magic_sc(self, parameter_s=''):
2934 def magic_sc(self, parameter_s=''):
2937 """Shell capture - execute a shell command and capture its output.
2935 """Shell capture - execute a shell command and capture its output.
2938
2936
2939 DEPRECATED. Suboptimal, retained for backwards compatibility.
2937 DEPRECATED. Suboptimal, retained for backwards compatibility.
2940
2938
2941 You should use the form 'var = !command' instead. Example:
2939 You should use the form 'var = !command' instead. Example:
2942
2940
2943 "%sc -l myfiles = ls ~" should now be written as
2941 "%sc -l myfiles = ls ~" should now be written as
2944
2942
2945 "myfiles = !ls ~"
2943 "myfiles = !ls ~"
2946
2944
2947 myfiles.s, myfiles.l and myfiles.n still apply as documented
2945 myfiles.s, myfiles.l and myfiles.n still apply as documented
2948 below.
2946 below.
2949
2947
2950 --
2948 --
2951 %sc [options] varname=command
2949 %sc [options] varname=command
2952
2950
2953 IPython will run the given command using commands.getoutput(), and
2951 IPython will run the given command using commands.getoutput(), and
2954 will then update the user's interactive namespace with a variable
2952 will then update the user's interactive namespace with a variable
2955 called varname, containing the value of the call. Your command can
2953 called varname, containing the value of the call. Your command can
2956 contain shell wildcards, pipes, etc.
2954 contain shell wildcards, pipes, etc.
2957
2955
2958 The '=' sign in the syntax is mandatory, and the variable name you
2956 The '=' sign in the syntax is mandatory, and the variable name you
2959 supply must follow Python's standard conventions for valid names.
2957 supply must follow Python's standard conventions for valid names.
2960
2958
2961 (A special format without variable name exists for internal use)
2959 (A special format without variable name exists for internal use)
2962
2960
2963 Options:
2961 Options:
2964
2962
2965 -l: list output. Split the output on newlines into a list before
2963 -l: list output. Split the output on newlines into a list before
2966 assigning it to the given variable. By default the output is stored
2964 assigning it to the given variable. By default the output is stored
2967 as a single string.
2965 as a single string.
2968
2966
2969 -v: verbose. Print the contents of the variable.
2967 -v: verbose. Print the contents of the variable.
2970
2968
2971 In most cases you should not need to split as a list, because the
2969 In most cases you should not need to split as a list, because the
2972 returned value is a special type of string which can automatically
2970 returned value is a special type of string which can automatically
2973 provide its contents either as a list (split on newlines) or as a
2971 provide its contents either as a list (split on newlines) or as a
2974 space-separated string. These are convenient, respectively, either
2972 space-separated string. These are convenient, respectively, either
2975 for sequential processing or to be passed to a shell command.
2973 for sequential processing or to be passed to a shell command.
2976
2974
2977 For example:
2975 For example:
2978
2976
2979 # all-random
2977 # all-random
2980
2978
2981 # Capture into variable a
2979 # Capture into variable a
2982 In [1]: sc a=ls *py
2980 In [1]: sc a=ls *py
2983
2981
2984 # a is a string with embedded newlines
2982 # a is a string with embedded newlines
2985 In [2]: a
2983 In [2]: a
2986 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2984 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
2987
2985
2988 # which can be seen as a list:
2986 # which can be seen as a list:
2989 In [3]: a.l
2987 In [3]: a.l
2990 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2988 Out[3]: ['setup.py', 'win32_manual_post_install.py']
2991
2989
2992 # or as a whitespace-separated string:
2990 # or as a whitespace-separated string:
2993 In [4]: a.s
2991 In [4]: a.s
2994 Out[4]: 'setup.py win32_manual_post_install.py'
2992 Out[4]: 'setup.py win32_manual_post_install.py'
2995
2993
2996 # a.s is useful to pass as a single command line:
2994 # a.s is useful to pass as a single command line:
2997 In [5]: !wc -l $a.s
2995 In [5]: !wc -l $a.s
2998 146 setup.py
2996 146 setup.py
2999 130 win32_manual_post_install.py
2997 130 win32_manual_post_install.py
3000 276 total
2998 276 total
3001
2999
3002 # while the list form is useful to loop over:
3000 # while the list form is useful to loop over:
3003 In [6]: for f in a.l:
3001 In [6]: for f in a.l:
3004 ...: !wc -l $f
3002 ...: !wc -l $f
3005 ...:
3003 ...:
3006 146 setup.py
3004 146 setup.py
3007 130 win32_manual_post_install.py
3005 130 win32_manual_post_install.py
3008
3006
3009 Similiarly, the lists returned by the -l option are also special, in
3007 Similiarly, the lists returned by the -l option are also special, in
3010 the sense that you can equally invoke the .s attribute on them to
3008 the sense that you can equally invoke the .s attribute on them to
3011 automatically get a whitespace-separated string from their contents:
3009 automatically get a whitespace-separated string from their contents:
3012
3010
3013 In [7]: sc -l b=ls *py
3011 In [7]: sc -l b=ls *py
3014
3012
3015 In [8]: b
3013 In [8]: b
3016 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3014 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3017
3015
3018 In [9]: b.s
3016 In [9]: b.s
3019 Out[9]: 'setup.py win32_manual_post_install.py'
3017 Out[9]: 'setup.py win32_manual_post_install.py'
3020
3018
3021 In summary, both the lists and strings used for ouptut capture have
3019 In summary, both the lists and strings used for ouptut capture have
3022 the following special attributes:
3020 the following special attributes:
3023
3021
3024 .l (or .list) : value as list.
3022 .l (or .list) : value as list.
3025 .n (or .nlstr): value as newline-separated string.
3023 .n (or .nlstr): value as newline-separated string.
3026 .s (or .spstr): value as space-separated string.
3024 .s (or .spstr): value as space-separated string.
3027 """
3025 """
3028
3026
3029 opts,args = self.parse_options(parameter_s,'lv')
3027 opts,args = self.parse_options(parameter_s,'lv')
3030 # Try to get a variable name and command to run
3028 # Try to get a variable name and command to run
3031 try:
3029 try:
3032 # the variable name must be obtained from the parse_options
3030 # the variable name must be obtained from the parse_options
3033 # output, which uses shlex.split to strip options out.
3031 # output, which uses shlex.split to strip options out.
3034 var,_ = args.split('=',1)
3032 var,_ = args.split('=',1)
3035 var = var.strip()
3033 var = var.strip()
3036 # But the the command has to be extracted from the original input
3034 # But the the command has to be extracted from the original input
3037 # parameter_s, not on what parse_options returns, to avoid the
3035 # parameter_s, not on what parse_options returns, to avoid the
3038 # quote stripping which shlex.split performs on it.
3036 # quote stripping which shlex.split performs on it.
3039 _,cmd = parameter_s.split('=',1)
3037 _,cmd = parameter_s.split('=',1)
3040 except ValueError:
3038 except ValueError:
3041 var,cmd = '',''
3039 var,cmd = '',''
3042 # If all looks ok, proceed
3040 # If all looks ok, proceed
3043 split = 'l' in opts
3041 split = 'l' in opts
3044 out = self.shell.getoutput(cmd, split=split)
3042 out = self.shell.getoutput(cmd, split=split)
3045 if opts.has_key('v'):
3043 if opts.has_key('v'):
3046 print '%s ==\n%s' % (var,pformat(out))
3044 print '%s ==\n%s' % (var,pformat(out))
3047 if var:
3045 if var:
3048 self.shell.user_ns.update({var:out})
3046 self.shell.user_ns.update({var:out})
3049 else:
3047 else:
3050 return out
3048 return out
3051
3049
3052 def magic_sx(self, parameter_s=''):
3050 def magic_sx(self, parameter_s=''):
3053 """Shell execute - run a shell command and capture its output.
3051 """Shell execute - run a shell command and capture its output.
3054
3052
3055 %sx command
3053 %sx command
3056
3054
3057 IPython will run the given command using commands.getoutput(), and
3055 IPython will run the given command using commands.getoutput(), and
3058 return the result formatted as a list (split on '\\n'). Since the
3056 return the result formatted as a list (split on '\\n'). Since the
3059 output is _returned_, it will be stored in ipython's regular output
3057 output is _returned_, it will be stored in ipython's regular output
3060 cache Out[N] and in the '_N' automatic variables.
3058 cache Out[N] and in the '_N' automatic variables.
3061
3059
3062 Notes:
3060 Notes:
3063
3061
3064 1) If an input line begins with '!!', then %sx is automatically
3062 1) If an input line begins with '!!', then %sx is automatically
3065 invoked. That is, while:
3063 invoked. That is, while:
3066 !ls
3064 !ls
3067 causes ipython to simply issue system('ls'), typing
3065 causes ipython to simply issue system('ls'), typing
3068 !!ls
3066 !!ls
3069 is a shorthand equivalent to:
3067 is a shorthand equivalent to:
3070 %sx ls
3068 %sx ls
3071
3069
3072 2) %sx differs from %sc in that %sx automatically splits into a list,
3070 2) %sx differs from %sc in that %sx automatically splits into a list,
3073 like '%sc -l'. The reason for this is to make it as easy as possible
3071 like '%sc -l'. The reason for this is to make it as easy as possible
3074 to process line-oriented shell output via further python commands.
3072 to process line-oriented shell output via further python commands.
3075 %sc is meant to provide much finer control, but requires more
3073 %sc is meant to provide much finer control, but requires more
3076 typing.
3074 typing.
3077
3075
3078 3) Just like %sc -l, this is a list with special attributes:
3076 3) Just like %sc -l, this is a list with special attributes:
3079
3077
3080 .l (or .list) : value as list.
3078 .l (or .list) : value as list.
3081 .n (or .nlstr): value as newline-separated string.
3079 .n (or .nlstr): value as newline-separated string.
3082 .s (or .spstr): value as whitespace-separated string.
3080 .s (or .spstr): value as whitespace-separated string.
3083
3081
3084 This is very useful when trying to use such lists as arguments to
3082 This is very useful when trying to use such lists as arguments to
3085 system commands."""
3083 system commands."""
3086
3084
3087 if parameter_s:
3085 if parameter_s:
3088 return self.shell.getoutput(parameter_s)
3086 return self.shell.getoutput(parameter_s)
3089
3087
3090
3088
3091 def magic_bookmark(self, parameter_s=''):
3089 def magic_bookmark(self, parameter_s=''):
3092 """Manage IPython's bookmark system.
3090 """Manage IPython's bookmark system.
3093
3091
3094 %bookmark <name> - set bookmark to current dir
3092 %bookmark <name> - set bookmark to current dir
3095 %bookmark <name> <dir> - set bookmark to <dir>
3093 %bookmark <name> <dir> - set bookmark to <dir>
3096 %bookmark -l - list all bookmarks
3094 %bookmark -l - list all bookmarks
3097 %bookmark -d <name> - remove bookmark
3095 %bookmark -d <name> - remove bookmark
3098 %bookmark -r - remove all bookmarks
3096 %bookmark -r - remove all bookmarks
3099
3097
3100 You can later on access a bookmarked folder with:
3098 You can later on access a bookmarked folder with:
3101 %cd -b <name>
3099 %cd -b <name>
3102 or simply '%cd <name>' if there is no directory called <name> AND
3100 or simply '%cd <name>' if there is no directory called <name> AND
3103 there is such a bookmark defined.
3101 there is such a bookmark defined.
3104
3102
3105 Your bookmarks persist through IPython sessions, but they are
3103 Your bookmarks persist through IPython sessions, but they are
3106 associated with each profile."""
3104 associated with each profile."""
3107
3105
3108 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3106 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3109 if len(args) > 2:
3107 if len(args) > 2:
3110 raise UsageError("%bookmark: too many arguments")
3108 raise UsageError("%bookmark: too many arguments")
3111
3109
3112 bkms = self.db.get('bookmarks',{})
3110 bkms = self.db.get('bookmarks',{})
3113
3111
3114 if opts.has_key('d'):
3112 if opts.has_key('d'):
3115 try:
3113 try:
3116 todel = args[0]
3114 todel = args[0]
3117 except IndexError:
3115 except IndexError:
3118 raise UsageError(
3116 raise UsageError(
3119 "%bookmark -d: must provide a bookmark to delete")
3117 "%bookmark -d: must provide a bookmark to delete")
3120 else:
3118 else:
3121 try:
3119 try:
3122 del bkms[todel]
3120 del bkms[todel]
3123 except KeyError:
3121 except KeyError:
3124 raise UsageError(
3122 raise UsageError(
3125 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3123 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3126
3124
3127 elif opts.has_key('r'):
3125 elif opts.has_key('r'):
3128 bkms = {}
3126 bkms = {}
3129 elif opts.has_key('l'):
3127 elif opts.has_key('l'):
3130 bks = bkms.keys()
3128 bks = bkms.keys()
3131 bks.sort()
3129 bks.sort()
3132 if bks:
3130 if bks:
3133 size = max(map(len,bks))
3131 size = max(map(len,bks))
3134 else:
3132 else:
3135 size = 0
3133 size = 0
3136 fmt = '%-'+str(size)+'s -> %s'
3134 fmt = '%-'+str(size)+'s -> %s'
3137 print 'Current bookmarks:'
3135 print 'Current bookmarks:'
3138 for bk in bks:
3136 for bk in bks:
3139 print fmt % (bk,bkms[bk])
3137 print fmt % (bk,bkms[bk])
3140 else:
3138 else:
3141 if not args:
3139 if not args:
3142 raise UsageError("%bookmark: You must specify the bookmark name")
3140 raise UsageError("%bookmark: You must specify the bookmark name")
3143 elif len(args)==1:
3141 elif len(args)==1:
3144 bkms[args[0]] = os.getcwd()
3142 bkms[args[0]] = os.getcwd()
3145 elif len(args)==2:
3143 elif len(args)==2:
3146 bkms[args[0]] = args[1]
3144 bkms[args[0]] = args[1]
3147 self.db['bookmarks'] = bkms
3145 self.db['bookmarks'] = bkms
3148
3146
3149 def magic_pycat(self, parameter_s=''):
3147 def magic_pycat(self, parameter_s=''):
3150 """Show a syntax-highlighted file through a pager.
3148 """Show a syntax-highlighted file through a pager.
3151
3149
3152 This magic is similar to the cat utility, but it will assume the file
3150 This magic is similar to the cat utility, but it will assume the file
3153 to be Python source and will show it with syntax highlighting. """
3151 to be Python source and will show it with syntax highlighting. """
3154
3152
3155 try:
3153 try:
3156 filename = get_py_filename(parameter_s)
3154 filename = get_py_filename(parameter_s)
3157 cont = file_read(filename)
3155 cont = file_read(filename)
3158 except IOError:
3156 except IOError:
3159 try:
3157 try:
3160 cont = eval(parameter_s,self.user_ns)
3158 cont = eval(parameter_s,self.user_ns)
3161 except NameError:
3159 except NameError:
3162 cont = None
3160 cont = None
3163 if cont is None:
3161 if cont is None:
3164 print "Error: no such file or variable"
3162 print "Error: no such file or variable"
3165 return
3163 return
3166
3164
3167 page.page(self.shell.pycolorize(cont))
3165 page.page(self.shell.pycolorize(cont))
3168
3166
3169 def _rerun_pasted(self):
3167 def _rerun_pasted(self):
3170 """ Rerun a previously pasted command.
3168 """ Rerun a previously pasted command.
3171 """
3169 """
3172 b = self.user_ns.get('pasted_block', None)
3170 b = self.user_ns.get('pasted_block', None)
3173 if b is None:
3171 if b is None:
3174 raise UsageError('No previous pasted block available')
3172 raise UsageError('No previous pasted block available')
3175 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3173 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
3176 exec b in self.user_ns
3174 exec b in self.user_ns
3177
3175
3178 def _get_pasted_lines(self, sentinel):
3176 def _get_pasted_lines(self, sentinel):
3179 """ Yield pasted lines until the user enters the given sentinel value.
3177 """ Yield pasted lines until the user enters the given sentinel value.
3180 """
3178 """
3181 from IPython.core import interactiveshell
3179 from IPython.core import interactiveshell
3182 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3180 print "Pasting code; enter '%s' alone on the line to stop." % sentinel
3183 while True:
3181 while True:
3184 l = interactiveshell.raw_input_original(':')
3182 l = interactiveshell.raw_input_original(':')
3185 if l == sentinel:
3183 if l == sentinel:
3186 return
3184 return
3187 else:
3185 else:
3188 yield l
3186 yield l
3189
3187
3190 def _strip_pasted_lines_for_code(self, raw_lines):
3188 def _strip_pasted_lines_for_code(self, raw_lines):
3191 """ Strip non-code parts of a sequence of lines to return a block of
3189 """ Strip non-code parts of a sequence of lines to return a block of
3192 code.
3190 code.
3193 """
3191 """
3194 # Regular expressions that declare text we strip from the input:
3192 # Regular expressions that declare text we strip from the input:
3195 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3193 strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt
3196 r'^\s*(\s?>)+', # Python input prompt
3194 r'^\s*(\s?>)+', # Python input prompt
3197 r'^\s*\.{3,}', # Continuation prompts
3195 r'^\s*\.{3,}', # Continuation prompts
3198 r'^\++',
3196 r'^\++',
3199 ]
3197 ]
3200
3198
3201 strip_from_start = map(re.compile,strip_re)
3199 strip_from_start = map(re.compile,strip_re)
3202
3200
3203 lines = []
3201 lines = []
3204 for l in raw_lines:
3202 for l in raw_lines:
3205 for pat in strip_from_start:
3203 for pat in strip_from_start:
3206 l = pat.sub('',l)
3204 l = pat.sub('',l)
3207 lines.append(l)
3205 lines.append(l)
3208
3206
3209 block = "\n".join(lines) + '\n'
3207 block = "\n".join(lines) + '\n'
3210 #print "block:\n",block
3208 #print "block:\n",block
3211 return block
3209 return block
3212
3210
3213 def _execute_block(self, block, par):
3211 def _execute_block(self, block, par):
3214 """ Execute a block, or store it in a variable, per the user's request.
3212 """ Execute a block, or store it in a variable, per the user's request.
3215 """
3213 """
3216 if not par:
3214 if not par:
3217 b = textwrap.dedent(block)
3215 b = textwrap.dedent(block)
3218 self.user_ns['pasted_block'] = b
3216 self.user_ns['pasted_block'] = b
3219 exec b in self.user_ns
3217 exec b in self.user_ns
3220 else:
3218 else:
3221 self.user_ns[par] = SList(block.splitlines())
3219 self.user_ns[par] = SList(block.splitlines())
3222 print "Block assigned to '%s'" % par
3220 print "Block assigned to '%s'" % par
3223
3221
3224 def magic_quickref(self,arg):
3222 def magic_quickref(self,arg):
3225 """ Show a quick reference sheet """
3223 """ Show a quick reference sheet """
3226 import IPython.core.usage
3224 import IPython.core.usage
3227 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3225 qr = IPython.core.usage.quick_reference + self.magic_magic('-brief')
3228
3226
3229 page.page(qr)
3227 page.page(qr)
3230
3228
3231 def magic_doctest_mode(self,parameter_s=''):
3229 def magic_doctest_mode(self,parameter_s=''):
3232 """Toggle doctest mode on and off.
3230 """Toggle doctest mode on and off.
3233
3231
3234 This mode is intended to make IPython behave as much as possible like a
3232 This mode is intended to make IPython behave as much as possible like a
3235 plain Python shell, from the perspective of how its prompts, exceptions
3233 plain Python shell, from the perspective of how its prompts, exceptions
3236 and output look. This makes it easy to copy and paste parts of a
3234 and output look. This makes it easy to copy and paste parts of a
3237 session into doctests. It does so by:
3235 session into doctests. It does so by:
3238
3236
3239 - Changing the prompts to the classic ``>>>`` ones.
3237 - Changing the prompts to the classic ``>>>`` ones.
3240 - Changing the exception reporting mode to 'Plain'.
3238 - Changing the exception reporting mode to 'Plain'.
3241 - Disabling pretty-printing of output.
3239 - Disabling pretty-printing of output.
3242
3240
3243 Note that IPython also supports the pasting of code snippets that have
3241 Note that IPython also supports the pasting of code snippets that have
3244 leading '>>>' and '...' prompts in them. This means that you can paste
3242 leading '>>>' and '...' prompts in them. This means that you can paste
3245 doctests from files or docstrings (even if they have leading
3243 doctests from files or docstrings (even if they have leading
3246 whitespace), and the code will execute correctly. You can then use
3244 whitespace), and the code will execute correctly. You can then use
3247 '%history -t' to see the translated history; this will give you the
3245 '%history -t' to see the translated history; this will give you the
3248 input after removal of all the leading prompts and whitespace, which
3246 input after removal of all the leading prompts and whitespace, which
3249 can be pasted back into an editor.
3247 can be pasted back into an editor.
3250
3248
3251 With these features, you can switch into this mode easily whenever you
3249 With these features, you can switch into this mode easily whenever you
3252 need to do testing and changes to doctests, without having to leave
3250 need to do testing and changes to doctests, without having to leave
3253 your existing IPython session.
3251 your existing IPython session.
3254 """
3252 """
3255
3253
3256 from IPython.utils.ipstruct import Struct
3254 from IPython.utils.ipstruct import Struct
3257
3255
3258 # Shorthands
3256 # Shorthands
3259 shell = self.shell
3257 shell = self.shell
3260 oc = shell.displayhook
3258 oc = shell.displayhook
3261 meta = shell.meta
3259 meta = shell.meta
3262 disp_formatter = self.shell.display_formatter
3260 disp_formatter = self.shell.display_formatter
3263 ptformatter = disp_formatter.formatters['text/plain']
3261 ptformatter = disp_formatter.formatters['text/plain']
3264 # dstore is a data store kept in the instance metadata bag to track any
3262 # dstore is a data store kept in the instance metadata bag to track any
3265 # changes we make, so we can undo them later.
3263 # changes we make, so we can undo them later.
3266 dstore = meta.setdefault('doctest_mode',Struct())
3264 dstore = meta.setdefault('doctest_mode',Struct())
3267 save_dstore = dstore.setdefault
3265 save_dstore = dstore.setdefault
3268
3266
3269 # save a few values we'll need to recover later
3267 # save a few values we'll need to recover later
3270 mode = save_dstore('mode',False)
3268 mode = save_dstore('mode',False)
3271 save_dstore('rc_pprint',ptformatter.pprint)
3269 save_dstore('rc_pprint',ptformatter.pprint)
3272 save_dstore('xmode',shell.InteractiveTB.mode)
3270 save_dstore('xmode',shell.InteractiveTB.mode)
3273 save_dstore('rc_separate_out',shell.separate_out)
3271 save_dstore('rc_separate_out',shell.separate_out)
3274 save_dstore('rc_separate_out2',shell.separate_out2)
3272 save_dstore('rc_separate_out2',shell.separate_out2)
3275 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3273 save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
3276 save_dstore('rc_separate_in',shell.separate_in)
3274 save_dstore('rc_separate_in',shell.separate_in)
3277 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3275 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
3278
3276
3279 if mode == False:
3277 if mode == False:
3280 # turn on
3278 # turn on
3281 oc.prompt1.p_template = '>>> '
3279 oc.prompt1.p_template = '>>> '
3282 oc.prompt2.p_template = '... '
3280 oc.prompt2.p_template = '... '
3283 oc.prompt_out.p_template = ''
3281 oc.prompt_out.p_template = ''
3284
3282
3285 # Prompt separators like plain python
3283 # Prompt separators like plain python
3286 oc.input_sep = oc.prompt1.sep = ''
3284 oc.input_sep = oc.prompt1.sep = ''
3287 oc.output_sep = ''
3285 oc.output_sep = ''
3288 oc.output_sep2 = ''
3286 oc.output_sep2 = ''
3289
3287
3290 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3288 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3291 oc.prompt_out.pad_left = False
3289 oc.prompt_out.pad_left = False
3292
3290
3293 ptformatter.pprint = False
3291 ptformatter.pprint = False
3294 disp_formatter.plain_text_only = True
3292 disp_formatter.plain_text_only = True
3295
3293
3296 shell.magic_xmode('Plain')
3294 shell.magic_xmode('Plain')
3297 else:
3295 else:
3298 # turn off
3296 # turn off
3299 oc.prompt1.p_template = shell.prompt_in1
3297 oc.prompt1.p_template = shell.prompt_in1
3300 oc.prompt2.p_template = shell.prompt_in2
3298 oc.prompt2.p_template = shell.prompt_in2
3301 oc.prompt_out.p_template = shell.prompt_out
3299 oc.prompt_out.p_template = shell.prompt_out
3302
3300
3303 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3301 oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
3304
3302
3305 oc.output_sep = dstore.rc_separate_out
3303 oc.output_sep = dstore.rc_separate_out
3306 oc.output_sep2 = dstore.rc_separate_out2
3304 oc.output_sep2 = dstore.rc_separate_out2
3307
3305
3308 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3306 oc.prompt1.pad_left = oc.prompt2.pad_left = \
3309 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3307 oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
3310
3308
3311 ptformatter.pprint = dstore.rc_pprint
3309 ptformatter.pprint = dstore.rc_pprint
3312 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3310 disp_formatter.plain_text_only = dstore.rc_plain_text_only
3313
3311
3314 shell.magic_xmode(dstore.xmode)
3312 shell.magic_xmode(dstore.xmode)
3315
3313
3316 # Store new mode and inform
3314 # Store new mode and inform
3317 dstore.mode = bool(1-int(mode))
3315 dstore.mode = bool(1-int(mode))
3318 mode_label = ['OFF','ON'][dstore.mode]
3316 mode_label = ['OFF','ON'][dstore.mode]
3319 print 'Doctest mode is:', mode_label
3317 print 'Doctest mode is:', mode_label
3320
3318
3321 def magic_gui(self, parameter_s=''):
3319 def magic_gui(self, parameter_s=''):
3322 """Enable or disable IPython GUI event loop integration.
3320 """Enable or disable IPython GUI event loop integration.
3323
3321
3324 %gui [GUINAME]
3322 %gui [GUINAME]
3325
3323
3326 This magic replaces IPython's threaded shells that were activated
3324 This magic replaces IPython's threaded shells that were activated
3327 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3325 using the (pylab/wthread/etc.) command line flags. GUI toolkits
3328 can now be enabled, disabled and changed at runtime and keyboard
3326 can now be enabled, disabled and changed at runtime and keyboard
3329 interrupts should work without any problems. The following toolkits
3327 interrupts should work without any problems. The following toolkits
3330 are supported: wxPython, PyQt4, PyGTK, and Tk::
3328 are supported: wxPython, PyQt4, PyGTK, and Tk::
3331
3329
3332 %gui wx # enable wxPython event loop integration
3330 %gui wx # enable wxPython event loop integration
3333 %gui qt4|qt # enable PyQt4 event loop integration
3331 %gui qt4|qt # enable PyQt4 event loop integration
3334 %gui gtk # enable PyGTK event loop integration
3332 %gui gtk # enable PyGTK event loop integration
3335 %gui tk # enable Tk event loop integration
3333 %gui tk # enable Tk event loop integration
3336 %gui # disable all event loop integration
3334 %gui # disable all event loop integration
3337
3335
3338 WARNING: after any of these has been called you can simply create
3336 WARNING: after any of these has been called you can simply create
3339 an application object, but DO NOT start the event loop yourself, as
3337 an application object, but DO NOT start the event loop yourself, as
3340 we have already handled that.
3338 we have already handled that.
3341 """
3339 """
3342 from IPython.lib.inputhook import enable_gui
3340 from IPython.lib.inputhook import enable_gui
3343 opts, arg = self.parse_options(parameter_s, '')
3341 opts, arg = self.parse_options(parameter_s, '')
3344 if arg=='': arg = None
3342 if arg=='': arg = None
3345 return enable_gui(arg)
3343 return enable_gui(arg)
3346
3344
3347 def magic_load_ext(self, module_str):
3345 def magic_load_ext(self, module_str):
3348 """Load an IPython extension by its module name."""
3346 """Load an IPython extension by its module name."""
3349 return self.extension_manager.load_extension(module_str)
3347 return self.extension_manager.load_extension(module_str)
3350
3348
3351 def magic_unload_ext(self, module_str):
3349 def magic_unload_ext(self, module_str):
3352 """Unload an IPython extension by its module name."""
3350 """Unload an IPython extension by its module name."""
3353 self.extension_manager.unload_extension(module_str)
3351 self.extension_manager.unload_extension(module_str)
3354
3352
3355 def magic_reload_ext(self, module_str):
3353 def magic_reload_ext(self, module_str):
3356 """Reload an IPython extension by its module name."""
3354 """Reload an IPython extension by its module name."""
3357 self.extension_manager.reload_extension(module_str)
3355 self.extension_manager.reload_extension(module_str)
3358
3356
3359 @skip_doctest
3357 @skip_doctest
3360 def magic_install_profiles(self, s):
3358 def magic_install_profiles(self, s):
3361 """Install the default IPython profiles into the .ipython dir.
3359 """Install the default IPython profiles into the .ipython dir.
3362
3360
3363 If the default profiles have already been installed, they will not
3361 If the default profiles have already been installed, they will not
3364 be overwritten. You can force overwriting them by using the ``-o``
3362 be overwritten. You can force overwriting them by using the ``-o``
3365 option::
3363 option::
3366
3364
3367 In [1]: %install_profiles -o
3365 In [1]: %install_profiles -o
3368 """
3366 """
3369 if '-o' in s:
3367 if '-o' in s:
3370 overwrite = True
3368 overwrite = True
3371 else:
3369 else:
3372 overwrite = False
3370 overwrite = False
3373 from IPython.config import profile
3371 from IPython.config import profile
3374 profile_dir = os.path.dirname(profile.__file__)
3372 profile_dir = os.path.dirname(profile.__file__)
3375 ipython_dir = self.ipython_dir
3373 ipython_dir = self.ipython_dir
3376 print "Installing profiles to: %s [overwrite=%s]"%(ipython_dir,overwrite)
3374 print "Installing profiles to: %s [overwrite=%s]"%(ipython_dir,overwrite)
3377 for src in os.listdir(profile_dir):
3375 for src in os.listdir(profile_dir):
3378 if src.startswith('profile_'):
3376 if src.startswith('profile_'):
3379 name = src.replace('profile_', '')
3377 name = src.replace('profile_', '')
3380 print " %s"%name
3378 print " %s"%name
3381 pd = ProfileDir.create_profile_dir_by_name(ipython_dir, name)
3379 pd = ProfileDir.create_profile_dir_by_name(ipython_dir, name)
3382 pd.copy_config_file('ipython_config.py', path=src,
3380 pd.copy_config_file('ipython_config.py', path=src,
3383 overwrite=overwrite)
3381 overwrite=overwrite)
3384
3382
3385 @skip_doctest
3383 @skip_doctest
3386 def magic_install_default_config(self, s):
3384 def magic_install_default_config(self, s):
3387 """Install IPython's default config file into the .ipython dir.
3385 """Install IPython's default config file into the .ipython dir.
3388
3386
3389 If the default config file (:file:`ipython_config.py`) is already
3387 If the default config file (:file:`ipython_config.py`) is already
3390 installed, it will not be overwritten. You can force overwriting
3388 installed, it will not be overwritten. You can force overwriting
3391 by using the ``-o`` option::
3389 by using the ``-o`` option::
3392
3390
3393 In [1]: %install_default_config
3391 In [1]: %install_default_config
3394 """
3392 """
3395 if '-o' in s:
3393 if '-o' in s:
3396 overwrite = True
3394 overwrite = True
3397 else:
3395 else:
3398 overwrite = False
3396 overwrite = False
3399 pd = self.shell.profile_dir
3397 pd = self.shell.profile_dir
3400 print "Installing default config file in: %s" % pd.location
3398 print "Installing default config file in: %s" % pd.location
3401 pd.copy_config_file('ipython_config.py', overwrite=overwrite)
3399 pd.copy_config_file('ipython_config.py', overwrite=overwrite)
3402
3400
3403 # Pylab support: simple wrappers that activate pylab, load gui input
3401 # Pylab support: simple wrappers that activate pylab, load gui input
3404 # handling and modify slightly %run
3402 # handling and modify slightly %run
3405
3403
3406 @skip_doctest
3404 @skip_doctest
3407 def _pylab_magic_run(self, parameter_s=''):
3405 def _pylab_magic_run(self, parameter_s=''):
3408 Magic.magic_run(self, parameter_s,
3406 Magic.magic_run(self, parameter_s,
3409 runner=mpl_runner(self.shell.safe_execfile))
3407 runner=mpl_runner(self.shell.safe_execfile))
3410
3408
3411 _pylab_magic_run.__doc__ = magic_run.__doc__
3409 _pylab_magic_run.__doc__ = magic_run.__doc__
3412
3410
3413 @skip_doctest
3411 @skip_doctest
3414 def magic_pylab(self, s):
3412 def magic_pylab(self, s):
3415 """Load numpy and matplotlib to work interactively.
3413 """Load numpy and matplotlib to work interactively.
3416
3414
3417 %pylab [GUINAME]
3415 %pylab [GUINAME]
3418
3416
3419 This function lets you activate pylab (matplotlib, numpy and
3417 This function lets you activate pylab (matplotlib, numpy and
3420 interactive support) at any point during an IPython session.
3418 interactive support) at any point during an IPython session.
3421
3419
3422 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3420 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3423 pylab and mlab, as well as all names from numpy and pylab.
3421 pylab and mlab, as well as all names from numpy and pylab.
3424
3422
3425 Parameters
3423 Parameters
3426 ----------
3424 ----------
3427 guiname : optional
3425 guiname : optional
3428 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or
3426 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or
3429 'tk'). If given, the corresponding Matplotlib backend is used,
3427 'tk'). If given, the corresponding Matplotlib backend is used,
3430 otherwise matplotlib's default (which you can override in your
3428 otherwise matplotlib's default (which you can override in your
3431 matplotlib config file) is used.
3429 matplotlib config file) is used.
3432
3430
3433 Examples
3431 Examples
3434 --------
3432 --------
3435 In this case, where the MPL default is TkAgg:
3433 In this case, where the MPL default is TkAgg:
3436 In [2]: %pylab
3434 In [2]: %pylab
3437
3435
3438 Welcome to pylab, a matplotlib-based Python environment.
3436 Welcome to pylab, a matplotlib-based Python environment.
3439 Backend in use: TkAgg
3437 Backend in use: TkAgg
3440 For more information, type 'help(pylab)'.
3438 For more information, type 'help(pylab)'.
3441
3439
3442 But you can explicitly request a different backend:
3440 But you can explicitly request a different backend:
3443 In [3]: %pylab qt
3441 In [3]: %pylab qt
3444
3442
3445 Welcome to pylab, a matplotlib-based Python environment.
3443 Welcome to pylab, a matplotlib-based Python environment.
3446 Backend in use: Qt4Agg
3444 Backend in use: Qt4Agg
3447 For more information, type 'help(pylab)'.
3445 For more information, type 'help(pylab)'.
3448 """
3446 """
3449 self.shell.enable_pylab(s)
3447 self.shell.enable_pylab(s)
3450
3448
3451 def magic_tb(self, s):
3449 def magic_tb(self, s):
3452 """Print the last traceback with the currently active exception mode.
3450 """Print the last traceback with the currently active exception mode.
3453
3451
3454 See %xmode for changing exception reporting modes."""
3452 See %xmode for changing exception reporting modes."""
3455 self.shell.showtraceback()
3453 self.shell.showtraceback()
3456
3454
3457 @skip_doctest
3455 @skip_doctest
3458 def magic_precision(self, s=''):
3456 def magic_precision(self, s=''):
3459 """Set floating point precision for pretty printing.
3457 """Set floating point precision for pretty printing.
3460
3458
3461 Can set either integer precision or a format string.
3459 Can set either integer precision or a format string.
3462
3460
3463 If numpy has been imported and precision is an int,
3461 If numpy has been imported and precision is an int,
3464 numpy display precision will also be set, via ``numpy.set_printoptions``.
3462 numpy display precision will also be set, via ``numpy.set_printoptions``.
3465
3463
3466 If no argument is given, defaults will be restored.
3464 If no argument is given, defaults will be restored.
3467
3465
3468 Examples
3466 Examples
3469 --------
3467 --------
3470 ::
3468 ::
3471
3469
3472 In [1]: from math import pi
3470 In [1]: from math import pi
3473
3471
3474 In [2]: %precision 3
3472 In [2]: %precision 3
3475 Out[2]: '%.3f'
3473 Out[2]: '%.3f'
3476
3474
3477 In [3]: pi
3475 In [3]: pi
3478 Out[3]: 3.142
3476 Out[3]: 3.142
3479
3477
3480 In [4]: %precision %i
3478 In [4]: %precision %i
3481 Out[4]: '%i'
3479 Out[4]: '%i'
3482
3480
3483 In [5]: pi
3481 In [5]: pi
3484 Out[5]: 3
3482 Out[5]: 3
3485
3483
3486 In [6]: %precision %e
3484 In [6]: %precision %e
3487 Out[6]: '%e'
3485 Out[6]: '%e'
3488
3486
3489 In [7]: pi**10
3487 In [7]: pi**10
3490 Out[7]: 9.364805e+04
3488 Out[7]: 9.364805e+04
3491
3489
3492 In [8]: %precision
3490 In [8]: %precision
3493 Out[8]: '%r'
3491 Out[8]: '%r'
3494
3492
3495 In [9]: pi**10
3493 In [9]: pi**10
3496 Out[9]: 93648.047476082982
3494 Out[9]: 93648.047476082982
3497
3495
3498 """
3496 """
3499
3497
3500 ptformatter = self.shell.display_formatter.formatters['text/plain']
3498 ptformatter = self.shell.display_formatter.formatters['text/plain']
3501 ptformatter.float_precision = s
3499 ptformatter.float_precision = s
3502 return ptformatter.float_format
3500 return ptformatter.float_format
3503
3501
3504 # end Magic
3502 # end Magic
General Comments 0
You need to be logged in to leave comments. Login now