##// END OF EJS Templates
Ready for 0.7.0 release!...
fperez -
Show More

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

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