##// END OF EJS Templates
Added %paste magic
vivainio -
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -1,2762 +1,2804 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3
3
4 $Id: Magic.py 1034 2006-01-20 12:59:31Z vivainio $"""
4 $Id: Magic.py 1068 2006-01-23 20:31:43Z vivainio $"""
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
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 # Modules and globals
15 # Modules and globals
16
16
17 from IPython import Release
17 from IPython import Release
18 __author__ = '%s <%s>\n%s <%s>' % \
18 __author__ = '%s <%s>\n%s <%s>' % \
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
19 ( Release.authors['Janko'] + Release.authors['Fernando'] )
20 __license__ = Release.license
20 __license__ = Release.license
21
21
22 # Python standard modules
22 # Python standard modules
23 import __builtin__
23 import __builtin__
24 import bdb
24 import bdb
25 import inspect
25 import inspect
26 import os
26 import os
27 import pdb
27 import pdb
28 import pydoc
28 import pydoc
29 import sys
29 import sys
30 import re
30 import re
31 import tempfile
31 import tempfile
32 import time
32 import time
33 import cPickle as pickle
33 import cPickle as pickle
34 import textwrap
34 import textwrap
35 from cStringIO import StringIO
35 from cStringIO import StringIO
36 from getopt import getopt
36 from getopt import getopt
37 from pprint import pprint, pformat
37 from pprint import pprint, pformat
38
38
39 # profile isn't bundled by default in Debian for license reasons
39 # profile isn't bundled by default in Debian for license reasons
40 try:
40 try:
41 import profile,pstats
41 import profile,pstats
42 except ImportError:
42 except ImportError:
43 profile = pstats = None
43 profile = pstats = None
44
44
45 # Homebrewed
45 # Homebrewed
46 from IPython import Debugger, OInspect, wildcard
46 from IPython import Debugger, OInspect, wildcard
47 from IPython.FakeModule import FakeModule
47 from IPython.FakeModule import FakeModule
48 from IPython.Itpl import Itpl, itpl, printpl,itplns
48 from IPython.Itpl import Itpl, itpl, printpl,itplns
49 from IPython.PyColorize import Parser
49 from IPython.PyColorize import Parser
50 from IPython.ipstruct import Struct
50 from IPython.ipstruct import Struct
51 from IPython.macro import Macro
51 from IPython.macro import Macro
52 from IPython.genutils import *
52 from IPython.genutils import *
53 from IPython import platutils
53 from IPython import platutils
54
54 #***************************************************************************
55 #***************************************************************************
55 # Utility functions
56 # Utility functions
56 def on_off(tag):
57 def on_off(tag):
57 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
58 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
58 return ['OFF','ON'][tag]
59 return ['OFF','ON'][tag]
59
60
60 class Bunch: pass
61 class Bunch: pass
61
62
62 #***************************************************************************
63 #***************************************************************************
63 # Main class implementing Magic functionality
64 # Main class implementing Magic functionality
64 class Magic:
65 class Magic:
65 """Magic functions for InteractiveShell.
66 """Magic functions for InteractiveShell.
66
67
67 Shell functions which can be reached as %function_name. All magic
68 Shell functions which can be reached as %function_name. All magic
68 functions should accept a string, which they can parse for their own
69 functions should accept a string, which they can parse for their own
69 needs. This can make some functions easier to type, eg `%cd ../`
70 needs. This can make some functions easier to type, eg `%cd ../`
70 vs. `%cd("../")`
71 vs. `%cd("../")`
71
72
72 ALL definitions MUST begin with the prefix magic_. The user won't need it
73 ALL definitions MUST begin with the prefix magic_. The user won't need it
73 at the command line, but it is is needed in the definition. """
74 at the command line, but it is is needed in the definition. """
74
75
75 # class globals
76 # class globals
76 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
77 auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.',
77 'Automagic is ON, % prefix NOT needed for magic functions.']
78 'Automagic is ON, % prefix NOT needed for magic functions.']
78
79
79 #......................................................................
80 #......................................................................
80 # some utility functions
81 # some utility functions
81
82
82 def __init__(self,shell):
83 def __init__(self,shell):
83
84
84 self.options_table = {}
85 self.options_table = {}
85 if profile is None:
86 if profile is None:
86 self.magic_prun = self.profile_missing_notice
87 self.magic_prun = self.profile_missing_notice
87 self.shell = shell
88 self.shell = shell
88
89
89 # namespace for holding state we may need
90 # namespace for holding state we may need
90 self._magic_state = Bunch()
91 self._magic_state = Bunch()
91
92
92 def profile_missing_notice(self, *args, **kwargs):
93 def profile_missing_notice(self, *args, **kwargs):
93 error("""\
94 error("""\
94 The profile module could not be found. If you are a Debian user,
95 The profile module could not be found. If you are a Debian user,
95 it has been removed from the standard Debian package because of its non-free
96 it has been removed from the standard Debian package because of its non-free
96 license. To use profiling, please install"python2.3-profiler" from non-free.""")
97 license. To use profiling, please install"python2.3-profiler" from non-free.""")
97
98
98 def default_option(self,fn,optstr):
99 def default_option(self,fn,optstr):
99 """Make an entry in the options_table for fn, with value optstr"""
100 """Make an entry in the options_table for fn, with value optstr"""
100
101
101 if fn not in self.lsmagic():
102 if fn not in self.lsmagic():
102 error("%s is not a magic function" % fn)
103 error("%s is not a magic function" % fn)
103 self.options_table[fn] = optstr
104 self.options_table[fn] = optstr
104
105
105 def lsmagic(self):
106 def lsmagic(self):
106 """Return a list of currently available magic functions.
107 """Return a list of currently available magic functions.
107
108
108 Gives a list of the bare names after mangling (['ls','cd', ...], not
109 Gives a list of the bare names after mangling (['ls','cd', ...], not
109 ['magic_ls','magic_cd',...]"""
110 ['magic_ls','magic_cd',...]"""
110
111
111 # FIXME. This needs a cleanup, in the way the magics list is built.
112 # FIXME. This needs a cleanup, in the way the magics list is built.
112
113
113 # magics in class definition
114 # magics in class definition
114 class_magic = lambda fn: fn.startswith('magic_') and \
115 class_magic = lambda fn: fn.startswith('magic_') and \
115 callable(Magic.__dict__[fn])
116 callable(Magic.__dict__[fn])
116 # in instance namespace (run-time user additions)
117 # in instance namespace (run-time user additions)
117 inst_magic = lambda fn: fn.startswith('magic_') and \
118 inst_magic = lambda fn: fn.startswith('magic_') and \
118 callable(self.__dict__[fn])
119 callable(self.__dict__[fn])
119 # and bound magics by user (so they can access self):
120 # and bound magics by user (so they can access self):
120 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
121 inst_bound_magic = lambda fn: fn.startswith('magic_') and \
121 callable(self.__class__.__dict__[fn])
122 callable(self.__class__.__dict__[fn])
122 magics = filter(class_magic,Magic.__dict__.keys()) + \
123 magics = filter(class_magic,Magic.__dict__.keys()) + \
123 filter(inst_magic,self.__dict__.keys()) + \
124 filter(inst_magic,self.__dict__.keys()) + \
124 filter(inst_bound_magic,self.__class__.__dict__.keys())
125 filter(inst_bound_magic,self.__class__.__dict__.keys())
125 out = []
126 out = []
126 for fn in magics:
127 for fn in magics:
127 out.append(fn.replace('magic_','',1))
128 out.append(fn.replace('magic_','',1))
128 out.sort()
129 out.sort()
129 return out
130 return out
130
131
131 def extract_input_slices(self,slices):
132 def extract_input_slices(self,slices):
132 """Return as a string a set of input history slices.
133 """Return as a string a set of input history slices.
133
134
134 The set of slices is given as a list of strings (like ['1','4:8','9'],
135 The set of slices is given as a list of strings (like ['1','4:8','9'],
135 since this function is for use by magic functions which get their
136 since this function is for use by magic functions which get their
136 arguments as strings.
137 arguments as strings.
137
138
138 Note that slices can be called with two notations:
139 Note that slices can be called with two notations:
139
140
140 N:M -> standard python form, means including items N...(M-1).
141 N:M -> standard python form, means including items N...(M-1).
141
142
142 N-M -> include items N..M (closed endpoint)."""
143 N-M -> include items N..M (closed endpoint)."""
143
144
144 cmds = []
145 cmds = []
145 for chunk in slices:
146 for chunk in slices:
146 if ':' in chunk:
147 if ':' in chunk:
147 ini,fin = map(int,chunk.split(':'))
148 ini,fin = map(int,chunk.split(':'))
148 elif '-' in chunk:
149 elif '-' in chunk:
149 ini,fin = map(int,chunk.split('-'))
150 ini,fin = map(int,chunk.split('-'))
150 fin += 1
151 fin += 1
151 else:
152 else:
152 ini = int(chunk)
153 ini = int(chunk)
153 fin = ini+1
154 fin = ini+1
154 cmds.append(self.shell.input_hist[ini:fin])
155 cmds.append(self.shell.input_hist[ini:fin])
155 return cmds
156 return cmds
156
157
157 def _ofind(self,oname):
158 def _ofind(self,oname):
158 """Find an object in the available namespaces.
159 """Find an object in the available namespaces.
159
160
160 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
161 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
161
162
162 Has special code to detect magic functions.
163 Has special code to detect magic functions.
163 """
164 """
164
165
165 oname = oname.strip()
166 oname = oname.strip()
166
167
167 # Namespaces to search in:
168 # Namespaces to search in:
168 user_ns = self.shell.user_ns
169 user_ns = self.shell.user_ns
169 internal_ns = self.shell.internal_ns
170 internal_ns = self.shell.internal_ns
170 builtin_ns = __builtin__.__dict__
171 builtin_ns = __builtin__.__dict__
171 alias_ns = self.shell.alias_table
172 alias_ns = self.shell.alias_table
172
173
173 # Put them in a list. The order is important so that we find things in
174 # Put them in a list. The order is important so that we find things in
174 # the same order that Python finds them.
175 # the same order that Python finds them.
175 namespaces = [ ('Interactive',user_ns),
176 namespaces = [ ('Interactive',user_ns),
176 ('IPython internal',internal_ns),
177 ('IPython internal',internal_ns),
177 ('Python builtin',builtin_ns),
178 ('Python builtin',builtin_ns),
178 ('Alias',alias_ns),
179 ('Alias',alias_ns),
179 ]
180 ]
180
181
181 # initialize results to 'null'
182 # initialize results to 'null'
182 found = 0; obj = None; ospace = None; ds = None;
183 found = 0; obj = None; ospace = None; ds = None;
183 ismagic = 0; isalias = 0
184 ismagic = 0; isalias = 0
184
185
185 # Look for the given name by splitting it in parts. If the head is
186 # Look for the given name by splitting it in parts. If the head is
186 # found, then we look for all the remaining parts as members, and only
187 # found, then we look for all the remaining parts as members, and only
187 # declare success if we can find them all.
188 # declare success if we can find them all.
188 oname_parts = oname.split('.')
189 oname_parts = oname.split('.')
189 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
190 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
190 for nsname,ns in namespaces:
191 for nsname,ns in namespaces:
191 try:
192 try:
192 obj = ns[oname_head]
193 obj = ns[oname_head]
193 except KeyError:
194 except KeyError:
194 continue
195 continue
195 else:
196 else:
196 for part in oname_rest:
197 for part in oname_rest:
197 try:
198 try:
198 obj = getattr(obj,part)
199 obj = getattr(obj,part)
199 except:
200 except:
200 # Blanket except b/c some badly implemented objects
201 # Blanket except b/c some badly implemented objects
201 # allow __getattr__ to raise exceptions other than
202 # allow __getattr__ to raise exceptions other than
202 # AttributeError, which then crashes IPython.
203 # AttributeError, which then crashes IPython.
203 break
204 break
204 else:
205 else:
205 # If we finish the for loop (no break), we got all members
206 # If we finish the for loop (no break), we got all members
206 found = 1
207 found = 1
207 ospace = nsname
208 ospace = nsname
208 if ns == alias_ns:
209 if ns == alias_ns:
209 isalias = 1
210 isalias = 1
210 break # namespace loop
211 break # namespace loop
211
212
212 # Try to see if it's magic
213 # Try to see if it's magic
213 if not found:
214 if not found:
214 if oname.startswith(self.shell.ESC_MAGIC):
215 if oname.startswith(self.shell.ESC_MAGIC):
215 oname = oname[1:]
216 oname = oname[1:]
216 obj = getattr(self,'magic_'+oname,None)
217 obj = getattr(self,'magic_'+oname,None)
217 if obj is not None:
218 if obj is not None:
218 found = 1
219 found = 1
219 ospace = 'IPython internal'
220 ospace = 'IPython internal'
220 ismagic = 1
221 ismagic = 1
221
222
222 # Last try: special-case some literals like '', [], {}, etc:
223 # Last try: special-case some literals like '', [], {}, etc:
223 if not found and oname_head in ["''",'""','[]','{}','()']:
224 if not found and oname_head in ["''",'""','[]','{}','()']:
224 obj = eval(oname_head)
225 obj = eval(oname_head)
225 found = 1
226 found = 1
226 ospace = 'Interactive'
227 ospace = 'Interactive'
227
228
228 return {'found':found, 'obj':obj, 'namespace':ospace,
229 return {'found':found, 'obj':obj, 'namespace':ospace,
229 'ismagic':ismagic, 'isalias':isalias}
230 'ismagic':ismagic, 'isalias':isalias}
230
231
231 def arg_err(self,func):
232 def arg_err(self,func):
232 """Print docstring if incorrect arguments were passed"""
233 """Print docstring if incorrect arguments were passed"""
233 print 'Error in arguments:'
234 print 'Error in arguments:'
234 print OInspect.getdoc(func)
235 print OInspect.getdoc(func)
235
236
236 def format_latex(self,strng):
237 def format_latex(self,strng):
237 """Format a string for latex inclusion."""
238 """Format a string for latex inclusion."""
238
239
239 # Characters that need to be escaped for latex:
240 # Characters that need to be escaped for latex:
240 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
241 escape_re = re.compile(r'(%|_|\$|#)',re.MULTILINE)
241 # Magic command names as headers:
242 # Magic command names as headers:
242 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
243 cmd_name_re = re.compile(r'^(%s.*?):' % self.shell.ESC_MAGIC,
243 re.MULTILINE)
244 re.MULTILINE)
244 # Magic commands
245 # Magic commands
245 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
246 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % self.shell.ESC_MAGIC,
246 re.MULTILINE)
247 re.MULTILINE)
247 # Paragraph continue
248 # Paragraph continue
248 par_re = re.compile(r'\\$',re.MULTILINE)
249 par_re = re.compile(r'\\$',re.MULTILINE)
249
250
250 # The "\n" symbol
251 # The "\n" symbol
251 newline_re = re.compile(r'\\n')
252 newline_re = re.compile(r'\\n')
252
253
253 # Now build the string for output:
254 # Now build the string for output:
254 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
255 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
255 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
256 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
256 strng)
257 strng)
257 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
258 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
258 strng = par_re.sub(r'\\\\',strng)
259 strng = par_re.sub(r'\\\\',strng)
259 strng = escape_re.sub(r'\\\1',strng)
260 strng = escape_re.sub(r'\\\1',strng)
260 strng = newline_re.sub(r'\\textbackslash{}n',strng)
261 strng = newline_re.sub(r'\\textbackslash{}n',strng)
261 return strng
262 return strng
262
263
263 def format_screen(self,strng):
264 def format_screen(self,strng):
264 """Format a string for screen printing.
265 """Format a string for screen printing.
265
266
266 This removes some latex-type format codes."""
267 This removes some latex-type format codes."""
267 # Paragraph continue
268 # Paragraph continue
268 par_re = re.compile(r'\\$',re.MULTILINE)
269 par_re = re.compile(r'\\$',re.MULTILINE)
269 strng = par_re.sub('',strng)
270 strng = par_re.sub('',strng)
270 return strng
271 return strng
271
272
272 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
273 def parse_options(self,arg_str,opt_str,*long_opts,**kw):
273 """Parse options passed to an argument string.
274 """Parse options passed to an argument string.
274
275
275 The interface is similar to that of getopt(), but it returns back a
276 The interface is similar to that of getopt(), but it returns back a
276 Struct with the options as keys and the stripped argument string still
277 Struct with the options as keys and the stripped argument string still
277 as a string.
278 as a string.
278
279
279 arg_str is quoted as a true sys.argv vector by using shlex.split.
280 arg_str is quoted as a true sys.argv vector by using shlex.split.
280 This allows us to easily expand variables, glob files, quote
281 This allows us to easily expand variables, glob files, quote
281 arguments, etc.
282 arguments, etc.
282
283
283 Options:
284 Options:
284 -mode: default 'string'. If given as 'list', the argument string is
285 -mode: default 'string'. If given as 'list', the argument string is
285 returned as a list (split on whitespace) instead of a string.
286 returned as a list (split on whitespace) instead of a string.
286
287
287 -list_all: put all option values in lists. Normally only options
288 -list_all: put all option values in lists. Normally only options
288 appearing more than once are put in a list."""
289 appearing more than once are put in a list."""
289
290
290 # inject default options at the beginning of the input line
291 # inject default options at the beginning of the input line
291 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
292 caller = sys._getframe(1).f_code.co_name.replace('magic_','')
292 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
293 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
293
294
294 mode = kw.get('mode','string')
295 mode = kw.get('mode','string')
295 if mode not in ['string','list']:
296 if mode not in ['string','list']:
296 raise ValueError,'incorrect mode given: %s' % mode
297 raise ValueError,'incorrect mode given: %s' % mode
297 # Get options
298 # Get options
298 list_all = kw.get('list_all',0)
299 list_all = kw.get('list_all',0)
299
300
300 # Check if we have more than one argument to warrant extra processing:
301 # Check if we have more than one argument to warrant extra processing:
301 odict = {} # Dictionary with options
302 odict = {} # Dictionary with options
302 args = arg_str.split()
303 args = arg_str.split()
303 if len(args) >= 1:
304 if len(args) >= 1:
304 # If the list of inputs only has 0 or 1 thing in it, there's no
305 # If the list of inputs only has 0 or 1 thing in it, there's no
305 # need to look for options
306 # need to look for options
306 argv = shlex_split(arg_str)
307 argv = shlex_split(arg_str)
307 # Do regular option processing
308 # Do regular option processing
308 opts,args = getopt(argv,opt_str,*long_opts)
309 opts,args = getopt(argv,opt_str,*long_opts)
309 for o,a in opts:
310 for o,a in opts:
310 if o.startswith('--'):
311 if o.startswith('--'):
311 o = o[2:]
312 o = o[2:]
312 else:
313 else:
313 o = o[1:]
314 o = o[1:]
314 try:
315 try:
315 odict[o].append(a)
316 odict[o].append(a)
316 except AttributeError:
317 except AttributeError:
317 odict[o] = [odict[o],a]
318 odict[o] = [odict[o],a]
318 except KeyError:
319 except KeyError:
319 if list_all:
320 if list_all:
320 odict[o] = [a]
321 odict[o] = [a]
321 else:
322 else:
322 odict[o] = a
323 odict[o] = a
323
324
324 # Prepare opts,args for return
325 # Prepare opts,args for return
325 opts = Struct(odict)
326 opts = Struct(odict)
326 if mode == 'string':
327 if mode == 'string':
327 args = ' '.join(args)
328 args = ' '.join(args)
328
329
329 return opts,args
330 return opts,args
330
331
331 #......................................................................
332 #......................................................................
332 # And now the actual magic functions
333 # And now the actual magic functions
333
334
334 # Functions for IPython shell work (vars,funcs, config, etc)
335 # Functions for IPython shell work (vars,funcs, config, etc)
335 def magic_lsmagic(self, parameter_s = ''):
336 def magic_lsmagic(self, parameter_s = ''):
336 """List currently available magic functions."""
337 """List currently available magic functions."""
337 mesc = self.shell.ESC_MAGIC
338 mesc = self.shell.ESC_MAGIC
338 print 'Available magic functions:\n'+mesc+\
339 print 'Available magic functions:\n'+mesc+\
339 (' '+mesc).join(self.lsmagic())
340 (' '+mesc).join(self.lsmagic())
340 print '\n' + Magic.auto_status[self.shell.rc.automagic]
341 print '\n' + Magic.auto_status[self.shell.rc.automagic]
341 return None
342 return None
342
343
343 def magic_magic(self, parameter_s = ''):
344 def magic_magic(self, parameter_s = ''):
344 """Print information about the magic function system."""
345 """Print information about the magic function system."""
345
346
346 mode = ''
347 mode = ''
347 try:
348 try:
348 if parameter_s.split()[0] == '-latex':
349 if parameter_s.split()[0] == '-latex':
349 mode = 'latex'
350 mode = 'latex'
350 except:
351 except:
351 pass
352 pass
352
353
353 magic_docs = []
354 magic_docs = []
354 for fname in self.lsmagic():
355 for fname in self.lsmagic():
355 mname = 'magic_' + fname
356 mname = 'magic_' + fname
356 for space in (Magic,self,self.__class__):
357 for space in (Magic,self,self.__class__):
357 try:
358 try:
358 fn = space.__dict__[mname]
359 fn = space.__dict__[mname]
359 except KeyError:
360 except KeyError:
360 pass
361 pass
361 else:
362 else:
362 break
363 break
363 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
364 magic_docs.append('%s%s:\n\t%s\n' %(self.shell.ESC_MAGIC,
364 fname,fn.__doc__))
365 fname,fn.__doc__))
365 magic_docs = ''.join(magic_docs)
366 magic_docs = ''.join(magic_docs)
366
367
367 if mode == 'latex':
368 if mode == 'latex':
368 print self.format_latex(magic_docs)
369 print self.format_latex(magic_docs)
369 return
370 return
370 else:
371 else:
371 magic_docs = self.format_screen(magic_docs)
372 magic_docs = self.format_screen(magic_docs)
372
373
373 outmsg = """
374 outmsg = """
374 IPython's 'magic' functions
375 IPython's 'magic' functions
375 ===========================
376 ===========================
376
377
377 The magic function system provides a series of functions which allow you to
378 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
379 control the behavior of IPython itself, plus a lot of system-type
379 features. All these functions are prefixed with a % character, but parameters
380 features. All these functions are prefixed with a % character, but parameters
380 are given without parentheses or quotes.
381 are given without parentheses or quotes.
381
382
382 NOTE: If you have 'automagic' enabled (via the command line option or with the
383 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,
384 %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.
385 IPython ships with automagic on, so you should only rarely need the % escape.
385
386
386 Example: typing '%cd mydir' (without the quotes) changes you working directory
387 Example: typing '%cd mydir' (without the quotes) changes you working directory
387 to 'mydir', if it exists.
388 to 'mydir', if it exists.
388
389
389 You can define your own magic functions to extend the system. See the supplied
390 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
391 ipythonrc and example-magic.py files for details (in your ipython
391 configuration directory, typically $HOME/.ipython/).
392 configuration directory, typically $HOME/.ipython/).
392
393
393 You can also define your own aliased names for magic functions. In your
394 You can also define your own aliased names for magic functions. In your
394 ipythonrc file, placing a line like:
395 ipythonrc file, placing a line like:
395
396
396 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
397 execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile
397
398
398 will define %pf as a new name for %profile.
399 will define %pf as a new name for %profile.
399
400
400 You can also call magics in code using the ipmagic() function, which IPython
401 You can also call magics in code using the ipmagic() function, which IPython
401 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
402 automatically adds to the builtin namespace. Type 'ipmagic?' for details.
402
403
403 For a list of the available magic functions, use %lsmagic. For a description
404 For a list of the available magic functions, use %lsmagic. For a description
404 of any of them, type %magic_name?, e.g. '%cd?'.
405 of any of them, type %magic_name?, e.g. '%cd?'.
405
406
406 Currently the magic system has the following functions:\n"""
407 Currently the magic system has the following functions:\n"""
407
408
408 mesc = self.shell.ESC_MAGIC
409 mesc = self.shell.ESC_MAGIC
409 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
410 outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):"
410 "\n\n%s%s\n\n%s" % (outmsg,
411 "\n\n%s%s\n\n%s" % (outmsg,
411 magic_docs,mesc,mesc,
412 magic_docs,mesc,mesc,
412 (' '+mesc).join(self.lsmagic()),
413 (' '+mesc).join(self.lsmagic()),
413 Magic.auto_status[self.shell.rc.automagic] ) )
414 Magic.auto_status[self.shell.rc.automagic] ) )
414
415
415 page(outmsg,screen_lines=self.shell.rc.screen_length)
416 page(outmsg,screen_lines=self.shell.rc.screen_length)
416
417
417 def magic_automagic(self, parameter_s = ''):
418 def magic_automagic(self, parameter_s = ''):
418 """Make magic functions callable without having to type the initial %.
419 """Make magic functions callable without having to type the initial %.
419
420
420 Toggles on/off (when off, you must call it as %automagic, of
421 Toggles on/off (when off, you must call it as %automagic, of
421 course). Note that magic functions have lowest priority, so if there's
422 course). Note that magic functions have lowest priority, so if there's
422 a variable whose name collides with that of a magic fn, automagic
423 a variable whose name collides with that of a magic fn, automagic
423 won't work for that function (you get the variable instead). However,
424 won't work for that function (you get the variable instead). However,
424 if you delete the variable (del var), the previously shadowed magic
425 if you delete the variable (del var), the previously shadowed magic
425 function becomes visible to automagic again."""
426 function becomes visible to automagic again."""
426
427
427 rc = self.shell.rc
428 rc = self.shell.rc
428 rc.automagic = not rc.automagic
429 rc.automagic = not rc.automagic
429 print '\n' + Magic.auto_status[rc.automagic]
430 print '\n' + Magic.auto_status[rc.automagic]
430
431
431 def magic_autocall(self, parameter_s = ''):
432 def magic_autocall(self, parameter_s = ''):
432 """Make functions callable without having to type parentheses.
433 """Make functions callable without having to type parentheses.
433
434
434 Usage:
435 Usage:
435
436
436 %autocall [mode]
437 %autocall [mode]
437
438
438 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
439 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
439 value is toggled on and off (remembering the previous state)."""
440 value is toggled on and off (remembering the previous state)."""
440
441
441 rc = self.shell.rc
442 rc = self.shell.rc
442
443
443 if parameter_s:
444 if parameter_s:
444 arg = int(parameter_s)
445 arg = int(parameter_s)
445 else:
446 else:
446 arg = 'toggle'
447 arg = 'toggle'
447
448
448 if not arg in (0,1,2,'toggle'):
449 if not arg in (0,1,2,'toggle'):
449 error('Valid modes: (0->Off, 1->Smart, 2->Full')
450 error('Valid modes: (0->Off, 1->Smart, 2->Full')
450 return
451 return
451
452
452 if arg in (0,1,2):
453 if arg in (0,1,2):
453 rc.autocall = arg
454 rc.autocall = arg
454 else: # toggle
455 else: # toggle
455 if rc.autocall:
456 if rc.autocall:
456 self._magic_state.autocall_save = rc.autocall
457 self._magic_state.autocall_save = rc.autocall
457 rc.autocall = 0
458 rc.autocall = 0
458 else:
459 else:
459 try:
460 try:
460 rc.autocall = self._magic_state.autocall_save
461 rc.autocall = self._magic_state.autocall_save
461 except AttributeError:
462 except AttributeError:
462 rc.autocall = self._magic_state.autocall_save = 1
463 rc.autocall = self._magic_state.autocall_save = 1
463
464
464 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
465 print "Automatic calling is:",['OFF','Smart','Full'][rc.autocall]
465
466
466 def magic_autoindent(self, parameter_s = ''):
467 def magic_autoindent(self, parameter_s = ''):
467 """Toggle autoindent on/off (if available)."""
468 """Toggle autoindent on/off (if available)."""
468
469
469 self.shell.set_autoindent()
470 self.shell.set_autoindent()
470 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
471 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
471
472
472 def magic_system_verbose(self, parameter_s = ''):
473 def magic_system_verbose(self, parameter_s = ''):
473 """Toggle verbose printing of system calls on/off."""
474 """Toggle verbose printing of system calls on/off."""
474
475
475 self.shell.rc_set_toggle('system_verbose')
476 self.shell.rc_set_toggle('system_verbose')
476 print "System verbose printing is:",\
477 print "System verbose printing is:",\
477 ['OFF','ON'][self.shell.rc.system_verbose]
478 ['OFF','ON'][self.shell.rc.system_verbose]
478
479
479 def magic_history(self, parameter_s = ''):
480 def magic_history(self, parameter_s = ''):
480 """Print input history (_i<n> variables), with most recent last.
481 """Print input history (_i<n> variables), with most recent last.
481
482
482 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
483 %history [-n] -> print at most 40 inputs (some may be multi-line)\\
483 %history [-n] n -> print at most n inputs\\
484 %history [-n] n -> print at most n inputs\\
484 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
485 %history [-n] n1 n2 -> print inputs between n1 and n2 (n2 not included)\\
485
486
486 Each input's number <n> is shown, and is accessible as the
487 Each input's number <n> is shown, and is accessible as the
487 automatically generated variable _i<n>. Multi-line statements are
488 automatically generated variable _i<n>. Multi-line statements are
488 printed starting at a new line for easy copy/paste.
489 printed starting at a new line for easy copy/paste.
489
490
490 If option -n is used, input numbers are not printed. This is useful if
491 If option -n is used, input numbers are not printed. This is useful if
491 you want to get a printout of many lines which can be directly pasted
492 you want to get a printout of many lines which can be directly pasted
492 into a text editor.
493 into a text editor.
493
494
494 This feature is only available if numbered prompts are in use."""
495 This feature is only available if numbered prompts are in use."""
495
496
496 shell = self.shell
497 shell = self.shell
497 if not shell.outputcache.do_full_cache:
498 if not shell.outputcache.do_full_cache:
498 print 'This feature is only available if numbered prompts are in use.'
499 print 'This feature is only available if numbered prompts are in use.'
499 return
500 return
500 opts,args = self.parse_options(parameter_s,'n',mode='list')
501 opts,args = self.parse_options(parameter_s,'n',mode='list')
501
502
502 input_hist = shell.input_hist
503 input_hist = shell.input_hist
503 default_length = 40
504 default_length = 40
504 if len(args) == 0:
505 if len(args) == 0:
505 final = len(input_hist)
506 final = len(input_hist)
506 init = max(1,final-default_length)
507 init = max(1,final-default_length)
507 elif len(args) == 1:
508 elif len(args) == 1:
508 final = len(input_hist)
509 final = len(input_hist)
509 init = max(1,final-int(args[0]))
510 init = max(1,final-int(args[0]))
510 elif len(args) == 2:
511 elif len(args) == 2:
511 init,final = map(int,args)
512 init,final = map(int,args)
512 else:
513 else:
513 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
514 warn('%hist takes 0, 1 or 2 arguments separated by spaces.')
514 print self.magic_hist.__doc__
515 print self.magic_hist.__doc__
515 return
516 return
516 width = len(str(final))
517 width = len(str(final))
517 line_sep = ['','\n']
518 line_sep = ['','\n']
518 print_nums = not opts.has_key('n')
519 print_nums = not opts.has_key('n')
519 for in_num in range(init,final):
520 for in_num in range(init,final):
520 inline = input_hist[in_num]
521 inline = input_hist[in_num]
521 multiline = int(inline.count('\n') > 1)
522 multiline = int(inline.count('\n') > 1)
522 if print_nums:
523 if print_nums:
523 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
524 print '%s:%s' % (str(in_num).ljust(width),line_sep[multiline]),
524 print inline,
525 print inline,
525
526
526 def magic_hist(self, parameter_s=''):
527 def magic_hist(self, parameter_s=''):
527 """Alternate name for %history."""
528 """Alternate name for %history."""
528 return self.magic_history(parameter_s)
529 return self.magic_history(parameter_s)
529
530
530 def magic_p(self, parameter_s=''):
531 def magic_p(self, parameter_s=''):
531 """Just a short alias for Python's 'print'."""
532 """Just a short alias for Python's 'print'."""
532 exec 'print ' + parameter_s in self.shell.user_ns
533 exec 'print ' + parameter_s in self.shell.user_ns
533
534
534 def magic_r(self, parameter_s=''):
535 def magic_r(self, parameter_s=''):
535 """Repeat previous input.
536 """Repeat previous input.
536
537
537 If given an argument, repeats the previous command which starts with
538 If given an argument, repeats the previous command which starts with
538 the same string, otherwise it just repeats the previous input.
539 the same string, otherwise it just repeats the previous input.
539
540
540 Shell escaped commands (with ! as first character) are not recognized
541 Shell escaped commands (with ! as first character) are not recognized
541 by this system, only pure python code and magic commands.
542 by this system, only pure python code and magic commands.
542 """
543 """
543
544
544 start = parameter_s.strip()
545 start = parameter_s.strip()
545 esc_magic = self.shell.ESC_MAGIC
546 esc_magic = self.shell.ESC_MAGIC
546 # Identify magic commands even if automagic is on (which means
547 # Identify magic commands even if automagic is on (which means
547 # the in-memory version is different from that typed by the user).
548 # the in-memory version is different from that typed by the user).
548 if self.shell.rc.automagic:
549 if self.shell.rc.automagic:
549 start_magic = esc_magic+start
550 start_magic = esc_magic+start
550 else:
551 else:
551 start_magic = start
552 start_magic = start
552 # Look through the input history in reverse
553 # Look through the input history in reverse
553 for n in range(len(self.shell.input_hist)-2,0,-1):
554 for n in range(len(self.shell.input_hist)-2,0,-1):
554 input = self.shell.input_hist[n]
555 input = self.shell.input_hist[n]
555 # skip plain 'r' lines so we don't recurse to infinity
556 # skip plain 'r' lines so we don't recurse to infinity
556 if input != 'ipmagic("r")\n' and \
557 if input != 'ipmagic("r")\n' and \
557 (input.startswith(start) or input.startswith(start_magic)):
558 (input.startswith(start) or input.startswith(start_magic)):
558 #print 'match',`input` # dbg
559 #print 'match',`input` # dbg
559 print 'Executing:',input,
560 print 'Executing:',input,
560 self.shell.runlines(input)
561 self.shell.runlines(input)
561 return
562 return
562 print 'No previous input matching `%s` found.' % start
563 print 'No previous input matching `%s` found.' % start
563
564
564 def magic_page(self, parameter_s=''):
565 def magic_page(self, parameter_s=''):
565 """Pretty print the object and display it through a pager.
566 """Pretty print the object and display it through a pager.
566
567
567 If no parameter is given, use _ (last output)."""
568 If no parameter is given, use _ (last output)."""
568 # After a function contributed by Olivier Aubert, slightly modified.
569 # After a function contributed by Olivier Aubert, slightly modified.
569
570
570 oname = parameter_s and parameter_s or '_'
571 oname = parameter_s and parameter_s or '_'
571 info = self._ofind(oname)
572 info = self._ofind(oname)
572 if info['found']:
573 if info['found']:
573 page(pformat(info['obj']))
574 page(pformat(info['obj']))
574 else:
575 else:
575 print 'Object `%s` not found' % oname
576 print 'Object `%s` not found' % oname
576
577
577 def magic_profile(self, parameter_s=''):
578 def magic_profile(self, parameter_s=''):
578 """Print your currently active IPyhton profile."""
579 """Print your currently active IPyhton profile."""
579 if self.shell.rc.profile:
580 if self.shell.rc.profile:
580 printpl('Current IPython profile: $self.shell.rc.profile.')
581 printpl('Current IPython profile: $self.shell.rc.profile.')
581 else:
582 else:
582 print 'No profile active.'
583 print 'No profile active.'
583
584
584 def _inspect(self,meth,oname,**kw):
585 def _inspect(self,meth,oname,**kw):
585 """Generic interface to the inspector system.
586 """Generic interface to the inspector system.
586
587
587 This function is meant to be called by pdef, pdoc & friends."""
588 This function is meant to be called by pdef, pdoc & friends."""
588
589
589 oname = oname.strip()
590 oname = oname.strip()
590 info = Struct(self._ofind(oname))
591 info = Struct(self._ofind(oname))
591 if info.found:
592 if info.found:
592 pmethod = getattr(self.shell.inspector,meth)
593 pmethod = getattr(self.shell.inspector,meth)
593 formatter = info.ismagic and self.format_screen or None
594 formatter = info.ismagic and self.format_screen or None
594 if meth == 'pdoc':
595 if meth == 'pdoc':
595 pmethod(info.obj,oname,formatter)
596 pmethod(info.obj,oname,formatter)
596 elif meth == 'pinfo':
597 elif meth == 'pinfo':
597 pmethod(info.obj,oname,formatter,info,**kw)
598 pmethod(info.obj,oname,formatter,info,**kw)
598 else:
599 else:
599 pmethod(info.obj,oname)
600 pmethod(info.obj,oname)
600 else:
601 else:
601 print 'Object `%s` not found.' % oname
602 print 'Object `%s` not found.' % oname
602 return 'not found' # so callers can take other action
603 return 'not found' # so callers can take other action
603
604
604 def magic_pdef(self, parameter_s=''):
605 def magic_pdef(self, parameter_s=''):
605 """Print the definition header for any callable object.
606 """Print the definition header for any callable object.
606
607
607 If the object is a class, print the constructor information."""
608 If the object is a class, print the constructor information."""
608 self._inspect('pdef',parameter_s)
609 self._inspect('pdef',parameter_s)
609
610
610 def magic_pdoc(self, parameter_s=''):
611 def magic_pdoc(self, parameter_s=''):
611 """Print the docstring for an object.
612 """Print the docstring for an object.
612
613
613 If the given object is a class, it will print both the class and the
614 If the given object is a class, it will print both the class and the
614 constructor docstrings."""
615 constructor docstrings."""
615 self._inspect('pdoc',parameter_s)
616 self._inspect('pdoc',parameter_s)
616
617
617 def magic_psource(self, parameter_s=''):
618 def magic_psource(self, parameter_s=''):
618 """Print (or run through pager) the source code for an object."""
619 """Print (or run through pager) the source code for an object."""
619 self._inspect('psource',parameter_s)
620 self._inspect('psource',parameter_s)
620
621
621 def magic_pfile(self, parameter_s=''):
622 def magic_pfile(self, parameter_s=''):
622 """Print (or run through pager) the file where an object is defined.
623 """Print (or run through pager) the file where an object is defined.
623
624
624 The file opens at the line where the object definition begins. IPython
625 The file opens at the line where the object definition begins. IPython
625 will honor the environment variable PAGER if set, and otherwise will
626 will honor the environment variable PAGER if set, and otherwise will
626 do its best to print the file in a convenient form.
627 do its best to print the file in a convenient form.
627
628
628 If the given argument is not an object currently defined, IPython will
629 If the given argument is not an object currently defined, IPython will
629 try to interpret it as a filename (automatically adding a .py extension
630 try to interpret it as a filename (automatically adding a .py extension
630 if needed). You can thus use %pfile as a syntax highlighting code
631 if needed). You can thus use %pfile as a syntax highlighting code
631 viewer."""
632 viewer."""
632
633
633 # first interpret argument as an object name
634 # first interpret argument as an object name
634 out = self._inspect('pfile',parameter_s)
635 out = self._inspect('pfile',parameter_s)
635 # if not, try the input as a filename
636 # if not, try the input as a filename
636 if out == 'not found':
637 if out == 'not found':
637 try:
638 try:
638 filename = get_py_filename(parameter_s)
639 filename = get_py_filename(parameter_s)
639 except IOError,msg:
640 except IOError,msg:
640 print msg
641 print msg
641 return
642 return
642 page(self.shell.inspector.format(file(filename).read()))
643 page(self.shell.inspector.format(file(filename).read()))
643
644
644 def magic_pinfo(self, parameter_s=''):
645 def magic_pinfo(self, parameter_s=''):
645 """Provide detailed information about an object.
646 """Provide detailed information about an object.
646
647
647 '%pinfo object' is just a synonym for object? or ?object."""
648 '%pinfo object' is just a synonym for object? or ?object."""
648
649
649 #print 'pinfo par: <%s>' % parameter_s # dbg
650 #print 'pinfo par: <%s>' % parameter_s # dbg
650
651
651 # detail_level: 0 -> obj? , 1 -> obj??
652 # detail_level: 0 -> obj? , 1 -> obj??
652 detail_level = 0
653 detail_level = 0
653 # We need to detect if we got called as 'pinfo pinfo foo', which can
654 # We need to detect if we got called as 'pinfo pinfo foo', which can
654 # happen if the user types 'pinfo foo?' at the cmd line.
655 # happen if the user types 'pinfo foo?' at the cmd line.
655 pinfo,qmark1,oname,qmark2 = \
656 pinfo,qmark1,oname,qmark2 = \
656 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
657 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
657 if pinfo or qmark1 or qmark2:
658 if pinfo or qmark1 or qmark2:
658 detail_level = 1
659 detail_level = 1
659 if "*" in oname:
660 if "*" in oname:
660 self.magic_psearch(oname)
661 self.magic_psearch(oname)
661 else:
662 else:
662 self._inspect('pinfo',oname,detail_level=detail_level)
663 self._inspect('pinfo',oname,detail_level=detail_level)
663
664
664 def magic_psearch(self, parameter_s=''):
665 def magic_psearch(self, parameter_s=''):
665 """Search for object in namespaces by wildcard.
666 """Search for object in namespaces by wildcard.
666
667
667 %psearch [options] PATTERN [OBJECT TYPE]
668 %psearch [options] PATTERN [OBJECT TYPE]
668
669
669 Note: ? can be used as a synonym for %psearch, at the beginning or at
670 Note: ? can be used as a synonym for %psearch, at the beginning or at
670 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
671 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
671 rest of the command line must be unchanged (options come first), so
672 rest of the command line must be unchanged (options come first), so
672 for example the following forms are equivalent
673 for example the following forms are equivalent
673
674
674 %psearch -i a* function
675 %psearch -i a* function
675 -i a* function?
676 -i a* function?
676 ?-i a* function
677 ?-i a* function
677
678
678 Arguments:
679 Arguments:
679
680
680 PATTERN
681 PATTERN
681
682
682 where PATTERN is a string containing * as a wildcard similar to its
683 where PATTERN is a string containing * as a wildcard similar to its
683 use in a shell. The pattern is matched in all namespaces on the
684 use in a shell. The pattern is matched in all namespaces on the
684 search path. By default objects starting with a single _ are not
685 search path. By default objects starting with a single _ are not
685 matched, many IPython generated objects have a single
686 matched, many IPython generated objects have a single
686 underscore. The default is case insensitive matching. Matching is
687 underscore. The default is case insensitive matching. Matching is
687 also done on the attributes of objects and not only on the objects
688 also done on the attributes of objects and not only on the objects
688 in a module.
689 in a module.
689
690
690 [OBJECT TYPE]
691 [OBJECT TYPE]
691
692
692 Is the name of a python type from the types module. The name is
693 Is the name of a python type from the types module. The name is
693 given in lowercase without the ending type, ex. StringType is
694 given in lowercase without the ending type, ex. StringType is
694 written string. By adding a type here only objects matching the
695 written string. By adding a type here only objects matching the
695 given type are matched. Using all here makes the pattern match all
696 given type are matched. Using all here makes the pattern match all
696 types (this is the default).
697 types (this is the default).
697
698
698 Options:
699 Options:
699
700
700 -a: makes the pattern match even objects whose names start with a
701 -a: makes the pattern match even objects whose names start with a
701 single underscore. These names are normally ommitted from the
702 single underscore. These names are normally ommitted from the
702 search.
703 search.
703
704
704 -i/-c: make the pattern case insensitive/sensitive. If neither of
705 -i/-c: make the pattern case insensitive/sensitive. If neither of
705 these options is given, the default is read from your ipythonrc
706 these options is given, the default is read from your ipythonrc
706 file. The option name which sets this value is
707 file. The option name which sets this value is
707 'wildcards_case_sensitive'. If this option is not specified in your
708 'wildcards_case_sensitive'. If this option is not specified in your
708 ipythonrc file, IPython's internal default is to do a case sensitive
709 ipythonrc file, IPython's internal default is to do a case sensitive
709 search.
710 search.
710
711
711 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
712 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
712 specifiy can be searched in any of the following namespaces:
713 specifiy can be searched in any of the following namespaces:
713 'builtin', 'user', 'user_global','internal', 'alias', where
714 'builtin', 'user', 'user_global','internal', 'alias', where
714 'builtin' and 'user' are the search defaults. Note that you should
715 'builtin' and 'user' are the search defaults. Note that you should
715 not use quotes when specifying namespaces.
716 not use quotes when specifying namespaces.
716
717
717 'Builtin' contains the python module builtin, 'user' contains all
718 'Builtin' contains the python module builtin, 'user' contains all
718 user data, 'alias' only contain the shell aliases and no python
719 user data, 'alias' only contain the shell aliases and no python
719 objects, 'internal' contains objects used by IPython. The
720 objects, 'internal' contains objects used by IPython. The
720 'user_global' namespace is only used by embedded IPython instances,
721 'user_global' namespace is only used by embedded IPython instances,
721 and it contains module-level globals. You can add namespaces to the
722 and it contains module-level globals. You can add namespaces to the
722 search with -s or exclude them with -e (these options can be given
723 search with -s or exclude them with -e (these options can be given
723 more than once).
724 more than once).
724
725
725 Examples:
726 Examples:
726
727
727 %psearch a* -> objects beginning with an a
728 %psearch a* -> objects beginning with an a
728 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
729 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
729 %psearch a* function -> all functions beginning with an a
730 %psearch a* function -> all functions beginning with an a
730 %psearch re.e* -> objects beginning with an e in module re
731 %psearch re.e* -> objects beginning with an e in module re
731 %psearch r*.e* -> objects that start with e in modules starting in r
732 %psearch r*.e* -> objects that start with e in modules starting in r
732 %psearch r*.* string -> all strings in modules beginning with r
733 %psearch r*.* string -> all strings in modules beginning with r
733
734
734 Case sensitve search:
735 Case sensitve search:
735
736
736 %psearch -c a* list all object beginning with lower case a
737 %psearch -c a* list all object beginning with lower case a
737
738
738 Show objects beginning with a single _:
739 Show objects beginning with a single _:
739
740
740 %psearch -a _* list objects beginning with a single underscore"""
741 %psearch -a _* list objects beginning with a single underscore"""
741
742
742 # default namespaces to be searched
743 # default namespaces to be searched
743 def_search = ['user','builtin']
744 def_search = ['user','builtin']
744
745
745 # Process options/args
746 # Process options/args
746 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
747 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
747 opt = opts.get
748 opt = opts.get
748 shell = self.shell
749 shell = self.shell
749 psearch = shell.inspector.psearch
750 psearch = shell.inspector.psearch
750
751
751 # select case options
752 # select case options
752 if opts.has_key('i'):
753 if opts.has_key('i'):
753 ignore_case = True
754 ignore_case = True
754 elif opts.has_key('c'):
755 elif opts.has_key('c'):
755 ignore_case = False
756 ignore_case = False
756 else:
757 else:
757 ignore_case = not shell.rc.wildcards_case_sensitive
758 ignore_case = not shell.rc.wildcards_case_sensitive
758
759
759 # Build list of namespaces to search from user options
760 # Build list of namespaces to search from user options
760 def_search.extend(opt('s',[]))
761 def_search.extend(opt('s',[]))
761 ns_exclude = ns_exclude=opt('e',[])
762 ns_exclude = ns_exclude=opt('e',[])
762 ns_search = [nm for nm in def_search if nm not in ns_exclude]
763 ns_search = [nm for nm in def_search if nm not in ns_exclude]
763
764
764 # Call the actual search
765 # Call the actual search
765 try:
766 try:
766 psearch(args,shell.ns_table,ns_search,
767 psearch(args,shell.ns_table,ns_search,
767 show_all=opt('a'),ignore_case=ignore_case)
768 show_all=opt('a'),ignore_case=ignore_case)
768 except:
769 except:
769 shell.showtraceback()
770 shell.showtraceback()
770
771
771 def magic_who_ls(self, parameter_s=''):
772 def magic_who_ls(self, parameter_s=''):
772 """Return a sorted list of all interactive variables.
773 """Return a sorted list of all interactive variables.
773
774
774 If arguments are given, only variables of types matching these
775 If arguments are given, only variables of types matching these
775 arguments are returned."""
776 arguments are returned."""
776
777
777 user_ns = self.shell.user_ns
778 user_ns = self.shell.user_ns
778 internal_ns = self.shell.internal_ns
779 internal_ns = self.shell.internal_ns
779 user_config_ns = self.shell.user_config_ns
780 user_config_ns = self.shell.user_config_ns
780 out = []
781 out = []
781 typelist = parameter_s.split()
782 typelist = parameter_s.split()
782
783
783 for i in user_ns:
784 for i in user_ns:
784 if not (i.startswith('_') or i.startswith('_i')) \
785 if not (i.startswith('_') or i.startswith('_i')) \
785 and not (i in internal_ns or i in user_config_ns):
786 and not (i in internal_ns or i in user_config_ns):
786 if typelist:
787 if typelist:
787 if type(user_ns[i]).__name__ in typelist:
788 if type(user_ns[i]).__name__ in typelist:
788 out.append(i)
789 out.append(i)
789 else:
790 else:
790 out.append(i)
791 out.append(i)
791 out.sort()
792 out.sort()
792 return out
793 return out
793
794
794 def magic_who(self, parameter_s=''):
795 def magic_who(self, parameter_s=''):
795 """Print all interactive variables, with some minimal formatting.
796 """Print all interactive variables, with some minimal formatting.
796
797
797 If any arguments are given, only variables whose type matches one of
798 If any arguments are given, only variables whose type matches one of
798 these are printed. For example:
799 these are printed. For example:
799
800
800 %who function str
801 %who function str
801
802
802 will only list functions and strings, excluding all other types of
803 will only list functions and strings, excluding all other types of
803 variables. To find the proper type names, simply use type(var) at a
804 variables. To find the proper type names, simply use type(var) at a
804 command line to see how python prints type names. For example:
805 command line to see how python prints type names. For example:
805
806
806 In [1]: type('hello')\\
807 In [1]: type('hello')\\
807 Out[1]: <type 'str'>
808 Out[1]: <type 'str'>
808
809
809 indicates that the type name for strings is 'str'.
810 indicates that the type name for strings is 'str'.
810
811
811 %who always excludes executed names loaded through your configuration
812 %who always excludes executed names loaded through your configuration
812 file and things which are internal to IPython.
813 file and things which are internal to IPython.
813
814
814 This is deliberate, as typically you may load many modules and the
815 This is deliberate, as typically you may load many modules and the
815 purpose of %who is to show you only what you've manually defined."""
816 purpose of %who is to show you only what you've manually defined."""
816
817
817 varlist = self.magic_who_ls(parameter_s)
818 varlist = self.magic_who_ls(parameter_s)
818 if not varlist:
819 if not varlist:
819 print 'Interactive namespace is empty.'
820 print 'Interactive namespace is empty.'
820 return
821 return
821
822
822 # if we have variables, move on...
823 # if we have variables, move on...
823
824
824 # stupid flushing problem: when prompts have no separators, stdout is
825 # stupid flushing problem: when prompts have no separators, stdout is
825 # getting lost. I'm starting to think this is a python bug. I'm having
826 # getting lost. I'm starting to think this is a python bug. I'm having
826 # to force a flush with a print because even a sys.stdout.flush
827 # to force a flush with a print because even a sys.stdout.flush
827 # doesn't seem to do anything!
828 # doesn't seem to do anything!
828
829
829 count = 0
830 count = 0
830 for i in varlist:
831 for i in varlist:
831 print i+'\t',
832 print i+'\t',
832 count += 1
833 count += 1
833 if count > 8:
834 if count > 8:
834 count = 0
835 count = 0
835 print
836 print
836 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
837 sys.stdout.flush() # FIXME. Why the hell isn't this flushing???
837
838
838 print # well, this does force a flush at the expense of an extra \n
839 print # well, this does force a flush at the expense of an extra \n
839
840
840 def magic_whos(self, parameter_s=''):
841 def magic_whos(self, parameter_s=''):
841 """Like %who, but gives some extra information about each variable.
842 """Like %who, but gives some extra information about each variable.
842
843
843 The same type filtering of %who can be applied here.
844 The same type filtering of %who can be applied here.
844
845
845 For all variables, the type is printed. Additionally it prints:
846 For all variables, the type is printed. Additionally it prints:
846
847
847 - For {},[],(): their length.
848 - For {},[],(): their length.
848
849
849 - For Numeric arrays, a summary with shape, number of elements,
850 - For Numeric arrays, a summary with shape, number of elements,
850 typecode and size in memory.
851 typecode and size in memory.
851
852
852 - Everything else: a string representation, snipping their middle if
853 - Everything else: a string representation, snipping their middle if
853 too long."""
854 too long."""
854
855
855 varnames = self.magic_who_ls(parameter_s)
856 varnames = self.magic_who_ls(parameter_s)
856 if not varnames:
857 if not varnames:
857 print 'Interactive namespace is empty.'
858 print 'Interactive namespace is empty.'
858 return
859 return
859
860
860 # if we have variables, move on...
861 # if we have variables, move on...
861
862
862 # for these types, show len() instead of data:
863 # for these types, show len() instead of data:
863 seq_types = [types.DictType,types.ListType,types.TupleType]
864 seq_types = [types.DictType,types.ListType,types.TupleType]
864
865
865 # for Numeric arrays, display summary info
866 # for Numeric arrays, display summary info
866 try:
867 try:
867 import Numeric
868 import Numeric
868 except ImportError:
869 except ImportError:
869 array_type = None
870 array_type = None
870 else:
871 else:
871 array_type = Numeric.ArrayType.__name__
872 array_type = Numeric.ArrayType.__name__
872
873
873 # Find all variable names and types so we can figure out column sizes
874 # Find all variable names and types so we can figure out column sizes
874 get_vars = lambda i: self.shell.user_ns[i]
875 get_vars = lambda i: self.shell.user_ns[i]
875 type_name = lambda v: type(v).__name__
876 type_name = lambda v: type(v).__name__
876 varlist = map(get_vars,varnames)
877 varlist = map(get_vars,varnames)
877
878
878 typelist = []
879 typelist = []
879 for vv in varlist:
880 for vv in varlist:
880 tt = type_name(vv)
881 tt = type_name(vv)
881 if tt=='instance':
882 if tt=='instance':
882 typelist.append(str(vv.__class__))
883 typelist.append(str(vv.__class__))
883 else:
884 else:
884 typelist.append(tt)
885 typelist.append(tt)
885
886
886 # column labels and # of spaces as separator
887 # column labels and # of spaces as separator
887 varlabel = 'Variable'
888 varlabel = 'Variable'
888 typelabel = 'Type'
889 typelabel = 'Type'
889 datalabel = 'Data/Info'
890 datalabel = 'Data/Info'
890 colsep = 3
891 colsep = 3
891 # variable format strings
892 # variable format strings
892 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
893 vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)"
893 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
894 vfmt_short = '$vstr[:25]<...>$vstr[-25:]'
894 aformat = "%s: %s elems, type `%s`, %s bytes"
895 aformat = "%s: %s elems, type `%s`, %s bytes"
895 # find the size of the columns to format the output nicely
896 # find the size of the columns to format the output nicely
896 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
897 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
897 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
898 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
898 # table header
899 # table header
899 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
900 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
900 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
901 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
901 # and the table itself
902 # and the table itself
902 kb = 1024
903 kb = 1024
903 Mb = 1048576 # kb**2
904 Mb = 1048576 # kb**2
904 for vname,var,vtype in zip(varnames,varlist,typelist):
905 for vname,var,vtype in zip(varnames,varlist,typelist):
905 print itpl(vformat),
906 print itpl(vformat),
906 if vtype in seq_types:
907 if vtype in seq_types:
907 print len(var)
908 print len(var)
908 elif vtype==array_type:
909 elif vtype==array_type:
909 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
910 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
910 vsize = Numeric.size(var)
911 vsize = Numeric.size(var)
911 vbytes = vsize*var.itemsize()
912 vbytes = vsize*var.itemsize()
912 if vbytes < 100000:
913 if vbytes < 100000:
913 print aformat % (vshape,vsize,var.typecode(),vbytes)
914 print aformat % (vshape,vsize,var.typecode(),vbytes)
914 else:
915 else:
915 print aformat % (vshape,vsize,var.typecode(),vbytes),
916 print aformat % (vshape,vsize,var.typecode(),vbytes),
916 if vbytes < Mb:
917 if vbytes < Mb:
917 print '(%s kb)' % (vbytes/kb,)
918 print '(%s kb)' % (vbytes/kb,)
918 else:
919 else:
919 print '(%s Mb)' % (vbytes/Mb,)
920 print '(%s Mb)' % (vbytes/Mb,)
920 else:
921 else:
921 vstr = str(var).replace('\n','\\n')
922 vstr = str(var).replace('\n','\\n')
922 if len(vstr) < 50:
923 if len(vstr) < 50:
923 print vstr
924 print vstr
924 else:
925 else:
925 printpl(vfmt_short)
926 printpl(vfmt_short)
926
927
927 def magic_reset(self, parameter_s=''):
928 def magic_reset(self, parameter_s=''):
928 """Resets the namespace by removing all names defined by the user.
929 """Resets the namespace by removing all names defined by the user.
929
930
930 Input/Output history are left around in case you need them."""
931 Input/Output history are left around in case you need them."""
931
932
932 ans = raw_input(
933 ans = raw_input(
933 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
934 "Once deleted, variables cannot be recovered. Proceed (y/n)? ")
934 if not ans.lower() == 'y':
935 if not ans.lower() == 'y':
935 print 'Nothing done.'
936 print 'Nothing done.'
936 return
937 return
937 user_ns = self.shell.user_ns
938 user_ns = self.shell.user_ns
938 for i in self.magic_who_ls():
939 for i in self.magic_who_ls():
939 del(user_ns[i])
940 del(user_ns[i])
940
941
941 def magic_config(self,parameter_s=''):
942 def magic_config(self,parameter_s=''):
942 """Show IPython's internal configuration."""
943 """Show IPython's internal configuration."""
943
944
944 page('Current configuration structure:\n'+
945 page('Current configuration structure:\n'+
945 pformat(self.shell.rc.dict()))
946 pformat(self.shell.rc.dict()))
946
947
947 def magic_logstart(self,parameter_s=''):
948 def magic_logstart(self,parameter_s=''):
948 """Start logging anywhere in a session.
949 """Start logging anywhere in a session.
949
950
950 %logstart [-o|-t] [log_name [log_mode]]
951 %logstart [-o|-t] [log_name [log_mode]]
951
952
952 If no name is given, it defaults to a file named 'ipython_log.py' in your
953 If no name is given, it defaults to a file named 'ipython_log.py' in your
953 current directory, in 'rotate' mode (see below).
954 current directory, in 'rotate' mode (see below).
954
955
955 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
956 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
956 history up to that point and then continues logging.
957 history up to that point and then continues logging.
957
958
958 %logstart takes a second optional parameter: logging mode. This can be one
959 %logstart takes a second optional parameter: logging mode. This can be one
959 of (note that the modes are given unquoted):\\
960 of (note that the modes are given unquoted):\\
960 append: well, that says it.\\
961 append: well, that says it.\\
961 backup: rename (if exists) to name~ and start name.\\
962 backup: rename (if exists) to name~ and start name.\\
962 global: single logfile in your home dir, appended to.\\
963 global: single logfile in your home dir, appended to.\\
963 over : overwrite existing log.\\
964 over : overwrite existing log.\\
964 rotate: create rotating logs name.1~, name.2~, etc.
965 rotate: create rotating logs name.1~, name.2~, etc.
965
966
966 Options:
967 Options:
967
968
968 -o: log also IPython's output. In this mode, all commands which
969 -o: log also IPython's output. In this mode, all commands which
969 generate an Out[NN] prompt are recorded to the logfile, right after
970 generate an Out[NN] prompt are recorded to the logfile, right after
970 their corresponding input line. The output lines are always
971 their corresponding input line. The output lines are always
971 prepended with a '#[Out]# ' marker, so that the log remains valid
972 prepended with a '#[Out]# ' marker, so that the log remains valid
972 Python code.
973 Python code.
973
974
974 Since this marker is always the same, filtering only the output from
975 Since this marker is always the same, filtering only the output from
975 a log is very easy, using for example a simple awk call:
976 a log is very easy, using for example a simple awk call:
976
977
977 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
978 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
978
979
979 -t: put timestamps before each input line logged (these are put in
980 -t: put timestamps before each input line logged (these are put in
980 comments)."""
981 comments)."""
981
982
982 opts,par = self.parse_options(parameter_s,'ot')
983 opts,par = self.parse_options(parameter_s,'ot')
983 log_output = 'o' in opts
984 log_output = 'o' in opts
984 timestamp = 't' in opts
985 timestamp = 't' in opts
985
986
986 rc = self.shell.rc
987 rc = self.shell.rc
987 logger = self.shell.logger
988 logger = self.shell.logger
988
989
989 # if no args are given, the defaults set in the logger constructor by
990 # if no args are given, the defaults set in the logger constructor by
990 # ipytohn remain valid
991 # ipytohn remain valid
991 if par:
992 if par:
992 try:
993 try:
993 logfname,logmode = par.split()
994 logfname,logmode = par.split()
994 except:
995 except:
995 logfname = par
996 logfname = par
996 logmode = 'backup'
997 logmode = 'backup'
997 else:
998 else:
998 logfname = logger.logfname
999 logfname = logger.logfname
999 logmode = logger.logmode
1000 logmode = logger.logmode
1000 # put logfname into rc struct as if it had been called on the command
1001 # put logfname into rc struct as if it had been called on the command
1001 # line, so it ends up saved in the log header Save it in case we need
1002 # line, so it ends up saved in the log header Save it in case we need
1002 # to restore it...
1003 # to restore it...
1003 old_logfile = rc.opts.get('logfile','')
1004 old_logfile = rc.opts.get('logfile','')
1004 if logfname:
1005 if logfname:
1005 logfname = os.path.expanduser(logfname)
1006 logfname = os.path.expanduser(logfname)
1006 rc.opts.logfile = logfname
1007 rc.opts.logfile = logfname
1007 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1008 loghead = self.shell.loghead_tpl % (rc.opts,rc.args)
1008 try:
1009 try:
1009 started = logger.logstart(logfname,loghead,logmode,
1010 started = logger.logstart(logfname,loghead,logmode,
1010 log_output,timestamp)
1011 log_output,timestamp)
1011 except:
1012 except:
1012 rc.opts.logfile = old_logfile
1013 rc.opts.logfile = old_logfile
1013 warn("Couldn't start log: %s" % sys.exc_info()[1])
1014 warn("Couldn't start log: %s" % sys.exc_info()[1])
1014 else:
1015 else:
1015 # log input history up to this point, optionally interleaving
1016 # log input history up to this point, optionally interleaving
1016 # output if requested
1017 # output if requested
1017
1018
1018 if timestamp:
1019 if timestamp:
1019 # disable timestamping for the previous history, since we've
1020 # disable timestamping for the previous history, since we've
1020 # lost those already (no time machine here).
1021 # lost those already (no time machine here).
1021 logger.timestamp = False
1022 logger.timestamp = False
1022 if log_output:
1023 if log_output:
1023 log_write = logger.log_write
1024 log_write = logger.log_write
1024 input_hist = self.shell.input_hist
1025 input_hist = self.shell.input_hist
1025 output_hist = self.shell.output_hist
1026 output_hist = self.shell.output_hist
1026 for n in range(1,len(input_hist)-1):
1027 for n in range(1,len(input_hist)-1):
1027 log_write(input_hist[n].rstrip())
1028 log_write(input_hist[n].rstrip())
1028 if n in output_hist:
1029 if n in output_hist:
1029 log_write(repr(output_hist[n]),'output')
1030 log_write(repr(output_hist[n]),'output')
1030 else:
1031 else:
1031 logger.log_write(self.shell.input_hist[1:])
1032 logger.log_write(self.shell.input_hist[1:])
1032 if timestamp:
1033 if timestamp:
1033 # re-enable timestamping
1034 # re-enable timestamping
1034 logger.timestamp = True
1035 logger.timestamp = True
1035
1036
1036 print ('Activating auto-logging. '
1037 print ('Activating auto-logging. '
1037 'Current session state plus future input saved.')
1038 'Current session state plus future input saved.')
1038 logger.logstate()
1039 logger.logstate()
1039
1040
1040 def magic_logoff(self,parameter_s=''):
1041 def magic_logoff(self,parameter_s=''):
1041 """Temporarily stop logging.
1042 """Temporarily stop logging.
1042
1043
1043 You must have previously started logging."""
1044 You must have previously started logging."""
1044 self.shell.logger.switch_log(0)
1045 self.shell.logger.switch_log(0)
1045
1046
1046 def magic_logon(self,parameter_s=''):
1047 def magic_logon(self,parameter_s=''):
1047 """Restart logging.
1048 """Restart logging.
1048
1049
1049 This function is for restarting logging which you've temporarily
1050 This function is for restarting logging which you've temporarily
1050 stopped with %logoff. For starting logging for the first time, you
1051 stopped with %logoff. For starting logging for the first time, you
1051 must use the %logstart function, which allows you to specify an
1052 must use the %logstart function, which allows you to specify an
1052 optional log filename."""
1053 optional log filename."""
1053
1054
1054 self.shell.logger.switch_log(1)
1055 self.shell.logger.switch_log(1)
1055
1056
1056 def magic_logstate(self,parameter_s=''):
1057 def magic_logstate(self,parameter_s=''):
1057 """Print the status of the logging system."""
1058 """Print the status of the logging system."""
1058
1059
1059 self.shell.logger.logstate()
1060 self.shell.logger.logstate()
1060
1061
1061 def magic_pdb(self, parameter_s=''):
1062 def magic_pdb(self, parameter_s=''):
1062 """Control the calling of the pdb interactive debugger.
1063 """Control the calling of the pdb interactive debugger.
1063
1064
1064 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1065 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1065 argument it works as a toggle.
1066 argument it works as a toggle.
1066
1067
1067 When an exception is triggered, IPython can optionally call the
1068 When an exception is triggered, IPython can optionally call the
1068 interactive pdb debugger after the traceback printout. %pdb toggles
1069 interactive pdb debugger after the traceback printout. %pdb toggles
1069 this feature on and off."""
1070 this feature on and off."""
1070
1071
1071 par = parameter_s.strip().lower()
1072 par = parameter_s.strip().lower()
1072
1073
1073 if par:
1074 if par:
1074 try:
1075 try:
1075 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1076 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
1076 except KeyError:
1077 except KeyError:
1077 print ('Incorrect argument. Use on/1, off/0, '
1078 print ('Incorrect argument. Use on/1, off/0, '
1078 'or nothing for a toggle.')
1079 'or nothing for a toggle.')
1079 return
1080 return
1080 else:
1081 else:
1081 # toggle
1082 # toggle
1082 new_pdb = not self.shell.InteractiveTB.call_pdb
1083 new_pdb = not self.shell.InteractiveTB.call_pdb
1083
1084
1084 # set on the shell
1085 # set on the shell
1085 self.shell.call_pdb = new_pdb
1086 self.shell.call_pdb = new_pdb
1086 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1087 print 'Automatic pdb calling has been turned',on_off(new_pdb)
1087
1088
1088 def magic_prun(self, parameter_s ='',user_mode=1,
1089 def magic_prun(self, parameter_s ='',user_mode=1,
1089 opts=None,arg_lst=None,prog_ns=None):
1090 opts=None,arg_lst=None,prog_ns=None):
1090
1091
1091 """Run a statement through the python code profiler.
1092 """Run a statement through the python code profiler.
1092
1093
1093 Usage:\\
1094 Usage:\\
1094 %prun [options] statement
1095 %prun [options] statement
1095
1096
1096 The given statement (which doesn't require quote marks) is run via the
1097 The given statement (which doesn't require quote marks) is run via the
1097 python profiler in a manner similar to the profile.run() function.
1098 python profiler in a manner similar to the profile.run() function.
1098 Namespaces are internally managed to work correctly; profile.run
1099 Namespaces are internally managed to work correctly; profile.run
1099 cannot be used in IPython because it makes certain assumptions about
1100 cannot be used in IPython because it makes certain assumptions about
1100 namespaces which do not hold under IPython.
1101 namespaces which do not hold under IPython.
1101
1102
1102 Options:
1103 Options:
1103
1104
1104 -l <limit>: you can place restrictions on what or how much of the
1105 -l <limit>: you can place restrictions on what or how much of the
1105 profile gets printed. The limit value can be:
1106 profile gets printed. The limit value can be:
1106
1107
1107 * A string: only information for function names containing this string
1108 * A string: only information for function names containing this string
1108 is printed.
1109 is printed.
1109
1110
1110 * An integer: only these many lines are printed.
1111 * An integer: only these many lines are printed.
1111
1112
1112 * A float (between 0 and 1): this fraction of the report is printed
1113 * A float (between 0 and 1): this fraction of the report is printed
1113 (for example, use a limit of 0.4 to see the topmost 40% only).
1114 (for example, use a limit of 0.4 to see the topmost 40% only).
1114
1115
1115 You can combine several limits with repeated use of the option. For
1116 You can combine several limits with repeated use of the option. For
1116 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1117 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1117 information about class constructors.
1118 information about class constructors.
1118
1119
1119 -r: return the pstats.Stats object generated by the profiling. This
1120 -r: return the pstats.Stats object generated by the profiling. This
1120 object has all the information about the profile in it, and you can
1121 object has all the information about the profile in it, and you can
1121 later use it for further analysis or in other functions.
1122 later use it for further analysis or in other functions.
1122
1123
1123 Since magic functions have a particular form of calling which prevents
1124 Since magic functions have a particular form of calling which prevents
1124 you from writing something like:\\
1125 you from writing something like:\\
1125 In [1]: p = %prun -r print 4 # invalid!\\
1126 In [1]: p = %prun -r print 4 # invalid!\\
1126 you must instead use IPython's automatic variables to assign this:\\
1127 you must instead use IPython's automatic variables to assign this:\\
1127 In [1]: %prun -r print 4 \\
1128 In [1]: %prun -r print 4 \\
1128 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1129 Out[1]: <pstats.Stats instance at 0x8222cec>\\
1129 In [2]: stats = _
1130 In [2]: stats = _
1130
1131
1131 If you really need to assign this value via an explicit function call,
1132 If you really need to assign this value via an explicit function call,
1132 you can always tap directly into the true name of the magic function
1133 you can always tap directly into the true name of the magic function
1133 by using the ipmagic function (which IPython automatically adds to the
1134 by using the ipmagic function (which IPython automatically adds to the
1134 builtins):\\
1135 builtins):\\
1135 In [3]: stats = ipmagic('prun','-r print 4')
1136 In [3]: stats = ipmagic('prun','-r print 4')
1136
1137
1137 You can type ipmagic? for more details on ipmagic.
1138 You can type ipmagic? for more details on ipmagic.
1138
1139
1139 -s <key>: sort profile by given key. You can provide more than one key
1140 -s <key>: sort profile by given key. You can provide more than one key
1140 by using the option several times: '-s key1 -s key2 -s key3...'. The
1141 by using the option several times: '-s key1 -s key2 -s key3...'. The
1141 default sorting key is 'time'.
1142 default sorting key is 'time'.
1142
1143
1143 The following is copied verbatim from the profile documentation
1144 The following is copied verbatim from the profile documentation
1144 referenced below:
1145 referenced below:
1145
1146
1146 When more than one key is provided, additional keys are used as
1147 When more than one key is provided, additional keys are used as
1147 secondary criteria when the there is equality in all keys selected
1148 secondary criteria when the there is equality in all keys selected
1148 before them.
1149 before them.
1149
1150
1150 Abbreviations can be used for any key names, as long as the
1151 Abbreviations can be used for any key names, as long as the
1151 abbreviation is unambiguous. The following are the keys currently
1152 abbreviation is unambiguous. The following are the keys currently
1152 defined:
1153 defined:
1153
1154
1154 Valid Arg Meaning\\
1155 Valid Arg Meaning\\
1155 "calls" call count\\
1156 "calls" call count\\
1156 "cumulative" cumulative time\\
1157 "cumulative" cumulative time\\
1157 "file" file name\\
1158 "file" file name\\
1158 "module" file name\\
1159 "module" file name\\
1159 "pcalls" primitive call count\\
1160 "pcalls" primitive call count\\
1160 "line" line number\\
1161 "line" line number\\
1161 "name" function name\\
1162 "name" function name\\
1162 "nfl" name/file/line\\
1163 "nfl" name/file/line\\
1163 "stdname" standard name\\
1164 "stdname" standard name\\
1164 "time" internal time
1165 "time" internal time
1165
1166
1166 Note that all sorts on statistics are in descending order (placing
1167 Note that all sorts on statistics are in descending order (placing
1167 most time consuming items first), where as name, file, and line number
1168 most time consuming items first), where as name, file, and line number
1168 searches are in ascending order (i.e., alphabetical). The subtle
1169 searches are in ascending order (i.e., alphabetical). The subtle
1169 distinction between "nfl" and "stdname" is that the standard name is a
1170 distinction between "nfl" and "stdname" is that the standard name is a
1170 sort of the name as printed, which means that the embedded line
1171 sort of the name as printed, which means that the embedded line
1171 numbers get compared in an odd way. For example, lines 3, 20, and 40
1172 numbers get compared in an odd way. For example, lines 3, 20, and 40
1172 would (if the file names were the same) appear in the string order
1173 would (if the file names were the same) appear in the string order
1173 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1174 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1174 line numbers. In fact, sort_stats("nfl") is the same as
1175 line numbers. In fact, sort_stats("nfl") is the same as
1175 sort_stats("name", "file", "line").
1176 sort_stats("name", "file", "line").
1176
1177
1177 -T <filename>: save profile results as shown on screen to a text
1178 -T <filename>: save profile results as shown on screen to a text
1178 file. The profile is still shown on screen.
1179 file. The profile is still shown on screen.
1179
1180
1180 -D <filename>: save (via dump_stats) profile statistics to given
1181 -D <filename>: save (via dump_stats) profile statistics to given
1181 filename. This data is in a format understod by the pstats module, and
1182 filename. This data is in a format understod by the pstats module, and
1182 is generated by a call to the dump_stats() method of profile
1183 is generated by a call to the dump_stats() method of profile
1183 objects. The profile is still shown on screen.
1184 objects. The profile is still shown on screen.
1184
1185
1185 If you want to run complete programs under the profiler's control, use
1186 If you want to run complete programs under the profiler's control, use
1186 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1187 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1187 contains profiler specific options as described here.
1188 contains profiler specific options as described here.
1188
1189
1189 You can read the complete documentation for the profile module with:\\
1190 You can read the complete documentation for the profile module with:\\
1190 In [1]: import profile; profile.help() """
1191 In [1]: import profile; profile.help() """
1191
1192
1192 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1193 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1193 # protect user quote marks
1194 # protect user quote marks
1194 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1195 parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'")
1195
1196
1196 if user_mode: # regular user call
1197 if user_mode: # regular user call
1197 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1198 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:',
1198 list_all=1)
1199 list_all=1)
1199 namespace = self.shell.user_ns
1200 namespace = self.shell.user_ns
1200 else: # called to run a program by %run -p
1201 else: # called to run a program by %run -p
1201 try:
1202 try:
1202 filename = get_py_filename(arg_lst[0])
1203 filename = get_py_filename(arg_lst[0])
1203 except IOError,msg:
1204 except IOError,msg:
1204 error(msg)
1205 error(msg)
1205 return
1206 return
1206
1207
1207 arg_str = 'execfile(filename,prog_ns)'
1208 arg_str = 'execfile(filename,prog_ns)'
1208 namespace = locals()
1209 namespace = locals()
1209
1210
1210 opts.merge(opts_def)
1211 opts.merge(opts_def)
1211
1212
1212 prof = profile.Profile()
1213 prof = profile.Profile()
1213 try:
1214 try:
1214 prof = prof.runctx(arg_str,namespace,namespace)
1215 prof = prof.runctx(arg_str,namespace,namespace)
1215 sys_exit = ''
1216 sys_exit = ''
1216 except SystemExit:
1217 except SystemExit:
1217 sys_exit = """*** SystemExit exception caught in code being profiled."""
1218 sys_exit = """*** SystemExit exception caught in code being profiled."""
1218
1219
1219 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1220 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1220
1221
1221 lims = opts.l
1222 lims = opts.l
1222 if lims:
1223 if lims:
1223 lims = [] # rebuild lims with ints/floats/strings
1224 lims = [] # rebuild lims with ints/floats/strings
1224 for lim in opts.l:
1225 for lim in opts.l:
1225 try:
1226 try:
1226 lims.append(int(lim))
1227 lims.append(int(lim))
1227 except ValueError:
1228 except ValueError:
1228 try:
1229 try:
1229 lims.append(float(lim))
1230 lims.append(float(lim))
1230 except ValueError:
1231 except ValueError:
1231 lims.append(lim)
1232 lims.append(lim)
1232
1233
1233 # trap output
1234 # trap output
1234 sys_stdout = sys.stdout
1235 sys_stdout = sys.stdout
1235 stdout_trap = StringIO()
1236 stdout_trap = StringIO()
1236 try:
1237 try:
1237 sys.stdout = stdout_trap
1238 sys.stdout = stdout_trap
1238 stats.print_stats(*lims)
1239 stats.print_stats(*lims)
1239 finally:
1240 finally:
1240 sys.stdout = sys_stdout
1241 sys.stdout = sys_stdout
1241 output = stdout_trap.getvalue()
1242 output = stdout_trap.getvalue()
1242 output = output.rstrip()
1243 output = output.rstrip()
1243
1244
1244 page(output,screen_lines=self.shell.rc.screen_length)
1245 page(output,screen_lines=self.shell.rc.screen_length)
1245 print sys_exit,
1246 print sys_exit,
1246
1247
1247 dump_file = opts.D[0]
1248 dump_file = opts.D[0]
1248 text_file = opts.T[0]
1249 text_file = opts.T[0]
1249 if dump_file:
1250 if dump_file:
1250 prof.dump_stats(dump_file)
1251 prof.dump_stats(dump_file)
1251 print '\n*** Profile stats marshalled to file',\
1252 print '\n*** Profile stats marshalled to file',\
1252 `dump_file`+'.',sys_exit
1253 `dump_file`+'.',sys_exit
1253 if text_file:
1254 if text_file:
1254 file(text_file,'w').write(output)
1255 file(text_file,'w').write(output)
1255 print '\n*** Profile printout saved to text file',\
1256 print '\n*** Profile printout saved to text file',\
1256 `text_file`+'.',sys_exit
1257 `text_file`+'.',sys_exit
1257
1258
1258 if opts.has_key('r'):
1259 if opts.has_key('r'):
1259 return stats
1260 return stats
1260 else:
1261 else:
1261 return None
1262 return None
1262
1263
1263 def magic_run(self, parameter_s ='',runner=None):
1264 def magic_run(self, parameter_s ='',runner=None):
1264 """Run the named file inside IPython as a program.
1265 """Run the named file inside IPython as a program.
1265
1266
1266 Usage:\\
1267 Usage:\\
1267 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1268 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
1268
1269
1269 Parameters after the filename are passed as command-line arguments to
1270 Parameters after the filename are passed as command-line arguments to
1270 the program (put in sys.argv). Then, control returns to IPython's
1271 the program (put in sys.argv). Then, control returns to IPython's
1271 prompt.
1272 prompt.
1272
1273
1273 This is similar to running at a system prompt:\\
1274 This is similar to running at a system prompt:\\
1274 $ python file args\\
1275 $ python file args\\
1275 but with the advantage of giving you IPython's tracebacks, and of
1276 but with the advantage of giving you IPython's tracebacks, and of
1276 loading all variables into your interactive namespace for further use
1277 loading all variables into your interactive namespace for further use
1277 (unless -p is used, see below).
1278 (unless -p is used, see below).
1278
1279
1279 The file is executed in a namespace initially consisting only of
1280 The file is executed in a namespace initially consisting only of
1280 __name__=='__main__' and sys.argv constructed as indicated. It thus
1281 __name__=='__main__' and sys.argv constructed as indicated. It thus
1281 sees its environment as if it were being run as a stand-alone
1282 sees its environment as if it were being run as a stand-alone
1282 program. But after execution, the IPython interactive namespace gets
1283 program. But after execution, the IPython interactive namespace gets
1283 updated with all variables defined in the program (except for __name__
1284 updated with all variables defined in the program (except for __name__
1284 and sys.argv). This allows for very convenient loading of code for
1285 and sys.argv). This allows for very convenient loading of code for
1285 interactive work, while giving each program a 'clean sheet' to run in.
1286 interactive work, while giving each program a 'clean sheet' to run in.
1286
1287
1287 Options:
1288 Options:
1288
1289
1289 -n: __name__ is NOT set to '__main__', but to the running file's name
1290 -n: __name__ is NOT set to '__main__', but to the running file's name
1290 without extension (as python does under import). This allows running
1291 without extension (as python does under import). This allows running
1291 scripts and reloading the definitions in them without calling code
1292 scripts and reloading the definitions in them without calling code
1292 protected by an ' if __name__ == "__main__" ' clause.
1293 protected by an ' if __name__ == "__main__" ' clause.
1293
1294
1294 -i: run the file in IPython's namespace instead of an empty one. This
1295 -i: run the file in IPython's namespace instead of an empty one. This
1295 is useful if you are experimenting with code written in a text editor
1296 is useful if you are experimenting with code written in a text editor
1296 which depends on variables defined interactively.
1297 which depends on variables defined interactively.
1297
1298
1298 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1299 -e: ignore sys.exit() calls or SystemExit exceptions in the script
1299 being run. This is particularly useful if IPython is being used to
1300 being run. This is particularly useful if IPython is being used to
1300 run unittests, which always exit with a sys.exit() call. In such
1301 run unittests, which always exit with a sys.exit() call. In such
1301 cases you are interested in the output of the test results, not in
1302 cases you are interested in the output of the test results, not in
1302 seeing a traceback of the unittest module.
1303 seeing a traceback of the unittest module.
1303
1304
1304 -t: print timing information at the end of the run. IPython will give
1305 -t: print timing information at the end of the run. IPython will give
1305 you an estimated CPU time consumption for your script, which under
1306 you an estimated CPU time consumption for your script, which under
1306 Unix uses the resource module to avoid the wraparound problems of
1307 Unix uses the resource module to avoid the wraparound problems of
1307 time.clock(). Under Unix, an estimate of time spent on system tasks
1308 time.clock(). Under Unix, an estimate of time spent on system tasks
1308 is also given (for Windows platforms this is reported as 0.0).
1309 is also given (for Windows platforms this is reported as 0.0).
1309
1310
1310 If -t is given, an additional -N<N> option can be given, where <N>
1311 If -t is given, an additional -N<N> option can be given, where <N>
1311 must be an integer indicating how many times you want the script to
1312 must be an integer indicating how many times you want the script to
1312 run. The final timing report will include total and per run results.
1313 run. The final timing report will include total and per run results.
1313
1314
1314 For example (testing the script uniq_stable.py):
1315 For example (testing the script uniq_stable.py):
1315
1316
1316 In [1]: run -t uniq_stable
1317 In [1]: run -t uniq_stable
1317
1318
1318 IPython CPU timings (estimated):\\
1319 IPython CPU timings (estimated):\\
1319 User : 0.19597 s.\\
1320 User : 0.19597 s.\\
1320 System: 0.0 s.\\
1321 System: 0.0 s.\\
1321
1322
1322 In [2]: run -t -N5 uniq_stable
1323 In [2]: run -t -N5 uniq_stable
1323
1324
1324 IPython CPU timings (estimated):\\
1325 IPython CPU timings (estimated):\\
1325 Total runs performed: 5\\
1326 Total runs performed: 5\\
1326 Times : Total Per run\\
1327 Times : Total Per run\\
1327 User : 0.910862 s, 0.1821724 s.\\
1328 User : 0.910862 s, 0.1821724 s.\\
1328 System: 0.0 s, 0.0 s.
1329 System: 0.0 s, 0.0 s.
1329
1330
1330 -d: run your program under the control of pdb, the Python debugger.
1331 -d: run your program under the control of pdb, the Python debugger.
1331 This allows you to execute your program step by step, watch variables,
1332 This allows you to execute your program step by step, watch variables,
1332 etc. Internally, what IPython does is similar to calling:
1333 etc. Internally, what IPython does is similar to calling:
1333
1334
1334 pdb.run('execfile("YOURFILENAME")')
1335 pdb.run('execfile("YOURFILENAME")')
1335
1336
1336 with a breakpoint set on line 1 of your file. You can change the line
1337 with a breakpoint set on line 1 of your file. You can change the line
1337 number for this automatic breakpoint to be <N> by using the -bN option
1338 number for this automatic breakpoint to be <N> by using the -bN option
1338 (where N must be an integer). For example:
1339 (where N must be an integer). For example:
1339
1340
1340 %run -d -b40 myscript
1341 %run -d -b40 myscript
1341
1342
1342 will set the first breakpoint at line 40 in myscript.py. Note that
1343 will set the first breakpoint at line 40 in myscript.py. Note that
1343 the first breakpoint must be set on a line which actually does
1344 the first breakpoint must be set on a line which actually does
1344 something (not a comment or docstring) for it to stop execution.
1345 something (not a comment or docstring) for it to stop execution.
1345
1346
1346 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1347 When the pdb debugger starts, you will see a (Pdb) prompt. You must
1347 first enter 'c' (without qoutes) to start execution up to the first
1348 first enter 'c' (without qoutes) to start execution up to the first
1348 breakpoint.
1349 breakpoint.
1349
1350
1350 Entering 'help' gives information about the use of the debugger. You
1351 Entering 'help' gives information about the use of the debugger. You
1351 can easily see pdb's full documentation with "import pdb;pdb.help()"
1352 can easily see pdb's full documentation with "import pdb;pdb.help()"
1352 at a prompt.
1353 at a prompt.
1353
1354
1354 -p: run program under the control of the Python profiler module (which
1355 -p: run program under the control of the Python profiler module (which
1355 prints a detailed report of execution times, function calls, etc).
1356 prints a detailed report of execution times, function calls, etc).
1356
1357
1357 You can pass other options after -p which affect the behavior of the
1358 You can pass other options after -p which affect the behavior of the
1358 profiler itself. See the docs for %prun for details.
1359 profiler itself. See the docs for %prun for details.
1359
1360
1360 In this mode, the program's variables do NOT propagate back to the
1361 In this mode, the program's variables do NOT propagate back to the
1361 IPython interactive namespace (because they remain in the namespace
1362 IPython interactive namespace (because they remain in the namespace
1362 where the profiler executes them).
1363 where the profiler executes them).
1363
1364
1364 Internally this triggers a call to %prun, see its documentation for
1365 Internally this triggers a call to %prun, see its documentation for
1365 details on the options available specifically for profiling."""
1366 details on the options available specifically for profiling."""
1366
1367
1367 # get arguments and set sys.argv for program to be run.
1368 # get arguments and set sys.argv for program to be run.
1368 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1369 opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e',
1369 mode='list',list_all=1)
1370 mode='list',list_all=1)
1370
1371
1371 try:
1372 try:
1372 filename = get_py_filename(arg_lst[0])
1373 filename = get_py_filename(arg_lst[0])
1373 except IndexError:
1374 except IndexError:
1374 warn('you must provide at least a filename.')
1375 warn('you must provide at least a filename.')
1375 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1376 print '\n%run:\n',OInspect.getdoc(self.magic_run)
1376 return
1377 return
1377 except IOError,msg:
1378 except IOError,msg:
1378 error(msg)
1379 error(msg)
1379 return
1380 return
1380
1381
1381 # Control the response to exit() calls made by the script being run
1382 # Control the response to exit() calls made by the script being run
1382 exit_ignore = opts.has_key('e')
1383 exit_ignore = opts.has_key('e')
1383
1384
1384 # Make sure that the running script gets a proper sys.argv as if it
1385 # Make sure that the running script gets a proper sys.argv as if it
1385 # were run from a system shell.
1386 # were run from a system shell.
1386 save_argv = sys.argv # save it for later restoring
1387 save_argv = sys.argv # save it for later restoring
1387 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1388 sys.argv = [filename]+ arg_lst[1:] # put in the proper filename
1388
1389
1389 if opts.has_key('i'):
1390 if opts.has_key('i'):
1390 prog_ns = self.shell.user_ns
1391 prog_ns = self.shell.user_ns
1391 __name__save = self.shell.user_ns['__name__']
1392 __name__save = self.shell.user_ns['__name__']
1392 prog_ns['__name__'] = '__main__'
1393 prog_ns['__name__'] = '__main__'
1393 else:
1394 else:
1394 if opts.has_key('n'):
1395 if opts.has_key('n'):
1395 name = os.path.splitext(os.path.basename(filename))[0]
1396 name = os.path.splitext(os.path.basename(filename))[0]
1396 else:
1397 else:
1397 name = '__main__'
1398 name = '__main__'
1398 prog_ns = {'__name__':name}
1399 prog_ns = {'__name__':name}
1399
1400
1400 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1401 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
1401 # set the __file__ global in the script's namespace
1402 # set the __file__ global in the script's namespace
1402 prog_ns['__file__'] = filename
1403 prog_ns['__file__'] = filename
1403
1404
1404 # pickle fix. See iplib for an explanation. But we need to make sure
1405 # pickle fix. See iplib for an explanation. But we need to make sure
1405 # that, if we overwrite __main__, we replace it at the end
1406 # that, if we overwrite __main__, we replace it at the end
1406 if prog_ns['__name__'] == '__main__':
1407 if prog_ns['__name__'] == '__main__':
1407 restore_main = sys.modules['__main__']
1408 restore_main = sys.modules['__main__']
1408 else:
1409 else:
1409 restore_main = False
1410 restore_main = False
1410
1411
1411 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1412 sys.modules[prog_ns['__name__']] = FakeModule(prog_ns)
1412
1413
1413 stats = None
1414 stats = None
1414 try:
1415 try:
1415 if opts.has_key('p'):
1416 if opts.has_key('p'):
1416 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1417 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1417 else:
1418 else:
1418 if opts.has_key('d'):
1419 if opts.has_key('d'):
1419 deb = Debugger.Pdb(self.shell.rc.colors)
1420 deb = Debugger.Pdb(self.shell.rc.colors)
1420 # reset Breakpoint state, which is moronically kept
1421 # reset Breakpoint state, which is moronically kept
1421 # in a class
1422 # in a class
1422 bdb.Breakpoint.next = 1
1423 bdb.Breakpoint.next = 1
1423 bdb.Breakpoint.bplist = {}
1424 bdb.Breakpoint.bplist = {}
1424 bdb.Breakpoint.bpbynumber = [None]
1425 bdb.Breakpoint.bpbynumber = [None]
1425 # Set an initial breakpoint to stop execution
1426 # Set an initial breakpoint to stop execution
1426 maxtries = 10
1427 maxtries = 10
1427 bp = int(opts.get('b',[1])[0])
1428 bp = int(opts.get('b',[1])[0])
1428 checkline = deb.checkline(filename,bp)
1429 checkline = deb.checkline(filename,bp)
1429 if not checkline:
1430 if not checkline:
1430 for bp in range(bp+1,bp+maxtries+1):
1431 for bp in range(bp+1,bp+maxtries+1):
1431 if deb.checkline(filename,bp):
1432 if deb.checkline(filename,bp):
1432 break
1433 break
1433 else:
1434 else:
1434 msg = ("\nI failed to find a valid line to set "
1435 msg = ("\nI failed to find a valid line to set "
1435 "a breakpoint\n"
1436 "a breakpoint\n"
1436 "after trying up to line: %s.\n"
1437 "after trying up to line: %s.\n"
1437 "Please set a valid breakpoint manually "
1438 "Please set a valid breakpoint manually "
1438 "with the -b option." % bp)
1439 "with the -b option." % bp)
1439 error(msg)
1440 error(msg)
1440 return
1441 return
1441 # if we find a good linenumber, set the breakpoint
1442 # if we find a good linenumber, set the breakpoint
1442 deb.do_break('%s:%s' % (filename,bp))
1443 deb.do_break('%s:%s' % (filename,bp))
1443 # Start file run
1444 # Start file run
1444 print "NOTE: Enter 'c' at the",
1445 print "NOTE: Enter 'c' at the",
1445 print "ipdb> prompt to start your script."
1446 print "ipdb> prompt to start your script."
1446 try:
1447 try:
1447 deb.run('execfile("%s")' % filename,prog_ns)
1448 deb.run('execfile("%s")' % filename,prog_ns)
1448 except:
1449 except:
1449 etype, value, tb = sys.exc_info()
1450 etype, value, tb = sys.exc_info()
1450 # Skip three frames in the traceback: the %run one,
1451 # Skip three frames in the traceback: the %run one,
1451 # one inside bdb.py, and the command-line typed by the
1452 # one inside bdb.py, and the command-line typed by the
1452 # user (run by exec in pdb itself).
1453 # user (run by exec in pdb itself).
1453 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1454 self.shell.InteractiveTB(etype,value,tb,tb_offset=3)
1454 else:
1455 else:
1455 if runner is None:
1456 if runner is None:
1456 runner = self.shell.safe_execfile
1457 runner = self.shell.safe_execfile
1457 if opts.has_key('t'):
1458 if opts.has_key('t'):
1458 try:
1459 try:
1459 nruns = int(opts['N'][0])
1460 nruns = int(opts['N'][0])
1460 if nruns < 1:
1461 if nruns < 1:
1461 error('Number of runs must be >=1')
1462 error('Number of runs must be >=1')
1462 return
1463 return
1463 except (KeyError):
1464 except (KeyError):
1464 nruns = 1
1465 nruns = 1
1465 if nruns == 1:
1466 if nruns == 1:
1466 t0 = clock2()
1467 t0 = clock2()
1467 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1468 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1468 t1 = clock2()
1469 t1 = clock2()
1469 t_usr = t1[0]-t0[0]
1470 t_usr = t1[0]-t0[0]
1470 t_sys = t1[1]-t1[1]
1471 t_sys = t1[1]-t1[1]
1471 print "\nIPython CPU timings (estimated):"
1472 print "\nIPython CPU timings (estimated):"
1472 print " User : %10s s." % t_usr
1473 print " User : %10s s." % t_usr
1473 print " System: %10s s." % t_sys
1474 print " System: %10s s." % t_sys
1474 else:
1475 else:
1475 runs = range(nruns)
1476 runs = range(nruns)
1476 t0 = clock2()
1477 t0 = clock2()
1477 for nr in runs:
1478 for nr in runs:
1478 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1479 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1479 t1 = clock2()
1480 t1 = clock2()
1480 t_usr = t1[0]-t0[0]
1481 t_usr = t1[0]-t0[0]
1481 t_sys = t1[1]-t1[1]
1482 t_sys = t1[1]-t1[1]
1482 print "\nIPython CPU timings (estimated):"
1483 print "\nIPython CPU timings (estimated):"
1483 print "Total runs performed:",nruns
1484 print "Total runs performed:",nruns
1484 print " Times : %10s %10s" % ('Total','Per run')
1485 print " Times : %10s %10s" % ('Total','Per run')
1485 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1486 print " User : %10s s, %10s s." % (t_usr,t_usr/nruns)
1486 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1487 print " System: %10s s, %10s s." % (t_sys,t_sys/nruns)
1487
1488
1488 else:
1489 else:
1489 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1490 runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore)
1490 if opts.has_key('i'):
1491 if opts.has_key('i'):
1491 self.shell.user_ns['__name__'] = __name__save
1492 self.shell.user_ns['__name__'] = __name__save
1492 else:
1493 else:
1493 # update IPython interactive namespace
1494 # update IPython interactive namespace
1494 del prog_ns['__name__']
1495 del prog_ns['__name__']
1495 self.shell.user_ns.update(prog_ns)
1496 self.shell.user_ns.update(prog_ns)
1496 finally:
1497 finally:
1497 sys.argv = save_argv
1498 sys.argv = save_argv
1498 if restore_main:
1499 if restore_main:
1499 sys.modules['__main__'] = restore_main
1500 sys.modules['__main__'] = restore_main
1500 return stats
1501 return stats
1501
1502
1502 def magic_runlog(self, parameter_s =''):
1503 def magic_runlog(self, parameter_s =''):
1503 """Run files as logs.
1504 """Run files as logs.
1504
1505
1505 Usage:\\
1506 Usage:\\
1506 %runlog file1 file2 ...
1507 %runlog file1 file2 ...
1507
1508
1508 Run the named files (treating them as log files) in sequence inside
1509 Run the named files (treating them as log files) in sequence inside
1509 the interpreter, and return to the prompt. This is much slower than
1510 the interpreter, and return to the prompt. This is much slower than
1510 %run because each line is executed in a try/except block, but it
1511 %run because each line is executed in a try/except block, but it
1511 allows running files with syntax errors in them.
1512 allows running files with syntax errors in them.
1512
1513
1513 Normally IPython will guess when a file is one of its own logfiles, so
1514 Normally IPython will guess when a file is one of its own logfiles, so
1514 you can typically use %run even for logs. This shorthand allows you to
1515 you can typically use %run even for logs. This shorthand allows you to
1515 force any file to be treated as a log file."""
1516 force any file to be treated as a log file."""
1516
1517
1517 for f in parameter_s.split():
1518 for f in parameter_s.split():
1518 self.shell.safe_execfile(f,self.shell.user_ns,
1519 self.shell.safe_execfile(f,self.shell.user_ns,
1519 self.shell.user_ns,islog=1)
1520 self.shell.user_ns,islog=1)
1520
1521
1521 def magic_time(self,parameter_s = ''):
1522 def magic_time(self,parameter_s = ''):
1522 """Time execution of a Python statement or expression.
1523 """Time execution of a Python statement or expression.
1523
1524
1524 The CPU and wall clock times are printed, and the value of the
1525 The CPU and wall clock times are printed, and the value of the
1525 expression (if any) is returned. Note that under Win32, system time
1526 expression (if any) is returned. Note that under Win32, system time
1526 is always reported as 0, since it can not be measured.
1527 is always reported as 0, since it can not be measured.
1527
1528
1528 This function provides very basic timing functionality. In Python
1529 This function provides very basic timing functionality. In Python
1529 2.3, the timeit module offers more control and sophistication, but for
1530 2.3, the timeit module offers more control and sophistication, but for
1530 now IPython supports Python 2.2, so we can not rely on timeit being
1531 now IPython supports Python 2.2, so we can not rely on timeit being
1531 present.
1532 present.
1532
1533
1533 Some examples:
1534 Some examples:
1534
1535
1535 In [1]: time 2**128
1536 In [1]: time 2**128
1536 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1537 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1537 Wall time: 0.00
1538 Wall time: 0.00
1538 Out[1]: 340282366920938463463374607431768211456L
1539 Out[1]: 340282366920938463463374607431768211456L
1539
1540
1540 In [2]: n = 1000000
1541 In [2]: n = 1000000
1541
1542
1542 In [3]: time sum(range(n))
1543 In [3]: time sum(range(n))
1543 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1544 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1544 Wall time: 1.37
1545 Wall time: 1.37
1545 Out[3]: 499999500000L
1546 Out[3]: 499999500000L
1546
1547
1547 In [4]: time print 'hello world'
1548 In [4]: time print 'hello world'
1548 hello world
1549 hello world
1549 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1550 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1550 Wall time: 0.00
1551 Wall time: 0.00
1551 """
1552 """
1552
1553
1553 # fail immediately if the given expression can't be compiled
1554 # fail immediately if the given expression can't be compiled
1554 try:
1555 try:
1555 mode = 'eval'
1556 mode = 'eval'
1556 code = compile(parameter_s,'<timed eval>',mode)
1557 code = compile(parameter_s,'<timed eval>',mode)
1557 except SyntaxError:
1558 except SyntaxError:
1558 mode = 'exec'
1559 mode = 'exec'
1559 code = compile(parameter_s,'<timed exec>',mode)
1560 code = compile(parameter_s,'<timed exec>',mode)
1560 # skew measurement as little as possible
1561 # skew measurement as little as possible
1561 glob = self.shell.user_ns
1562 glob = self.shell.user_ns
1562 clk = clock2
1563 clk = clock2
1563 wtime = time.time
1564 wtime = time.time
1564 # time execution
1565 # time execution
1565 wall_st = wtime()
1566 wall_st = wtime()
1566 if mode=='eval':
1567 if mode=='eval':
1567 st = clk()
1568 st = clk()
1568 out = eval(code,glob)
1569 out = eval(code,glob)
1569 end = clk()
1570 end = clk()
1570 else:
1571 else:
1571 st = clk()
1572 st = clk()
1572 exec code in glob
1573 exec code in glob
1573 end = clk()
1574 end = clk()
1574 out = None
1575 out = None
1575 wall_end = wtime()
1576 wall_end = wtime()
1576 # Compute actual times and report
1577 # Compute actual times and report
1577 wall_time = wall_end-wall_st
1578 wall_time = wall_end-wall_st
1578 cpu_user = end[0]-st[0]
1579 cpu_user = end[0]-st[0]
1579 cpu_sys = end[1]-st[1]
1580 cpu_sys = end[1]-st[1]
1580 cpu_tot = cpu_user+cpu_sys
1581 cpu_tot = cpu_user+cpu_sys
1581 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1582 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
1582 (cpu_user,cpu_sys,cpu_tot)
1583 (cpu_user,cpu_sys,cpu_tot)
1583 print "Wall time: %.2f" % wall_time
1584 print "Wall time: %.2f" % wall_time
1584 return out
1585 return out
1585
1586
1586 def magic_macro(self,parameter_s = ''):
1587 def magic_macro(self,parameter_s = ''):
1587 """Define a set of input lines as a macro for future re-execution.
1588 """Define a set of input lines as a macro for future re-execution.
1588
1589
1589 Usage:\\
1590 Usage:\\
1590 %macro name n1-n2 n3-n4 ... n5 .. n6 ...
1591 %macro name n1-n2 n3-n4 ... n5 .. n6 ...
1591
1592
1592 This will define a global variable called `name` which is a string
1593 This will define a global variable called `name` which is a string
1593 made of joining the slices and lines you specify (n1,n2,... numbers
1594 made of joining the slices and lines you specify (n1,n2,... numbers
1594 above) from your input history into a single string. This variable
1595 above) from your input history into a single string. This variable
1595 acts like an automatic function which re-executes those lines as if
1596 acts like an automatic function which re-executes those lines as if
1596 you had typed them. You just type 'name' at the prompt and the code
1597 you had typed them. You just type 'name' at the prompt and the code
1597 executes.
1598 executes.
1598
1599
1599 The notation for indicating number ranges is: n1-n2 means 'use line
1600 The notation for indicating number ranges is: n1-n2 means 'use line
1600 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1601 numbers n1,...n2' (the endpoint is included). That is, '5-7' means
1601 using the lines numbered 5,6 and 7.
1602 using the lines numbered 5,6 and 7.
1602
1603
1603 Note: as a 'hidden' feature, you can also use traditional python slice
1604 Note: as a 'hidden' feature, you can also use traditional python slice
1604 notation, where N:M means numbers N through M-1.
1605 notation, where N:M means numbers N through M-1.
1605
1606
1606 For example, if your history contains (%hist prints it):
1607 For example, if your history contains (%hist prints it):
1607
1608
1608 44: x=1\\
1609 44: x=1\\
1609 45: y=3\\
1610 45: y=3\\
1610 46: z=x+y\\
1611 46: z=x+y\\
1611 47: print x\\
1612 47: print x\\
1612 48: a=5\\
1613 48: a=5\\
1613 49: print 'x',x,'y',y\\
1614 49: print 'x',x,'y',y\\
1614
1615
1615 you can create a macro with lines 44 through 47 (included) and line 49
1616 you can create a macro with lines 44 through 47 (included) and line 49
1616 called my_macro with:
1617 called my_macro with:
1617
1618
1618 In [51]: %macro my_macro 44-47 49
1619 In [51]: %macro my_macro 44-47 49
1619
1620
1620 Now, typing `my_macro` (without quotes) will re-execute all this code
1621 Now, typing `my_macro` (without quotes) will re-execute all this code
1621 in one pass.
1622 in one pass.
1622
1623
1623 You don't need to give the line-numbers in order, and any given line
1624 You don't need to give the line-numbers in order, and any given line
1624 number can appear multiple times. You can assemble macros with any
1625 number can appear multiple times. You can assemble macros with any
1625 lines from your input history in any order.
1626 lines from your input history in any order.
1626
1627
1627 The macro is a simple object which holds its value in an attribute,
1628 The macro is a simple object which holds its value in an attribute,
1628 but IPython's display system checks for macros and executes them as
1629 but IPython's display system checks for macros and executes them as
1629 code instead of printing them when you type their name.
1630 code instead of printing them when you type their name.
1630
1631
1631 You can view a macro's contents by explicitly printing it with:
1632 You can view a macro's contents by explicitly printing it with:
1632
1633
1633 'print macro_name'.
1634 'print macro_name'.
1634
1635
1635 For one-off cases which DON'T contain magic function calls in them you
1636 For one-off cases which DON'T contain magic function calls in them you
1636 can obtain similar results by explicitly executing slices from your
1637 can obtain similar results by explicitly executing slices from your
1637 input history with:
1638 input history with:
1638
1639
1639 In [60]: exec In[44:48]+In[49]"""
1640 In [60]: exec In[44:48]+In[49]"""
1640
1641
1641 args = parameter_s.split()
1642 args = parameter_s.split()
1642 name,ranges = args[0], args[1:]
1643 name,ranges = args[0], args[1:]
1643 #print 'rng',ranges # dbg
1644 #print 'rng',ranges # dbg
1644 lines = self.extract_input_slices(ranges)
1645 lines = self.extract_input_slices(ranges)
1645 macro = Macro(lines)
1646 macro = Macro(lines)
1646 self.shell.user_ns.update({name:macro})
1647 self.shell.user_ns.update({name:macro})
1647 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1648 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1648 print 'Macro contents:'
1649 print 'Macro contents:'
1649 print macro,
1650 print macro,
1650
1651
1651 def magic_save(self,parameter_s = ''):
1652 def magic_save(self,parameter_s = ''):
1652 """Save a set of lines to a given filename.
1653 """Save a set of lines to a given filename.
1653
1654
1654 Usage:\\
1655 Usage:\\
1655 %save filename n1-n2 n3-n4 ... n5 .. n6 ...
1656 %save filename n1-n2 n3-n4 ... n5 .. n6 ...
1656
1657
1657 This function uses the same syntax as %macro for line extraction, but
1658 This function uses the same syntax as %macro for line extraction, but
1658 instead of creating a macro it saves the resulting string to the
1659 instead of creating a macro it saves the resulting string to the
1659 filename you specify.
1660 filename you specify.
1660
1661
1661 It adds a '.py' extension to the file if you don't do so yourself, and
1662 It adds a '.py' extension to the file if you don't do so yourself, and
1662 it asks for confirmation before overwriting existing files."""
1663 it asks for confirmation before overwriting existing files."""
1663
1664
1664 args = parameter_s.split()
1665 args = parameter_s.split()
1665 fname,ranges = args[0], args[1:]
1666 fname,ranges = args[0], args[1:]
1666 if not fname.endswith('.py'):
1667 if not fname.endswith('.py'):
1667 fname += '.py'
1668 fname += '.py'
1668 if os.path.isfile(fname):
1669 if os.path.isfile(fname):
1669 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1670 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
1670 if ans.lower() not in ['y','yes']:
1671 if ans.lower() not in ['y','yes']:
1671 print 'Operation cancelled.'
1672 print 'Operation cancelled.'
1672 return
1673 return
1673 cmds = ''.join(self.extract_input_slices(ranges))
1674 cmds = ''.join(self.extract_input_slices(ranges))
1674 f = file(fname,'w')
1675 f = file(fname,'w')
1675 f.write(cmds)
1676 f.write(cmds)
1676 f.close()
1677 f.close()
1677 print 'The following commands were written to file `%s`:' % fname
1678 print 'The following commands were written to file `%s`:' % fname
1678 print cmds
1679 print cmds
1679
1680
1680 def _edit_macro(self,mname,macro):
1681 def _edit_macro(self,mname,macro):
1681 """open an editor with the macro data in a file"""
1682 """open an editor with the macro data in a file"""
1682 filename = self.shell.mktempfile(macro.value)
1683 filename = self.shell.mktempfile(macro.value)
1683 self.shell.hooks.editor(filename)
1684 self.shell.hooks.editor(filename)
1684
1685
1685 # and make a new macro object, to replace the old one
1686 # and make a new macro object, to replace the old one
1686 mfile = open(filename)
1687 mfile = open(filename)
1687 mvalue = mfile.read()
1688 mvalue = mfile.read()
1688 mfile.close()
1689 mfile.close()
1689 self.shell.user_ns[mname] = Macro(mvalue)
1690 self.shell.user_ns[mname] = Macro(mvalue)
1690
1691
1691 def magic_ed(self,parameter_s=''):
1692 def magic_ed(self,parameter_s=''):
1692 """Alias to %edit."""
1693 """Alias to %edit."""
1693 return self.magic_edit(parameter_s)
1694 return self.magic_edit(parameter_s)
1694
1695
1695 def magic_edit(self,parameter_s='',last_call=['','']):
1696 def magic_edit(self,parameter_s='',last_call=['','']):
1696 """Bring up an editor and execute the resulting code.
1697 """Bring up an editor and execute the resulting code.
1697
1698
1698 Usage:
1699 Usage:
1699 %edit [options] [args]
1700 %edit [options] [args]
1700
1701
1701 %edit runs IPython's editor hook. The default version of this hook is
1702 %edit runs IPython's editor hook. The default version of this hook is
1702 set to call the __IPYTHON__.rc.editor command. This is read from your
1703 set to call the __IPYTHON__.rc.editor command. This is read from your
1703 environment variable $EDITOR. If this isn't found, it will default to
1704 environment variable $EDITOR. If this isn't found, it will default to
1704 vi under Linux/Unix and to notepad under Windows. See the end of this
1705 vi under Linux/Unix and to notepad under Windows. See the end of this
1705 docstring for how to change the editor hook.
1706 docstring for how to change the editor hook.
1706
1707
1707 You can also set the value of this editor via the command line option
1708 You can also set the value of this editor via the command line option
1708 '-editor' or in your ipythonrc file. This is useful if you wish to use
1709 '-editor' or in your ipythonrc file. This is useful if you wish to use
1709 specifically for IPython an editor different from your typical default
1710 specifically for IPython an editor different from your typical default
1710 (and for Windows users who typically don't set environment variables).
1711 (and for Windows users who typically don't set environment variables).
1711
1712
1712 This command allows you to conveniently edit multi-line code right in
1713 This command allows you to conveniently edit multi-line code right in
1713 your IPython session.
1714 your IPython session.
1714
1715
1715 If called without arguments, %edit opens up an empty editor with a
1716 If called without arguments, %edit opens up an empty editor with a
1716 temporary file and will execute the contents of this file when you
1717 temporary file and will execute the contents of this file when you
1717 close it (don't forget to save it!).
1718 close it (don't forget to save it!).
1718
1719
1719
1720
1720 Options:
1721 Options:
1721
1722
1722 -p: this will call the editor with the same data as the previous time
1723 -p: this will call the editor with the same data as the previous time
1723 it was used, regardless of how long ago (in your current session) it
1724 it was used, regardless of how long ago (in your current session) it
1724 was.
1725 was.
1725
1726
1726 -x: do not execute the edited code immediately upon exit. This is
1727 -x: do not execute the edited code immediately upon exit. This is
1727 mainly useful if you are editing programs which need to be called with
1728 mainly useful if you are editing programs which need to be called with
1728 command line arguments, which you can then do using %run.
1729 command line arguments, which you can then do using %run.
1729
1730
1730
1731
1731 Arguments:
1732 Arguments:
1732
1733
1733 If arguments are given, the following possibilites exist:
1734 If arguments are given, the following possibilites exist:
1734
1735
1735 - The arguments are numbers or pairs of colon-separated numbers (like
1736 - The arguments are numbers or pairs of colon-separated numbers (like
1736 1 4:8 9). These are interpreted as lines of previous input to be
1737 1 4:8 9). These are interpreted as lines of previous input to be
1737 loaded into the editor. The syntax is the same of the %macro command.
1738 loaded into the editor. The syntax is the same of the %macro command.
1738
1739
1739 - If the argument doesn't start with a number, it is evaluated as a
1740 - If the argument doesn't start with a number, it is evaluated as a
1740 variable and its contents loaded into the editor. You can thus edit
1741 variable and its contents loaded into the editor. You can thus edit
1741 any string which contains python code (including the result of
1742 any string which contains python code (including the result of
1742 previous edits).
1743 previous edits).
1743
1744
1744 - If the argument is the name of an object (other than a string),
1745 - If the argument is the name of an object (other than a string),
1745 IPython will try to locate the file where it was defined and open the
1746 IPython will try to locate the file where it was defined and open the
1746 editor at the point where it is defined. You can use `%edit function`
1747 editor at the point where it is defined. You can use `%edit function`
1747 to load an editor exactly at the point where 'function' is defined,
1748 to load an editor exactly at the point where 'function' is defined,
1748 edit it and have the file be executed automatically.
1749 edit it and have the file be executed automatically.
1749
1750
1750 If the object is a macro (see %macro for details), this opens up your
1751 If the object is a macro (see %macro for details), this opens up your
1751 specified editor with a temporary file containing the macro's data.
1752 specified editor with a temporary file containing the macro's data.
1752 Upon exit, the macro is reloaded with the contents of the file.
1753 Upon exit, the macro is reloaded with the contents of the file.
1753
1754
1754 Note: opening at an exact line is only supported under Unix, and some
1755 Note: opening at an exact line is only supported under Unix, and some
1755 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1756 editors (like kedit and gedit up to Gnome 2.8) do not understand the
1756 '+NUMBER' parameter necessary for this feature. Good editors like
1757 '+NUMBER' parameter necessary for this feature. Good editors like
1757 (X)Emacs, vi, jed, pico and joe all do.
1758 (X)Emacs, vi, jed, pico and joe all do.
1758
1759
1759 - If the argument is not found as a variable, IPython will look for a
1760 - If the argument is not found as a variable, IPython will look for a
1760 file with that name (adding .py if necessary) and load it into the
1761 file with that name (adding .py if necessary) and load it into the
1761 editor. It will execute its contents with execfile() when you exit,
1762 editor. It will execute its contents with execfile() when you exit,
1762 loading any code in the file into your interactive namespace.
1763 loading any code in the file into your interactive namespace.
1763
1764
1764 After executing your code, %edit will return as output the code you
1765 After executing your code, %edit will return as output the code you
1765 typed in the editor (except when it was an existing file). This way
1766 typed in the editor (except when it was an existing file). This way
1766 you can reload the code in further invocations of %edit as a variable,
1767 you can reload the code in further invocations of %edit as a variable,
1767 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1768 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
1768 the output.
1769 the output.
1769
1770
1770 Note that %edit is also available through the alias %ed.
1771 Note that %edit is also available through the alias %ed.
1771
1772
1772 This is an example of creating a simple function inside the editor and
1773 This is an example of creating a simple function inside the editor and
1773 then modifying it. First, start up the editor:
1774 then modifying it. First, start up the editor:
1774
1775
1775 In [1]: ed\\
1776 In [1]: ed\\
1776 Editing... done. Executing edited code...\\
1777 Editing... done. Executing edited code...\\
1777 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1778 Out[1]: 'def foo():\\n print "foo() was defined in an editing session"\\n'
1778
1779
1779 We can then call the function foo():
1780 We can then call the function foo():
1780
1781
1781 In [2]: foo()\\
1782 In [2]: foo()\\
1782 foo() was defined in an editing session
1783 foo() was defined in an editing session
1783
1784
1784 Now we edit foo. IPython automatically loads the editor with the
1785 Now we edit foo. IPython automatically loads the editor with the
1785 (temporary) file where foo() was previously defined:
1786 (temporary) file where foo() was previously defined:
1786
1787
1787 In [3]: ed foo\\
1788 In [3]: ed foo\\
1788 Editing... done. Executing edited code...
1789 Editing... done. Executing edited code...
1789
1790
1790 And if we call foo() again we get the modified version:
1791 And if we call foo() again we get the modified version:
1791
1792
1792 In [4]: foo()\\
1793 In [4]: foo()\\
1793 foo() has now been changed!
1794 foo() has now been changed!
1794
1795
1795 Here is an example of how to edit a code snippet successive
1796 Here is an example of how to edit a code snippet successive
1796 times. First we call the editor:
1797 times. First we call the editor:
1797
1798
1798 In [8]: ed\\
1799 In [8]: ed\\
1799 Editing... done. Executing edited code...\\
1800 Editing... done. Executing edited code...\\
1800 hello\\
1801 hello\\
1801 Out[8]: "print 'hello'\\n"
1802 Out[8]: "print 'hello'\\n"
1802
1803
1803 Now we call it again with the previous output (stored in _):
1804 Now we call it again with the previous output (stored in _):
1804
1805
1805 In [9]: ed _\\
1806 In [9]: ed _\\
1806 Editing... done. Executing edited code...\\
1807 Editing... done. Executing edited code...\\
1807 hello world\\
1808 hello world\\
1808 Out[9]: "print 'hello world'\\n"
1809 Out[9]: "print 'hello world'\\n"
1809
1810
1810 Now we call it with the output #8 (stored in _8, also as Out[8]):
1811 Now we call it with the output #8 (stored in _8, also as Out[8]):
1811
1812
1812 In [10]: ed _8\\
1813 In [10]: ed _8\\
1813 Editing... done. Executing edited code...\\
1814 Editing... done. Executing edited code...\\
1814 hello again\\
1815 hello again\\
1815 Out[10]: "print 'hello again'\\n"
1816 Out[10]: "print 'hello again'\\n"
1816
1817
1817
1818
1818 Changing the default editor hook:
1819 Changing the default editor hook:
1819
1820
1820 If you wish to write your own editor hook, you can put it in a
1821 If you wish to write your own editor hook, you can put it in a
1821 configuration file which you load at startup time. The default hook
1822 configuration file which you load at startup time. The default hook
1822 is defined in the IPython.hooks module, and you can use that as a
1823 is defined in the IPython.hooks module, and you can use that as a
1823 starting example for further modifications. That file also has
1824 starting example for further modifications. That file also has
1824 general instructions on how to set a new hook for use once you've
1825 general instructions on how to set a new hook for use once you've
1825 defined it."""
1826 defined it."""
1826
1827
1827 # FIXME: This function has become a convoluted mess. It needs a
1828 # FIXME: This function has become a convoluted mess. It needs a
1828 # ground-up rewrite with clean, simple logic.
1829 # ground-up rewrite with clean, simple logic.
1829
1830
1830 def make_filename(arg):
1831 def make_filename(arg):
1831 "Make a filename from the given args"
1832 "Make a filename from the given args"
1832 try:
1833 try:
1833 filename = get_py_filename(arg)
1834 filename = get_py_filename(arg)
1834 except IOError:
1835 except IOError:
1835 if args.endswith('.py'):
1836 if args.endswith('.py'):
1836 filename = arg
1837 filename = arg
1837 else:
1838 else:
1838 filename = None
1839 filename = None
1839 return filename
1840 return filename
1840
1841
1841 # custom exceptions
1842 # custom exceptions
1842 class DataIsObject(Exception): pass
1843 class DataIsObject(Exception): pass
1843
1844
1844 opts,args = self.parse_options(parameter_s,'px')
1845 opts,args = self.parse_options(parameter_s,'px')
1845
1846
1846 # Default line number value
1847 # Default line number value
1847 lineno = None
1848 lineno = None
1848 if opts.has_key('p'):
1849 if opts.has_key('p'):
1849 args = '_%s' % last_call[0]
1850 args = '_%s' % last_call[0]
1850 if not self.shell.user_ns.has_key(args):
1851 if not self.shell.user_ns.has_key(args):
1851 args = last_call[1]
1852 args = last_call[1]
1852
1853
1853 # use last_call to remember the state of the previous call, but don't
1854 # use last_call to remember the state of the previous call, but don't
1854 # let it be clobbered by successive '-p' calls.
1855 # let it be clobbered by successive '-p' calls.
1855 try:
1856 try:
1856 last_call[0] = self.shell.outputcache.prompt_count
1857 last_call[0] = self.shell.outputcache.prompt_count
1857 if not opts.has_key('p'):
1858 if not opts.has_key('p'):
1858 last_call[1] = parameter_s
1859 last_call[1] = parameter_s
1859 except:
1860 except:
1860 pass
1861 pass
1861
1862
1862 # by default this is done with temp files, except when the given
1863 # by default this is done with temp files, except when the given
1863 # arg is a filename
1864 # arg is a filename
1864 use_temp = 1
1865 use_temp = 1
1865
1866
1866 if re.match(r'\d',args):
1867 if re.match(r'\d',args):
1867 # Mode where user specifies ranges of lines, like in %macro.
1868 # Mode where user specifies ranges of lines, like in %macro.
1868 # This means that you can't edit files whose names begin with
1869 # This means that you can't edit files whose names begin with
1869 # numbers this way. Tough.
1870 # numbers this way. Tough.
1870 ranges = args.split()
1871 ranges = args.split()
1871 data = ''.join(self.extract_input_slices(ranges))
1872 data = ''.join(self.extract_input_slices(ranges))
1872 elif args.endswith('.py'):
1873 elif args.endswith('.py'):
1873 filename = make_filename(args)
1874 filename = make_filename(args)
1874 data = ''
1875 data = ''
1875 use_temp = 0
1876 use_temp = 0
1876 elif args:
1877 elif args:
1877 try:
1878 try:
1878 # Load the parameter given as a variable. If not a string,
1879 # Load the parameter given as a variable. If not a string,
1879 # process it as an object instead (below)
1880 # process it as an object instead (below)
1880
1881
1881 #print '*** args',args,'type',type(args) # dbg
1882 #print '*** args',args,'type',type(args) # dbg
1882 data = eval(args,self.shell.user_ns)
1883 data = eval(args,self.shell.user_ns)
1883 if not type(data) in StringTypes:
1884 if not type(data) in StringTypes:
1884 raise DataIsObject
1885 raise DataIsObject
1885
1886
1886 except (NameError,SyntaxError):
1887 except (NameError,SyntaxError):
1887 # given argument is not a variable, try as a filename
1888 # given argument is not a variable, try as a filename
1888 filename = make_filename(args)
1889 filename = make_filename(args)
1889 if filename is None:
1890 if filename is None:
1890 warn("Argument given (%s) can't be found as a variable "
1891 warn("Argument given (%s) can't be found as a variable "
1891 "or as a filename." % args)
1892 "or as a filename." % args)
1892 return
1893 return
1893
1894
1894 data = ''
1895 data = ''
1895 use_temp = 0
1896 use_temp = 0
1896 except DataIsObject:
1897 except DataIsObject:
1897
1898
1898 # macros have a special edit function
1899 # macros have a special edit function
1899 if isinstance(data,Macro):
1900 if isinstance(data,Macro):
1900 self._edit_macro(args,data)
1901 self._edit_macro(args,data)
1901 return
1902 return
1902
1903
1903 # For objects, try to edit the file where they are defined
1904 # For objects, try to edit the file where they are defined
1904 try:
1905 try:
1905 filename = inspect.getabsfile(data)
1906 filename = inspect.getabsfile(data)
1906 datafile = 1
1907 datafile = 1
1907 except TypeError:
1908 except TypeError:
1908 filename = make_filename(args)
1909 filename = make_filename(args)
1909 datafile = 1
1910 datafile = 1
1910 warn('Could not find file where `%s` is defined.\n'
1911 warn('Could not find file where `%s` is defined.\n'
1911 'Opening a file named `%s`' % (args,filename))
1912 'Opening a file named `%s`' % (args,filename))
1912 # Now, make sure we can actually read the source (if it was in
1913 # Now, make sure we can actually read the source (if it was in
1913 # a temp file it's gone by now).
1914 # a temp file it's gone by now).
1914 if datafile:
1915 if datafile:
1915 try:
1916 try:
1916 lineno = inspect.getsourcelines(data)[1]
1917 lineno = inspect.getsourcelines(data)[1]
1917 except IOError:
1918 except IOError:
1918 filename = make_filename(args)
1919 filename = make_filename(args)
1919 if filename is None:
1920 if filename is None:
1920 warn('The file `%s` where `%s` was defined cannot '
1921 warn('The file `%s` where `%s` was defined cannot '
1921 'be read.' % (filename,data))
1922 'be read.' % (filename,data))
1922 return
1923 return
1923 use_temp = 0
1924 use_temp = 0
1924 else:
1925 else:
1925 data = ''
1926 data = ''
1926
1927
1927 if use_temp:
1928 if use_temp:
1928 filename = self.shell.mktempfile(data)
1929 filename = self.shell.mktempfile(data)
1929 print 'IPython will make a temporary file named:',filename
1930 print 'IPython will make a temporary file named:',filename
1930
1931
1931 # do actual editing here
1932 # do actual editing here
1932 print 'Editing...',
1933 print 'Editing...',
1933 sys.stdout.flush()
1934 sys.stdout.flush()
1934 self.shell.hooks.editor(filename,lineno)
1935 self.shell.hooks.editor(filename,lineno)
1935 if opts.has_key('x'): # -x prevents actual execution
1936 if opts.has_key('x'): # -x prevents actual execution
1936 print
1937 print
1937 else:
1938 else:
1938 print 'done. Executing edited code...'
1939 print 'done. Executing edited code...'
1939 self.shell.safe_execfile(filename,self.shell.user_ns)
1940 self.shell.safe_execfile(filename,self.shell.user_ns)
1940 if use_temp:
1941 if use_temp:
1941 try:
1942 try:
1942 return open(filename).read()
1943 return open(filename).read()
1943 except IOError,msg:
1944 except IOError,msg:
1944 if msg.filename == filename:
1945 if msg.filename == filename:
1945 warn('File not found. Did you forget to save?')
1946 warn('File not found. Did you forget to save?')
1946 return
1947 return
1947 else:
1948 else:
1948 self.shell.showtraceback()
1949 self.shell.showtraceback()
1949
1950
1950 def magic_xmode(self,parameter_s = ''):
1951 def magic_xmode(self,parameter_s = ''):
1951 """Switch modes for the exception handlers.
1952 """Switch modes for the exception handlers.
1952
1953
1953 Valid modes: Plain, Context and Verbose.
1954 Valid modes: Plain, Context and Verbose.
1954
1955
1955 If called without arguments, acts as a toggle."""
1956 If called without arguments, acts as a toggle."""
1956
1957
1957 def xmode_switch_err(name):
1958 def xmode_switch_err(name):
1958 warn('Error changing %s exception modes.\n%s' %
1959 warn('Error changing %s exception modes.\n%s' %
1959 (name,sys.exc_info()[1]))
1960 (name,sys.exc_info()[1]))
1960
1961
1961 shell = self.shell
1962 shell = self.shell
1962 new_mode = parameter_s.strip().capitalize()
1963 new_mode = parameter_s.strip().capitalize()
1963 try:
1964 try:
1964 shell.InteractiveTB.set_mode(mode=new_mode)
1965 shell.InteractiveTB.set_mode(mode=new_mode)
1965 print 'Exception reporting mode:',shell.InteractiveTB.mode
1966 print 'Exception reporting mode:',shell.InteractiveTB.mode
1966 except:
1967 except:
1967 xmode_switch_err('user')
1968 xmode_switch_err('user')
1968
1969
1969 # threaded shells use a special handler in sys.excepthook
1970 # threaded shells use a special handler in sys.excepthook
1970 if shell.isthreaded:
1971 if shell.isthreaded:
1971 try:
1972 try:
1972 shell.sys_excepthook.set_mode(mode=new_mode)
1973 shell.sys_excepthook.set_mode(mode=new_mode)
1973 except:
1974 except:
1974 xmode_switch_err('threaded')
1975 xmode_switch_err('threaded')
1975
1976
1976 def magic_colors(self,parameter_s = ''):
1977 def magic_colors(self,parameter_s = ''):
1977 """Switch color scheme for prompts, info system and exception handlers.
1978 """Switch color scheme for prompts, info system and exception handlers.
1978
1979
1979 Currently implemented schemes: NoColor, Linux, LightBG.
1980 Currently implemented schemes: NoColor, Linux, LightBG.
1980
1981
1981 Color scheme names are not case-sensitive."""
1982 Color scheme names are not case-sensitive."""
1982
1983
1983 def color_switch_err(name):
1984 def color_switch_err(name):
1984 warn('Error changing %s color schemes.\n%s' %
1985 warn('Error changing %s color schemes.\n%s' %
1985 (name,sys.exc_info()[1]))
1986 (name,sys.exc_info()[1]))
1986
1987
1987
1988
1988 new_scheme = parameter_s.strip()
1989 new_scheme = parameter_s.strip()
1989 if not new_scheme:
1990 if not new_scheme:
1990 print 'You must specify a color scheme.'
1991 print 'You must specify a color scheme.'
1991 return
1992 return
1992 # Under Windows, check for Gary Bishop's readline, which is necessary
1993 # Under Windows, check for Gary Bishop's readline, which is necessary
1993 # for ANSI coloring
1994 # for ANSI coloring
1994 if os.name in ['nt','dos']:
1995 if os.name in ['nt','dos']:
1995 try:
1996 try:
1996 import readline
1997 import readline
1997 except ImportError:
1998 except ImportError:
1998 has_readline = 0
1999 has_readline = 0
1999 else:
2000 else:
2000 try:
2001 try:
2001 readline.GetOutputFile()
2002 readline.GetOutputFile()
2002 except AttributeError:
2003 except AttributeError:
2003 has_readline = 0
2004 has_readline = 0
2004 else:
2005 else:
2005 has_readline = 1
2006 has_readline = 1
2006 if not has_readline:
2007 if not has_readline:
2007 msg = """\
2008 msg = """\
2008 Proper color support under MS Windows requires Gary Bishop's readline library.
2009 Proper color support under MS Windows requires Gary Bishop's readline library.
2009 You can find it at:
2010 You can find it at:
2010 http://sourceforge.net/projects/uncpythontools
2011 http://sourceforge.net/projects/uncpythontools
2011 Gary's readline needs the ctypes module, from:
2012 Gary's readline needs the ctypes module, from:
2012 http://starship.python.net/crew/theller/ctypes
2013 http://starship.python.net/crew/theller/ctypes
2013
2014
2014 Defaulting color scheme to 'NoColor'"""
2015 Defaulting color scheme to 'NoColor'"""
2015 new_scheme = 'NoColor'
2016 new_scheme = 'NoColor'
2016 warn(msg)
2017 warn(msg)
2017 # local shortcut
2018 # local shortcut
2018 shell = self.shell
2019 shell = self.shell
2019
2020
2020 # Set prompt colors
2021 # Set prompt colors
2021 try:
2022 try:
2022 shell.outputcache.set_colors(new_scheme)
2023 shell.outputcache.set_colors(new_scheme)
2023 except:
2024 except:
2024 color_switch_err('prompt')
2025 color_switch_err('prompt')
2025 else:
2026 else:
2026 shell.rc.colors = \
2027 shell.rc.colors = \
2027 shell.outputcache.color_table.active_scheme_name
2028 shell.outputcache.color_table.active_scheme_name
2028 # Set exception colors
2029 # Set exception colors
2029 try:
2030 try:
2030 shell.InteractiveTB.set_colors(scheme = new_scheme)
2031 shell.InteractiveTB.set_colors(scheme = new_scheme)
2031 shell.SyntaxTB.set_colors(scheme = new_scheme)
2032 shell.SyntaxTB.set_colors(scheme = new_scheme)
2032 except:
2033 except:
2033 color_switch_err('exception')
2034 color_switch_err('exception')
2034
2035
2035 # threaded shells use a verbose traceback in sys.excepthook
2036 # threaded shells use a verbose traceback in sys.excepthook
2036 if shell.isthreaded:
2037 if shell.isthreaded:
2037 try:
2038 try:
2038 shell.sys_excepthook.set_colors(scheme=new_scheme)
2039 shell.sys_excepthook.set_colors(scheme=new_scheme)
2039 except:
2040 except:
2040 color_switch_err('system exception handler')
2041 color_switch_err('system exception handler')
2041
2042
2042 # Set info (for 'object?') colors
2043 # Set info (for 'object?') colors
2043 if shell.rc.color_info:
2044 if shell.rc.color_info:
2044 try:
2045 try:
2045 shell.inspector.set_active_scheme(new_scheme)
2046 shell.inspector.set_active_scheme(new_scheme)
2046 except:
2047 except:
2047 color_switch_err('object inspector')
2048 color_switch_err('object inspector')
2048 else:
2049 else:
2049 shell.inspector.set_active_scheme('NoColor')
2050 shell.inspector.set_active_scheme('NoColor')
2050
2051
2051 def magic_color_info(self,parameter_s = ''):
2052 def magic_color_info(self,parameter_s = ''):
2052 """Toggle color_info.
2053 """Toggle color_info.
2053
2054
2054 The color_info configuration parameter controls whether colors are
2055 The color_info configuration parameter controls whether colors are
2055 used for displaying object details (by things like %psource, %pfile or
2056 used for displaying object details (by things like %psource, %pfile or
2056 the '?' system). This function toggles this value with each call.
2057 the '?' system). This function toggles this value with each call.
2057
2058
2058 Note that unless you have a fairly recent pager (less works better
2059 Note that unless you have a fairly recent pager (less works better
2059 than more) in your system, using colored object information displays
2060 than more) in your system, using colored object information displays
2060 will not work properly. Test it and see."""
2061 will not work properly. Test it and see."""
2061
2062
2062 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2063 self.shell.rc.color_info = 1 - self.shell.rc.color_info
2063 self.magic_colors(self.shell.rc.colors)
2064 self.magic_colors(self.shell.rc.colors)
2064 print 'Object introspection functions have now coloring:',
2065 print 'Object introspection functions have now coloring:',
2065 print ['OFF','ON'][self.shell.rc.color_info]
2066 print ['OFF','ON'][self.shell.rc.color_info]
2066
2067
2067 def magic_Pprint(self, parameter_s=''):
2068 def magic_Pprint(self, parameter_s=''):
2068 """Toggle pretty printing on/off."""
2069 """Toggle pretty printing on/off."""
2069
2070
2070 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2071 self.shell.outputcache.Pprint = 1 - self.shell.outputcache.Pprint
2071 print 'Pretty printing has been turned', \
2072 print 'Pretty printing has been turned', \
2072 ['OFF','ON'][self.shell.outputcache.Pprint]
2073 ['OFF','ON'][self.shell.outputcache.Pprint]
2073
2074
2074 def magic_exit(self, parameter_s=''):
2075 def magic_exit(self, parameter_s=''):
2075 """Exit IPython, confirming if configured to do so.
2076 """Exit IPython, confirming if configured to do so.
2076
2077
2077 You can configure whether IPython asks for confirmation upon exit by
2078 You can configure whether IPython asks for confirmation upon exit by
2078 setting the confirm_exit flag in the ipythonrc file."""
2079 setting the confirm_exit flag in the ipythonrc file."""
2079
2080
2080 self.shell.exit()
2081 self.shell.exit()
2081
2082
2082 def magic_quit(self, parameter_s=''):
2083 def magic_quit(self, parameter_s=''):
2083 """Exit IPython, confirming if configured to do so (like %exit)"""
2084 """Exit IPython, confirming if configured to do so (like %exit)"""
2084
2085
2085 self.shell.exit()
2086 self.shell.exit()
2086
2087
2087 def magic_Exit(self, parameter_s=''):
2088 def magic_Exit(self, parameter_s=''):
2088 """Exit IPython without confirmation."""
2089 """Exit IPython without confirmation."""
2089
2090
2090 self.shell.exit_now = True
2091 self.shell.exit_now = True
2091
2092
2092 def magic_Quit(self, parameter_s=''):
2093 def magic_Quit(self, parameter_s=''):
2093 """Exit IPython without confirmation (like %Exit)."""
2094 """Exit IPython without confirmation (like %Exit)."""
2094
2095
2095 self.shell.exit_now = True
2096 self.shell.exit_now = True
2096
2097
2097 #......................................................................
2098 #......................................................................
2098 # Functions to implement unix shell-type things
2099 # Functions to implement unix shell-type things
2099
2100
2100 def magic_alias(self, parameter_s = ''):
2101 def magic_alias(self, parameter_s = ''):
2101 """Define an alias for a system command.
2102 """Define an alias for a system command.
2102
2103
2103 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2104 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2104
2105
2105 Then, typing 'alias_name params' will execute the system command 'cmd
2106 Then, typing 'alias_name params' will execute the system command 'cmd
2106 params' (from your underlying operating system).
2107 params' (from your underlying operating system).
2107
2108
2108 Aliases have lower precedence than magic functions and Python normal
2109 Aliases have lower precedence than magic functions and Python normal
2109 variables, so if 'foo' is both a Python variable and an alias, the
2110 variables, so if 'foo' is both a Python variable and an alias, the
2110 alias can not be executed until 'del foo' removes the Python variable.
2111 alias can not be executed until 'del foo' removes the Python variable.
2111
2112
2112 You can use the %l specifier in an alias definition to represent the
2113 You can use the %l specifier in an alias definition to represent the
2113 whole line when the alias is called. For example:
2114 whole line when the alias is called. For example:
2114
2115
2115 In [2]: alias all echo "Input in brackets: <%l>"\\
2116 In [2]: alias all echo "Input in brackets: <%l>"\\
2116 In [3]: all hello world\\
2117 In [3]: all hello world\\
2117 Input in brackets: <hello world>
2118 Input in brackets: <hello world>
2118
2119
2119 You can also define aliases with parameters using %s specifiers (one
2120 You can also define aliases with parameters using %s specifiers (one
2120 per parameter):
2121 per parameter):
2121
2122
2122 In [1]: alias parts echo first %s second %s\\
2123 In [1]: alias parts echo first %s second %s\\
2123 In [2]: %parts A B\\
2124 In [2]: %parts A B\\
2124 first A second B\\
2125 first A second B\\
2125 In [3]: %parts A\\
2126 In [3]: %parts A\\
2126 Incorrect number of arguments: 2 expected.\\
2127 Incorrect number of arguments: 2 expected.\\
2127 parts is an alias to: 'echo first %s second %s'
2128 parts is an alias to: 'echo first %s second %s'
2128
2129
2129 Note that %l and %s are mutually exclusive. You can only use one or
2130 Note that %l and %s are mutually exclusive. You can only use one or
2130 the other in your aliases.
2131 the other in your aliases.
2131
2132
2132 Aliases expand Python variables just like system calls using ! or !!
2133 Aliases expand Python variables just like system calls using ! or !!
2133 do: all expressions prefixed with '$' get expanded. For details of
2134 do: all expressions prefixed with '$' get expanded. For details of
2134 the semantic rules, see PEP-215:
2135 the semantic rules, see PEP-215:
2135 http://www.python.org/peps/pep-0215.html. This is the library used by
2136 http://www.python.org/peps/pep-0215.html. This is the library used by
2136 IPython for variable expansion. If you want to access a true shell
2137 IPython for variable expansion. If you want to access a true shell
2137 variable, an extra $ is necessary to prevent its expansion by IPython:
2138 variable, an extra $ is necessary to prevent its expansion by IPython:
2138
2139
2139 In [6]: alias show echo\\
2140 In [6]: alias show echo\\
2140 In [7]: PATH='A Python string'\\
2141 In [7]: PATH='A Python string'\\
2141 In [8]: show $PATH\\
2142 In [8]: show $PATH\\
2142 A Python string\\
2143 A Python string\\
2143 In [9]: show $$PATH\\
2144 In [9]: show $$PATH\\
2144 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2145 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2145
2146
2146 You can use the alias facility to acess all of $PATH. See the %rehash
2147 You can use the alias facility to acess all of $PATH. See the %rehash
2147 and %rehashx functions, which automatically create aliases for the
2148 and %rehashx functions, which automatically create aliases for the
2148 contents of your $PATH.
2149 contents of your $PATH.
2149
2150
2150 If called with no parameters, %alias prints the current alias table."""
2151 If called with no parameters, %alias prints the current alias table."""
2151
2152
2152 par = parameter_s.strip()
2153 par = parameter_s.strip()
2153 if not par:
2154 if not par:
2154 if self.shell.rc.automagic:
2155 if self.shell.rc.automagic:
2155 prechar = ''
2156 prechar = ''
2156 else:
2157 else:
2157 prechar = self.shell.ESC_MAGIC
2158 prechar = self.shell.ESC_MAGIC
2158 print 'Alias\t\tSystem Command\n'+'-'*30
2159 print 'Alias\t\tSystem Command\n'+'-'*30
2159 atab = self.shell.alias_table
2160 atab = self.shell.alias_table
2160 aliases = atab.keys()
2161 aliases = atab.keys()
2161 aliases.sort()
2162 aliases.sort()
2162 for alias in aliases:
2163 for alias in aliases:
2163 print prechar+alias+'\t\t'+atab[alias][1]
2164 print prechar+alias+'\t\t'+atab[alias][1]
2164 print '-'*30+'\nTotal number of aliases:',len(aliases)
2165 print '-'*30+'\nTotal number of aliases:',len(aliases)
2165 return
2166 return
2166 try:
2167 try:
2167 alias,cmd = par.split(None,1)
2168 alias,cmd = par.split(None,1)
2168 except:
2169 except:
2169 print OInspect.getdoc(self.magic_alias)
2170 print OInspect.getdoc(self.magic_alias)
2170 else:
2171 else:
2171 nargs = cmd.count('%s')
2172 nargs = cmd.count('%s')
2172 if nargs>0 and cmd.find('%l')>=0:
2173 if nargs>0 and cmd.find('%l')>=0:
2173 error('The %s and %l specifiers are mutually exclusive '
2174 error('The %s and %l specifiers are mutually exclusive '
2174 'in alias definitions.')
2175 'in alias definitions.')
2175 else: # all looks OK
2176 else: # all looks OK
2176 self.shell.alias_table[alias] = (nargs,cmd)
2177 self.shell.alias_table[alias] = (nargs,cmd)
2177 self.shell.alias_table_validate(verbose=1)
2178 self.shell.alias_table_validate(verbose=1)
2178 # end magic_alias
2179 # end magic_alias
2179
2180
2180 def magic_unalias(self, parameter_s = ''):
2181 def magic_unalias(self, parameter_s = ''):
2181 """Remove an alias"""
2182 """Remove an alias"""
2182
2183
2183 aname = parameter_s.strip()
2184 aname = parameter_s.strip()
2184 if aname in self.shell.alias_table:
2185 if aname in self.shell.alias_table:
2185 del self.shell.alias_table[aname]
2186 del self.shell.alias_table[aname]
2186
2187
2187 def magic_rehash(self, parameter_s = ''):
2188 def magic_rehash(self, parameter_s = ''):
2188 """Update the alias table with all entries in $PATH.
2189 """Update the alias table with all entries in $PATH.
2189
2190
2190 This version does no checks on execute permissions or whether the
2191 This version does no checks on execute permissions or whether the
2191 contents of $PATH are truly files (instead of directories or something
2192 contents of $PATH are truly files (instead of directories or something
2192 else). For such a safer (but slower) version, use %rehashx."""
2193 else). For such a safer (but slower) version, use %rehashx."""
2193
2194
2194 # This function (and rehashx) manipulate the alias_table directly
2195 # This function (and rehashx) manipulate the alias_table directly
2195 # rather than calling magic_alias, for speed reasons. A rehash on a
2196 # rather than calling magic_alias, for speed reasons. A rehash on a
2196 # typical Linux box involves several thousand entries, so efficiency
2197 # typical Linux box involves several thousand entries, so efficiency
2197 # here is a top concern.
2198 # here is a top concern.
2198
2199
2199 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2200 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2200 alias_table = self.shell.alias_table
2201 alias_table = self.shell.alias_table
2201 for pdir in path:
2202 for pdir in path:
2202 for ff in os.listdir(pdir):
2203 for ff in os.listdir(pdir):
2203 # each entry in the alias table must be (N,name), where
2204 # each entry in the alias table must be (N,name), where
2204 # N is the number of positional arguments of the alias.
2205 # N is the number of positional arguments of the alias.
2205 alias_table[ff] = (0,ff)
2206 alias_table[ff] = (0,ff)
2206 # Make sure the alias table doesn't contain keywords or builtins
2207 # Make sure the alias table doesn't contain keywords or builtins
2207 self.shell.alias_table_validate()
2208 self.shell.alias_table_validate()
2208 # Call again init_auto_alias() so we get 'rm -i' and other modified
2209 # Call again init_auto_alias() so we get 'rm -i' and other modified
2209 # aliases since %rehash will probably clobber them
2210 # aliases since %rehash will probably clobber them
2210 self.shell.init_auto_alias()
2211 self.shell.init_auto_alias()
2211
2212
2212 def magic_rehashx(self, parameter_s = ''):
2213 def magic_rehashx(self, parameter_s = ''):
2213 """Update the alias table with all executable files in $PATH.
2214 """Update the alias table with all executable files in $PATH.
2214
2215
2215 This version explicitly checks that every entry in $PATH is a file
2216 This version explicitly checks that every entry in $PATH is a file
2216 with execute access (os.X_OK), so it is much slower than %rehash.
2217 with execute access (os.X_OK), so it is much slower than %rehash.
2217
2218
2218 Under Windows, it checks executability as a match agains a
2219 Under Windows, it checks executability as a match agains a
2219 '|'-separated string of extensions, stored in the IPython config
2220 '|'-separated string of extensions, stored in the IPython config
2220 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2221 variable win_exec_ext. This defaults to 'exe|com|bat'. """
2221
2222
2222 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2223 path = filter(os.path.isdir,os.environ['PATH'].split(os.pathsep))
2223 alias_table = self.shell.alias_table
2224 alias_table = self.shell.alias_table
2224
2225
2225 if os.name == 'posix':
2226 if os.name == 'posix':
2226 isexec = lambda fname:os.path.isfile(fname) and \
2227 isexec = lambda fname:os.path.isfile(fname) and \
2227 os.access(fname,os.X_OK)
2228 os.access(fname,os.X_OK)
2228 else:
2229 else:
2229
2230
2230 try:
2231 try:
2231 winext = os.environ['pathext'].replace(';','|').replace('.','')
2232 winext = os.environ['pathext'].replace(';','|').replace('.','')
2232 except KeyError:
2233 except KeyError:
2233 winext = 'exe|com|bat'
2234 winext = 'exe|com|bat'
2234
2235
2235 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2236 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2236 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2237 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2237 savedir = os.getcwd()
2238 savedir = os.getcwd()
2238 try:
2239 try:
2239 # write the whole loop for posix/Windows so we don't have an if in
2240 # write the whole loop for posix/Windows so we don't have an if in
2240 # the innermost part
2241 # the innermost part
2241 if os.name == 'posix':
2242 if os.name == 'posix':
2242 for pdir in path:
2243 for pdir in path:
2243 os.chdir(pdir)
2244 os.chdir(pdir)
2244 for ff in os.listdir(pdir):
2245 for ff in os.listdir(pdir):
2245 if isexec(ff):
2246 if isexec(ff):
2246 # each entry in the alias table must be (N,name),
2247 # each entry in the alias table must be (N,name),
2247 # where N is the number of positional arguments of the
2248 # where N is the number of positional arguments of the
2248 # alias.
2249 # alias.
2249 alias_table[ff] = (0,ff)
2250 alias_table[ff] = (0,ff)
2250 else:
2251 else:
2251 for pdir in path:
2252 for pdir in path:
2252 os.chdir(pdir)
2253 os.chdir(pdir)
2253 for ff in os.listdir(pdir):
2254 for ff in os.listdir(pdir):
2254 if isexec(ff):
2255 if isexec(ff):
2255 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2256 alias_table[execre.sub(r'\1',ff)] = (0,ff)
2256 # Make sure the alias table doesn't contain keywords or builtins
2257 # Make sure the alias table doesn't contain keywords or builtins
2257 self.shell.alias_table_validate()
2258 self.shell.alias_table_validate()
2258 # Call again init_auto_alias() so we get 'rm -i' and other
2259 # Call again init_auto_alias() so we get 'rm -i' and other
2259 # modified aliases since %rehashx will probably clobber them
2260 # modified aliases since %rehashx will probably clobber them
2260 self.shell.init_auto_alias()
2261 self.shell.init_auto_alias()
2261 finally:
2262 finally:
2262 os.chdir(savedir)
2263 os.chdir(savedir)
2263
2264
2264 def magic_pwd(self, parameter_s = ''):
2265 def magic_pwd(self, parameter_s = ''):
2265 """Return the current working directory path."""
2266 """Return the current working directory path."""
2266 return os.getcwd()
2267 return os.getcwd()
2267
2268
2268 def magic_cd(self, parameter_s=''):
2269 def magic_cd(self, parameter_s=''):
2269 """Change the current working directory.
2270 """Change the current working directory.
2270
2271
2271 This command automatically maintains an internal list of directories
2272 This command automatically maintains an internal list of directories
2272 you visit during your IPython session, in the variable _dh. The
2273 you visit during your IPython session, in the variable _dh. The
2273 command %dhist shows this history nicely formatted.
2274 command %dhist shows this history nicely formatted.
2274
2275
2275 Usage:
2276 Usage:
2276
2277
2277 cd 'dir': changes to directory 'dir'.
2278 cd 'dir': changes to directory 'dir'.
2278
2279
2279 cd -: changes to the last visited directory.
2280 cd -: changes to the last visited directory.
2280
2281
2281 cd -<n>: changes to the n-th directory in the directory history.
2282 cd -<n>: changes to the n-th directory in the directory history.
2282
2283
2283 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2284 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
2284 (note: cd <bookmark_name> is enough if there is no
2285 (note: cd <bookmark_name> is enough if there is no
2285 directory <bookmark_name>, but a bookmark with the name exists.)
2286 directory <bookmark_name>, but a bookmark with the name exists.)
2286
2287
2287 Options:
2288 Options:
2288
2289
2289 -q: quiet. Do not print the working directory after the cd command is
2290 -q: quiet. Do not print the working directory after the cd command is
2290 executed. By default IPython's cd command does print this directory,
2291 executed. By default IPython's cd command does print this directory,
2291 since the default prompts do not display path information.
2292 since the default prompts do not display path information.
2292
2293
2293 Note that !cd doesn't work for this purpose because the shell where
2294 Note that !cd doesn't work for this purpose because the shell where
2294 !command runs is immediately discarded after executing 'command'."""
2295 !command runs is immediately discarded after executing 'command'."""
2295
2296
2296 parameter_s = parameter_s.strip()
2297 parameter_s = parameter_s.strip()
2297 bkms = self.shell.persist.get("bookmarks",{})
2298 bkms = self.shell.persist.get("bookmarks",{})
2298
2299
2299 numcd = re.match(r'(-)(\d+)$',parameter_s)
2300 numcd = re.match(r'(-)(\d+)$',parameter_s)
2300 # jump in directory history by number
2301 # jump in directory history by number
2301 if numcd:
2302 if numcd:
2302 nn = int(numcd.group(2))
2303 nn = int(numcd.group(2))
2303 try:
2304 try:
2304 ps = self.shell.user_ns['_dh'][nn]
2305 ps = self.shell.user_ns['_dh'][nn]
2305 except IndexError:
2306 except IndexError:
2306 print 'The requested directory does not exist in history.'
2307 print 'The requested directory does not exist in history.'
2307 return
2308 return
2308 else:
2309 else:
2309 opts = {}
2310 opts = {}
2310 else:
2311 else:
2311 #turn all non-space-escaping backslashes to slashes,
2312 #turn all non-space-escaping backslashes to slashes,
2312 # for c:\windows\directory\names\
2313 # for c:\windows\directory\names\
2313 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2314 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
2314 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2315 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
2315 # jump to previous
2316 # jump to previous
2316 if ps == '-':
2317 if ps == '-':
2317 try:
2318 try:
2318 ps = self.shell.user_ns['_dh'][-2]
2319 ps = self.shell.user_ns['_dh'][-2]
2319 except IndexError:
2320 except IndexError:
2320 print 'No previous directory to change to.'
2321 print 'No previous directory to change to.'
2321 return
2322 return
2322 # jump to bookmark
2323 # jump to bookmark
2323 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2324 elif opts.has_key('b') or (bkms.has_key(ps) and not os.path.isdir(ps)):
2324 if bkms.has_key(ps):
2325 if bkms.has_key(ps):
2325 target = bkms[ps]
2326 target = bkms[ps]
2326 print '(bookmark:%s) -> %s' % (ps,target)
2327 print '(bookmark:%s) -> %s' % (ps,target)
2327 ps = target
2328 ps = target
2328 else:
2329 else:
2329 if bkms:
2330 if bkms:
2330 error("Bookmark '%s' not found. "
2331 error("Bookmark '%s' not found. "
2331 "Use '%%bookmark -l' to see your bookmarks." % ps)
2332 "Use '%%bookmark -l' to see your bookmarks." % ps)
2332 else:
2333 else:
2333 print "Bookmarks not set - use %bookmark <bookmarkname>"
2334 print "Bookmarks not set - use %bookmark <bookmarkname>"
2334 return
2335 return
2335
2336
2336 # at this point ps should point to the target dir
2337 # at this point ps should point to the target dir
2337 if ps:
2338 if ps:
2338 try:
2339 try:
2339 os.chdir(os.path.expanduser(ps))
2340 os.chdir(os.path.expanduser(ps))
2340 ttitle = ("IPy:" + (
2341 ttitle = ("IPy:" + (
2341 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2342 os.getcwd() == '/' and '/' or os.path.basename(os.getcwd())))
2342 platutils.set_term_title(ttitle)
2343 platutils.set_term_title(ttitle)
2343 except OSError:
2344 except OSError:
2344 print sys.exc_info()[1]
2345 print sys.exc_info()[1]
2345 else:
2346 else:
2346 self.shell.user_ns['_dh'].append(os.getcwd())
2347 self.shell.user_ns['_dh'].append(os.getcwd())
2347 else:
2348 else:
2348 os.chdir(self.shell.home_dir)
2349 os.chdir(self.shell.home_dir)
2349 platutils.set_term_title("IPy:~")
2350 platutils.set_term_title("IPy:~")
2350 self.shell.user_ns['_dh'].append(os.getcwd())
2351 self.shell.user_ns['_dh'].append(os.getcwd())
2351 if not 'q' in opts:
2352 if not 'q' in opts:
2352 print self.shell.user_ns['_dh'][-1]
2353 print self.shell.user_ns['_dh'][-1]
2353
2354
2354 def magic_dhist(self, parameter_s=''):
2355 def magic_dhist(self, parameter_s=''):
2355 """Print your history of visited directories.
2356 """Print your history of visited directories.
2356
2357
2357 %dhist -> print full history\\
2358 %dhist -> print full history\\
2358 %dhist n -> print last n entries only\\
2359 %dhist n -> print last n entries only\\
2359 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2360 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
2360
2361
2361 This history is automatically maintained by the %cd command, and
2362 This history is automatically maintained by the %cd command, and
2362 always available as the global list variable _dh. You can use %cd -<n>
2363 always available as the global list variable _dh. You can use %cd -<n>
2363 to go to directory number <n>."""
2364 to go to directory number <n>."""
2364
2365
2365 dh = self.shell.user_ns['_dh']
2366 dh = self.shell.user_ns['_dh']
2366 if parameter_s:
2367 if parameter_s:
2367 try:
2368 try:
2368 args = map(int,parameter_s.split())
2369 args = map(int,parameter_s.split())
2369 except:
2370 except:
2370 self.arg_err(Magic.magic_dhist)
2371 self.arg_err(Magic.magic_dhist)
2371 return
2372 return
2372 if len(args) == 1:
2373 if len(args) == 1:
2373 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2374 ini,fin = max(len(dh)-(args[0]),0),len(dh)
2374 elif len(args) == 2:
2375 elif len(args) == 2:
2375 ini,fin = args
2376 ini,fin = args
2376 else:
2377 else:
2377 self.arg_err(Magic.magic_dhist)
2378 self.arg_err(Magic.magic_dhist)
2378 return
2379 return
2379 else:
2380 else:
2380 ini,fin = 0,len(dh)
2381 ini,fin = 0,len(dh)
2381 nlprint(dh,
2382 nlprint(dh,
2382 header = 'Directory history (kept in _dh)',
2383 header = 'Directory history (kept in _dh)',
2383 start=ini,stop=fin)
2384 start=ini,stop=fin)
2384
2385
2385 def magic_env(self, parameter_s=''):
2386 def magic_env(self, parameter_s=''):
2386 """List environment variables."""
2387 """List environment variables."""
2387
2388
2388 return os.environ.data
2389 return os.environ.data
2389
2390
2390 def magic_pushd(self, parameter_s=''):
2391 def magic_pushd(self, parameter_s=''):
2391 """Place the current dir on stack and change directory.
2392 """Place the current dir on stack and change directory.
2392
2393
2393 Usage:\\
2394 Usage:\\
2394 %pushd ['dirname']
2395 %pushd ['dirname']
2395
2396
2396 %pushd with no arguments does a %pushd to your home directory.
2397 %pushd with no arguments does a %pushd to your home directory.
2397 """
2398 """
2398 if parameter_s == '': parameter_s = '~'
2399 if parameter_s == '': parameter_s = '~'
2399 dir_s = self.shell.dir_stack
2400 dir_s = self.shell.dir_stack
2400 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2401 if len(dir_s)>0 and os.path.expanduser(parameter_s) != \
2401 os.path.expanduser(self.shell.dir_stack[0]):
2402 os.path.expanduser(self.shell.dir_stack[0]):
2402 try:
2403 try:
2403 self.magic_cd(parameter_s)
2404 self.magic_cd(parameter_s)
2404 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2405 dir_s.insert(0,os.getcwd().replace(self.home_dir,'~'))
2405 self.magic_dirs()
2406 self.magic_dirs()
2406 except:
2407 except:
2407 print 'Invalid directory'
2408 print 'Invalid directory'
2408 else:
2409 else:
2409 print 'You are already there!'
2410 print 'You are already there!'
2410
2411
2411 def magic_popd(self, parameter_s=''):
2412 def magic_popd(self, parameter_s=''):
2412 """Change to directory popped off the top of the stack.
2413 """Change to directory popped off the top of the stack.
2413 """
2414 """
2414 if len (self.shell.dir_stack) > 1:
2415 if len (self.shell.dir_stack) > 1:
2415 self.shell.dir_stack.pop(0)
2416 self.shell.dir_stack.pop(0)
2416 self.magic_cd(self.shell.dir_stack[0])
2417 self.magic_cd(self.shell.dir_stack[0])
2417 print self.shell.dir_stack[0]
2418 print self.shell.dir_stack[0]
2418 else:
2419 else:
2419 print "You can't remove the starting directory from the stack:",\
2420 print "You can't remove the starting directory from the stack:",\
2420 self.shell.dir_stack
2421 self.shell.dir_stack
2421
2422
2422 def magic_dirs(self, parameter_s=''):
2423 def magic_dirs(self, parameter_s=''):
2423 """Return the current directory stack."""
2424 """Return the current directory stack."""
2424
2425
2425 return self.shell.dir_stack[:]
2426 return self.shell.dir_stack[:]
2426
2427
2427 def magic_sc(self, parameter_s=''):
2428 def magic_sc(self, parameter_s=''):
2428 """Shell capture - execute a shell command and capture its output.
2429 """Shell capture - execute a shell command and capture its output.
2429
2430
2430 %sc [options] varname=command
2431 %sc [options] varname=command
2431
2432
2432 IPython will run the given command using commands.getoutput(), and
2433 IPython will run the given command using commands.getoutput(), and
2433 will then update the user's interactive namespace with a variable
2434 will then update the user's interactive namespace with a variable
2434 called varname, containing the value of the call. Your command can
2435 called varname, containing the value of the call. Your command can
2435 contain shell wildcards, pipes, etc.
2436 contain shell wildcards, pipes, etc.
2436
2437
2437 The '=' sign in the syntax is mandatory, and the variable name you
2438 The '=' sign in the syntax is mandatory, and the variable name you
2438 supply must follow Python's standard conventions for valid names.
2439 supply must follow Python's standard conventions for valid names.
2439
2440
2440 Options:
2441 Options:
2441
2442
2442 -l: list output. Split the output on newlines into a list before
2443 -l: list output. Split the output on newlines into a list before
2443 assigning it to the given variable. By default the output is stored
2444 assigning it to the given variable. By default the output is stored
2444 as a single string.
2445 as a single string.
2445
2446
2446 -v: verbose. Print the contents of the variable.
2447 -v: verbose. Print the contents of the variable.
2447
2448
2448 In most cases you should not need to split as a list, because the
2449 In most cases you should not need to split as a list, because the
2449 returned value is a special type of string which can automatically
2450 returned value is a special type of string which can automatically
2450 provide its contents either as a list (split on newlines) or as a
2451 provide its contents either as a list (split on newlines) or as a
2451 space-separated string. These are convenient, respectively, either
2452 space-separated string. These are convenient, respectively, either
2452 for sequential processing or to be passed to a shell command.
2453 for sequential processing or to be passed to a shell command.
2453
2454
2454 For example:
2455 For example:
2455
2456
2456 # Capture into variable a
2457 # Capture into variable a
2457 In [9]: sc a=ls *py
2458 In [9]: sc a=ls *py
2458
2459
2459 # a is a string with embedded newlines
2460 # a is a string with embedded newlines
2460 In [10]: a
2461 In [10]: a
2461 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2462 Out[10]: 'setup.py\nwin32_manual_post_install.py'
2462
2463
2463 # which can be seen as a list:
2464 # which can be seen as a list:
2464 In [11]: a.l
2465 In [11]: a.l
2465 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2466 Out[11]: ['setup.py', 'win32_manual_post_install.py']
2466
2467
2467 # or as a whitespace-separated string:
2468 # or as a whitespace-separated string:
2468 In [12]: a.s
2469 In [12]: a.s
2469 Out[12]: 'setup.py win32_manual_post_install.py'
2470 Out[12]: 'setup.py win32_manual_post_install.py'
2470
2471
2471 # a.s is useful to pass as a single command line:
2472 # a.s is useful to pass as a single command line:
2472 In [13]: !wc -l $a.s
2473 In [13]: !wc -l $a.s
2473 146 setup.py
2474 146 setup.py
2474 130 win32_manual_post_install.py
2475 130 win32_manual_post_install.py
2475 276 total
2476 276 total
2476
2477
2477 # while the list form is useful to loop over:
2478 # while the list form is useful to loop over:
2478 In [14]: for f in a.l:
2479 In [14]: for f in a.l:
2479 ....: !wc -l $f
2480 ....: !wc -l $f
2480 ....:
2481 ....:
2481 146 setup.py
2482 146 setup.py
2482 130 win32_manual_post_install.py
2483 130 win32_manual_post_install.py
2483
2484
2484 Similiarly, the lists returned by the -l option are also special, in
2485 Similiarly, the lists returned by the -l option are also special, in
2485 the sense that you can equally invoke the .s attribute on them to
2486 the sense that you can equally invoke the .s attribute on them to
2486 automatically get a whitespace-separated string from their contents:
2487 automatically get a whitespace-separated string from their contents:
2487
2488
2488 In [1]: sc -l b=ls *py
2489 In [1]: sc -l b=ls *py
2489
2490
2490 In [2]: b
2491 In [2]: b
2491 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2492 Out[2]: ['setup.py', 'win32_manual_post_install.py']
2492
2493
2493 In [3]: b.s
2494 In [3]: b.s
2494 Out[3]: 'setup.py win32_manual_post_install.py'
2495 Out[3]: 'setup.py win32_manual_post_install.py'
2495
2496
2496 In summary, both the lists and strings used for ouptut capture have
2497 In summary, both the lists and strings used for ouptut capture have
2497 the following special attributes:
2498 the following special attributes:
2498
2499
2499 .l (or .list) : value as list.
2500 .l (or .list) : value as list.
2500 .n (or .nlstr): value as newline-separated string.
2501 .n (or .nlstr): value as newline-separated string.
2501 .s (or .spstr): value as space-separated string.
2502 .s (or .spstr): value as space-separated string.
2502 """
2503 """
2503
2504
2504 opts,args = self.parse_options(parameter_s,'lv')
2505 opts,args = self.parse_options(parameter_s,'lv')
2505 # Try to get a variable name and command to run
2506 # Try to get a variable name and command to run
2506 try:
2507 try:
2507 # the variable name must be obtained from the parse_options
2508 # the variable name must be obtained from the parse_options
2508 # output, which uses shlex.split to strip options out.
2509 # output, which uses shlex.split to strip options out.
2509 var,_ = args.split('=',1)
2510 var,_ = args.split('=',1)
2510 var = var.strip()
2511 var = var.strip()
2511 # But the the command has to be extracted from the original input
2512 # But the the command has to be extracted from the original input
2512 # parameter_s, not on what parse_options returns, to avoid the
2513 # parameter_s, not on what parse_options returns, to avoid the
2513 # quote stripping which shlex.split performs on it.
2514 # quote stripping which shlex.split performs on it.
2514 _,cmd = parameter_s.split('=',1)
2515 _,cmd = parameter_s.split('=',1)
2515 except ValueError:
2516 except ValueError:
2516 var,cmd = '',''
2517 var,cmd = '',''
2517 if not var:
2518 if not var:
2518 error('you must specify a variable to assign the command to.')
2519 error('you must specify a variable to assign the command to.')
2519 return
2520 return
2520 # If all looks ok, proceed
2521 # If all looks ok, proceed
2521 out,err = self.shell.getoutputerror(cmd)
2522 out,err = self.shell.getoutputerror(cmd)
2522 if err:
2523 if err:
2523 print >> Term.cerr,err
2524 print >> Term.cerr,err
2524 if opts.has_key('l'):
2525 if opts.has_key('l'):
2525 out = SList(out.split('\n'))
2526 out = SList(out.split('\n'))
2526 else:
2527 else:
2527 out = LSString(out)
2528 out = LSString(out)
2528 if opts.has_key('v'):
2529 if opts.has_key('v'):
2529 print '%s ==\n%s' % (var,pformat(out))
2530 print '%s ==\n%s' % (var,pformat(out))
2530 self.shell.user_ns.update({var:out})
2531 self.shell.user_ns.update({var:out})
2531
2532
2532 def magic_sx(self, parameter_s=''):
2533 def magic_sx(self, parameter_s=''):
2533 """Shell execute - run a shell command and capture its output.
2534 """Shell execute - run a shell command and capture its output.
2534
2535
2535 %sx command
2536 %sx command
2536
2537
2537 IPython will run the given command using commands.getoutput(), and
2538 IPython will run the given command using commands.getoutput(), and
2538 return the result formatted as a list (split on '\\n'). Since the
2539 return the result formatted as a list (split on '\\n'). Since the
2539 output is _returned_, it will be stored in ipython's regular output
2540 output is _returned_, it will be stored in ipython's regular output
2540 cache Out[N] and in the '_N' automatic variables.
2541 cache Out[N] and in the '_N' automatic variables.
2541
2542
2542 Notes:
2543 Notes:
2543
2544
2544 1) If an input line begins with '!!', then %sx is automatically
2545 1) If an input line begins with '!!', then %sx is automatically
2545 invoked. That is, while:
2546 invoked. That is, while:
2546 !ls
2547 !ls
2547 causes ipython to simply issue system('ls'), typing
2548 causes ipython to simply issue system('ls'), typing
2548 !!ls
2549 !!ls
2549 is a shorthand equivalent to:
2550 is a shorthand equivalent to:
2550 %sx ls
2551 %sx ls
2551
2552
2552 2) %sx differs from %sc in that %sx automatically splits into a list,
2553 2) %sx differs from %sc in that %sx automatically splits into a list,
2553 like '%sc -l'. The reason for this is to make it as easy as possible
2554 like '%sc -l'. The reason for this is to make it as easy as possible
2554 to process line-oriented shell output via further python commands.
2555 to process line-oriented shell output via further python commands.
2555 %sc is meant to provide much finer control, but requires more
2556 %sc is meant to provide much finer control, but requires more
2556 typing.
2557 typing.
2557
2558
2558 3) Just like %sc -l, this is a list with special attributes:
2559 3) Just like %sc -l, this is a list with special attributes:
2559
2560
2560 .l (or .list) : value as list.
2561 .l (or .list) : value as list.
2561 .n (or .nlstr): value as newline-separated string.
2562 .n (or .nlstr): value as newline-separated string.
2562 .s (or .spstr): value as whitespace-separated string.
2563 .s (or .spstr): value as whitespace-separated string.
2563
2564
2564 This is very useful when trying to use such lists as arguments to
2565 This is very useful when trying to use such lists as arguments to
2565 system commands."""
2566 system commands."""
2566
2567
2567 if parameter_s:
2568 if parameter_s:
2568 out,err = self.shell.getoutputerror(parameter_s)
2569 out,err = self.shell.getoutputerror(parameter_s)
2569 if err:
2570 if err:
2570 print >> Term.cerr,err
2571 print >> Term.cerr,err
2571 return SList(out.split('\n'))
2572 return SList(out.split('\n'))
2572
2573
2573 def magic_bg(self, parameter_s=''):
2574 def magic_bg(self, parameter_s=''):
2574 """Run a job in the background, in a separate thread.
2575 """Run a job in the background, in a separate thread.
2575
2576
2576 For example,
2577 For example,
2577
2578
2578 %bg myfunc(x,y,z=1)
2579 %bg myfunc(x,y,z=1)
2579
2580
2580 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2581 will execute 'myfunc(x,y,z=1)' in a background thread. As soon as the
2581 execution starts, a message will be printed indicating the job
2582 execution starts, a message will be printed indicating the job
2582 number. If your job number is 5, you can use
2583 number. If your job number is 5, you can use
2583
2584
2584 myvar = jobs.result(5) or myvar = jobs[5].result
2585 myvar = jobs.result(5) or myvar = jobs[5].result
2585
2586
2586 to assign this result to variable 'myvar'.
2587 to assign this result to variable 'myvar'.
2587
2588
2588 IPython has a job manager, accessible via the 'jobs' object. You can
2589 IPython has a job manager, accessible via the 'jobs' object. You can
2589 type jobs? to get more information about it, and use jobs.<TAB> to see
2590 type jobs? to get more information about it, and use jobs.<TAB> to see
2590 its attributes. All attributes not starting with an underscore are
2591 its attributes. All attributes not starting with an underscore are
2591 meant for public use.
2592 meant for public use.
2592
2593
2593 In particular, look at the jobs.new() method, which is used to create
2594 In particular, look at the jobs.new() method, which is used to create
2594 new jobs. This magic %bg function is just a convenience wrapper
2595 new jobs. This magic %bg function is just a convenience wrapper
2595 around jobs.new(), for expression-based jobs. If you want to create a
2596 around jobs.new(), for expression-based jobs. If you want to create a
2596 new job with an explicit function object and arguments, you must call
2597 new job with an explicit function object and arguments, you must call
2597 jobs.new() directly.
2598 jobs.new() directly.
2598
2599
2599 The jobs.new docstring also describes in detail several important
2600 The jobs.new docstring also describes in detail several important
2600 caveats associated with a thread-based model for background job
2601 caveats associated with a thread-based model for background job
2601 execution. Type jobs.new? for details.
2602 execution. Type jobs.new? for details.
2602
2603
2603 You can check the status of all jobs with jobs.status().
2604 You can check the status of all jobs with jobs.status().
2604
2605
2605 The jobs variable is set by IPython into the Python builtin namespace.
2606 The jobs variable is set by IPython into the Python builtin namespace.
2606 If you ever declare a variable named 'jobs', you will shadow this
2607 If you ever declare a variable named 'jobs', you will shadow this
2607 name. You can either delete your global jobs variable to regain
2608 name. You can either delete your global jobs variable to regain
2608 access to the job manager, or make a new name and assign it manually
2609 access to the job manager, or make a new name and assign it manually
2609 to the manager (stored in IPython's namespace). For example, to
2610 to the manager (stored in IPython's namespace). For example, to
2610 assign the job manager to the Jobs name, use:
2611 assign the job manager to the Jobs name, use:
2611
2612
2612 Jobs = __builtins__.jobs"""
2613 Jobs = __builtins__.jobs"""
2613
2614
2614 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2615 self.shell.jobs.new(parameter_s,self.shell.user_ns)
2615
2616
2616 def magic_store(self, parameter_s=''):
2617 def magic_store(self, parameter_s=''):
2617 """Lightweight persistence for python variables.
2618 """Lightweight persistence for python variables.
2618
2619
2619 Example:
2620 Example:
2620
2621
2621 ville@badger[~]|1> A = ['hello',10,'world']\\
2622 ville@badger[~]|1> A = ['hello',10,'world']\\
2622 ville@badger[~]|2> %store A\\
2623 ville@badger[~]|2> %store A\\
2623 ville@badger[~]|3> Exit
2624 ville@badger[~]|3> Exit
2624
2625
2625 (IPython session is closed and started again...)
2626 (IPython session is closed and started again...)
2626
2627
2627 ville@badger:~$ ipython -p pysh\\
2628 ville@badger:~$ ipython -p pysh\\
2628 ville@badger[~]|1> print A
2629 ville@badger[~]|1> print A
2629
2630
2630 ['hello', 10, 'world']
2631 ['hello', 10, 'world']
2631
2632
2632 Usage:
2633 Usage:
2633
2634
2634 %store - Show list of all variables and their current values\\
2635 %store - Show list of all variables and their current values\\
2635 %store <var> - Store the *current* value of the variable to disk\\
2636 %store <var> - Store the *current* value of the variable to disk\\
2636 %store -d <var> - Remove the variable and its value from storage\\
2637 %store -d <var> - Remove the variable and its value from storage\\
2637 %store -r - Remove all variables from storage
2638 %store -r - Remove all variables from storage
2638
2639
2639 It should be noted that if you change the value of a variable, you
2640 It should be noted that if you change the value of a variable, you
2640 need to %store it again if you want to persist the new value.
2641 need to %store it again if you want to persist the new value.
2641
2642
2642 Note also that the variables will need to be pickleable; most basic
2643 Note also that the variables will need to be pickleable; most basic
2643 python types can be safely %stored.
2644 python types can be safely %stored.
2644 """
2645 """
2645
2646
2646 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2647 opts,args = self.parse_options(parameter_s,'dr',mode='list')
2647 # delete
2648 # delete
2648 if opts.has_key('d'):
2649 if opts.has_key('d'):
2649 try:
2650 try:
2650 todel = args[0]
2651 todel = args[0]
2651 except IndexError:
2652 except IndexError:
2652 error('You must provide the variable to forget')
2653 error('You must provide the variable to forget')
2653 else:
2654 else:
2654 try:
2655 try:
2655 del self.shell.persist['S:' + todel]
2656 del self.shell.persist['S:' + todel]
2656 except:
2657 except:
2657 error("Can't delete variable '%s'" % todel)
2658 error("Can't delete variable '%s'" % todel)
2658 # reset
2659 # reset
2659 elif opts.has_key('r'):
2660 elif opts.has_key('r'):
2660 for k in self.shell.persist.keys():
2661 for k in self.shell.persist.keys():
2661 if k.startswith('S:'):
2662 if k.startswith('S:'):
2662 del self.shell.persist[k]
2663 del self.shell.persist[k]
2663
2664
2664 # run without arguments -> list variables & values
2665 # run without arguments -> list variables & values
2665 elif not args:
2666 elif not args:
2666 vars = [v[2:] for v in self.shell.persist.keys()
2667 vars = [v[2:] for v in self.shell.persist.keys()
2667 if v.startswith('S:')]
2668 if v.startswith('S:')]
2668 vars.sort()
2669 vars.sort()
2669 if vars:
2670 if vars:
2670 size = max(map(len,vars))
2671 size = max(map(len,vars))
2671 else:
2672 else:
2672 size = 0
2673 size = 0
2673
2674
2674 print 'Stored variables and their in-memory values:'
2675 print 'Stored variables and their in-memory values:'
2675 fmt = '%-'+str(size)+'s -> %s'
2676 fmt = '%-'+str(size)+'s -> %s'
2676 get = self.shell.user_ns.get
2677 get = self.shell.user_ns.get
2677 for var in vars:
2678 for var in vars:
2678 # print 30 first characters from every var
2679 # print 30 first characters from every var
2679 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2680 print fmt % (var,repr(get(var,'<unavailable>'))[:50])
2680
2681
2681 # default action - store the variable
2682 # default action - store the variable
2682 else:
2683 else:
2683 obj = self.shell.user_ns[args[0] ]
2684 obj = self.shell.user_ns[args[0] ]
2684 if isinstance(inspect.getmodule(obj), FakeModule):
2685 if isinstance(inspect.getmodule(obj), FakeModule):
2685 print textwrap.dedent("""\
2686 print textwrap.dedent("""\
2686 Warning:%s is %s
2687 Warning:%s is %s
2687 Proper storage of interactively declared classes (or instances
2688 Proper storage of interactively declared classes (or instances
2688 of those classes) is not possible! Only instances
2689 of those classes) is not possible! Only instances
2689 of classes in real modules on file system can be %%store'd.
2690 of classes in real modules on file system can be %%store'd.
2690 """ % (args[0], obj) )
2691 """ % (args[0], obj) )
2691 return
2692 return
2692 pickled = pickle.dumps(obj)
2693 pickled = pickle.dumps(obj)
2693 self.shell.persist[ 'S:' + args[0] ] = pickled
2694 self.shell.persist[ 'S:' + args[0] ] = pickled
2694 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2695 print "Stored '%s' (%d bytes)" % (args[0], len(pickled))
2695
2696
2696 def magic_bookmark(self, parameter_s=''):
2697 def magic_bookmark(self, parameter_s=''):
2697 """Manage IPython's bookmark system.
2698 """Manage IPython's bookmark system.
2698
2699
2699 %bookmark <name> - set bookmark to current dir
2700 %bookmark <name> - set bookmark to current dir
2700 %bookmark <name> <dir> - set bookmark to <dir>
2701 %bookmark <name> <dir> - set bookmark to <dir>
2701 %bookmark -l - list all bookmarks
2702 %bookmark -l - list all bookmarks
2702 %bookmark -d <name> - remove bookmark
2703 %bookmark -d <name> - remove bookmark
2703 %bookmark -r - remove all bookmarks
2704 %bookmark -r - remove all bookmarks
2704
2705
2705 You can later on access a bookmarked folder with:
2706 You can later on access a bookmarked folder with:
2706 %cd -b <name>
2707 %cd -b <name>
2707 or simply '%cd <name>' if there is no directory called <name> AND
2708 or simply '%cd <name>' if there is no directory called <name> AND
2708 there is such a bookmark defined.
2709 there is such a bookmark defined.
2709
2710
2710 Your bookmarks persist through IPython sessions, but they are
2711 Your bookmarks persist through IPython sessions, but they are
2711 associated with each profile."""
2712 associated with each profile."""
2712
2713
2713 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2714 opts,args = self.parse_options(parameter_s,'drl',mode='list')
2714 if len(args) > 2:
2715 if len(args) > 2:
2715 error('You can only give at most two arguments')
2716 error('You can only give at most two arguments')
2716 return
2717 return
2717
2718
2718 bkms = self.shell.persist.get('bookmarks',{})
2719 bkms = self.shell.persist.get('bookmarks',{})
2719
2720
2720 if opts.has_key('d'):
2721 if opts.has_key('d'):
2721 try:
2722 try:
2722 todel = args[0]
2723 todel = args[0]
2723 except IndexError:
2724 except IndexError:
2724 error('You must provide a bookmark to delete')
2725 error('You must provide a bookmark to delete')
2725 else:
2726 else:
2726 try:
2727 try:
2727 del bkms[todel]
2728 del bkms[todel]
2728 except:
2729 except:
2729 error("Can't delete bookmark '%s'" % todel)
2730 error("Can't delete bookmark '%s'" % todel)
2730 elif opts.has_key('r'):
2731 elif opts.has_key('r'):
2731 bkms = {}
2732 bkms = {}
2732 elif opts.has_key('l'):
2733 elif opts.has_key('l'):
2733 bks = bkms.keys()
2734 bks = bkms.keys()
2734 bks.sort()
2735 bks.sort()
2735 if bks:
2736 if bks:
2736 size = max(map(len,bks))
2737 size = max(map(len,bks))
2737 else:
2738 else:
2738 size = 0
2739 size = 0
2739 fmt = '%-'+str(size)+'s -> %s'
2740 fmt = '%-'+str(size)+'s -> %s'
2740 print 'Current bookmarks:'
2741 print 'Current bookmarks:'
2741 for bk in bks:
2742 for bk in bks:
2742 print fmt % (bk,bkms[bk])
2743 print fmt % (bk,bkms[bk])
2743 else:
2744 else:
2744 if not args:
2745 if not args:
2745 error("You must specify the bookmark name")
2746 error("You must specify the bookmark name")
2746 elif len(args)==1:
2747 elif len(args)==1:
2747 bkms[args[0]] = os.getcwd()
2748 bkms[args[0]] = os.getcwd()
2748 elif len(args)==2:
2749 elif len(args)==2:
2749 bkms[args[0]] = args[1]
2750 bkms[args[0]] = args[1]
2750 self.shell.persist['bookmarks'] = bkms
2751 self.shell.persist['bookmarks'] = bkms
2751
2752
2752 def magic_pycat(self, parameter_s=''):
2753 def magic_pycat(self, parameter_s=''):
2753 """Show a syntax-highlighted file through a pager.
2754 """Show a syntax-highlighted file through a pager.
2754
2755
2755 This magic is similar to the cat utility, but it will assume the file
2756 This magic is similar to the cat utility, but it will assume the file
2756 to be Python source and will show it with syntax highlighting. """
2757 to be Python source and will show it with syntax highlighting. """
2757
2758
2758 filename = get_py_filename(parameter_s)
2759 filename = get_py_filename(parameter_s)
2759 page(self.shell.pycolorize(file_read(filename)),
2760 page(self.shell.pycolorize(file_read(filename)),
2760 screen_lines=self.shell.rc.screen_length)
2761 screen_lines=self.shell.rc.screen_length)
2761
2762
2763 def magic_paste(self, parameter_s=''):
2764 """Allows you to paste & execute a pre-formatted code block from
2765 clipboard.
2766
2767 You must terminate the block with '--' (two minus-signs) alone on the
2768 line.
2769
2770 The block is dedented prior to execution to enable execution of
2771 method definitions. The executed block is also assigned to variable
2772 named 'pasted_block' for later editing with %edit.
2773
2774 You can also pass a variable name as an argument, e.g. '%paste foo'.
2775 This assigns the pasted block to variable 'foo' as string, without
2776 dedenting or executing it.
2777
2778 Do not be alarmed by garbled output on Windows (it's a readline bug).
2779 Just press enter and type -- (and press enter again) and the block
2780 will be what was just pasted.
2781
2782 IPython statements (magics, shell escapes) are not supported (yet).
2783 """
2784 par = parameter_s.strip()
2785 from IPython import iplib
2786 lines = []
2787 while 1:
2788 l = iplib.raw_input_original(':')
2789 if l =='--':
2790 break
2791 lines.append(l)
2792 block = "\n".join(lines)
2793 #print "block:\n",block
2794 if not par:
2795 b = textwrap.dedent(block)
2796 self.runsource(b)
2797 self.user_ns['pasted_block'] = b
2798 else:
2799 self.user_ns[par] = block
2800 print "Block assigned to '%s'" % par
2801
2802
2803
2762 # end Magic
2804 # end Magic
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now