##// END OF EJS Templates
%autocall fixes...
fperez -
Show More

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

@@ -1,1751 +1,1745 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 General purpose utilities.
3 General purpose utilities.
4
4
5 This is a grab-bag of stuff I find useful in most programs I write. Some of
5 This is a grab-bag of stuff I find useful in most programs I write. Some of
6 these things are also convenient when working at the command line.
6 these things are also convenient when working at the command line.
7
7
8 $Id: genutils.py 1007 2006-01-12 17:15:41Z vivainio $"""
8 $Id: genutils.py 1013 2006-01-13 08:33:32Z fperez $"""
9
9
10 #*****************************************************************************
10 #*****************************************************************************
11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
11 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
12 #
12 #
13 # Distributed under the terms of the BSD License. The full license is in
13 # Distributed under the terms of the BSD License. The full license is in
14 # the file COPYING, distributed as part of this software.
14 # the file COPYING, distributed as part of this software.
15 #*****************************************************************************
15 #*****************************************************************************
16
16
17 from __future__ import generators # 2.2 compatibility
17 from __future__ import generators # 2.2 compatibility
18
18
19 from IPython import Release
19 from IPython import Release
20 __author__ = '%s <%s>' % Release.authors['Fernando']
20 __author__ = '%s <%s>' % Release.authors['Fernando']
21 __license__ = Release.license
21 __license__ = Release.license
22
22
23 #****************************************************************************
23 #****************************************************************************
24 # required modules from the Python standard library
24 # required modules from the Python standard library
25 import __main__
25 import __main__
26 import commands
26 import commands
27 import os
27 import os
28 import re
28 import re
29 import shlex
29 import shlex
30 import shutil
30 import shutil
31 import sys
31 import sys
32 import tempfile
32 import tempfile
33 import time
33 import time
34 import types
34 import types
35
35
36 # Other IPython utilities
36 # Other IPython utilities
37 from IPython.Itpl import Itpl,itpl,printpl
37 from IPython.Itpl import Itpl,itpl,printpl
38 from IPython import DPyGetOpt
38 from IPython import DPyGetOpt
39
39
40 if os.name == "nt":
40 if os.name == "nt":
41 from IPython.winconsole import get_console_size
41 from IPython.winconsole import get_console_size
42
42
43 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
43 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
44 # 2.2-friendly
44 # 2.2-friendly
45 try:
45 try:
46 basestring
46 basestring
47 except NameError:
47 except NameError:
48 import types
48 import types
49 basestring = (types.StringType, types.UnicodeType)
49 basestring = (types.StringType, types.UnicodeType)
50 True = 1==1
50 True = 1==1
51 False = 1==0
51 False = 1==0
52
52
53 def enumerate(obj):
53 def enumerate(obj):
54 i = -1
54 i = -1
55 for item in obj:
55 for item in obj:
56 i += 1
56 i += 1
57 yield i, item
57 yield i, item
58
58
59 # add these to the builtin namespace, so that all modules find them
59 # add these to the builtin namespace, so that all modules find them
60 import __builtin__
60 import __builtin__
61 __builtin__.basestring = basestring
61 __builtin__.basestring = basestring
62 __builtin__.True = True
62 __builtin__.True = True
63 __builtin__.False = False
63 __builtin__.False = False
64 __builtin__.enumerate = enumerate
64 __builtin__.enumerate = enumerate
65
65
66 # Try to use shlex.split for converting an input string into a sys.argv-type
66 # Try to use shlex.split for converting an input string into a sys.argv-type
67 # list. This appeared in Python 2.3, so here's a quick backport for 2.2.
67 # list. This appeared in Python 2.3, so here's a quick backport for 2.2.
68 try:
68 try:
69 shlex_split = shlex.split
69 shlex_split = shlex.split
70 except AttributeError:
70 except AttributeError:
71 _quotesre = re.compile(r'[\'"](.*)[\'"]')
71 _quotesre = re.compile(r'[\'"](.*)[\'"]')
72 _wordchars = ('abcdfeghijklmnopqrstuvwxyz'
72 _wordchars = ('abcdfeghijklmnopqrstuvwxyz'
73 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?'
73 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-.~*?'
74 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
74 'ßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ'
75 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s'
75 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ%s'
76 % os.sep)
76 % os.sep)
77
77
78 def shlex_split(s):
78 def shlex_split(s):
79 """Simplified backport to Python 2.2 of shlex.split().
79 """Simplified backport to Python 2.2 of shlex.split().
80
80
81 This is a quick and dirty hack, since the shlex module under 2.2 lacks
81 This is a quick and dirty hack, since the shlex module under 2.2 lacks
82 several of the features needed to really match the functionality of
82 several of the features needed to really match the functionality of
83 shlex.split() in 2.3."""
83 shlex.split() in 2.3."""
84
84
85 lex = shlex.shlex(StringIO(s))
85 lex = shlex.shlex(StringIO(s))
86 # Try to get options, extensions and path separators as characters
86 # Try to get options, extensions and path separators as characters
87 lex.wordchars = _wordchars
87 lex.wordchars = _wordchars
88 lex.commenters = ''
88 lex.commenters = ''
89 # Make a list out of the lexer by hand, since in 2.2 it's not an
89 # Make a list out of the lexer by hand, since in 2.2 it's not an
90 # iterator.
90 # iterator.
91 lout = []
91 lout = []
92 while 1:
92 while 1:
93 token = lex.get_token()
93 token = lex.get_token()
94 if token == '':
94 if token == '':
95 break
95 break
96 # Try to handle quoted tokens correctly
96 # Try to handle quoted tokens correctly
97 quotes = _quotesre.match(token)
97 quotes = _quotesre.match(token)
98 if quotes:
98 if quotes:
99 token = quotes.group(1)
99 token = quotes.group(1)
100 lout.append(token)
100 lout.append(token)
101 return lout
101 return lout
102
102
103 #****************************************************************************
103 #****************************************************************************
104 # Exceptions
104 # Exceptions
105 class Error(Exception):
105 class Error(Exception):
106 """Base class for exceptions in this module."""
106 """Base class for exceptions in this module."""
107 pass
107 pass
108
108
109 #----------------------------------------------------------------------------
109 #----------------------------------------------------------------------------
110 class IOStream:
110 class IOStream:
111 def __init__(self,stream,fallback):
111 def __init__(self,stream,fallback):
112 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
112 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
113 stream = fallback
113 stream = fallback
114 self.stream = stream
114 self.stream = stream
115 self._swrite = stream.write
115 self._swrite = stream.write
116 self.flush = stream.flush
116 self.flush = stream.flush
117
117
118 def write(self,data):
118 def write(self,data):
119 try:
119 try:
120 self._swrite(data)
120 self._swrite(data)
121 except:
121 except:
122 try:
122 try:
123 # print handles some unicode issues which may trip a plain
123 # print handles some unicode issues which may trip a plain
124 # write() call. Attempt to emulate write() by using a
124 # write() call. Attempt to emulate write() by using a
125 # trailing comma
125 # trailing comma
126 print >> self.stream, data,
126 print >> self.stream, data,
127 except:
127 except:
128 # if we get here, something is seriously broken.
128 # if we get here, something is seriously broken.
129 print >> sys.stderr, \
129 print >> sys.stderr, \
130 'ERROR - failed to write data to stream:', stream
130 'ERROR - failed to write data to stream:', stream
131
131
132 class IOTerm:
132 class IOTerm:
133 """ Term holds the file or file-like objects for handling I/O operations.
133 """ Term holds the file or file-like objects for handling I/O operations.
134
134
135 These are normally just sys.stdin, sys.stdout and sys.stderr but for
135 These are normally just sys.stdin, sys.stdout and sys.stderr but for
136 Windows they can can replaced to allow editing the strings before they are
136 Windows they can can replaced to allow editing the strings before they are
137 displayed."""
137 displayed."""
138
138
139 # In the future, having IPython channel all its I/O operations through
139 # In the future, having IPython channel all its I/O operations through
140 # this class will make it easier to embed it into other environments which
140 # this class will make it easier to embed it into other environments which
141 # are not a normal terminal (such as a GUI-based shell)
141 # are not a normal terminal (such as a GUI-based shell)
142 def __init__(self,cin=None,cout=None,cerr=None):
142 def __init__(self,cin=None,cout=None,cerr=None):
143 self.cin = IOStream(cin,sys.stdin)
143 self.cin = IOStream(cin,sys.stdin)
144 self.cout = IOStream(cout,sys.stdout)
144 self.cout = IOStream(cout,sys.stdout)
145 self.cerr = IOStream(cerr,sys.stderr)
145 self.cerr = IOStream(cerr,sys.stderr)
146
146
147 # Global variable to be used for all I/O
147 # Global variable to be used for all I/O
148 Term = IOTerm()
148 Term = IOTerm()
149
149
150 # Windows-specific code to load Gary Bishop's readline and configure it
150 # Windows-specific code to load Gary Bishop's readline and configure it
151 # automatically for the users
151 # automatically for the users
152 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
152 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
153 # windows. Cygwin returns 'cygwin' for sys.platform.
153 # windows. Cygwin returns 'cygwin' for sys.platform.
154 if os.name == 'nt':
154 if os.name == 'nt':
155 try:
155 try:
156 import readline
156 import readline
157 except ImportError:
157 except ImportError:
158 pass
158 pass
159 else:
159 else:
160 try:
160 try:
161 _out = readline.GetOutputFile()
161 _out = readline.GetOutputFile()
162 except AttributeError:
162 except AttributeError:
163 pass
163 pass
164 else:
164 else:
165 # Remake Term to use the readline i/o facilities
165 # Remake Term to use the readline i/o facilities
166 Term = IOTerm(cout=_out,cerr=_out)
166 Term = IOTerm(cout=_out,cerr=_out)
167 del _out
167 del _out
168
168
169 #****************************************************************************
169 #****************************************************************************
170 # Generic warning/error printer, used by everything else
170 # Generic warning/error printer, used by everything else
171 def warn(msg,level=2,exit_val=1):
171 def warn(msg,level=2,exit_val=1):
172 """Standard warning printer. Gives formatting consistency.
172 """Standard warning printer. Gives formatting consistency.
173
173
174 Output is sent to Term.cerr (sys.stderr by default).
174 Output is sent to Term.cerr (sys.stderr by default).
175
175
176 Options:
176 Options:
177
177
178 -level(2): allows finer control:
178 -level(2): allows finer control:
179 0 -> Do nothing, dummy function.
179 0 -> Do nothing, dummy function.
180 1 -> Print message.
180 1 -> Print message.
181 2 -> Print 'WARNING:' + message. (Default level).
181 2 -> Print 'WARNING:' + message. (Default level).
182 3 -> Print 'ERROR:' + message.
182 3 -> Print 'ERROR:' + message.
183 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
183 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
184
184
185 -exit_val (1): exit value returned by sys.exit() for a level 4
185 -exit_val (1): exit value returned by sys.exit() for a level 4
186 warning. Ignored for all other levels."""
186 warning. Ignored for all other levels."""
187
187
188 if level>0:
188 if level>0:
189 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
189 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
190 print >> Term.cerr, '%s%s' % (header[level],msg)
190 print >> Term.cerr, '%s%s' % (header[level],msg)
191 if level == 4:
191 if level == 4:
192 print >> Term.cerr,'Exiting.\n'
192 print >> Term.cerr,'Exiting.\n'
193 sys.exit(exit_val)
193 sys.exit(exit_val)
194
194
195 def info(msg):
195 def info(msg):
196 """Equivalent to warn(msg,level=1)."""
196 """Equivalent to warn(msg,level=1)."""
197
197
198 warn(msg,level=1)
198 warn(msg,level=1)
199
199
200 def error(msg):
200 def error(msg):
201 """Equivalent to warn(msg,level=3)."""
201 """Equivalent to warn(msg,level=3)."""
202
202
203 warn(msg,level=3)
203 warn(msg,level=3)
204
204
205 def fatal(msg,exit_val=1):
205 def fatal(msg,exit_val=1):
206 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
206 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
207
207
208 warn(msg,exit_val=exit_val,level=4)
208 warn(msg,exit_val=exit_val,level=4)
209
209
210
210
211 # useful for debugging
211 # useful for debugging
212 def debugp(expr):
212 def debugp(expr):
213 """Print the value of an expression from the caller's frame.
213 """Print the value of an expression from the caller's frame.
214
214
215 Takes an expression, evaluates it in the caller's frame and prints both
215 Takes an expression, evaluates it in the caller's frame and prints both
216 the given expression and the resulting value. The input must be of a form
216 the given expression and the resulting value. The input must be of a form
217 suitable for eval()."""
217 suitable for eval()."""
218
218
219 cf = sys._getframe(1)
219 cf = sys._getframe(1)
220 print '[DBG] %s -> %r' % (expr,eval(expr,cf.f_globals,cf.f_locals))
220 print '[DBG] %s -> %r' % (expr,eval(expr,cf.f_globals,cf.f_locals))
221
221
222 #----------------------------------------------------------------------------
222 #----------------------------------------------------------------------------
223 StringTypes = types.StringTypes
223 StringTypes = types.StringTypes
224
224
225 # Basic timing functionality
225 # Basic timing functionality
226
226
227 # If possible (Unix), use the resource module instead of time.clock()
227 # If possible (Unix), use the resource module instead of time.clock()
228 try:
228 try:
229 import resource
229 import resource
230 def clock():
230 def clock():
231 """clock() -> floating point number
231 """clock() -> floating point number
232
232
233 Return the CPU time in seconds (user time only, system time is
233 Return the CPU time in seconds (user time only, system time is
234 ignored) since the start of the process. This is done via a call to
234 ignored) since the start of the process. This is done via a call to
235 resource.getrusage, so it avoids the wraparound problems in
235 resource.getrusage, so it avoids the wraparound problems in
236 time.clock()."""
236 time.clock()."""
237
237
238 return resource.getrusage(resource.RUSAGE_SELF)[0]
238 return resource.getrusage(resource.RUSAGE_SELF)[0]
239
239
240 def clock2():
240 def clock2():
241 """clock2() -> (t_user,t_system)
241 """clock2() -> (t_user,t_system)
242
242
243 Similar to clock(), but return a tuple of user/system times."""
243 Similar to clock(), but return a tuple of user/system times."""
244 return resource.getrusage(resource.RUSAGE_SELF)[:2]
244 return resource.getrusage(resource.RUSAGE_SELF)[:2]
245
245
246 except ImportError:
246 except ImportError:
247 clock = time.clock
247 clock = time.clock
248 def clock2():
248 def clock2():
249 """Under windows, system CPU time can't be measured.
249 """Under windows, system CPU time can't be measured.
250
250
251 This just returns clock() and zero."""
251 This just returns clock() and zero."""
252 return time.clock(),0.0
252 return time.clock(),0.0
253
253
254 def timings_out(reps,func,*args,**kw):
254 def timings_out(reps,func,*args,**kw):
255 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
255 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
256
256
257 Execute a function reps times, return a tuple with the elapsed total
257 Execute a function reps times, return a tuple with the elapsed total
258 CPU time in seconds, the time per call and the function's output.
258 CPU time in seconds, the time per call and the function's output.
259
259
260 Under Unix, the return value is the sum of user+system time consumed by
260 Under Unix, the return value is the sum of user+system time consumed by
261 the process, computed via the resource module. This prevents problems
261 the process, computed via the resource module. This prevents problems
262 related to the wraparound effect which the time.clock() function has.
262 related to the wraparound effect which the time.clock() function has.
263
263
264 Under Windows the return value is in wall clock seconds. See the
264 Under Windows the return value is in wall clock seconds. See the
265 documentation for the time module for more details."""
265 documentation for the time module for more details."""
266
266
267 reps = int(reps)
267 reps = int(reps)
268 assert reps >=1, 'reps must be >= 1'
268 assert reps >=1, 'reps must be >= 1'
269 if reps==1:
269 if reps==1:
270 start = clock()
270 start = clock()
271 out = func(*args,**kw)
271 out = func(*args,**kw)
272 tot_time = clock()-start
272 tot_time = clock()-start
273 else:
273 else:
274 rng = xrange(reps-1) # the last time is executed separately to store output
274 rng = xrange(reps-1) # the last time is executed separately to store output
275 start = clock()
275 start = clock()
276 for dummy in rng: func(*args,**kw)
276 for dummy in rng: func(*args,**kw)
277 out = func(*args,**kw) # one last time
277 out = func(*args,**kw) # one last time
278 tot_time = clock()-start
278 tot_time = clock()-start
279 av_time = tot_time / reps
279 av_time = tot_time / reps
280 return tot_time,av_time,out
280 return tot_time,av_time,out
281
281
282 def timings(reps,func,*args,**kw):
282 def timings(reps,func,*args,**kw):
283 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
283 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
284
284
285 Execute a function reps times, return a tuple with the elapsed total CPU
285 Execute a function reps times, return a tuple with the elapsed total CPU
286 time in seconds and the time per call. These are just the first two values
286 time in seconds and the time per call. These are just the first two values
287 in timings_out()."""
287 in timings_out()."""
288
288
289 return timings_out(reps,func,*args,**kw)[0:2]
289 return timings_out(reps,func,*args,**kw)[0:2]
290
290
291 def timing(func,*args,**kw):
291 def timing(func,*args,**kw):
292 """timing(func,*args,**kw) -> t_total
292 """timing(func,*args,**kw) -> t_total
293
293
294 Execute a function once, return the elapsed total CPU time in
294 Execute a function once, return the elapsed total CPU time in
295 seconds. This is just the first value in timings_out()."""
295 seconds. This is just the first value in timings_out()."""
296
296
297 return timings_out(1,func,*args,**kw)[0]
297 return timings_out(1,func,*args,**kw)[0]
298
298
299 #****************************************************************************
299 #****************************************************************************
300 # file and system
300 # file and system
301
301
302 def system(cmd,verbose=0,debug=0,header=''):
302 def system(cmd,verbose=0,debug=0,header=''):
303 """Execute a system command, return its exit status.
303 """Execute a system command, return its exit status.
304
304
305 Options:
305 Options:
306
306
307 - verbose (0): print the command to be executed.
307 - verbose (0): print the command to be executed.
308
308
309 - debug (0): only print, do not actually execute.
309 - debug (0): only print, do not actually execute.
310
310
311 - header (''): Header to print on screen prior to the executed command (it
311 - header (''): Header to print on screen prior to the executed command (it
312 is only prepended to the command, no newlines are added).
312 is only prepended to the command, no newlines are added).
313
313
314 Note: a stateful version of this function is available through the
314 Note: a stateful version of this function is available through the
315 SystemExec class."""
315 SystemExec class."""
316
316
317 stat = 0
317 stat = 0
318 if verbose or debug: print header+cmd
318 if verbose or debug: print header+cmd
319 sys.stdout.flush()
319 sys.stdout.flush()
320 if not debug: stat = os.system(cmd)
320 if not debug: stat = os.system(cmd)
321 return stat
321 return stat
322
322
323 # This function is used by ipython in a lot of places to make system calls.
323 # This function is used by ipython in a lot of places to make system calls.
324 # We need it to be slightly different under win32, due to the vagaries of
324 # We need it to be slightly different under win32, due to the vagaries of
325 # 'network shares'. A win32 override is below.
325 # 'network shares'. A win32 override is below.
326
326
327 def shell(cmd,verbose=0,debug=0,header=''):
327 def shell(cmd,verbose=0,debug=0,header=''):
328 """Execute a command in the system shell, always return None.
328 """Execute a command in the system shell, always return None.
329
329
330 Options:
330 Options:
331
331
332 - verbose (0): print the command to be executed.
332 - verbose (0): print the command to be executed.
333
333
334 - debug (0): only print, do not actually execute.
334 - debug (0): only print, do not actually execute.
335
335
336 - header (''): Header to print on screen prior to the executed command (it
336 - header (''): Header to print on screen prior to the executed command (it
337 is only prepended to the command, no newlines are added).
337 is only prepended to the command, no newlines are added).
338
338
339 Note: this is similar to genutils.system(), but it returns None so it can
339 Note: this is similar to genutils.system(), but it returns None so it can
340 be conveniently used in interactive loops without getting the return value
340 be conveniently used in interactive loops without getting the return value
341 (typically 0) printed many times."""
341 (typically 0) printed many times."""
342
342
343 stat = 0
343 stat = 0
344 if verbose or debug: print header+cmd
344 if verbose or debug: print header+cmd
345 # flush stdout so we don't mangle python's buffering
345 # flush stdout so we don't mangle python's buffering
346 sys.stdout.flush()
346 sys.stdout.flush()
347 if not debug:
347 if not debug:
348 os.system(cmd)
348 os.system(cmd)
349
349
350 # override shell() for win32 to deal with network shares
350 # override shell() for win32 to deal with network shares
351 if os.name in ('nt','dos'):
351 if os.name in ('nt','dos'):
352
352
353 shell_ori = shell
353 shell_ori = shell
354
354
355 def shell(cmd,verbose=0,debug=0,header=''):
355 def shell(cmd,verbose=0,debug=0,header=''):
356 if os.getcwd().startswith(r"\\"):
356 if os.getcwd().startswith(r"\\"):
357 path = os.getcwd()
357 path = os.getcwd()
358 # change to c drive (cannot be on UNC-share when issuing os.system,
358 # change to c drive (cannot be on UNC-share when issuing os.system,
359 # as cmd.exe cannot handle UNC addresses)
359 # as cmd.exe cannot handle UNC addresses)
360 os.chdir("c:")
360 os.chdir("c:")
361 # issue pushd to the UNC-share and then run the command
361 # issue pushd to the UNC-share and then run the command
362 try:
362 try:
363 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
363 shell_ori('"pushd %s&&"'%path+cmd,verbose,debug,header)
364 finally:
364 finally:
365 os.chdir(path)
365 os.chdir(path)
366 else:
366 else:
367 shell_ori(cmd,verbose,debug,header)
367 shell_ori(cmd,verbose,debug,header)
368
368
369 shell.__doc__ = shell_ori.__doc__
369 shell.__doc__ = shell_ori.__doc__
370
370
371 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
371 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
372 """Dummy substitute for perl's backquotes.
372 """Dummy substitute for perl's backquotes.
373
373
374 Executes a command and returns the output.
374 Executes a command and returns the output.
375
375
376 Accepts the same arguments as system(), plus:
376 Accepts the same arguments as system(), plus:
377
377
378 - split(0): if true, the output is returned as a list split on newlines.
378 - split(0): if true, the output is returned as a list split on newlines.
379
379
380 Note: a stateful version of this function is available through the
380 Note: a stateful version of this function is available through the
381 SystemExec class."""
381 SystemExec class."""
382
382
383 if verbose or debug: print header+cmd
383 if verbose or debug: print header+cmd
384 if not debug:
384 if not debug:
385 output = commands.getoutput(cmd)
385 output = commands.getoutput(cmd)
386 if split:
386 if split:
387 return output.split('\n')
387 return output.split('\n')
388 else:
388 else:
389 return output
389 return output
390
390
391 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
391 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
392 """Return (standard output,standard error) of executing cmd in a shell.
392 """Return (standard output,standard error) of executing cmd in a shell.
393
393
394 Accepts the same arguments as system(), plus:
394 Accepts the same arguments as system(), plus:
395
395
396 - split(0): if true, each of stdout/err is returned as a list split on
396 - split(0): if true, each of stdout/err is returned as a list split on
397 newlines.
397 newlines.
398
398
399 Note: a stateful version of this function is available through the
399 Note: a stateful version of this function is available through the
400 SystemExec class."""
400 SystemExec class."""
401
401
402 if verbose or debug: print header+cmd
402 if verbose or debug: print header+cmd
403 if not cmd:
403 if not cmd:
404 if split:
404 if split:
405 return [],[]
405 return [],[]
406 else:
406 else:
407 return '',''
407 return '',''
408 if not debug:
408 if not debug:
409 pin,pout,perr = os.popen3(cmd)
409 pin,pout,perr = os.popen3(cmd)
410 tout = pout.read().rstrip()
410 tout = pout.read().rstrip()
411 terr = perr.read().rstrip()
411 terr = perr.read().rstrip()
412 pin.close()
412 pin.close()
413 pout.close()
413 pout.close()
414 perr.close()
414 perr.close()
415 if split:
415 if split:
416 return tout.split('\n'),terr.split('\n')
416 return tout.split('\n'),terr.split('\n')
417 else:
417 else:
418 return tout,terr
418 return tout,terr
419
419
420 # for compatibility with older naming conventions
420 # for compatibility with older naming conventions
421 xsys = system
421 xsys = system
422 bq = getoutput
422 bq = getoutput
423
423
424 class SystemExec:
424 class SystemExec:
425 """Access the system and getoutput functions through a stateful interface.
425 """Access the system and getoutput functions through a stateful interface.
426
426
427 Note: here we refer to the system and getoutput functions from this
427 Note: here we refer to the system and getoutput functions from this
428 library, not the ones from the standard python library.
428 library, not the ones from the standard python library.
429
429
430 This class offers the system and getoutput functions as methods, but the
430 This class offers the system and getoutput functions as methods, but the
431 verbose, debug and header parameters can be set for the instance (at
431 verbose, debug and header parameters can be set for the instance (at
432 creation time or later) so that they don't need to be specified on each
432 creation time or later) so that they don't need to be specified on each
433 call.
433 call.
434
434
435 For efficiency reasons, there's no way to override the parameters on a
435 For efficiency reasons, there's no way to override the parameters on a
436 per-call basis other than by setting instance attributes. If you need
436 per-call basis other than by setting instance attributes. If you need
437 local overrides, it's best to directly call system() or getoutput().
437 local overrides, it's best to directly call system() or getoutput().
438
438
439 The following names are provided as alternate options:
439 The following names are provided as alternate options:
440 - xsys: alias to system
440 - xsys: alias to system
441 - bq: alias to getoutput
441 - bq: alias to getoutput
442
442
443 An instance can then be created as:
443 An instance can then be created as:
444 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
444 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
445
445
446 And used as:
446 And used as:
447 >>> sysexec.xsys('pwd')
447 >>> sysexec.xsys('pwd')
448 >>> dirlist = sysexec.bq('ls -l')
448 >>> dirlist = sysexec.bq('ls -l')
449 """
449 """
450
450
451 def __init__(self,verbose=0,debug=0,header='',split=0):
451 def __init__(self,verbose=0,debug=0,header='',split=0):
452 """Specify the instance's values for verbose, debug and header."""
452 """Specify the instance's values for verbose, debug and header."""
453 setattr_list(self,'verbose debug header split')
453 setattr_list(self,'verbose debug header split')
454
454
455 def system(self,cmd):
455 def system(self,cmd):
456 """Stateful interface to system(), with the same keyword parameters."""
456 """Stateful interface to system(), with the same keyword parameters."""
457
457
458 system(cmd,self.verbose,self.debug,self.header)
458 system(cmd,self.verbose,self.debug,self.header)
459
459
460 def shell(self,cmd):
460 def shell(self,cmd):
461 """Stateful interface to shell(), with the same keyword parameters."""
461 """Stateful interface to shell(), with the same keyword parameters."""
462
462
463 shell(cmd,self.verbose,self.debug,self.header)
463 shell(cmd,self.verbose,self.debug,self.header)
464
464
465 xsys = system # alias
465 xsys = system # alias
466
466
467 def getoutput(self,cmd):
467 def getoutput(self,cmd):
468 """Stateful interface to getoutput()."""
468 """Stateful interface to getoutput()."""
469
469
470 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
470 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
471
471
472 def getoutputerror(self,cmd):
472 def getoutputerror(self,cmd):
473 """Stateful interface to getoutputerror()."""
473 """Stateful interface to getoutputerror()."""
474
474
475 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
475 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
476
476
477 bq = getoutput # alias
477 bq = getoutput # alias
478
478
479 #-----------------------------------------------------------------------------
479 #-----------------------------------------------------------------------------
480 def mutex_opts(dict,ex_op):
480 def mutex_opts(dict,ex_op):
481 """Check for presence of mutually exclusive keys in a dict.
481 """Check for presence of mutually exclusive keys in a dict.
482
482
483 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
483 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
484 for op1,op2 in ex_op:
484 for op1,op2 in ex_op:
485 if op1 in dict and op2 in dict:
485 if op1 in dict and op2 in dict:
486 raise ValueError,'\n*** ERROR in Arguments *** '\
486 raise ValueError,'\n*** ERROR in Arguments *** '\
487 'Options '+op1+' and '+op2+' are mutually exclusive.'
487 'Options '+op1+' and '+op2+' are mutually exclusive.'
488
488
489 #-----------------------------------------------------------------------------
489 #-----------------------------------------------------------------------------
490 def get_py_filename(name):
490 def get_py_filename(name):
491 """Return a valid python filename in the current directory.
491 """Return a valid python filename in the current directory.
492
492
493 If the given name is not a file, it adds '.py' and searches again.
493 If the given name is not a file, it adds '.py' and searches again.
494 Raises IOError with an informative message if the file isn't found."""
494 Raises IOError with an informative message if the file isn't found."""
495
495
496 name = os.path.expanduser(name)
496 name = os.path.expanduser(name)
497 if not os.path.isfile(name) and not name.endswith('.py'):
497 if not os.path.isfile(name) and not name.endswith('.py'):
498 name += '.py'
498 name += '.py'
499 if os.path.isfile(name):
499 if os.path.isfile(name):
500 return name
500 return name
501 else:
501 else:
502 raise IOError,'File `%s` not found.' % name
502 raise IOError,'File `%s` not found.' % name
503
503
504 #-----------------------------------------------------------------------------
504 #-----------------------------------------------------------------------------
505 def filefind(fname,alt_dirs = None):
505 def filefind(fname,alt_dirs = None):
506 """Return the given filename either in the current directory, if it
506 """Return the given filename either in the current directory, if it
507 exists, or in a specified list of directories.
507 exists, or in a specified list of directories.
508
508
509 ~ expansion is done on all file and directory names.
509 ~ expansion is done on all file and directory names.
510
510
511 Upon an unsuccessful search, raise an IOError exception."""
511 Upon an unsuccessful search, raise an IOError exception."""
512
512
513 if alt_dirs is None:
513 if alt_dirs is None:
514 try:
514 try:
515 alt_dirs = get_home_dir()
515 alt_dirs = get_home_dir()
516 except HomeDirError:
516 except HomeDirError:
517 alt_dirs = os.getcwd()
517 alt_dirs = os.getcwd()
518 search = [fname] + list_strings(alt_dirs)
518 search = [fname] + list_strings(alt_dirs)
519 search = map(os.path.expanduser,search)
519 search = map(os.path.expanduser,search)
520 #print 'search list for',fname,'list:',search # dbg
520 #print 'search list for',fname,'list:',search # dbg
521 fname = search[0]
521 fname = search[0]
522 if os.path.isfile(fname):
522 if os.path.isfile(fname):
523 return fname
523 return fname
524 for direc in search[1:]:
524 for direc in search[1:]:
525 testname = os.path.join(direc,fname)
525 testname = os.path.join(direc,fname)
526 #print 'testname',testname # dbg
526 #print 'testname',testname # dbg
527 if os.path.isfile(testname):
527 if os.path.isfile(testname):
528 return testname
528 return testname
529 raise IOError,'File' + `fname` + \
529 raise IOError,'File' + `fname` + \
530 ' not found in current or supplied directories:' + `alt_dirs`
530 ' not found in current or supplied directories:' + `alt_dirs`
531
531
532 #----------------------------------------------------------------------------
532 #----------------------------------------------------------------------------
533 def file_read(filename):
533 def file_read(filename):
534 """Read a file and close it. Returns the file source."""
534 """Read a file and close it. Returns the file source."""
535 fobj=open(filename,'r');
535 fobj=open(filename,'r');
536 source = fobj.read();
536 source = fobj.read();
537 fobj.close()
537 fobj.close()
538 return source
538 return source
539
539
540 #----------------------------------------------------------------------------
540 #----------------------------------------------------------------------------
541 def target_outdated(target,deps):
541 def target_outdated(target,deps):
542 """Determine whether a target is out of date.
542 """Determine whether a target is out of date.
543
543
544 target_outdated(target,deps) -> 1/0
544 target_outdated(target,deps) -> 1/0
545
545
546 deps: list of filenames which MUST exist.
546 deps: list of filenames which MUST exist.
547 target: single filename which may or may not exist.
547 target: single filename which may or may not exist.
548
548
549 If target doesn't exist or is older than any file listed in deps, return
549 If target doesn't exist or is older than any file listed in deps, return
550 true, otherwise return false.
550 true, otherwise return false.
551 """
551 """
552 try:
552 try:
553 target_time = os.path.getmtime(target)
553 target_time = os.path.getmtime(target)
554 except os.error:
554 except os.error:
555 return 1
555 return 1
556 for dep in deps:
556 for dep in deps:
557 dep_time = os.path.getmtime(dep)
557 dep_time = os.path.getmtime(dep)
558 if dep_time > target_time:
558 if dep_time > target_time:
559 #print "For target",target,"Dep failed:",dep # dbg
559 #print "For target",target,"Dep failed:",dep # dbg
560 #print "times (dep,tar):",dep_time,target_time # dbg
560 #print "times (dep,tar):",dep_time,target_time # dbg
561 return 1
561 return 1
562 return 0
562 return 0
563
563
564 #-----------------------------------------------------------------------------
564 #-----------------------------------------------------------------------------
565 def target_update(target,deps,cmd):
565 def target_update(target,deps,cmd):
566 """Update a target with a given command given a list of dependencies.
566 """Update a target with a given command given a list of dependencies.
567
567
568 target_update(target,deps,cmd) -> runs cmd if target is outdated.
568 target_update(target,deps,cmd) -> runs cmd if target is outdated.
569
569
570 This is just a wrapper around target_outdated() which calls the given
570 This is just a wrapper around target_outdated() which calls the given
571 command if target is outdated."""
571 command if target is outdated."""
572
572
573 if target_outdated(target,deps):
573 if target_outdated(target,deps):
574 xsys(cmd)
574 xsys(cmd)
575
575
576 #----------------------------------------------------------------------------
576 #----------------------------------------------------------------------------
577 def unquote_ends(istr):
577 def unquote_ends(istr):
578 """Remove a single pair of quotes from the endpoints of a string."""
578 """Remove a single pair of quotes from the endpoints of a string."""
579
579
580 if not istr:
580 if not istr:
581 return istr
581 return istr
582 if (istr[0]=="'" and istr[-1]=="'") or \
582 if (istr[0]=="'" and istr[-1]=="'") or \
583 (istr[0]=='"' and istr[-1]=='"'):
583 (istr[0]=='"' and istr[-1]=='"'):
584 return istr[1:-1]
584 return istr[1:-1]
585 else:
585 else:
586 return istr
586 return istr
587
587
588 #----------------------------------------------------------------------------
588 #----------------------------------------------------------------------------
589 def process_cmdline(argv,names=[],defaults={},usage=''):
589 def process_cmdline(argv,names=[],defaults={},usage=''):
590 """ Process command-line options and arguments.
590 """ Process command-line options and arguments.
591
591
592 Arguments:
592 Arguments:
593
593
594 - argv: list of arguments, typically sys.argv.
594 - argv: list of arguments, typically sys.argv.
595
595
596 - names: list of option names. See DPyGetOpt docs for details on options
596 - names: list of option names. See DPyGetOpt docs for details on options
597 syntax.
597 syntax.
598
598
599 - defaults: dict of default values.
599 - defaults: dict of default values.
600
600
601 - usage: optional usage notice to print if a wrong argument is passed.
601 - usage: optional usage notice to print if a wrong argument is passed.
602
602
603 Return a dict of options and a list of free arguments."""
603 Return a dict of options and a list of free arguments."""
604
604
605 getopt = DPyGetOpt.DPyGetOpt()
605 getopt = DPyGetOpt.DPyGetOpt()
606 getopt.setIgnoreCase(0)
606 getopt.setIgnoreCase(0)
607 getopt.parseConfiguration(names)
607 getopt.parseConfiguration(names)
608
608
609 try:
609 try:
610 getopt.processArguments(argv)
610 getopt.processArguments(argv)
611 except:
611 except:
612 print usage
612 print usage
613 warn(`sys.exc_value`,level=4)
613 warn(`sys.exc_value`,level=4)
614
614
615 defaults.update(getopt.optionValues)
615 defaults.update(getopt.optionValues)
616 args = getopt.freeValues
616 args = getopt.freeValues
617
617
618 return defaults,args
618 return defaults,args
619
619
620 #----------------------------------------------------------------------------
620 #----------------------------------------------------------------------------
621 def optstr2types(ostr):
621 def optstr2types(ostr):
622 """Convert a string of option names to a dict of type mappings.
622 """Convert a string of option names to a dict of type mappings.
623
623
624 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
624 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
625
625
626 This is used to get the types of all the options in a string formatted
626 This is used to get the types of all the options in a string formatted
627 with the conventions of DPyGetOpt. The 'type' None is used for options
627 with the conventions of DPyGetOpt. The 'type' None is used for options
628 which are strings (they need no further conversion). This function's main
628 which are strings (they need no further conversion). This function's main
629 use is to get a typemap for use with read_dict().
629 use is to get a typemap for use with read_dict().
630 """
630 """
631
631
632 typeconv = {None:'',int:'',float:''}
632 typeconv = {None:'',int:'',float:''}
633 typemap = {'s':None,'i':int,'f':float}
633 typemap = {'s':None,'i':int,'f':float}
634 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
634 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
635
635
636 for w in ostr.split():
636 for w in ostr.split():
637 oname,alias,otype = opt_re.match(w).groups()
637 oname,alias,otype = opt_re.match(w).groups()
638 if otype == '' or alias == '!': # simple switches are integers too
638 if otype == '' or alias == '!': # simple switches are integers too
639 otype = 'i'
639 otype = 'i'
640 typeconv[typemap[otype]] += oname + ' '
640 typeconv[typemap[otype]] += oname + ' '
641 return typeconv
641 return typeconv
642
642
643 #----------------------------------------------------------------------------
643 #----------------------------------------------------------------------------
644 def read_dict(filename,type_conv=None,**opt):
644 def read_dict(filename,type_conv=None,**opt):
645
645
646 """Read a dictionary of key=value pairs from an input file, optionally
646 """Read a dictionary of key=value pairs from an input file, optionally
647 performing conversions on the resulting values.
647 performing conversions on the resulting values.
648
648
649 read_dict(filename,type_conv,**opt) -> dict
649 read_dict(filename,type_conv,**opt) -> dict
650
650
651 Only one value per line is accepted, the format should be
651 Only one value per line is accepted, the format should be
652 # optional comments are ignored
652 # optional comments are ignored
653 key value\n
653 key value\n
654
654
655 Args:
655 Args:
656
656
657 - type_conv: A dictionary specifying which keys need to be converted to
657 - type_conv: A dictionary specifying which keys need to be converted to
658 which types. By default all keys are read as strings. This dictionary
658 which types. By default all keys are read as strings. This dictionary
659 should have as its keys valid conversion functions for strings
659 should have as its keys valid conversion functions for strings
660 (int,long,float,complex, or your own). The value for each key
660 (int,long,float,complex, or your own). The value for each key
661 (converter) should be a whitespace separated string containing the names
661 (converter) should be a whitespace separated string containing the names
662 of all the entries in the file to be converted using that function. For
662 of all the entries in the file to be converted using that function. For
663 keys to be left alone, use None as the conversion function (only needed
663 keys to be left alone, use None as the conversion function (only needed
664 with purge=1, see below).
664 with purge=1, see below).
665
665
666 - opt: dictionary with extra options as below (default in parens)
666 - opt: dictionary with extra options as below (default in parens)
667
667
668 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
668 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
669 of the dictionary to be returned. If purge is going to be used, the
669 of the dictionary to be returned. If purge is going to be used, the
670 set of keys to be left as strings also has to be explicitly specified
670 set of keys to be left as strings also has to be explicitly specified
671 using the (non-existent) conversion function None.
671 using the (non-existent) conversion function None.
672
672
673 fs(None): field separator. This is the key/value separator to be used
673 fs(None): field separator. This is the key/value separator to be used
674 when parsing the file. The None default means any whitespace [behavior
674 when parsing the file. The None default means any whitespace [behavior
675 of string.split()].
675 of string.split()].
676
676
677 strip(0): if 1, strip string values of leading/trailinig whitespace.
677 strip(0): if 1, strip string values of leading/trailinig whitespace.
678
678
679 warn(1): warning level if requested keys are not found in file.
679 warn(1): warning level if requested keys are not found in file.
680 - 0: silently ignore.
680 - 0: silently ignore.
681 - 1: inform but proceed.
681 - 1: inform but proceed.
682 - 2: raise KeyError exception.
682 - 2: raise KeyError exception.
683
683
684 no_empty(0): if 1, remove keys with whitespace strings as a value.
684 no_empty(0): if 1, remove keys with whitespace strings as a value.
685
685
686 unique([]): list of keys (or space separated string) which can't be
686 unique([]): list of keys (or space separated string) which can't be
687 repeated. If one such key is found in the file, each new instance
687 repeated. If one such key is found in the file, each new instance
688 overwrites the previous one. For keys not listed here, the behavior is
688 overwrites the previous one. For keys not listed here, the behavior is
689 to make a list of all appearances.
689 to make a list of all appearances.
690
690
691 Example:
691 Example:
692 If the input file test.ini has:
692 If the input file test.ini has:
693 i 3
693 i 3
694 x 4.5
694 x 4.5
695 y 5.5
695 y 5.5
696 s hi ho
696 s hi ho
697 Then:
697 Then:
698
698
699 >>> type_conv={int:'i',float:'x',None:'s'}
699 >>> type_conv={int:'i',float:'x',None:'s'}
700 >>> read_dict('test.ini')
700 >>> read_dict('test.ini')
701 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
701 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
702 >>> read_dict('test.ini',type_conv)
702 >>> read_dict('test.ini',type_conv)
703 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
703 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
704 >>> read_dict('test.ini',type_conv,purge=1)
704 >>> read_dict('test.ini',type_conv,purge=1)
705 {'i': 3, 's': 'hi ho', 'x': 4.5}
705 {'i': 3, 's': 'hi ho', 'x': 4.5}
706 """
706 """
707
707
708 # starting config
708 # starting config
709 opt.setdefault('purge',0)
709 opt.setdefault('purge',0)
710 opt.setdefault('fs',None) # field sep defaults to any whitespace
710 opt.setdefault('fs',None) # field sep defaults to any whitespace
711 opt.setdefault('strip',0)
711 opt.setdefault('strip',0)
712 opt.setdefault('warn',1)
712 opt.setdefault('warn',1)
713 opt.setdefault('no_empty',0)
713 opt.setdefault('no_empty',0)
714 opt.setdefault('unique','')
714 opt.setdefault('unique','')
715 if type(opt['unique']) in StringTypes:
715 if type(opt['unique']) in StringTypes:
716 unique_keys = qw(opt['unique'])
716 unique_keys = qw(opt['unique'])
717 elif type(opt['unique']) in (types.TupleType,types.ListType):
717 elif type(opt['unique']) in (types.TupleType,types.ListType):
718 unique_keys = opt['unique']
718 unique_keys = opt['unique']
719 else:
719 else:
720 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
720 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
721
721
722 dict = {}
722 dict = {}
723 # first read in table of values as strings
723 # first read in table of values as strings
724 file = open(filename,'r')
724 file = open(filename,'r')
725 for line in file.readlines():
725 for line in file.readlines():
726 line = line.strip()
726 line = line.strip()
727 if len(line) and line[0]=='#': continue
727 if len(line) and line[0]=='#': continue
728 if len(line)>0:
728 if len(line)>0:
729 lsplit = line.split(opt['fs'],1)
729 lsplit = line.split(opt['fs'],1)
730 try:
730 try:
731 key,val = lsplit
731 key,val = lsplit
732 except ValueError:
732 except ValueError:
733 key,val = lsplit[0],''
733 key,val = lsplit[0],''
734 key = key.strip()
734 key = key.strip()
735 if opt['strip']: val = val.strip()
735 if opt['strip']: val = val.strip()
736 if val == "''" or val == '""': val = ''
736 if val == "''" or val == '""': val = ''
737 if opt['no_empty'] and (val=='' or val.isspace()):
737 if opt['no_empty'] and (val=='' or val.isspace()):
738 continue
738 continue
739 # if a key is found more than once in the file, build a list
739 # if a key is found more than once in the file, build a list
740 # unless it's in the 'unique' list. In that case, last found in file
740 # unless it's in the 'unique' list. In that case, last found in file
741 # takes precedence. User beware.
741 # takes precedence. User beware.
742 try:
742 try:
743 if dict[key] and key in unique_keys:
743 if dict[key] and key in unique_keys:
744 dict[key] = val
744 dict[key] = val
745 elif type(dict[key]) is types.ListType:
745 elif type(dict[key]) is types.ListType:
746 dict[key].append(val)
746 dict[key].append(val)
747 else:
747 else:
748 dict[key] = [dict[key],val]
748 dict[key] = [dict[key],val]
749 except KeyError:
749 except KeyError:
750 dict[key] = val
750 dict[key] = val
751 # purge if requested
751 # purge if requested
752 if opt['purge']:
752 if opt['purge']:
753 accepted_keys = qwflat(type_conv.values())
753 accepted_keys = qwflat(type_conv.values())
754 for key in dict.keys():
754 for key in dict.keys():
755 if key in accepted_keys: continue
755 if key in accepted_keys: continue
756 del(dict[key])
756 del(dict[key])
757 # now convert if requested
757 # now convert if requested
758 if type_conv==None: return dict
758 if type_conv==None: return dict
759 conversions = type_conv.keys()
759 conversions = type_conv.keys()
760 try: conversions.remove(None)
760 try: conversions.remove(None)
761 except: pass
761 except: pass
762 for convert in conversions:
762 for convert in conversions:
763 for val in qw(type_conv[convert]):
763 for val in qw(type_conv[convert]):
764 try:
764 try:
765 dict[val] = convert(dict[val])
765 dict[val] = convert(dict[val])
766 except KeyError,e:
766 except KeyError,e:
767 if opt['warn'] == 0:
767 if opt['warn'] == 0:
768 pass
768 pass
769 elif opt['warn'] == 1:
769 elif opt['warn'] == 1:
770 print >>sys.stderr, 'Warning: key',val,\
770 print >>sys.stderr, 'Warning: key',val,\
771 'not found in file',filename
771 'not found in file',filename
772 elif opt['warn'] == 2:
772 elif opt['warn'] == 2:
773 raise KeyError,e
773 raise KeyError,e
774 else:
774 else:
775 raise ValueError,'Warning level must be 0,1 or 2'
775 raise ValueError,'Warning level must be 0,1 or 2'
776
776
777 return dict
777 return dict
778
778
779 #----------------------------------------------------------------------------
779 #----------------------------------------------------------------------------
780 def flag_calls(func):
780 def flag_calls(func):
781 """Wrap a function to detect and flag when it gets called.
781 """Wrap a function to detect and flag when it gets called.
782
782
783 This is a decorator which takes a function and wraps it in a function with
783 This is a decorator which takes a function and wraps it in a function with
784 a 'called' attribute. wrapper.called is initialized to False.
784 a 'called' attribute. wrapper.called is initialized to False.
785
785
786 The wrapper.called attribute is set to False right before each call to the
786 The wrapper.called attribute is set to False right before each call to the
787 wrapped function, so if the call fails it remains False. After the call
787 wrapped function, so if the call fails it remains False. After the call
788 completes, wrapper.called is set to True and the output is returned.
788 completes, wrapper.called is set to True and the output is returned.
789
789
790 Testing for truth in wrapper.called allows you to determine if a call to
790 Testing for truth in wrapper.called allows you to determine if a call to
791 func() was attempted and succeeded."""
791 func() was attempted and succeeded."""
792
792
793 def wrapper(*args,**kw):
793 def wrapper(*args,**kw):
794 wrapper.called = False
794 wrapper.called = False
795 out = func(*args,**kw)
795 out = func(*args,**kw)
796 wrapper.called = True
796 wrapper.called = True
797 return out
797 return out
798
798
799 wrapper.called = False
799 wrapper.called = False
800 wrapper.__doc__ = func.__doc__
800 wrapper.__doc__ = func.__doc__
801 return wrapper
801 return wrapper
802
802
803 #----------------------------------------------------------------------------
803 #----------------------------------------------------------------------------
804 class HomeDirError(Error):
804 class HomeDirError(Error):
805 pass
805 pass
806
806
807 def get_home_dir():
807 def get_home_dir():
808 """Return the closest possible equivalent to a 'home' directory.
808 """Return the closest possible equivalent to a 'home' directory.
809
809
810 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
810 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
811
811
812 Currently only Posix and NT are implemented, a HomeDirError exception is
812 Currently only Posix and NT are implemented, a HomeDirError exception is
813 raised for all other OSes. """
813 raised for all other OSes. """
814
814
815 isdir = os.path.isdir
815 isdir = os.path.isdir
816 env = os.environ
816 env = os.environ
817 try:
817 try:
818 homedir = env['HOME']
818 homedir = env['HOME']
819 if not isdir(homedir):
819 if not isdir(homedir):
820 # in case a user stuck some string which does NOT resolve to a
820 # in case a user stuck some string which does NOT resolve to a
821 # valid path, it's as good as if we hadn't foud it
821 # valid path, it's as good as if we hadn't foud it
822 raise KeyError
822 raise KeyError
823 return homedir
823 return homedir
824 except KeyError:
824 except KeyError:
825 if os.name == 'posix':
825 if os.name == 'posix':
826 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
826 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
827 elif os.name == 'nt':
827 elif os.name == 'nt':
828 # For some strange reason, win9x returns 'nt' for os.name.
828 # For some strange reason, win9x returns 'nt' for os.name.
829 try:
829 try:
830 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
830 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
831 if not isdir(homedir):
831 if not isdir(homedir):
832 homedir = os.path.join(env['USERPROFILE'])
832 homedir = os.path.join(env['USERPROFILE'])
833 if not isdir(homedir):
833 if not isdir(homedir):
834 raise HomeDirError
834 raise HomeDirError
835 return homedir
835 return homedir
836 except:
836 except:
837 try:
837 try:
838 # Use the registry to get the 'My Documents' folder.
838 # Use the registry to get the 'My Documents' folder.
839 import _winreg as wreg
839 import _winreg as wreg
840 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
840 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
841 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
841 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
842 homedir = wreg.QueryValueEx(key,'Personal')[0]
842 homedir = wreg.QueryValueEx(key,'Personal')[0]
843 key.Close()
843 key.Close()
844 if not isdir(homedir):
844 if not isdir(homedir):
845 e = ('Invalid "Personal" folder registry key '
845 e = ('Invalid "Personal" folder registry key '
846 'typically "My Documents".\n'
846 'typically "My Documents".\n'
847 'Value: %s\n'
847 'Value: %s\n'
848 'This is not a valid directory on your system.' %
848 'This is not a valid directory on your system.' %
849 homedir)
849 homedir)
850 raise HomeDirError(e)
850 raise HomeDirError(e)
851 return homedir
851 return homedir
852 except HomeDirError:
852 except HomeDirError:
853 raise
853 raise
854 except:
854 except:
855 return 'C:\\'
855 return 'C:\\'
856 elif os.name == 'dos':
856 elif os.name == 'dos':
857 # Desperate, may do absurd things in classic MacOS. May work under DOS.
857 # Desperate, may do absurd things in classic MacOS. May work under DOS.
858 return 'C:\\'
858 return 'C:\\'
859 else:
859 else:
860 raise HomeDirError,'support for your operating system not implemented.'
860 raise HomeDirError,'support for your operating system not implemented.'
861
861
862 #****************************************************************************
862 #****************************************************************************
863 # strings and text
863 # strings and text
864
864
865 class LSString(str):
865 class LSString(str):
866 """String derivative with a special access attributes.
866 """String derivative with a special access attributes.
867
867
868 These are normal strings, but with the special attributes:
868 These are normal strings, but with the special attributes:
869
869
870 .l (or .list) : value as list (split on newlines).
870 .l (or .list) : value as list (split on newlines).
871 .n (or .nlstr): original value (the string itself).
871 .n (or .nlstr): original value (the string itself).
872 .s (or .spstr): value as whitespace-separated string.
872 .s (or .spstr): value as whitespace-separated string.
873
873
874 Any values which require transformations are computed only once and
874 Any values which require transformations are computed only once and
875 cached.
875 cached.
876
876
877 Such strings are very useful to efficiently interact with the shell, which
877 Such strings are very useful to efficiently interact with the shell, which
878 typically only understands whitespace-separated options for commands."""
878 typically only understands whitespace-separated options for commands."""
879
879
880 def get_list(self):
880 def get_list(self):
881 try:
881 try:
882 return self.__list
882 return self.__list
883 except AttributeError:
883 except AttributeError:
884 self.__list = self.split('\n')
884 self.__list = self.split('\n')
885 return self.__list
885 return self.__list
886
886
887 l = list = property(get_list)
887 l = list = property(get_list)
888
888
889 def get_spstr(self):
889 def get_spstr(self):
890 try:
890 try:
891 return self.__spstr
891 return self.__spstr
892 except AttributeError:
892 except AttributeError:
893 self.__spstr = self.replace('\n',' ')
893 self.__spstr = self.replace('\n',' ')
894 return self.__spstr
894 return self.__spstr
895
895
896 s = spstr = property(get_spstr)
896 s = spstr = property(get_spstr)
897
897
898 def get_nlstr(self):
898 def get_nlstr(self):
899 return self
899 return self
900
900
901 n = nlstr = property(get_nlstr)
901 n = nlstr = property(get_nlstr)
902
902
903 #----------------------------------------------------------------------------
903 #----------------------------------------------------------------------------
904 class SList(list):
904 class SList(list):
905 """List derivative with a special access attributes.
905 """List derivative with a special access attributes.
906
906
907 These are normal lists, but with the special attributes:
907 These are normal lists, but with the special attributes:
908
908
909 .l (or .list) : value as list (the list itself).
909 .l (or .list) : value as list (the list itself).
910 .n (or .nlstr): value as a string, joined on newlines.
910 .n (or .nlstr): value as a string, joined on newlines.
911 .s (or .spstr): value as a string, joined on spaces.
911 .s (or .spstr): value as a string, joined on spaces.
912
912
913 Any values which require transformations are computed only once and
913 Any values which require transformations are computed only once and
914 cached."""
914 cached."""
915
915
916 def get_list(self):
916 def get_list(self):
917 return self
917 return self
918
918
919 l = list = property(get_list)
919 l = list = property(get_list)
920
920
921 def get_spstr(self):
921 def get_spstr(self):
922 try:
922 try:
923 return self.__spstr
923 return self.__spstr
924 except AttributeError:
924 except AttributeError:
925 self.__spstr = ' '.join(self)
925 self.__spstr = ' '.join(self)
926 return self.__spstr
926 return self.__spstr
927
927
928 s = spstr = property(get_spstr)
928 s = spstr = property(get_spstr)
929
929
930 def get_nlstr(self):
930 def get_nlstr(self):
931 try:
931 try:
932 return self.__nlstr
932 return self.__nlstr
933 except AttributeError:
933 except AttributeError:
934 self.__nlstr = '\n'.join(self)
934 self.__nlstr = '\n'.join(self)
935 return self.__nlstr
935 return self.__nlstr
936
936
937 n = nlstr = property(get_nlstr)
937 n = nlstr = property(get_nlstr)
938
938
939 #----------------------------------------------------------------------------
939 #----------------------------------------------------------------------------
940 # This can be replaced with an isspace() call once we drop 2.2 compatibility
941 _isspace_match = re.compile(r'^\s+$').match
942 def isspace(s):
943 return bool(_isspace_match(s))
944
945 #----------------------------------------------------------------------------
946 def esc_quotes(strng):
940 def esc_quotes(strng):
947 """Return the input string with single and double quotes escaped out"""
941 """Return the input string with single and double quotes escaped out"""
948
942
949 return strng.replace('"','\\"').replace("'","\\'")
943 return strng.replace('"','\\"').replace("'","\\'")
950
944
951 #----------------------------------------------------------------------------
945 #----------------------------------------------------------------------------
952 def make_quoted_expr(s):
946 def make_quoted_expr(s):
953 """Return string s in appropriate quotes, using raw string if possible.
947 """Return string s in appropriate quotes, using raw string if possible.
954
948
955 Effectively this turns string: cd \ao\ao\
949 Effectively this turns string: cd \ao\ao\
956 to: r"cd \ao\ao\_"[:-1]
950 to: r"cd \ao\ao\_"[:-1]
957
951
958 Note the use of raw string and padding at the end to allow trailing backslash.
952 Note the use of raw string and padding at the end to allow trailing backslash.
959
953
960 """
954 """
961
955
962 tail = ''
956 tail = ''
963 tailpadding = ''
957 tailpadding = ''
964 raw = ''
958 raw = ''
965 if "\\" in s:
959 if "\\" in s:
966 raw = 'r'
960 raw = 'r'
967 if s.endswith('\\'):
961 if s.endswith('\\'):
968 tail = '[:-1]'
962 tail = '[:-1]'
969 tailpadding = '_'
963 tailpadding = '_'
970 if '"' not in s:
964 if '"' not in s:
971 quote = '"'
965 quote = '"'
972 elif "'" not in s:
966 elif "'" not in s:
973 quote = "'"
967 quote = "'"
974 elif '"""' not in s and not s.endswith('"'):
968 elif '"""' not in s and not s.endswith('"'):
975 quote = '"""'
969 quote = '"""'
976 elif "'''" not in s and not s.endswith("'"):
970 elif "'''" not in s and not s.endswith("'"):
977 quote = "'''"
971 quote = "'''"
978 else:
972 else:
979 # give up, backslash-escaped string will do
973 # give up, backslash-escaped string will do
980 return '"%s"' % esc_quotes(s)
974 return '"%s"' % esc_quotes(s)
981 res = itpl("$raw$quote$s$tailpadding$quote$tail")
975 res = itpl("$raw$quote$s$tailpadding$quote$tail")
982 return res
976 return res
983
977
984
978
985 #----------------------------------------------------------------------------
979 #----------------------------------------------------------------------------
986 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
980 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
987 """Take multiple lines of input.
981 """Take multiple lines of input.
988
982
989 A list with each line of input as a separate element is returned when a
983 A list with each line of input as a separate element is returned when a
990 termination string is entered (defaults to a single '.'). Input can also
984 termination string is entered (defaults to a single '.'). Input can also
991 terminate via EOF (^D in Unix, ^Z-RET in Windows).
985 terminate via EOF (^D in Unix, ^Z-RET in Windows).
992
986
993 Lines of input which end in \\ are joined into single entries (and a
987 Lines of input which end in \\ are joined into single entries (and a
994 secondary continuation prompt is issued as long as the user terminates
988 secondary continuation prompt is issued as long as the user terminates
995 lines with \\). This allows entering very long strings which are still
989 lines with \\). This allows entering very long strings which are still
996 meant to be treated as single entities.
990 meant to be treated as single entities.
997 """
991 """
998
992
999 try:
993 try:
1000 if header:
994 if header:
1001 header += '\n'
995 header += '\n'
1002 lines = [raw_input(header + ps1)]
996 lines = [raw_input(header + ps1)]
1003 except EOFError:
997 except EOFError:
1004 return []
998 return []
1005 terminate = [terminate_str]
999 terminate = [terminate_str]
1006 try:
1000 try:
1007 while lines[-1:] != terminate:
1001 while lines[-1:] != terminate:
1008 new_line = raw_input(ps1)
1002 new_line = raw_input(ps1)
1009 while new_line.endswith('\\'):
1003 while new_line.endswith('\\'):
1010 new_line = new_line[:-1] + raw_input(ps2)
1004 new_line = new_line[:-1] + raw_input(ps2)
1011 lines.append(new_line)
1005 lines.append(new_line)
1012
1006
1013 return lines[:-1] # don't return the termination command
1007 return lines[:-1] # don't return the termination command
1014 except EOFError:
1008 except EOFError:
1015 print
1009 print
1016 return lines
1010 return lines
1017
1011
1018 #----------------------------------------------------------------------------
1012 #----------------------------------------------------------------------------
1019 def raw_input_ext(prompt='', ps2='... '):
1013 def raw_input_ext(prompt='', ps2='... '):
1020 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1014 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
1021
1015
1022 line = raw_input(prompt)
1016 line = raw_input(prompt)
1023 while line.endswith('\\'):
1017 while line.endswith('\\'):
1024 line = line[:-1] + raw_input(ps2)
1018 line = line[:-1] + raw_input(ps2)
1025 return line
1019 return line
1026
1020
1027 #----------------------------------------------------------------------------
1021 #----------------------------------------------------------------------------
1028 def ask_yes_no(prompt,default=None):
1022 def ask_yes_no(prompt,default=None):
1029 """Asks a question and returns an integer 1/0 (y/n) answer.
1023 """Asks a question and returns an integer 1/0 (y/n) answer.
1030
1024
1031 If default is given (one of 'y','n'), it is used if the user input is
1025 If default is given (one of 'y','n'), it is used if the user input is
1032 empty. Otherwise the question is repeated until an answer is given.
1026 empty. Otherwise the question is repeated until an answer is given.
1033 If EOF occurs 20 times consecutively, the default answer is assumed,
1027 If EOF occurs 20 times consecutively, the default answer is assumed,
1034 or if there is no default, an exception is raised to prevent infinite
1028 or if there is no default, an exception is raised to prevent infinite
1035 loops.
1029 loops.
1036
1030
1037 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1031 Valid answers are: y/yes/n/no (match is not case sensitive)."""
1038
1032
1039 answers = {'y':True,'n':False,'yes':True,'no':False}
1033 answers = {'y':True,'n':False,'yes':True,'no':False}
1040 ans = None
1034 ans = None
1041 eofs, max_eofs = 0, 20
1035 eofs, max_eofs = 0, 20
1042 while ans not in answers.keys():
1036 while ans not in answers.keys():
1043 try:
1037 try:
1044 ans = raw_input(prompt+' ').lower()
1038 ans = raw_input(prompt+' ').lower()
1045 if not ans: # response was an empty string
1039 if not ans: # response was an empty string
1046 ans = default
1040 ans = default
1047 eofs = 0
1041 eofs = 0
1048 except (EOFError,KeyboardInterrupt):
1042 except (EOFError,KeyboardInterrupt):
1049 eofs = eofs + 1
1043 eofs = eofs + 1
1050 if eofs >= max_eofs:
1044 if eofs >= max_eofs:
1051 if default in answers.keys():
1045 if default in answers.keys():
1052 ans = default
1046 ans = default
1053 else:
1047 else:
1054 raise
1048 raise
1055
1049
1056 return answers[ans]
1050 return answers[ans]
1057
1051
1058 #----------------------------------------------------------------------------
1052 #----------------------------------------------------------------------------
1059 def marquee(txt='',width=78,mark='*'):
1053 def marquee(txt='',width=78,mark='*'):
1060 """Return the input string centered in a 'marquee'."""
1054 """Return the input string centered in a 'marquee'."""
1061 if not txt:
1055 if not txt:
1062 return (mark*width)[:width]
1056 return (mark*width)[:width]
1063 nmark = (width-len(txt)-2)/len(mark)/2
1057 nmark = (width-len(txt)-2)/len(mark)/2
1064 if nmark < 0: nmark =0
1058 if nmark < 0: nmark =0
1065 marks = mark*nmark
1059 marks = mark*nmark
1066 return '%s %s %s' % (marks,txt,marks)
1060 return '%s %s %s' % (marks,txt,marks)
1067
1061
1068 #----------------------------------------------------------------------------
1062 #----------------------------------------------------------------------------
1069 class EvalDict:
1063 class EvalDict:
1070 """
1064 """
1071 Emulate a dict which evaluates its contents in the caller's frame.
1065 Emulate a dict which evaluates its contents in the caller's frame.
1072
1066
1073 Usage:
1067 Usage:
1074 >>>number = 19
1068 >>>number = 19
1075 >>>text = "python"
1069 >>>text = "python"
1076 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1070 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
1077 """
1071 """
1078
1072
1079 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1073 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
1080 # modified (shorter) version of:
1074 # modified (shorter) version of:
1081 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1075 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
1082 # Skip Montanaro (skip@pobox.com).
1076 # Skip Montanaro (skip@pobox.com).
1083
1077
1084 def __getitem__(self, name):
1078 def __getitem__(self, name):
1085 frame = sys._getframe(1)
1079 frame = sys._getframe(1)
1086 return eval(name, frame.f_globals, frame.f_locals)
1080 return eval(name, frame.f_globals, frame.f_locals)
1087
1081
1088 EvalString = EvalDict # for backwards compatibility
1082 EvalString = EvalDict # for backwards compatibility
1089 #----------------------------------------------------------------------------
1083 #----------------------------------------------------------------------------
1090 def qw(words,flat=0,sep=None,maxsplit=-1):
1084 def qw(words,flat=0,sep=None,maxsplit=-1):
1091 """Similar to Perl's qw() operator, but with some more options.
1085 """Similar to Perl's qw() operator, but with some more options.
1092
1086
1093 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1087 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
1094
1088
1095 words can also be a list itself, and with flat=1, the output will be
1089 words can also be a list itself, and with flat=1, the output will be
1096 recursively flattened. Examples:
1090 recursively flattened. Examples:
1097
1091
1098 >>> qw('1 2')
1092 >>> qw('1 2')
1099 ['1', '2']
1093 ['1', '2']
1100 >>> qw(['a b','1 2',['m n','p q']])
1094 >>> qw(['a b','1 2',['m n','p q']])
1101 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1095 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
1102 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1096 >>> qw(['a b','1 2',['m n','p q']],flat=1)
1103 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1097 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
1104
1098
1105 if type(words) in StringTypes:
1099 if type(words) in StringTypes:
1106 return [word.strip() for word in words.split(sep,maxsplit)
1100 return [word.strip() for word in words.split(sep,maxsplit)
1107 if word and not word.isspace() ]
1101 if word and not word.isspace() ]
1108 if flat:
1102 if flat:
1109 return flatten(map(qw,words,[1]*len(words)))
1103 return flatten(map(qw,words,[1]*len(words)))
1110 return map(qw,words)
1104 return map(qw,words)
1111
1105
1112 #----------------------------------------------------------------------------
1106 #----------------------------------------------------------------------------
1113 def qwflat(words,sep=None,maxsplit=-1):
1107 def qwflat(words,sep=None,maxsplit=-1):
1114 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1108 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
1115 return qw(words,1,sep,maxsplit)
1109 return qw(words,1,sep,maxsplit)
1116
1110
1117 #----------------------------------------------------------------------------
1111 #----------------------------------------------------------------------------
1118 def qw_lol(indata):
1112 def qw_lol(indata):
1119 """qw_lol('a b') -> [['a','b']],
1113 """qw_lol('a b') -> [['a','b']],
1120 otherwise it's just a call to qw().
1114 otherwise it's just a call to qw().
1121
1115
1122 We need this to make sure the modules_some keys *always* end up as a
1116 We need this to make sure the modules_some keys *always* end up as a
1123 list of lists."""
1117 list of lists."""
1124
1118
1125 if type(indata) in StringTypes:
1119 if type(indata) in StringTypes:
1126 return [qw(indata)]
1120 return [qw(indata)]
1127 else:
1121 else:
1128 return qw(indata)
1122 return qw(indata)
1129
1123
1130 #-----------------------------------------------------------------------------
1124 #-----------------------------------------------------------------------------
1131 def list_strings(arg):
1125 def list_strings(arg):
1132 """Always return a list of strings, given a string or list of strings
1126 """Always return a list of strings, given a string or list of strings
1133 as input."""
1127 as input."""
1134
1128
1135 if type(arg) in StringTypes: return [arg]
1129 if type(arg) in StringTypes: return [arg]
1136 else: return arg
1130 else: return arg
1137
1131
1138 #----------------------------------------------------------------------------
1132 #----------------------------------------------------------------------------
1139 def grep(pat,list,case=1):
1133 def grep(pat,list,case=1):
1140 """Simple minded grep-like function.
1134 """Simple minded grep-like function.
1141 grep(pat,list) returns occurrences of pat in list, None on failure.
1135 grep(pat,list) returns occurrences of pat in list, None on failure.
1142
1136
1143 It only does simple string matching, with no support for regexps. Use the
1137 It only does simple string matching, with no support for regexps. Use the
1144 option case=0 for case-insensitive matching."""
1138 option case=0 for case-insensitive matching."""
1145
1139
1146 # This is pretty crude. At least it should implement copying only references
1140 # This is pretty crude. At least it should implement copying only references
1147 # to the original data in case it's big. Now it copies the data for output.
1141 # to the original data in case it's big. Now it copies the data for output.
1148 out=[]
1142 out=[]
1149 if case:
1143 if case:
1150 for term in list:
1144 for term in list:
1151 if term.find(pat)>-1: out.append(term)
1145 if term.find(pat)>-1: out.append(term)
1152 else:
1146 else:
1153 lpat=pat.lower()
1147 lpat=pat.lower()
1154 for term in list:
1148 for term in list:
1155 if term.lower().find(lpat)>-1: out.append(term)
1149 if term.lower().find(lpat)>-1: out.append(term)
1156
1150
1157 if len(out): return out
1151 if len(out): return out
1158 else: return None
1152 else: return None
1159
1153
1160 #----------------------------------------------------------------------------
1154 #----------------------------------------------------------------------------
1161 def dgrep(pat,*opts):
1155 def dgrep(pat,*opts):
1162 """Return grep() on dir()+dir(__builtins__).
1156 """Return grep() on dir()+dir(__builtins__).
1163
1157
1164 A very common use of grep() when working interactively."""
1158 A very common use of grep() when working interactively."""
1165
1159
1166 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1160 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
1167
1161
1168 #----------------------------------------------------------------------------
1162 #----------------------------------------------------------------------------
1169 def idgrep(pat):
1163 def idgrep(pat):
1170 """Case-insensitive dgrep()"""
1164 """Case-insensitive dgrep()"""
1171
1165
1172 return dgrep(pat,0)
1166 return dgrep(pat,0)
1173
1167
1174 #----------------------------------------------------------------------------
1168 #----------------------------------------------------------------------------
1175 def igrep(pat,list):
1169 def igrep(pat,list):
1176 """Synonym for case-insensitive grep."""
1170 """Synonym for case-insensitive grep."""
1177
1171
1178 return grep(pat,list,case=0)
1172 return grep(pat,list,case=0)
1179
1173
1180 #----------------------------------------------------------------------------
1174 #----------------------------------------------------------------------------
1181 def indent(str,nspaces=4,ntabs=0):
1175 def indent(str,nspaces=4,ntabs=0):
1182 """Indent a string a given number of spaces or tabstops.
1176 """Indent a string a given number of spaces or tabstops.
1183
1177
1184 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1178 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
1185 """
1179 """
1186 if str is None:
1180 if str is None:
1187 return
1181 return
1188 ind = '\t'*ntabs+' '*nspaces
1182 ind = '\t'*ntabs+' '*nspaces
1189 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1183 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1190 if outstr.endswith(os.linesep+ind):
1184 if outstr.endswith(os.linesep+ind):
1191 return outstr[:-len(ind)]
1185 return outstr[:-len(ind)]
1192 else:
1186 else:
1193 return outstr
1187 return outstr
1194
1188
1195 #-----------------------------------------------------------------------------
1189 #-----------------------------------------------------------------------------
1196 def native_line_ends(filename,backup=1):
1190 def native_line_ends(filename,backup=1):
1197 """Convert (in-place) a file to line-ends native to the current OS.
1191 """Convert (in-place) a file to line-ends native to the current OS.
1198
1192
1199 If the optional backup argument is given as false, no backup of the
1193 If the optional backup argument is given as false, no backup of the
1200 original file is left. """
1194 original file is left. """
1201
1195
1202 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1196 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1203
1197
1204 bak_filename = filename + backup_suffixes[os.name]
1198 bak_filename = filename + backup_suffixes[os.name]
1205
1199
1206 original = open(filename).read()
1200 original = open(filename).read()
1207 shutil.copy2(filename,bak_filename)
1201 shutil.copy2(filename,bak_filename)
1208 try:
1202 try:
1209 new = open(filename,'wb')
1203 new = open(filename,'wb')
1210 new.write(os.linesep.join(original.splitlines()))
1204 new.write(os.linesep.join(original.splitlines()))
1211 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1205 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1212 new.close()
1206 new.close()
1213 except:
1207 except:
1214 os.rename(bak_filename,filename)
1208 os.rename(bak_filename,filename)
1215 if not backup:
1209 if not backup:
1216 try:
1210 try:
1217 os.remove(bak_filename)
1211 os.remove(bak_filename)
1218 except:
1212 except:
1219 pass
1213 pass
1220
1214
1221 #----------------------------------------------------------------------------
1215 #----------------------------------------------------------------------------
1222 def get_pager_cmd(pager_cmd = None):
1216 def get_pager_cmd(pager_cmd = None):
1223 """Return a pager command.
1217 """Return a pager command.
1224
1218
1225 Makes some attempts at finding an OS-correct one."""
1219 Makes some attempts at finding an OS-correct one."""
1226
1220
1227 if os.name == 'posix':
1221 if os.name == 'posix':
1228 default_pager_cmd = 'less -r' # -r for color control sequences
1222 default_pager_cmd = 'less -r' # -r for color control sequences
1229 elif os.name in ['nt','dos']:
1223 elif os.name in ['nt','dos']:
1230 default_pager_cmd = 'type'
1224 default_pager_cmd = 'type'
1231
1225
1232 if pager_cmd is None:
1226 if pager_cmd is None:
1233 try:
1227 try:
1234 pager_cmd = os.environ['PAGER']
1228 pager_cmd = os.environ['PAGER']
1235 except:
1229 except:
1236 pager_cmd = default_pager_cmd
1230 pager_cmd = default_pager_cmd
1237 return pager_cmd
1231 return pager_cmd
1238
1232
1239 #-----------------------------------------------------------------------------
1233 #-----------------------------------------------------------------------------
1240 def get_pager_start(pager,start):
1234 def get_pager_start(pager,start):
1241 """Return the string for paging files with an offset.
1235 """Return the string for paging files with an offset.
1242
1236
1243 This is the '+N' argument which less and more (under Unix) accept.
1237 This is the '+N' argument which less and more (under Unix) accept.
1244 """
1238 """
1245
1239
1246 if pager in ['less','more']:
1240 if pager in ['less','more']:
1247 if start:
1241 if start:
1248 start_string = '+' + str(start)
1242 start_string = '+' + str(start)
1249 else:
1243 else:
1250 start_string = ''
1244 start_string = ''
1251 else:
1245 else:
1252 start_string = ''
1246 start_string = ''
1253 return start_string
1247 return start_string
1254
1248
1255 #----------------------------------------------------------------------------
1249 #----------------------------------------------------------------------------
1256 if os.name == "nt":
1250 if os.name == "nt":
1257 import msvcrt
1251 import msvcrt
1258 def page_more():
1252 def page_more():
1259 """ Smart pausing between pages
1253 """ Smart pausing between pages
1260
1254
1261 @return: True if need print more lines, False if quit
1255 @return: True if need print more lines, False if quit
1262 """
1256 """
1263 Term.cout.write('---Return to continue, q to quit--- ')
1257 Term.cout.write('---Return to continue, q to quit--- ')
1264 ans = msvcrt.getch()
1258 ans = msvcrt.getch()
1265 if ans in ("q", "Q"):
1259 if ans in ("q", "Q"):
1266 result = False
1260 result = False
1267 else:
1261 else:
1268 result = True
1262 result = True
1269 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1263 Term.cout.write("\b"*37 + " "*37 + "\b"*37)
1270 return result
1264 return result
1271 else:
1265 else:
1272 def page_more():
1266 def page_more():
1273 ans = raw_input('---Return to continue, q to quit--- ')
1267 ans = raw_input('---Return to continue, q to quit--- ')
1274 if ans.lower().startswith('q'):
1268 if ans.lower().startswith('q'):
1275 return False
1269 return False
1276 else:
1270 else:
1277 return True
1271 return True
1278
1272
1279 esc_re = re.compile(r"(\x1b[^m]+m)")
1273 esc_re = re.compile(r"(\x1b[^m]+m)")
1280
1274
1281 def page_dumb(strng,start=0,screen_lines=25):
1275 def page_dumb(strng,start=0,screen_lines=25):
1282 """Very dumb 'pager' in Python, for when nothing else works.
1276 """Very dumb 'pager' in Python, for when nothing else works.
1283
1277
1284 Only moves forward, same interface as page(), except for pager_cmd and
1278 Only moves forward, same interface as page(), except for pager_cmd and
1285 mode."""
1279 mode."""
1286
1280
1287 out_ln = strng.splitlines()[start:]
1281 out_ln = strng.splitlines()[start:]
1288 screens = chop(out_ln,screen_lines-1)
1282 screens = chop(out_ln,screen_lines-1)
1289 if len(screens) == 1:
1283 if len(screens) == 1:
1290 print >>Term.cout, os.linesep.join(screens[0])
1284 print >>Term.cout, os.linesep.join(screens[0])
1291 else:
1285 else:
1292 last_escape = ""
1286 last_escape = ""
1293 for scr in screens[0:-1]:
1287 for scr in screens[0:-1]:
1294 hunk = os.linesep.join(scr)
1288 hunk = os.linesep.join(scr)
1295 print >>Term.cout, last_escape + hunk
1289 print >>Term.cout, last_escape + hunk
1296 if not page_more():
1290 if not page_more():
1297 return
1291 return
1298 esc_list = esc_re.findall(hunk)
1292 esc_list = esc_re.findall(hunk)
1299 if len(esc_list) > 0:
1293 if len(esc_list) > 0:
1300 last_escape = esc_list[-1]
1294 last_escape = esc_list[-1]
1301 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1295 print >>Term.cout, last_escape + os.linesep.join(screens[-1])
1302
1296
1303 #----------------------------------------------------------------------------
1297 #----------------------------------------------------------------------------
1304 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1298 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1305 """Print a string, piping through a pager after a certain length.
1299 """Print a string, piping through a pager after a certain length.
1306
1300
1307 The screen_lines parameter specifies the number of *usable* lines of your
1301 The screen_lines parameter specifies the number of *usable* lines of your
1308 terminal screen (total lines minus lines you need to reserve to show other
1302 terminal screen (total lines minus lines you need to reserve to show other
1309 information).
1303 information).
1310
1304
1311 If you set screen_lines to a number <=0, page() will try to auto-determine
1305 If you set screen_lines to a number <=0, page() will try to auto-determine
1312 your screen size and will only use up to (screen_size+screen_lines) for
1306 your screen size and will only use up to (screen_size+screen_lines) for
1313 printing, paging after that. That is, if you want auto-detection but need
1307 printing, paging after that. That is, if you want auto-detection but need
1314 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1308 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1315 auto-detection without any lines reserved simply use screen_lines = 0.
1309 auto-detection without any lines reserved simply use screen_lines = 0.
1316
1310
1317 If a string won't fit in the allowed lines, it is sent through the
1311 If a string won't fit in the allowed lines, it is sent through the
1318 specified pager command. If none given, look for PAGER in the environment,
1312 specified pager command. If none given, look for PAGER in the environment,
1319 and ultimately default to less.
1313 and ultimately default to less.
1320
1314
1321 If no system pager works, the string is sent through a 'dumb pager'
1315 If no system pager works, the string is sent through a 'dumb pager'
1322 written in python, very simplistic.
1316 written in python, very simplistic.
1323 """
1317 """
1324
1318
1325 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1319 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1326 TERM = os.environ.get('TERM','dumb')
1320 TERM = os.environ.get('TERM','dumb')
1327 if TERM in ['dumb','emacs'] and os.name != 'nt':
1321 if TERM in ['dumb','emacs'] and os.name != 'nt':
1328 print strng
1322 print strng
1329 return
1323 return
1330 # chop off the topmost part of the string we don't want to see
1324 # chop off the topmost part of the string we don't want to see
1331 str_lines = strng.split(os.linesep)[start:]
1325 str_lines = strng.split(os.linesep)[start:]
1332 str_toprint = os.linesep.join(str_lines)
1326 str_toprint = os.linesep.join(str_lines)
1333 num_newlines = len(str_lines)
1327 num_newlines = len(str_lines)
1334 len_str = len(str_toprint)
1328 len_str = len(str_toprint)
1335
1329
1336 # Dumb heuristics to guesstimate number of on-screen lines the string
1330 # Dumb heuristics to guesstimate number of on-screen lines the string
1337 # takes. Very basic, but good enough for docstrings in reasonable
1331 # takes. Very basic, but good enough for docstrings in reasonable
1338 # terminals. If someone later feels like refining it, it's not hard.
1332 # terminals. If someone later feels like refining it, it's not hard.
1339 numlines = max(num_newlines,int(len_str/80)+1)
1333 numlines = max(num_newlines,int(len_str/80)+1)
1340
1334
1341 if os.name == "nt":
1335 if os.name == "nt":
1342 screen_lines_def = get_console_size(defaulty=25)[1]
1336 screen_lines_def = get_console_size(defaulty=25)[1]
1343 else:
1337 else:
1344 screen_lines_def = 25 # default value if we can't auto-determine
1338 screen_lines_def = 25 # default value if we can't auto-determine
1345
1339
1346 # auto-determine screen size
1340 # auto-determine screen size
1347 if screen_lines <= 0:
1341 if screen_lines <= 0:
1348 if TERM=='xterm':
1342 if TERM=='xterm':
1349 try:
1343 try:
1350 import curses
1344 import curses
1351 if hasattr(curses,'initscr'):
1345 if hasattr(curses,'initscr'):
1352 use_curses = 1
1346 use_curses = 1
1353 else:
1347 else:
1354 use_curses = 0
1348 use_curses = 0
1355 except ImportError:
1349 except ImportError:
1356 use_curses = 0
1350 use_curses = 0
1357 else:
1351 else:
1358 # curses causes problems on many terminals other than xterm.
1352 # curses causes problems on many terminals other than xterm.
1359 use_curses = 0
1353 use_curses = 0
1360 if use_curses:
1354 if use_curses:
1361 scr = curses.initscr()
1355 scr = curses.initscr()
1362 screen_lines_real,screen_cols = scr.getmaxyx()
1356 screen_lines_real,screen_cols = scr.getmaxyx()
1363 curses.endwin()
1357 curses.endwin()
1364 screen_lines += screen_lines_real
1358 screen_lines += screen_lines_real
1365 #print '***Screen size:',screen_lines_real,'lines x',\
1359 #print '***Screen size:',screen_lines_real,'lines x',\
1366 #screen_cols,'columns.' # dbg
1360 #screen_cols,'columns.' # dbg
1367 else:
1361 else:
1368 screen_lines += screen_lines_def
1362 screen_lines += screen_lines_def
1369
1363
1370 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1364 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1371 if numlines <= screen_lines :
1365 if numlines <= screen_lines :
1372 #print '*** normal print' # dbg
1366 #print '*** normal print' # dbg
1373 print >>Term.cout, str_toprint
1367 print >>Term.cout, str_toprint
1374 else:
1368 else:
1375 # Try to open pager and default to internal one if that fails.
1369 # Try to open pager and default to internal one if that fails.
1376 # All failure modes are tagged as 'retval=1', to match the return
1370 # All failure modes are tagged as 'retval=1', to match the return
1377 # value of a failed system command. If any intermediate attempt
1371 # value of a failed system command. If any intermediate attempt
1378 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1372 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1379 pager_cmd = get_pager_cmd(pager_cmd)
1373 pager_cmd = get_pager_cmd(pager_cmd)
1380 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1374 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1381 if os.name == 'nt':
1375 if os.name == 'nt':
1382 if pager_cmd.startswith('type'):
1376 if pager_cmd.startswith('type'):
1383 # The default WinXP 'type' command is failing on complex strings.
1377 # The default WinXP 'type' command is failing on complex strings.
1384 retval = 1
1378 retval = 1
1385 else:
1379 else:
1386 tmpname = tempfile.mktemp('.txt')
1380 tmpname = tempfile.mktemp('.txt')
1387 tmpfile = file(tmpname,'wt')
1381 tmpfile = file(tmpname,'wt')
1388 tmpfile.write(strng)
1382 tmpfile.write(strng)
1389 tmpfile.close()
1383 tmpfile.close()
1390 cmd = "%s < %s" % (pager_cmd,tmpname)
1384 cmd = "%s < %s" % (pager_cmd,tmpname)
1391 if os.system(cmd):
1385 if os.system(cmd):
1392 retval = 1
1386 retval = 1
1393 else:
1387 else:
1394 retval = None
1388 retval = None
1395 os.remove(tmpname)
1389 os.remove(tmpname)
1396 else:
1390 else:
1397 try:
1391 try:
1398 retval = None
1392 retval = None
1399 # if I use popen4, things hang. No idea why.
1393 # if I use popen4, things hang. No idea why.
1400 #pager,shell_out = os.popen4(pager_cmd)
1394 #pager,shell_out = os.popen4(pager_cmd)
1401 pager = os.popen(pager_cmd,'w')
1395 pager = os.popen(pager_cmd,'w')
1402 pager.write(strng)
1396 pager.write(strng)
1403 pager.close()
1397 pager.close()
1404 retval = pager.close() # success returns None
1398 retval = pager.close() # success returns None
1405 except IOError,msg: # broken pipe when user quits
1399 except IOError,msg: # broken pipe when user quits
1406 if msg.args == (32,'Broken pipe'):
1400 if msg.args == (32,'Broken pipe'):
1407 retval = None
1401 retval = None
1408 else:
1402 else:
1409 retval = 1
1403 retval = 1
1410 except OSError:
1404 except OSError:
1411 # Other strange problems, sometimes seen in Win2k/cygwin
1405 # Other strange problems, sometimes seen in Win2k/cygwin
1412 retval = 1
1406 retval = 1
1413 if retval is not None:
1407 if retval is not None:
1414 page_dumb(strng,screen_lines=screen_lines)
1408 page_dumb(strng,screen_lines=screen_lines)
1415
1409
1416 #----------------------------------------------------------------------------
1410 #----------------------------------------------------------------------------
1417 def page_file(fname,start = 0, pager_cmd = None):
1411 def page_file(fname,start = 0, pager_cmd = None):
1418 """Page a file, using an optional pager command and starting line.
1412 """Page a file, using an optional pager command and starting line.
1419 """
1413 """
1420
1414
1421 pager_cmd = get_pager_cmd(pager_cmd)
1415 pager_cmd = get_pager_cmd(pager_cmd)
1422 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1416 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1423
1417
1424 try:
1418 try:
1425 if os.environ['TERM'] in ['emacs','dumb']:
1419 if os.environ['TERM'] in ['emacs','dumb']:
1426 raise EnvironmentError
1420 raise EnvironmentError
1427 xsys(pager_cmd + ' ' + fname)
1421 xsys(pager_cmd + ' ' + fname)
1428 except:
1422 except:
1429 try:
1423 try:
1430 if start > 0:
1424 if start > 0:
1431 start -= 1
1425 start -= 1
1432 page(open(fname).read(),start)
1426 page(open(fname).read(),start)
1433 except:
1427 except:
1434 print 'Unable to show file',`fname`
1428 print 'Unable to show file',`fname`
1435
1429
1436 #----------------------------------------------------------------------------
1430 #----------------------------------------------------------------------------
1437 def snip_print(str,width = 75,print_full = 0,header = ''):
1431 def snip_print(str,width = 75,print_full = 0,header = ''):
1438 """Print a string snipping the midsection to fit in width.
1432 """Print a string snipping the midsection to fit in width.
1439
1433
1440 print_full: mode control:
1434 print_full: mode control:
1441 - 0: only snip long strings
1435 - 0: only snip long strings
1442 - 1: send to page() directly.
1436 - 1: send to page() directly.
1443 - 2: snip long strings and ask for full length viewing with page()
1437 - 2: snip long strings and ask for full length viewing with page()
1444 Return 1 if snipping was necessary, 0 otherwise."""
1438 Return 1 if snipping was necessary, 0 otherwise."""
1445
1439
1446 if print_full == 1:
1440 if print_full == 1:
1447 page(header+str)
1441 page(header+str)
1448 return 0
1442 return 0
1449
1443
1450 print header,
1444 print header,
1451 if len(str) < width:
1445 if len(str) < width:
1452 print str
1446 print str
1453 snip = 0
1447 snip = 0
1454 else:
1448 else:
1455 whalf = int((width -5)/2)
1449 whalf = int((width -5)/2)
1456 print str[:whalf] + ' <...> ' + str[-whalf:]
1450 print str[:whalf] + ' <...> ' + str[-whalf:]
1457 snip = 1
1451 snip = 1
1458 if snip and print_full == 2:
1452 if snip and print_full == 2:
1459 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1453 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1460 page(str)
1454 page(str)
1461 return snip
1455 return snip
1462
1456
1463 #****************************************************************************
1457 #****************************************************************************
1464 # lists, dicts and structures
1458 # lists, dicts and structures
1465
1459
1466 def belong(candidates,checklist):
1460 def belong(candidates,checklist):
1467 """Check whether a list of items appear in a given list of options.
1461 """Check whether a list of items appear in a given list of options.
1468
1462
1469 Returns a list of 1 and 0, one for each candidate given."""
1463 Returns a list of 1 and 0, one for each candidate given."""
1470
1464
1471 return [x in checklist for x in candidates]
1465 return [x in checklist for x in candidates]
1472
1466
1473 #----------------------------------------------------------------------------
1467 #----------------------------------------------------------------------------
1474 def uniq_stable(elems):
1468 def uniq_stable(elems):
1475 """uniq_stable(elems) -> list
1469 """uniq_stable(elems) -> list
1476
1470
1477 Return from an iterable, a list of all the unique elements in the input,
1471 Return from an iterable, a list of all the unique elements in the input,
1478 but maintaining the order in which they first appear.
1472 but maintaining the order in which they first appear.
1479
1473
1480 A naive solution to this problem which just makes a dictionary with the
1474 A naive solution to this problem which just makes a dictionary with the
1481 elements as keys fails to respect the stability condition, since
1475 elements as keys fails to respect the stability condition, since
1482 dictionaries are unsorted by nature.
1476 dictionaries are unsorted by nature.
1483
1477
1484 Note: All elements in the input must be valid dictionary keys for this
1478 Note: All elements in the input must be valid dictionary keys for this
1485 routine to work, as it internally uses a dictionary for efficiency
1479 routine to work, as it internally uses a dictionary for efficiency
1486 reasons."""
1480 reasons."""
1487
1481
1488 unique = []
1482 unique = []
1489 unique_dict = {}
1483 unique_dict = {}
1490 for nn in elems:
1484 for nn in elems:
1491 if nn not in unique_dict:
1485 if nn not in unique_dict:
1492 unique.append(nn)
1486 unique.append(nn)
1493 unique_dict[nn] = None
1487 unique_dict[nn] = None
1494 return unique
1488 return unique
1495
1489
1496 #----------------------------------------------------------------------------
1490 #----------------------------------------------------------------------------
1497 class NLprinter:
1491 class NLprinter:
1498 """Print an arbitrarily nested list, indicating index numbers.
1492 """Print an arbitrarily nested list, indicating index numbers.
1499
1493
1500 An instance of this class called nlprint is available and callable as a
1494 An instance of this class called nlprint is available and callable as a
1501 function.
1495 function.
1502
1496
1503 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1497 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1504 and using 'sep' to separate the index from the value. """
1498 and using 'sep' to separate the index from the value. """
1505
1499
1506 def __init__(self):
1500 def __init__(self):
1507 self.depth = 0
1501 self.depth = 0
1508
1502
1509 def __call__(self,lst,pos='',**kw):
1503 def __call__(self,lst,pos='',**kw):
1510 """Prints the nested list numbering levels."""
1504 """Prints the nested list numbering levels."""
1511 kw.setdefault('indent',' ')
1505 kw.setdefault('indent',' ')
1512 kw.setdefault('sep',': ')
1506 kw.setdefault('sep',': ')
1513 kw.setdefault('start',0)
1507 kw.setdefault('start',0)
1514 kw.setdefault('stop',len(lst))
1508 kw.setdefault('stop',len(lst))
1515 # we need to remove start and stop from kw so they don't propagate
1509 # we need to remove start and stop from kw so they don't propagate
1516 # into a recursive call for a nested list.
1510 # into a recursive call for a nested list.
1517 start = kw['start']; del kw['start']
1511 start = kw['start']; del kw['start']
1518 stop = kw['stop']; del kw['stop']
1512 stop = kw['stop']; del kw['stop']
1519 if self.depth == 0 and 'header' in kw.keys():
1513 if self.depth == 0 and 'header' in kw.keys():
1520 print kw['header']
1514 print kw['header']
1521
1515
1522 for idx in range(start,stop):
1516 for idx in range(start,stop):
1523 elem = lst[idx]
1517 elem = lst[idx]
1524 if type(elem)==type([]):
1518 if type(elem)==type([]):
1525 self.depth += 1
1519 self.depth += 1
1526 self.__call__(elem,itpl('$pos$idx,'),**kw)
1520 self.__call__(elem,itpl('$pos$idx,'),**kw)
1527 self.depth -= 1
1521 self.depth -= 1
1528 else:
1522 else:
1529 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1523 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1530
1524
1531 nlprint = NLprinter()
1525 nlprint = NLprinter()
1532 #----------------------------------------------------------------------------
1526 #----------------------------------------------------------------------------
1533 def all_belong(candidates,checklist):
1527 def all_belong(candidates,checklist):
1534 """Check whether a list of items ALL appear in a given list of options.
1528 """Check whether a list of items ALL appear in a given list of options.
1535
1529
1536 Returns a single 1 or 0 value."""
1530 Returns a single 1 or 0 value."""
1537
1531
1538 return 1-(0 in [x in checklist for x in candidates])
1532 return 1-(0 in [x in checklist for x in candidates])
1539
1533
1540 #----------------------------------------------------------------------------
1534 #----------------------------------------------------------------------------
1541 def sort_compare(lst1,lst2,inplace = 1):
1535 def sort_compare(lst1,lst2,inplace = 1):
1542 """Sort and compare two lists.
1536 """Sort and compare two lists.
1543
1537
1544 By default it does it in place, thus modifying the lists. Use inplace = 0
1538 By default it does it in place, thus modifying the lists. Use inplace = 0
1545 to avoid that (at the cost of temporary copy creation)."""
1539 to avoid that (at the cost of temporary copy creation)."""
1546 if not inplace:
1540 if not inplace:
1547 lst1 = lst1[:]
1541 lst1 = lst1[:]
1548 lst2 = lst2[:]
1542 lst2 = lst2[:]
1549 lst1.sort(); lst2.sort()
1543 lst1.sort(); lst2.sort()
1550 return lst1 == lst2
1544 return lst1 == lst2
1551
1545
1552 #----------------------------------------------------------------------------
1546 #----------------------------------------------------------------------------
1553 def mkdict(**kwargs):
1547 def mkdict(**kwargs):
1554 """Return a dict from a keyword list.
1548 """Return a dict from a keyword list.
1555
1549
1556 It's just syntactic sugar for making ditcionary creation more convenient:
1550 It's just syntactic sugar for making ditcionary creation more convenient:
1557 # the standard way
1551 # the standard way
1558 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1552 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1559 # a cleaner way
1553 # a cleaner way
1560 >>>data = dict(red=1, green=2, blue=3)
1554 >>>data = dict(red=1, green=2, blue=3)
1561
1555
1562 If you need more than this, look at the Struct() class."""
1556 If you need more than this, look at the Struct() class."""
1563
1557
1564 return kwargs
1558 return kwargs
1565
1559
1566 #----------------------------------------------------------------------------
1560 #----------------------------------------------------------------------------
1567 def list2dict(lst):
1561 def list2dict(lst):
1568 """Takes a list of (key,value) pairs and turns it into a dict."""
1562 """Takes a list of (key,value) pairs and turns it into a dict."""
1569
1563
1570 dic = {}
1564 dic = {}
1571 for k,v in lst: dic[k] = v
1565 for k,v in lst: dic[k] = v
1572 return dic
1566 return dic
1573
1567
1574 #----------------------------------------------------------------------------
1568 #----------------------------------------------------------------------------
1575 def list2dict2(lst,default=''):
1569 def list2dict2(lst,default=''):
1576 """Takes a list and turns it into a dict.
1570 """Takes a list and turns it into a dict.
1577 Much slower than list2dict, but more versatile. This version can take
1571 Much slower than list2dict, but more versatile. This version can take
1578 lists with sublists of arbitrary length (including sclars)."""
1572 lists with sublists of arbitrary length (including sclars)."""
1579
1573
1580 dic = {}
1574 dic = {}
1581 for elem in lst:
1575 for elem in lst:
1582 if type(elem) in (types.ListType,types.TupleType):
1576 if type(elem) in (types.ListType,types.TupleType):
1583 size = len(elem)
1577 size = len(elem)
1584 if size == 0:
1578 if size == 0:
1585 pass
1579 pass
1586 elif size == 1:
1580 elif size == 1:
1587 dic[elem] = default
1581 dic[elem] = default
1588 else:
1582 else:
1589 k,v = elem[0], elem[1:]
1583 k,v = elem[0], elem[1:]
1590 if len(v) == 1: v = v[0]
1584 if len(v) == 1: v = v[0]
1591 dic[k] = v
1585 dic[k] = v
1592 else:
1586 else:
1593 dic[elem] = default
1587 dic[elem] = default
1594 return dic
1588 return dic
1595
1589
1596 #----------------------------------------------------------------------------
1590 #----------------------------------------------------------------------------
1597 def flatten(seq):
1591 def flatten(seq):
1598 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1592 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1599
1593
1600 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1594 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1601
1595
1602 # if the x=0 isn't made, a *global* variable x is left over after calling
1596 # if the x=0 isn't made, a *global* variable x is left over after calling
1603 # this function, with the value of the last element in the return
1597 # this function, with the value of the last element in the return
1604 # list. This does seem like a bug big time to me.
1598 # list. This does seem like a bug big time to me.
1605
1599
1606 # the problem is fixed with the x=0, which seems to force the creation of
1600 # the problem is fixed with the x=0, which seems to force the creation of
1607 # a local name
1601 # a local name
1608
1602
1609 x = 0
1603 x = 0
1610 return [x for subseq in seq for x in subseq]
1604 return [x for subseq in seq for x in subseq]
1611
1605
1612 #----------------------------------------------------------------------------
1606 #----------------------------------------------------------------------------
1613 def get_slice(seq,start=0,stop=None,step=1):
1607 def get_slice(seq,start=0,stop=None,step=1):
1614 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1608 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1615 if stop == None:
1609 if stop == None:
1616 stop = len(seq)
1610 stop = len(seq)
1617 item = lambda i: seq[i]
1611 item = lambda i: seq[i]
1618 return map(item,xrange(start,stop,step))
1612 return map(item,xrange(start,stop,step))
1619
1613
1620 #----------------------------------------------------------------------------
1614 #----------------------------------------------------------------------------
1621 def chop(seq,size):
1615 def chop(seq,size):
1622 """Chop a sequence into chunks of the given size."""
1616 """Chop a sequence into chunks of the given size."""
1623 chunk = lambda i: seq[i:i+size]
1617 chunk = lambda i: seq[i:i+size]
1624 return map(chunk,xrange(0,len(seq),size))
1618 return map(chunk,xrange(0,len(seq),size))
1625
1619
1626 #----------------------------------------------------------------------------
1620 #----------------------------------------------------------------------------
1627 def with(object, **args):
1621 def with(object, **args):
1628 """Set multiple attributes for an object, similar to Pascal's with.
1622 """Set multiple attributes for an object, similar to Pascal's with.
1629
1623
1630 Example:
1624 Example:
1631 with(jim,
1625 with(jim,
1632 born = 1960,
1626 born = 1960,
1633 haircolour = 'Brown',
1627 haircolour = 'Brown',
1634 eyecolour = 'Green')
1628 eyecolour = 'Green')
1635
1629
1636 Credit: Greg Ewing, in
1630 Credit: Greg Ewing, in
1637 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1631 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1638
1632
1639 object.__dict__.update(args)
1633 object.__dict__.update(args)
1640
1634
1641 #----------------------------------------------------------------------------
1635 #----------------------------------------------------------------------------
1642 def setattr_list(obj,alist,nspace = None):
1636 def setattr_list(obj,alist,nspace = None):
1643 """Set a list of attributes for an object taken from a namespace.
1637 """Set a list of attributes for an object taken from a namespace.
1644
1638
1645 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1639 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1646 alist with their values taken from nspace, which must be a dict (something
1640 alist with their values taken from nspace, which must be a dict (something
1647 like locals() will often do) If nspace isn't given, locals() of the
1641 like locals() will often do) If nspace isn't given, locals() of the
1648 *caller* is used, so in most cases you can omit it.
1642 *caller* is used, so in most cases you can omit it.
1649
1643
1650 Note that alist can be given as a string, which will be automatically
1644 Note that alist can be given as a string, which will be automatically
1651 split into a list on whitespace. If given as a list, it must be a list of
1645 split into a list on whitespace. If given as a list, it must be a list of
1652 *strings* (the variable names themselves), not of variables."""
1646 *strings* (the variable names themselves), not of variables."""
1653
1647
1654 # this grabs the local variables from the *previous* call frame -- that is
1648 # this grabs the local variables from the *previous* call frame -- that is
1655 # the locals from the function that called setattr_list().
1649 # the locals from the function that called setattr_list().
1656 # - snipped from weave.inline()
1650 # - snipped from weave.inline()
1657 if nspace is None:
1651 if nspace is None:
1658 call_frame = sys._getframe().f_back
1652 call_frame = sys._getframe().f_back
1659 nspace = call_frame.f_locals
1653 nspace = call_frame.f_locals
1660
1654
1661 if type(alist) in StringTypes:
1655 if type(alist) in StringTypes:
1662 alist = alist.split()
1656 alist = alist.split()
1663 for attr in alist:
1657 for attr in alist:
1664 val = eval(attr,nspace)
1658 val = eval(attr,nspace)
1665 setattr(obj,attr,val)
1659 setattr(obj,attr,val)
1666
1660
1667 #----------------------------------------------------------------------------
1661 #----------------------------------------------------------------------------
1668 def getattr_list(obj,alist,*args):
1662 def getattr_list(obj,alist,*args):
1669 """getattr_list(obj,alist[, default]) -> attribute list.
1663 """getattr_list(obj,alist[, default]) -> attribute list.
1670
1664
1671 Get a list of named attributes for an object. When a default argument is
1665 Get a list of named attributes for an object. When a default argument is
1672 given, it is returned when the attribute doesn't exist; without it, an
1666 given, it is returned when the attribute doesn't exist; without it, an
1673 exception is raised in that case.
1667 exception is raised in that case.
1674
1668
1675 Note that alist can be given as a string, which will be automatically
1669 Note that alist can be given as a string, which will be automatically
1676 split into a list on whitespace. If given as a list, it must be a list of
1670 split into a list on whitespace. If given as a list, it must be a list of
1677 *strings* (the variable names themselves), not of variables."""
1671 *strings* (the variable names themselves), not of variables."""
1678
1672
1679 if type(alist) in StringTypes:
1673 if type(alist) in StringTypes:
1680 alist = alist.split()
1674 alist = alist.split()
1681 if args:
1675 if args:
1682 if len(args)==1:
1676 if len(args)==1:
1683 default = args[0]
1677 default = args[0]
1684 return map(lambda attr: getattr(obj,attr,default),alist)
1678 return map(lambda attr: getattr(obj,attr,default),alist)
1685 else:
1679 else:
1686 raise ValueError,'getattr_list() takes only one optional argument'
1680 raise ValueError,'getattr_list() takes only one optional argument'
1687 else:
1681 else:
1688 return map(lambda attr: getattr(obj,attr),alist)
1682 return map(lambda attr: getattr(obj,attr),alist)
1689
1683
1690 #----------------------------------------------------------------------------
1684 #----------------------------------------------------------------------------
1691 def map_method(method,object_list,*argseq,**kw):
1685 def map_method(method,object_list,*argseq,**kw):
1692 """map_method(method,object_list,*args,**kw) -> list
1686 """map_method(method,object_list,*args,**kw) -> list
1693
1687
1694 Return a list of the results of applying the methods to the items of the
1688 Return a list of the results of applying the methods to the items of the
1695 argument sequence(s). If more than one sequence is given, the method is
1689 argument sequence(s). If more than one sequence is given, the method is
1696 called with an argument list consisting of the corresponding item of each
1690 called with an argument list consisting of the corresponding item of each
1697 sequence. All sequences must be of the same length.
1691 sequence. All sequences must be of the same length.
1698
1692
1699 Keyword arguments are passed verbatim to all objects called.
1693 Keyword arguments are passed verbatim to all objects called.
1700
1694
1701 This is Python code, so it's not nearly as fast as the builtin map()."""
1695 This is Python code, so it's not nearly as fast as the builtin map()."""
1702
1696
1703 out_list = []
1697 out_list = []
1704 idx = 0
1698 idx = 0
1705 for object in object_list:
1699 for object in object_list:
1706 try:
1700 try:
1707 handler = getattr(object, method)
1701 handler = getattr(object, method)
1708 except AttributeError:
1702 except AttributeError:
1709 out_list.append(None)
1703 out_list.append(None)
1710 else:
1704 else:
1711 if argseq:
1705 if argseq:
1712 args = map(lambda lst:lst[idx],argseq)
1706 args = map(lambda lst:lst[idx],argseq)
1713 #print 'ob',object,'hand',handler,'ar',args # dbg
1707 #print 'ob',object,'hand',handler,'ar',args # dbg
1714 out_list.append(handler(args,**kw))
1708 out_list.append(handler(args,**kw))
1715 else:
1709 else:
1716 out_list.append(handler(**kw))
1710 out_list.append(handler(**kw))
1717 idx += 1
1711 idx += 1
1718 return out_list
1712 return out_list
1719
1713
1720 #----------------------------------------------------------------------------
1714 #----------------------------------------------------------------------------
1721 def import_fail_info(mod_name,fns=None):
1715 def import_fail_info(mod_name,fns=None):
1722 """Inform load failure for a module."""
1716 """Inform load failure for a module."""
1723
1717
1724 if fns == None:
1718 if fns == None:
1725 warn("Loading of %s failed.\n" % (mod_name,))
1719 warn("Loading of %s failed.\n" % (mod_name,))
1726 else:
1720 else:
1727 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1721 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
1728
1722
1729 #----------------------------------------------------------------------------
1723 #----------------------------------------------------------------------------
1730 # Proposed popitem() extension, written as a method
1724 # Proposed popitem() extension, written as a method
1731
1725
1732 class NotGiven: pass
1726 class NotGiven: pass
1733
1727
1734 def popkey(dct,key,default=NotGiven):
1728 def popkey(dct,key,default=NotGiven):
1735 """Return dct[key] and delete dct[key].
1729 """Return dct[key] and delete dct[key].
1736
1730
1737 If default is given, return it if dct[key] doesn't exist, otherwise raise
1731 If default is given, return it if dct[key] doesn't exist, otherwise raise
1738 KeyError. """
1732 KeyError. """
1739
1733
1740 try:
1734 try:
1741 val = dct[key]
1735 val = dct[key]
1742 except KeyError:
1736 except KeyError:
1743 if default is NotGiven:
1737 if default is NotGiven:
1744 raise
1738 raise
1745 else:
1739 else:
1746 return default
1740 return default
1747 else:
1741 else:
1748 del dct[key]
1742 del dct[key]
1749 return val
1743 return val
1750 #*************************** end of file <genutils.py> **********************
1744 #*************************** end of file <genutils.py> **********************
1751
1745
@@ -1,2157 +1,2191 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 1012 2006-01-12 21:29:37Z vivainio $
9 $Id: iplib.py 1013 2006-01-13 08:33:32Z 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.ipstruct import Struct
73 from IPython.ipstruct 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+)')
86 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
85 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
87
86
88
87
89 #****************************************************************************
88 #****************************************************************************
90 # Some utility function definitions
89 # Some utility function definitions
91
90
91 ini_spaces_re = re.compile(r'^(\s+)')
92
93 def num_ini_spaces(strng):
94 """Return the number of initial spaces in a string"""
95
96 ini_spaces = ini_spaces_re.match(strng)
97 if ini_spaces:
98 return ini_spaces.end()
99 else:
100 return 0
101
92 def softspace(file, newvalue):
102 def softspace(file, newvalue):
93 """Copied from code.py, to remove the dependency"""
103 """Copied from code.py, to remove the dependency"""
104
94 oldvalue = 0
105 oldvalue = 0
95 try:
106 try:
96 oldvalue = file.softspace
107 oldvalue = file.softspace
97 except AttributeError:
108 except AttributeError:
98 pass
109 pass
99 try:
110 try:
100 file.softspace = newvalue
111 file.softspace = newvalue
101 except (AttributeError, TypeError):
112 except (AttributeError, TypeError):
102 # "attribute-less object" or "read-only attributes"
113 # "attribute-less object" or "read-only attributes"
103 pass
114 pass
104 return oldvalue
115 return oldvalue
105
116
106
117
107 #****************************************************************************
118 #****************************************************************************
108 # Local use exceptions
119 # Local use exceptions
109 class SpaceInInput(exceptions.Exception): pass
120 class SpaceInInput(exceptions.Exception): pass
110
121
111
122
112 #****************************************************************************
123 #****************************************************************************
113 # Local use classes
124 # Local use classes
114 class Bunch: pass
125 class Bunch: pass
115
126
116 class Undefined: pass
127 class Undefined: pass
117
128
118 class InputList(list):
129 class InputList(list):
119 """Class to store user input.
130 """Class to store user input.
120
131
121 It's basically a list, but slices return a string instead of a list, thus
132 It's basically a list, but slices return a string instead of a list, thus
122 allowing things like (assuming 'In' is an instance):
133 allowing things like (assuming 'In' is an instance):
123
134
124 exec In[4:7]
135 exec In[4:7]
125
136
126 or
137 or
127
138
128 exec In[5:9] + In[14] + In[21:25]"""
139 exec In[5:9] + In[14] + In[21:25]"""
129
140
130 def __getslice__(self,i,j):
141 def __getslice__(self,i,j):
131 return ''.join(list.__getslice__(self,i,j))
142 return ''.join(list.__getslice__(self,i,j))
132
143
133 class SyntaxTB(ultraTB.ListTB):
144 class SyntaxTB(ultraTB.ListTB):
134 """Extension which holds some state: the last exception value"""
145 """Extension which holds some state: the last exception value"""
135
146
136 def __init__(self,color_scheme = 'NoColor'):
147 def __init__(self,color_scheme = 'NoColor'):
137 ultraTB.ListTB.__init__(self,color_scheme)
148 ultraTB.ListTB.__init__(self,color_scheme)
138 self.last_syntax_error = None
149 self.last_syntax_error = None
139
150
140 def __call__(self, etype, value, elist):
151 def __call__(self, etype, value, elist):
141 self.last_syntax_error = value
152 self.last_syntax_error = value
142 ultraTB.ListTB.__call__(self,etype,value,elist)
153 ultraTB.ListTB.__call__(self,etype,value,elist)
143
154
144 def clear_err_state(self):
155 def clear_err_state(self):
145 """Return the current error state and clear it"""
156 """Return the current error state and clear it"""
146 e = self.last_syntax_error
157 e = self.last_syntax_error
147 self.last_syntax_error = None
158 self.last_syntax_error = None
148 return e
159 return e
149
160
150 #****************************************************************************
161 #****************************************************************************
151 # Main IPython class
162 # Main IPython class
152
163
153 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
164 # 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
165 # 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
166 # 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.
167 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
157 #
168 #
158 # But at least now, all the pieces have been separated and we could, in
169 # 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
170 # principle, stop using the mixin. This will ease the transition to the
160 # chainsaw branch.
171 # chainsaw branch.
161
172
162 # For reference, the following is the list of 'self.foo' uses in the Magic
173 # 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
174 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
164 # class, to prevent clashes.
175 # class, to prevent clashes.
165
176
166 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
177 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
167 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
178 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
168 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
179 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
169 # 'self.value']
180 # 'self.value']
170
181
171 class InteractiveShell(object,Magic):
182 class InteractiveShell(object,Magic):
172 """An enhanced console for Python."""
183 """An enhanced console for Python."""
173
184
174 # class attribute to indicate whether the class supports threads or not.
185 # class attribute to indicate whether the class supports threads or not.
175 # Subclasses with thread support should override this as needed.
186 # Subclasses with thread support should override this as needed.
176 isthreaded = False
187 isthreaded = False
177
188
178 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
189 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
179 user_ns = None,user_global_ns=None,banner2='',
190 user_ns = None,user_global_ns=None,banner2='',
180 custom_exceptions=((),None),embedded=False):
191 custom_exceptions=((),None),embedded=False):
181
192
182 # some minimal strict typechecks. For some core data structures, I
193 # some minimal strict typechecks. For some core data structures, I
183 # want actual basic python types, not just anything that looks like
194 # want actual basic python types, not just anything that looks like
184 # one. This is especially true for namespaces.
195 # one. This is especially true for namespaces.
185 for ns in (user_ns,user_global_ns):
196 for ns in (user_ns,user_global_ns):
186 if ns is not None and type(ns) != types.DictType:
197 if ns is not None and type(ns) != types.DictType:
187 raise TypeError,'namespace must be a dictionary'
198 raise TypeError,'namespace must be a dictionary'
188
199
189 # Job manager (for jobs run as background threads)
200 # Job manager (for jobs run as background threads)
190 self.jobs = BackgroundJobManager()
201 self.jobs = BackgroundJobManager()
191
202
192 # track which builtins we add, so we can clean up later
203 # track which builtins we add, so we can clean up later
193 self.builtins_added = {}
204 self.builtins_added = {}
194 # This method will add the necessary builtins for operation, but
205 # This method will add the necessary builtins for operation, but
195 # tracking what it did via the builtins_added dict.
206 # tracking what it did via the builtins_added dict.
196 self.add_builtins()
207 self.add_builtins()
197
208
198 # Do the intuitively correct thing for quit/exit: we remove the
209 # Do the intuitively correct thing for quit/exit: we remove the
199 # builtins if they exist, and our own magics will deal with this
210 # builtins if they exist, and our own magics will deal with this
200 try:
211 try:
201 del __builtin__.exit, __builtin__.quit
212 del __builtin__.exit, __builtin__.quit
202 except AttributeError:
213 except AttributeError:
203 pass
214 pass
204
215
205 # Store the actual shell's name
216 # Store the actual shell's name
206 self.name = name
217 self.name = name
207
218
208 # We need to know whether the instance is meant for embedding, since
219 # We need to know whether the instance is meant for embedding, since
209 # global/local namespaces need to be handled differently in that case
220 # global/local namespaces need to be handled differently in that case
210 self.embedded = embedded
221 self.embedded = embedded
211
222
212 # command compiler
223 # command compiler
213 self.compile = codeop.CommandCompiler()
224 self.compile = codeop.CommandCompiler()
214
225
215 # User input buffer
226 # User input buffer
216 self.buffer = []
227 self.buffer = []
217
228
218 # Default name given in compilation of code
229 # Default name given in compilation of code
219 self.filename = '<ipython console>'
230 self.filename = '<ipython console>'
220
231
221 # Make an empty namespace, which extension writers can rely on both
232 # Make an empty namespace, which extension writers can rely on both
222 # existing and NEVER being used by ipython itself. This gives them a
233 # existing and NEVER being used by ipython itself. This gives them a
223 # convenient location for storing additional information and state
234 # convenient location for storing additional information and state
224 # their extensions may require, without fear of collisions with other
235 # their extensions may require, without fear of collisions with other
225 # ipython names that may develop later.
236 # ipython names that may develop later.
226 self.meta = Bunch()
237 self.meta = Bunch()
227
238
228 # Create the namespace where the user will operate. user_ns is
239 # 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
240 # 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
241 # the locals argument. But we do carry a user_global_ns namespace
231 # given as the exec 'globals' argument, This is useful in embedding
242 # given as the exec 'globals' argument, This is useful in embedding
232 # situations where the ipython shell opens in a context where the
243 # situations where the ipython shell opens in a context where the
233 # distinction between locals and globals is meaningful.
244 # distinction between locals and globals is meaningful.
234
245
235 # FIXME. For some strange reason, __builtins__ is showing up at user
246 # 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
247 # 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
248 # should really track down where the problem is coming from. Alex
238 # Schmolck reported this problem first.
249 # Schmolck reported this problem first.
239
250
240 # A useful post by Alex Martelli on this topic:
251 # A useful post by Alex Martelli on this topic:
241 # Re: inconsistent value from __builtins__
252 # Re: inconsistent value from __builtins__
242 # Von: Alex Martelli <aleaxit@yahoo.com>
253 # Von: Alex Martelli <aleaxit@yahoo.com>
243 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
254 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
244 # Gruppen: comp.lang.python
255 # Gruppen: comp.lang.python
245
256
246 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
257 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
247 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
258 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
248 # > <type 'dict'>
259 # > <type 'dict'>
249 # > >>> print type(__builtins__)
260 # > >>> print type(__builtins__)
250 # > <type 'module'>
261 # > <type 'module'>
251 # > Is this difference in return value intentional?
262 # > Is this difference in return value intentional?
252
263
253 # Well, it's documented that '__builtins__' can be either a dictionary
264 # 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
265 # 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
266 # 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
267 # that if you need to access the built-in namespace directly, you
257 # should start with "import __builtin__" (note, no 's') which will
268 # should start with "import __builtin__" (note, no 's') which will
258 # definitely give you a module. Yeah, it's somewhat confusing:-(.
269 # definitely give you a module. Yeah, it's somewhat confusing:-(.
259
270
260 if user_ns is None:
271 if user_ns is None:
261 # Set __name__ to __main__ to better match the behavior of the
272 # Set __name__ to __main__ to better match the behavior of the
262 # normal interpreter.
273 # normal interpreter.
263 user_ns = {'__name__' :'__main__',
274 user_ns = {'__name__' :'__main__',
264 '__builtins__' : __builtin__,
275 '__builtins__' : __builtin__,
265 }
276 }
266
277
267 if user_global_ns is None:
278 if user_global_ns is None:
268 user_global_ns = {}
279 user_global_ns = {}
269
280
270 # Assign namespaces
281 # Assign namespaces
271 # This is the namespace where all normal user variables live
282 # This is the namespace where all normal user variables live
272 self.user_ns = user_ns
283 self.user_ns = user_ns
273 # Embedded instances require a separate namespace for globals.
284 # Embedded instances require a separate namespace for globals.
274 # Normally this one is unused by non-embedded instances.
285 # Normally this one is unused by non-embedded instances.
275 self.user_global_ns = user_global_ns
286 self.user_global_ns = user_global_ns
276 # A namespace to keep track of internal data structures to prevent
287 # A namespace to keep track of internal data structures to prevent
277 # them from cluttering user-visible stuff. Will be updated later
288 # them from cluttering user-visible stuff. Will be updated later
278 self.internal_ns = {}
289 self.internal_ns = {}
279
290
280 # Namespace of system aliases. Each entry in the alias
291 # 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
292 # table must be a 2-tuple of the form (N,name), where N is the number
282 # of positional arguments of the alias.
293 # of positional arguments of the alias.
283 self.alias_table = {}
294 self.alias_table = {}
284
295
285 # A table holding all the namespaces IPython deals with, so that
296 # A table holding all the namespaces IPython deals with, so that
286 # introspection facilities can search easily.
297 # introspection facilities can search easily.
287 self.ns_table = {'user':user_ns,
298 self.ns_table = {'user':user_ns,
288 'user_global':user_global_ns,
299 'user_global':user_global_ns,
289 'alias':self.alias_table,
300 'alias':self.alias_table,
290 'internal':self.internal_ns,
301 'internal':self.internal_ns,
291 'builtin':__builtin__.__dict__
302 'builtin':__builtin__.__dict__
292 }
303 }
293
304
294 # The user namespace MUST have a pointer to the shell itself.
305 # The user namespace MUST have a pointer to the shell itself.
295 self.user_ns[name] = self
306 self.user_ns[name] = self
296
307
297 # We need to insert into sys.modules something that looks like a
308 # We need to insert into sys.modules something that looks like a
298 # module but which accesses the IPython namespace, for shelve and
309 # module but which accesses the IPython namespace, for shelve and
299 # pickle to work interactively. Normally they rely on getting
310 # pickle to work interactively. Normally they rely on getting
300 # everything out of __main__, but for embedding purposes each IPython
311 # everything out of __main__, but for embedding purposes each IPython
301 # instance has its own private namespace, so we can't go shoving
312 # instance has its own private namespace, so we can't go shoving
302 # everything into __main__.
313 # everything into __main__.
303
314
304 # note, however, that we should only do this for non-embedded
315 # note, however, that we should only do this for non-embedded
305 # ipythons, which really mimic the __main__.__dict__ with their own
316 # ipythons, which really mimic the __main__.__dict__ with their own
306 # namespace. Embedded instances, on the other hand, should not do
317 # namespace. Embedded instances, on the other hand, should not do
307 # this because they need to manage the user local/global namespaces
318 # this because they need to manage the user local/global namespaces
308 # only, but they live within a 'normal' __main__ (meaning, they
319 # only, but they live within a 'normal' __main__ (meaning, they
309 # shouldn't overtake the execution environment of the script they're
320 # shouldn't overtake the execution environment of the script they're
310 # embedded in).
321 # embedded in).
311
322
312 if not embedded:
323 if not embedded:
313 try:
324 try:
314 main_name = self.user_ns['__name__']
325 main_name = self.user_ns['__name__']
315 except KeyError:
326 except KeyError:
316 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
327 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
317 else:
328 else:
318 #print "pickle hack in place" # dbg
329 #print "pickle hack in place" # dbg
319 #print 'main_name:',main_name # dbg
330 #print 'main_name:',main_name # dbg
320 sys.modules[main_name] = FakeModule(self.user_ns)
331 sys.modules[main_name] = FakeModule(self.user_ns)
321
332
322 # List of input with multi-line handling.
333 # List of input with multi-line handling.
323 # Fill its zero entry, user counter starts at 1
334 # Fill its zero entry, user counter starts at 1
324 self.input_hist = InputList(['\n'])
335 self.input_hist = InputList(['\n'])
325
336
326 # list of visited directories
337 # list of visited directories
327 try:
338 try:
328 self.dir_hist = [os.getcwd()]
339 self.dir_hist = [os.getcwd()]
329 except IOError, e:
340 except IOError, e:
330 self.dir_hist = []
341 self.dir_hist = []
331
342
332 # dict of output history
343 # dict of output history
333 self.output_hist = {}
344 self.output_hist = {}
334
345
335 # dict of things NOT to alias (keywords, builtins and some magics)
346 # dict of things NOT to alias (keywords, builtins and some magics)
336 no_alias = {}
347 no_alias = {}
337 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
348 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
338 for key in keyword.kwlist + no_alias_magics:
349 for key in keyword.kwlist + no_alias_magics:
339 no_alias[key] = 1
350 no_alias[key] = 1
340 no_alias.update(__builtin__.__dict__)
351 no_alias.update(__builtin__.__dict__)
341 self.no_alias = no_alias
352 self.no_alias = no_alias
342
353
343 # make global variables for user access to these
354 # make global variables for user access to these
344 self.user_ns['_ih'] = self.input_hist
355 self.user_ns['_ih'] = self.input_hist
345 self.user_ns['_oh'] = self.output_hist
356 self.user_ns['_oh'] = self.output_hist
346 self.user_ns['_dh'] = self.dir_hist
357 self.user_ns['_dh'] = self.dir_hist
347
358
348 # user aliases to input and output histories
359 # user aliases to input and output histories
349 self.user_ns['In'] = self.input_hist
360 self.user_ns['In'] = self.input_hist
350 self.user_ns['Out'] = self.output_hist
361 self.user_ns['Out'] = self.output_hist
351
362
352 # Object variable to store code object waiting execution. This is
363 # Object variable to store code object waiting execution. This is
353 # used mainly by the multithreaded shells, but it can come in handy in
364 # 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
365 # other situations. No need to use a Queue here, since it's a single
355 # item which gets cleared once run.
366 # item which gets cleared once run.
356 self.code_to_run = None
367 self.code_to_run = None
357
368
358 # escapes for automatic behavior on the command line
369 # escapes for automatic behavior on the command line
359 self.ESC_SHELL = '!'
370 self.ESC_SHELL = '!'
360 self.ESC_HELP = '?'
371 self.ESC_HELP = '?'
361 self.ESC_MAGIC = '%'
372 self.ESC_MAGIC = '%'
362 self.ESC_QUOTE = ','
373 self.ESC_QUOTE = ','
363 self.ESC_QUOTE2 = ';'
374 self.ESC_QUOTE2 = ';'
364 self.ESC_PAREN = '/'
375 self.ESC_PAREN = '/'
365
376
366 # And their associated handlers
377 # And their associated handlers
367 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
378 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
368 self.ESC_QUOTE : self.handle_auto,
379 self.ESC_QUOTE : self.handle_auto,
369 self.ESC_QUOTE2 : self.handle_auto,
380 self.ESC_QUOTE2 : self.handle_auto,
370 self.ESC_MAGIC : self.handle_magic,
381 self.ESC_MAGIC : self.handle_magic,
371 self.ESC_HELP : self.handle_help,
382 self.ESC_HELP : self.handle_help,
372 self.ESC_SHELL : self.handle_shell_escape,
383 self.ESC_SHELL : self.handle_shell_escape,
373 }
384 }
374
385
375 # class initializations
386 # class initializations
376 Magic.__init__(self,self)
387 Magic.__init__(self,self)
377
388
378 # Python source parser/formatter for syntax highlighting
389 # Python source parser/formatter for syntax highlighting
379 pyformat = PyColorize.Parser().format
390 pyformat = PyColorize.Parser().format
380 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
391 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
381
392
382 # hooks holds pointers used for user-side customizations
393 # hooks holds pointers used for user-side customizations
383 self.hooks = Struct()
394 self.hooks = Struct()
384
395
385 # Set all default hooks, defined in the IPython.hooks module.
396 # Set all default hooks, defined in the IPython.hooks module.
386 hooks = IPython.hooks
397 hooks = IPython.hooks
387 for hook_name in hooks.__all__:
398 for hook_name in hooks.__all__:
388 self.set_hook(hook_name,getattr(hooks,hook_name))
399 self.set_hook(hook_name,getattr(hooks,hook_name))
389
400
390 # Flag to mark unconditional exit
401 # Flag to mark unconditional exit
391 self.exit_now = False
402 self.exit_now = False
392
403
393 self.usage_min = """\
404 self.usage_min = """\
394 An enhanced console for Python.
405 An enhanced console for Python.
395 Some of its features are:
406 Some of its features are:
396 - Readline support if the readline library is present.
407 - Readline support if the readline library is present.
397 - Tab completion in the local namespace.
408 - Tab completion in the local namespace.
398 - Logging of input, see command-line options.
409 - Logging of input, see command-line options.
399 - System shell escape via ! , eg !ls.
410 - System shell escape via ! , eg !ls.
400 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
411 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
401 - Keeps track of locally defined variables via %who, %whos.
412 - Keeps track of locally defined variables via %who, %whos.
402 - Show object information with a ? eg ?x or x? (use ?? for more info).
413 - Show object information with a ? eg ?x or x? (use ?? for more info).
403 """
414 """
404 if usage: self.usage = usage
415 if usage: self.usage = usage
405 else: self.usage = self.usage_min
416 else: self.usage = self.usage_min
406
417
407 # Storage
418 # Storage
408 self.rc = rc # This will hold all configuration information
419 self.rc = rc # This will hold all configuration information
409 self.pager = 'less'
420 self.pager = 'less'
410 # temporary files used for various purposes. Deleted at exit.
421 # temporary files used for various purposes. Deleted at exit.
411 self.tempfiles = []
422 self.tempfiles = []
412
423
413 # Keep track of readline usage (later set by init_readline)
424 # Keep track of readline usage (later set by init_readline)
414 self.has_readline = False
425 self.has_readline = False
415
426
416 # template for logfile headers. It gets resolved at runtime by the
427 # template for logfile headers. It gets resolved at runtime by the
417 # logstart method.
428 # logstart method.
418 self.loghead_tpl = \
429 self.loghead_tpl = \
419 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
430 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
420 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
431 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
421 #log# opts = %s
432 #log# opts = %s
422 #log# args = %s
433 #log# args = %s
423 #log# It is safe to make manual edits below here.
434 #log# It is safe to make manual edits below here.
424 #log#-----------------------------------------------------------------------
435 #log#-----------------------------------------------------------------------
425 """
436 """
426 # for pushd/popd management
437 # for pushd/popd management
427 try:
438 try:
428 self.home_dir = get_home_dir()
439 self.home_dir = get_home_dir()
429 except HomeDirError,msg:
440 except HomeDirError,msg:
430 fatal(msg)
441 fatal(msg)
431
442
432 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
443 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
433
444
434 # Functions to call the underlying shell.
445 # Functions to call the underlying shell.
435
446
436 # utility to expand user variables via Itpl
447 # utility to expand user variables via Itpl
437 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
448 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
438 self.user_ns))
449 self.user_ns))
439 # The first is similar to os.system, but it doesn't return a value,
450 # 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.
451 # and it allows interpolation of variables in the user's namespace.
441 self.system = lambda cmd: shell(self.var_expand(cmd),
452 self.system = lambda cmd: shell(self.var_expand(cmd),
442 header='IPython system call: ',
453 header='IPython system call: ',
443 verbose=self.rc.system_verbose)
454 verbose=self.rc.system_verbose)
444 # These are for getoutput and getoutputerror:
455 # These are for getoutput and getoutputerror:
445 self.getoutput = lambda cmd: \
456 self.getoutput = lambda cmd: \
446 getoutput(self.var_expand(cmd),
457 getoutput(self.var_expand(cmd),
447 header='IPython system call: ',
458 header='IPython system call: ',
448 verbose=self.rc.system_verbose)
459 verbose=self.rc.system_verbose)
449 self.getoutputerror = lambda cmd: \
460 self.getoutputerror = lambda cmd: \
450 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
461 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
451 self.user_ns)),
462 self.user_ns)),
452 header='IPython system call: ',
463 header='IPython system call: ',
453 verbose=self.rc.system_verbose)
464 verbose=self.rc.system_verbose)
454
465
455 # RegExp for splitting line contents into pre-char//first
466 # RegExp for splitting line contents into pre-char//first
456 # word-method//rest. For clarity, each group in on one line.
467 # word-method//rest. For clarity, each group in on one line.
457
468
458 # WARNING: update the regexp if the above escapes are changed, as they
469 # WARNING: update the regexp if the above escapes are changed, as they
459 # are hardwired in.
470 # are hardwired in.
460
471
461 # Don't get carried away with trying to make the autocalling catch too
472 # 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
473 # much: it's better to be conservative rather than to trigger hidden
463 # evals() somewhere and end up causing side effects.
474 # evals() somewhere and end up causing side effects.
464
475
465 self.line_split = re.compile(r'^([\s*,;/])'
476 self.line_split = re.compile(r'^([\s*,;/])'
466 r'([\?\w\.]+\w*\s*)'
477 r'([\?\w\.]+\w*\s*)'
467 r'(\(?.*$)')
478 r'(\(?.*$)')
468
479
469 # Original re, keep around for a while in case changes break something
480 # Original re, keep around for a while in case changes break something
470 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
481 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
471 # r'(\s*[\?\w\.]+\w*\s*)'
482 # r'(\s*[\?\w\.]+\w*\s*)'
472 # r'(\(?.*$)')
483 # r'(\(?.*$)')
473
484
474 # RegExp to identify potential function names
485 # RegExp to identify potential function names
475 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
486 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
476 # RegExp to exclude strings with this start from autocalling
487
477 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
488 # RegExp to exclude strings with this start from autocalling. In
489 # particular, all binary operators should be excluded, so that if foo
490 # is callable, foo OP bar doesn't become foo(OP bar), which is
491 # invalid. The characters '!=()' don't need to be checked for, as the
492 # _prefilter routine explicitely does so, to catch direct calls and
493 # rebindings of existing names.
494
495 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
496 # it affects the rest of the group in square brackets.
497 self.re_exclude_auto = re.compile(r'^[<>,&^\|\*/\+-]'
498 '|^is |^not |^in |^and |^or ')
478
499
479 # try to catch also methods for stuff in lists/tuples/dicts: off
500 # try to catch also methods for stuff in lists/tuples/dicts: off
480 # (experimental). For this to work, the line_split regexp would need
501 # (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
502 # 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_.
503 # 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_.\[\]]*) ?$')
504 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
484
505
485 # keep track of where we started running (mainly for crash post-mortem)
506 # keep track of where we started running (mainly for crash post-mortem)
486 self.starting_dir = os.getcwd()
507 self.starting_dir = os.getcwd()
487
508
488 # Various switches which can be set
509 # Various switches which can be set
489 self.CACHELENGTH = 5000 # this is cheap, it's just text
510 self.CACHELENGTH = 5000 # this is cheap, it's just text
490 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
511 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
491 self.banner2 = banner2
512 self.banner2 = banner2
492
513
493 # TraceBack handlers:
514 # TraceBack handlers:
494
515
495 # Syntax error handler.
516 # Syntax error handler.
496 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
517 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
497
518
498 # The interactive one is initialized with an offset, meaning we always
519 # 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
520 # want to remove the topmost item in the traceback, which is our own
500 # internal code. Valid modes: ['Plain','Context','Verbose']
521 # internal code. Valid modes: ['Plain','Context','Verbose']
501 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
522 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
502 color_scheme='NoColor',
523 color_scheme='NoColor',
503 tb_offset = 1)
524 tb_offset = 1)
504
525
505 # IPython itself shouldn't crash. This will produce a detailed
526 # IPython itself shouldn't crash. This will produce a detailed
506 # post-mortem if it does. But we only install the crash handler for
527 # 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
528 # non-threaded shells, the threaded ones use a normal verbose reporter
508 # and lose the crash handler. This is because exceptions in the main
529 # and lose the crash handler. This is because exceptions in the main
509 # thread (such as in GUI code) propagate directly to sys.excepthook,
530 # 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.
531 # and there's no point in printing crash dumps for every user exception.
511 if self.isthreaded:
532 if self.isthreaded:
512 sys.excepthook = ultraTB.FormattedTB()
533 sys.excepthook = ultraTB.FormattedTB()
513 else:
534 else:
514 from IPython import CrashHandler
535 from IPython import CrashHandler
515 sys.excepthook = CrashHandler.CrashHandler(self)
536 sys.excepthook = CrashHandler.CrashHandler(self)
516
537
517 # The instance will store a pointer to this, so that runtime code
538 # The instance will store a pointer to this, so that runtime code
518 # (such as magics) can access it. This is because during the
539 # (such as magics) can access it. This is because during the
519 # read-eval loop, it gets temporarily overwritten (to deal with GUI
540 # read-eval loop, it gets temporarily overwritten (to deal with GUI
520 # frameworks).
541 # frameworks).
521 self.sys_excepthook = sys.excepthook
542 self.sys_excepthook = sys.excepthook
522
543
523 # and add any custom exception handlers the user may have specified
544 # and add any custom exception handlers the user may have specified
524 self.set_custom_exc(*custom_exceptions)
545 self.set_custom_exc(*custom_exceptions)
525
546
526 # Object inspector
547 # Object inspector
527 self.inspector = OInspect.Inspector(OInspect.InspectColors,
548 self.inspector = OInspect.Inspector(OInspect.InspectColors,
528 PyColorize.ANSICodeColors,
549 PyColorize.ANSICodeColors,
529 'NoColor')
550 'NoColor')
530 # indentation management
551 # indentation management
531 self.autoindent = False
552 self.autoindent = False
532 self.indent_current_nsp = 0
553 self.indent_current_nsp = 0
533 self.indent_current = '' # actual indent string
554 self.indent_current = '' # actual indent string
534
555
535 # Make some aliases automatically
556 # Make some aliases automatically
536 # Prepare list of shell aliases to auto-define
557 # Prepare list of shell aliases to auto-define
537 if os.name == 'posix':
558 if os.name == 'posix':
538 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
559 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
539 'mv mv -i','rm rm -i','cp cp -i',
560 'mv mv -i','rm rm -i','cp cp -i',
540 'cat cat','less less','clear clear',
561 'cat cat','less less','clear clear',
541 # a better ls
562 # a better ls
542 'ls ls -F',
563 'ls ls -F',
543 # long ls
564 # long ls
544 'll ls -lF',
565 'll ls -lF',
545 # color ls
566 # color ls
546 'lc ls -F -o --color',
567 'lc ls -F -o --color',
547 # ls normal files only
568 # ls normal files only
548 'lf ls -F -o --color %l | grep ^-',
569 'lf ls -F -o --color %l | grep ^-',
549 # ls symbolic links
570 # ls symbolic links
550 'lk ls -F -o --color %l | grep ^l',
571 'lk ls -F -o --color %l | grep ^l',
551 # directories or links to directories,
572 # directories or links to directories,
552 'ldir ls -F -o --color %l | grep /$',
573 'ldir ls -F -o --color %l | grep /$',
553 # things which are executable
574 # things which are executable
554 'lx ls -F -o --color %l | grep ^-..x',
575 'lx ls -F -o --color %l | grep ^-..x',
555 )
576 )
556 elif os.name in ['nt','dos']:
577 elif os.name in ['nt','dos']:
557 auto_alias = ('dir dir /on', 'ls dir /on',
578 auto_alias = ('dir dir /on', 'ls dir /on',
558 'ddir dir /ad /on', 'ldir dir /ad /on',
579 'ddir dir /ad /on', 'ldir dir /ad /on',
559 'mkdir mkdir','rmdir rmdir','echo echo',
580 'mkdir mkdir','rmdir rmdir','echo echo',
560 'ren ren','cls cls','copy copy')
581 'ren ren','cls cls','copy copy')
561 else:
582 else:
562 auto_alias = ()
583 auto_alias = ()
563 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
584 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
564 # Call the actual (public) initializer
585 # Call the actual (public) initializer
565 self.init_auto_alias()
586 self.init_auto_alias()
566 # end __init__
587 # end __init__
567
588
568 def post_config_initialization(self):
589 def post_config_initialization(self):
569 """Post configuration init method
590 """Post configuration init method
570
591
571 This is called after the configuration files have been processed to
592 This is called after the configuration files have been processed to
572 'finalize' the initialization."""
593 'finalize' the initialization."""
573
594
574 rc = self.rc
595 rc = self.rc
575
596
576 # Load readline proper
597 # Load readline proper
577 if rc.readline:
598 if rc.readline:
578 self.init_readline()
599 self.init_readline()
579
600
580 # log system
601 # log system
581 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
602 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
582 # local shortcut, this is used a LOT
603 # local shortcut, this is used a LOT
583 self.log = self.logger.log
604 self.log = self.logger.log
584
605
585 # Initialize cache, set in/out prompts and printing system
606 # Initialize cache, set in/out prompts and printing system
586 self.outputcache = CachedOutput(self,
607 self.outputcache = CachedOutput(self,
587 rc.cache_size,
608 rc.cache_size,
588 rc.pprint,
609 rc.pprint,
589 input_sep = rc.separate_in,
610 input_sep = rc.separate_in,
590 output_sep = rc.separate_out,
611 output_sep = rc.separate_out,
591 output_sep2 = rc.separate_out2,
612 output_sep2 = rc.separate_out2,
592 ps1 = rc.prompt_in1,
613 ps1 = rc.prompt_in1,
593 ps2 = rc.prompt_in2,
614 ps2 = rc.prompt_in2,
594 ps_out = rc.prompt_out,
615 ps_out = rc.prompt_out,
595 pad_left = rc.prompts_pad_left)
616 pad_left = rc.prompts_pad_left)
596
617
597 # user may have over-ridden the default print hook:
618 # user may have over-ridden the default print hook:
598 try:
619 try:
599 self.outputcache.__class__.display = self.hooks.display
620 self.outputcache.__class__.display = self.hooks.display
600 except AttributeError:
621 except AttributeError:
601 pass
622 pass
602
623
603 # I don't like assigning globally to sys, because it means when embedding
624 # I don't like assigning globally to sys, because it means when embedding
604 # instances, each embedded instance overrides the previous choice. But
625 # 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
626 # sys.displayhook seems to be called internally by exec, so I don't see a
606 # way around it.
627 # way around it.
607 sys.displayhook = self.outputcache
628 sys.displayhook = self.outputcache
608
629
609 # Set user colors (don't do it in the constructor above so that it
630 # Set user colors (don't do it in the constructor above so that it
610 # doesn't crash if colors option is invalid)
631 # doesn't crash if colors option is invalid)
611 self.magic_colors(rc.colors)
632 self.magic_colors(rc.colors)
612
633
613 # Set calling of pdb on exceptions
634 # Set calling of pdb on exceptions
614 self.call_pdb = rc.pdb
635 self.call_pdb = rc.pdb
615
636
616 # Load user aliases
637 # Load user aliases
617 for alias in rc.alias:
638 for alias in rc.alias:
618 self.magic_alias(alias)
639 self.magic_alias(alias)
619
640
620 # dynamic data that survives through sessions
641 # dynamic data that survives through sessions
621 # XXX make the filename a config option?
642 # XXX make the filename a config option?
622 persist_base = 'persist'
643 persist_base = 'persist'
623 if rc.profile:
644 if rc.profile:
624 persist_base += '_%s' % rc.profile
645 persist_base += '_%s' % rc.profile
625 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
646 self.persist_fname = os.path.join(rc.ipythondir,persist_base)
626
647
627 try:
648 try:
628 self.persist = pickle.load(file(self.persist_fname))
649 self.persist = pickle.load(file(self.persist_fname))
629 except:
650 except:
630 self.persist = {}
651 self.persist = {}
631
652
632
653
633 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
654 for (key, value) in [(k[2:],v) for (k,v) in self.persist.items() if k.startswith('S:')]:
634 try:
655 try:
635 obj = pickle.loads(value)
656 obj = pickle.loads(value)
636 except:
657 except:
637
658
638 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
659 print "Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % key
639 print "The error was:",sys.exc_info()[0]
660 print "The error was:",sys.exc_info()[0]
640 continue
661 continue
641
662
642
663
643 self.user_ns[key] = obj
664 self.user_ns[key] = obj
644
665
645 def add_builtins(self):
666 def add_builtins(self):
646 """Store ipython references into the builtin namespace.
667 """Store ipython references into the builtin namespace.
647
668
648 Some parts of ipython operate via builtins injected here, which hold a
669 Some parts of ipython operate via builtins injected here, which hold a
649 reference to IPython itself."""
670 reference to IPython itself."""
650
671
651 builtins_new = dict(__IPYTHON__ = self,
672 builtins_new = dict(__IPYTHON__ = self,
652 ip_set_hook = self.set_hook,
673 ip_set_hook = self.set_hook,
653 jobs = self.jobs,
674 jobs = self.jobs,
654 ipmagic = self.ipmagic,
675 ipmagic = self.ipmagic,
655 ipalias = self.ipalias,
676 ipalias = self.ipalias,
656 ipsystem = self.ipsystem,
677 ipsystem = self.ipsystem,
657 )
678 )
658 for biname,bival in builtins_new.items():
679 for biname,bival in builtins_new.items():
659 try:
680 try:
660 # store the orignal value so we can restore it
681 # store the orignal value so we can restore it
661 self.builtins_added[biname] = __builtin__.__dict__[biname]
682 self.builtins_added[biname] = __builtin__.__dict__[biname]
662 except KeyError:
683 except KeyError:
663 # or mark that it wasn't defined, and we'll just delete it at
684 # or mark that it wasn't defined, and we'll just delete it at
664 # cleanup
685 # cleanup
665 self.builtins_added[biname] = Undefined
686 self.builtins_added[biname] = Undefined
666 __builtin__.__dict__[biname] = bival
687 __builtin__.__dict__[biname] = bival
667
688
668 # Keep in the builtins a flag for when IPython is active. We set it
689 # 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
690 # with setdefault so that multiple nested IPythons don't clobber one
670 # another. Each will increase its value by one upon being activated,
691 # another. Each will increase its value by one upon being activated,
671 # which also gives us a way to determine the nesting level.
692 # which also gives us a way to determine the nesting level.
672 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
693 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
673
694
674 def clean_builtins(self):
695 def clean_builtins(self):
675 """Remove any builtins which might have been added by add_builtins, or
696 """Remove any builtins which might have been added by add_builtins, or
676 restore overwritten ones to their previous values."""
697 restore overwritten ones to their previous values."""
677 for biname,bival in self.builtins_added.items():
698 for biname,bival in self.builtins_added.items():
678 if bival is Undefined:
699 if bival is Undefined:
679 del __builtin__.__dict__[biname]
700 del __builtin__.__dict__[biname]
680 else:
701 else:
681 __builtin__.__dict__[biname] = bival
702 __builtin__.__dict__[biname] = bival
682 self.builtins_added.clear()
703 self.builtins_added.clear()
683
704
684 def set_hook(self,name,hook):
705 def set_hook(self,name,hook):
685 """set_hook(name,hook) -> sets an internal IPython hook.
706 """set_hook(name,hook) -> sets an internal IPython hook.
686
707
687 IPython exposes some of its internal API as user-modifiable hooks. By
708 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
709 resetting one of these hooks, you can modify IPython's behavior to
689 call at runtime your own routines."""
710 call at runtime your own routines."""
690
711
691 # At some point in the future, this should validate the hook before it
712 # 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
713 # accepts it. Probably at least check that the hook takes the number
693 # of args it's supposed to.
714 # of args it's supposed to.
694 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
715 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
695
716
696 def set_custom_exc(self,exc_tuple,handler):
717 def set_custom_exc(self,exc_tuple,handler):
697 """set_custom_exc(exc_tuple,handler)
718 """set_custom_exc(exc_tuple,handler)
698
719
699 Set a custom exception handler, which will be called if any of the
720 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
721 exceptions in exc_tuple occur in the mainloop (specifically, in the
701 runcode() method.
722 runcode() method.
702
723
703 Inputs:
724 Inputs:
704
725
705 - exc_tuple: a *tuple* of valid exceptions to call the defined
726 - 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
727 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
728 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:
729 you only want to trap a single exception, use a singleton tuple:
709
730
710 exc_tuple == (MyCustomException,)
731 exc_tuple == (MyCustomException,)
711
732
712 - handler: this must be defined as a function with the following
733 - handler: this must be defined as a function with the following
713 basic interface: def my_handler(self,etype,value,tb).
734 basic interface: def my_handler(self,etype,value,tb).
714
735
715 This will be made into an instance method (via new.instancemethod)
736 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
737 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
738 listed in the exc_tuple are caught. If the handler is None, an
718 internal basic one is used, which just prints basic info.
739 internal basic one is used, which just prints basic info.
719
740
720 WARNING: by putting in your own exception handler into IPython's main
741 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
742 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."""
743 facility should only be used if you really know what you are doing."""
723
744
724 assert type(exc_tuple)==type(()) , \
745 assert type(exc_tuple)==type(()) , \
725 "The custom exceptions must be given AS A TUPLE."
746 "The custom exceptions must be given AS A TUPLE."
726
747
727 def dummy_handler(self,etype,value,tb):
748 def dummy_handler(self,etype,value,tb):
728 print '*** Simple custom exception handler ***'
749 print '*** Simple custom exception handler ***'
729 print 'Exception type :',etype
750 print 'Exception type :',etype
730 print 'Exception value:',value
751 print 'Exception value:',value
731 print 'Traceback :',tb
752 print 'Traceback :',tb
732 print 'Source code :','\n'.join(self.buffer)
753 print 'Source code :','\n'.join(self.buffer)
733
754
734 if handler is None: handler = dummy_handler
755 if handler is None: handler = dummy_handler
735
756
736 self.CustomTB = new.instancemethod(handler,self,self.__class__)
757 self.CustomTB = new.instancemethod(handler,self,self.__class__)
737 self.custom_exceptions = exc_tuple
758 self.custom_exceptions = exc_tuple
738
759
739 def set_custom_completer(self,completer,pos=0):
760 def set_custom_completer(self,completer,pos=0):
740 """set_custom_completer(completer,pos=0)
761 """set_custom_completer(completer,pos=0)
741
762
742 Adds a new custom completer function.
763 Adds a new custom completer function.
743
764
744 The position argument (defaults to 0) is the index in the completers
765 The position argument (defaults to 0) is the index in the completers
745 list where you want the completer to be inserted."""
766 list where you want the completer to be inserted."""
746
767
747 newcomp = new.instancemethod(completer,self.Completer,
768 newcomp = new.instancemethod(completer,self.Completer,
748 self.Completer.__class__)
769 self.Completer.__class__)
749 self.Completer.matchers.insert(pos,newcomp)
770 self.Completer.matchers.insert(pos,newcomp)
750
771
751 def _get_call_pdb(self):
772 def _get_call_pdb(self):
752 return self._call_pdb
773 return self._call_pdb
753
774
754 def _set_call_pdb(self,val):
775 def _set_call_pdb(self,val):
755
776
756 if val not in (0,1,False,True):
777 if val not in (0,1,False,True):
757 raise ValueError,'new call_pdb value must be boolean'
778 raise ValueError,'new call_pdb value must be boolean'
758
779
759 # store value in instance
780 # store value in instance
760 self._call_pdb = val
781 self._call_pdb = val
761
782
762 # notify the actual exception handlers
783 # notify the actual exception handlers
763 self.InteractiveTB.call_pdb = val
784 self.InteractiveTB.call_pdb = val
764 if self.isthreaded:
785 if self.isthreaded:
765 try:
786 try:
766 self.sys_excepthook.call_pdb = val
787 self.sys_excepthook.call_pdb = val
767 except:
788 except:
768 warn('Failed to activate pdb for threaded exception handler')
789 warn('Failed to activate pdb for threaded exception handler')
769
790
770 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
791 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
771 'Control auto-activation of pdb at exceptions')
792 'Control auto-activation of pdb at exceptions')
772
793
773
794
774 # These special functions get installed in the builtin namespace, to
795 # These special functions get installed in the builtin namespace, to
775 # provide programmatic (pure python) access to magics, aliases and system
796 # provide programmatic (pure python) access to magics, aliases and system
776 # calls. This is important for logging, user scripting, and more.
797 # calls. This is important for logging, user scripting, and more.
777
798
778 # We are basically exposing, via normal python functions, the three
799 # We are basically exposing, via normal python functions, the three
779 # mechanisms in which ipython offers special call modes (magics for
800 # mechanisms in which ipython offers special call modes (magics for
780 # internal control, aliases for direct system access via pre-selected
801 # internal control, aliases for direct system access via pre-selected
781 # names, and !cmd for calling arbitrary system commands).
802 # names, and !cmd for calling arbitrary system commands).
782
803
783 def ipmagic(self,arg_s):
804 def ipmagic(self,arg_s):
784 """Call a magic function by name.
805 """Call a magic function by name.
785
806
786 Input: a string containing the name of the magic function to call and any
807 Input: a string containing the name of the magic function to call and any
787 additional arguments to be passed to the magic.
808 additional arguments to be passed to the magic.
788
809
789 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
810 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
790 prompt:
811 prompt:
791
812
792 In[1]: %name -opt foo bar
813 In[1]: %name -opt foo bar
793
814
794 To call a magic without arguments, simply use ipmagic('name').
815 To call a magic without arguments, simply use ipmagic('name').
795
816
796 This provides a proper Python function to call IPython's magics in any
817 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
818 valid Python code you can type at the interpreter, including loops and
798 compound statements. It is added by IPython to the Python builtin
819 compound statements. It is added by IPython to the Python builtin
799 namespace upon initialization."""
820 namespace upon initialization."""
800
821
801 args = arg_s.split(' ',1)
822 args = arg_s.split(' ',1)
802 magic_name = args[0]
823 magic_name = args[0]
803 if magic_name.startswith(self.ESC_MAGIC):
824 if magic_name.startswith(self.ESC_MAGIC):
804 magic_name = magic_name[1:]
825 magic_name = magic_name[1:]
805 try:
826 try:
806 magic_args = args[1]
827 magic_args = args[1]
807 except IndexError:
828 except IndexError:
808 magic_args = ''
829 magic_args = ''
809 fn = getattr(self,'magic_'+magic_name,None)
830 fn = getattr(self,'magic_'+magic_name,None)
810 if fn is None:
831 if fn is None:
811 error("Magic function `%s` not found." % magic_name)
832 error("Magic function `%s` not found." % magic_name)
812 else:
833 else:
813 magic_args = self.var_expand(magic_args)
834 magic_args = self.var_expand(magic_args)
814 return fn(magic_args)
835 return fn(magic_args)
815
836
816 def ipalias(self,arg_s):
837 def ipalias(self,arg_s):
817 """Call an alias by name.
838 """Call an alias by name.
818
839
819 Input: a string containing the name of the alias to call and any
840 Input: a string containing the name of the alias to call and any
820 additional arguments to be passed to the magic.
841 additional arguments to be passed to the magic.
821
842
822 ipalias('name -opt foo bar') is equivalent to typing at the ipython
843 ipalias('name -opt foo bar') is equivalent to typing at the ipython
823 prompt:
844 prompt:
824
845
825 In[1]: name -opt foo bar
846 In[1]: name -opt foo bar
826
847
827 To call an alias without arguments, simply use ipalias('name').
848 To call an alias without arguments, simply use ipalias('name').
828
849
829 This provides a proper Python function to call IPython's aliases in any
850 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
851 valid Python code you can type at the interpreter, including loops and
831 compound statements. It is added by IPython to the Python builtin
852 compound statements. It is added by IPython to the Python builtin
832 namespace upon initialization."""
853 namespace upon initialization."""
833
854
834 args = arg_s.split(' ',1)
855 args = arg_s.split(' ',1)
835 alias_name = args[0]
856 alias_name = args[0]
836 try:
857 try:
837 alias_args = args[1]
858 alias_args = args[1]
838 except IndexError:
859 except IndexError:
839 alias_args = ''
860 alias_args = ''
840 if alias_name in self.alias_table:
861 if alias_name in self.alias_table:
841 self.call_alias(alias_name,alias_args)
862 self.call_alias(alias_name,alias_args)
842 else:
863 else:
843 error("Alias `%s` not found." % alias_name)
864 error("Alias `%s` not found." % alias_name)
844
865
845 def ipsystem(self,arg_s):
866 def ipsystem(self,arg_s):
846 """Make a system call, using IPython."""
867 """Make a system call, using IPython."""
847
868
848 self.system(arg_s)
869 self.system(arg_s)
849
870
850 def complete(self,text):
871 def complete(self,text):
851 """Return a sorted list of all possible completions on text.
872 """Return a sorted list of all possible completions on text.
852
873
853 Inputs:
874 Inputs:
854
875
855 - text: a string of text to be completed on.
876 - text: a string of text to be completed on.
856
877
857 This is a wrapper around the completion mechanism, similar to what
878 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
879 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
880 exposing it as a method, it can be used by other non-readline
860 environments (such as GUIs) for text completion.
881 environments (such as GUIs) for text completion.
861
882
862 Simple usage example:
883 Simple usage example:
863
884
864 In [1]: x = 'hello'
885 In [1]: x = 'hello'
865
886
866 In [2]: __IP.complete('x.l')
887 In [2]: __IP.complete('x.l')
867 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
888 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
868
889
869 complete = self.Completer.complete
890 complete = self.Completer.complete
870 state = 0
891 state = 0
871 # use a dict so we get unique keys, since ipyhton's multiple
892 # use a dict so we get unique keys, since ipyhton's multiple
872 # completers can return duplicates.
893 # completers can return duplicates.
873 comps = {}
894 comps = {}
874 while True:
895 while True:
875 newcomp = complete(text,state)
896 newcomp = complete(text,state)
876 if newcomp is None:
897 if newcomp is None:
877 break
898 break
878 comps[newcomp] = 1
899 comps[newcomp] = 1
879 state += 1
900 state += 1
880 outcomps = comps.keys()
901 outcomps = comps.keys()
881 outcomps.sort()
902 outcomps.sort()
882 return outcomps
903 return outcomps
883
904
884 def set_completer_frame(self, frame=None):
905 def set_completer_frame(self, frame=None):
885 if frame:
906 if frame:
886 self.Completer.namespace = frame.f_locals
907 self.Completer.namespace = frame.f_locals
887 self.Completer.global_namespace = frame.f_globals
908 self.Completer.global_namespace = frame.f_globals
888 else:
909 else:
889 self.Completer.namespace = self.user_ns
910 self.Completer.namespace = self.user_ns
890 self.Completer.global_namespace = self.user_global_ns
911 self.Completer.global_namespace = self.user_global_ns
891
912
892 def init_auto_alias(self):
913 def init_auto_alias(self):
893 """Define some aliases automatically.
914 """Define some aliases automatically.
894
915
895 These are ALL parameter-less aliases"""
916 These are ALL parameter-less aliases"""
896
917
897 for alias,cmd in self.auto_alias:
918 for alias,cmd in self.auto_alias:
898 self.alias_table[alias] = (0,cmd)
919 self.alias_table[alias] = (0,cmd)
899
920
900 def alias_table_validate(self,verbose=0):
921 def alias_table_validate(self,verbose=0):
901 """Update information about the alias table.
922 """Update information about the alias table.
902
923
903 In particular, make sure no Python keywords/builtins are in it."""
924 In particular, make sure no Python keywords/builtins are in it."""
904
925
905 no_alias = self.no_alias
926 no_alias = self.no_alias
906 for k in self.alias_table.keys():
927 for k in self.alias_table.keys():
907 if k in no_alias:
928 if k in no_alias:
908 del self.alias_table[k]
929 del self.alias_table[k]
909 if verbose:
930 if verbose:
910 print ("Deleting alias <%s>, it's a Python "
931 print ("Deleting alias <%s>, it's a Python "
911 "keyword or builtin." % k)
932 "keyword or builtin." % k)
912
933
913 def set_autoindent(self,value=None):
934 def set_autoindent(self,value=None):
914 """Set the autoindent flag, checking for readline support.
935 """Set the autoindent flag, checking for readline support.
915
936
916 If called with no arguments, it acts as a toggle."""
937 If called with no arguments, it acts as a toggle."""
917
938
918 if not self.has_readline:
939 if not self.has_readline:
919 if os.name == 'posix':
940 if os.name == 'posix':
920 warn("The auto-indent feature requires the readline library")
941 warn("The auto-indent feature requires the readline library")
921 self.autoindent = 0
942 self.autoindent = 0
922 return
943 return
923 if value is None:
944 if value is None:
924 self.autoindent = not self.autoindent
945 self.autoindent = not self.autoindent
925 else:
946 else:
926 self.autoindent = value
947 self.autoindent = value
927
948
928 def rc_set_toggle(self,rc_field,value=None):
949 def rc_set_toggle(self,rc_field,value=None):
929 """Set or toggle a field in IPython's rc config. structure.
950 """Set or toggle a field in IPython's rc config. structure.
930
951
931 If called with no arguments, it acts as a toggle.
952 If called with no arguments, it acts as a toggle.
932
953
933 If called with a non-existent field, the resulting AttributeError
954 If called with a non-existent field, the resulting AttributeError
934 exception will propagate out."""
955 exception will propagate out."""
935
956
936 rc_val = getattr(self.rc,rc_field)
957 rc_val = getattr(self.rc,rc_field)
937 if value is None:
958 if value is None:
938 value = not rc_val
959 value = not rc_val
939 setattr(self.rc,rc_field,value)
960 setattr(self.rc,rc_field,value)
940
961
941 def user_setup(self,ipythondir,rc_suffix,mode='install'):
962 def user_setup(self,ipythondir,rc_suffix,mode='install'):
942 """Install the user configuration directory.
963 """Install the user configuration directory.
943
964
944 Can be called when running for the first time or to upgrade the user's
965 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'
966 .ipython/ directory with the mode parameter. Valid modes are 'install'
946 and 'upgrade'."""
967 and 'upgrade'."""
947
968
948 def wait():
969 def wait():
949 try:
970 try:
950 raw_input("Please press <RETURN> to start IPython.")
971 raw_input("Please press <RETURN> to start IPython.")
951 except EOFError:
972 except EOFError:
952 print >> Term.cout
973 print >> Term.cout
953 print '*'*70
974 print '*'*70
954
975
955 cwd = os.getcwd() # remember where we started
976 cwd = os.getcwd() # remember where we started
956 glb = glob.glob
977 glb = glob.glob
957 print '*'*70
978 print '*'*70
958 if mode == 'install':
979 if mode == 'install':
959 print \
980 print \
960 """Welcome to IPython. I will try to create a personal configuration directory
981 """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"""
982 where you can customize many aspects of IPython's functionality in:\n"""
962 else:
983 else:
963 print 'I am going to upgrade your configuration in:'
984 print 'I am going to upgrade your configuration in:'
964
985
965 print ipythondir
986 print ipythondir
966
987
967 rcdirend = os.path.join('IPython','UserConfig')
988 rcdirend = os.path.join('IPython','UserConfig')
968 cfg = lambda d: os.path.join(d,rcdirend)
989 cfg = lambda d: os.path.join(d,rcdirend)
969 try:
990 try:
970 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
991 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
971 except IOError:
992 except IOError:
972 warning = """
993 warning = """
973 Installation error. IPython's directory was not found.
994 Installation error. IPython's directory was not found.
974
995
975 Check the following:
996 Check the following:
976
997
977 The ipython/IPython directory should be in a directory belonging to your
998 The ipython/IPython directory should be in a directory belonging to your
978 PYTHONPATH environment variable (that is, it should be in a directory
999 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.
1000 belonging to sys.path). You can copy it explicitly there or just link to it.
980
1001
981 IPython will proceed with builtin defaults.
1002 IPython will proceed with builtin defaults.
982 """
1003 """
983 warn(warning)
1004 warn(warning)
984 wait()
1005 wait()
985 return
1006 return
986
1007
987 if mode == 'install':
1008 if mode == 'install':
988 try:
1009 try:
989 shutil.copytree(rcdir,ipythondir)
1010 shutil.copytree(rcdir,ipythondir)
990 os.chdir(ipythondir)
1011 os.chdir(ipythondir)
991 rc_files = glb("ipythonrc*")
1012 rc_files = glb("ipythonrc*")
992 for rc_file in rc_files:
1013 for rc_file in rc_files:
993 os.rename(rc_file,rc_file+rc_suffix)
1014 os.rename(rc_file,rc_file+rc_suffix)
994 except:
1015 except:
995 warning = """
1016 warning = """
996
1017
997 There was a problem with the installation:
1018 There was a problem with the installation:
998 %s
1019 %s
999 Try to correct it or contact the developers if you think it's a bug.
1020 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]
1021 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1001 warn(warning)
1022 warn(warning)
1002 wait()
1023 wait()
1003 return
1024 return
1004
1025
1005 elif mode == 'upgrade':
1026 elif mode == 'upgrade':
1006 try:
1027 try:
1007 os.chdir(ipythondir)
1028 os.chdir(ipythondir)
1008 except:
1029 except:
1009 print """
1030 print """
1010 Can not upgrade: changing to directory %s failed. Details:
1031 Can not upgrade: changing to directory %s failed. Details:
1011 %s
1032 %s
1012 """ % (ipythondir,sys.exc_info()[1])
1033 """ % (ipythondir,sys.exc_info()[1])
1013 wait()
1034 wait()
1014 return
1035 return
1015 else:
1036 else:
1016 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1037 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1017 for new_full_path in sources:
1038 for new_full_path in sources:
1018 new_filename = os.path.basename(new_full_path)
1039 new_filename = os.path.basename(new_full_path)
1019 if new_filename.startswith('ipythonrc'):
1040 if new_filename.startswith('ipythonrc'):
1020 new_filename = new_filename + rc_suffix
1041 new_filename = new_filename + rc_suffix
1021 # The config directory should only contain files, skip any
1042 # The config directory should only contain files, skip any
1022 # directories which may be there (like CVS)
1043 # directories which may be there (like CVS)
1023 if os.path.isdir(new_full_path):
1044 if os.path.isdir(new_full_path):
1024 continue
1045 continue
1025 if os.path.exists(new_filename):
1046 if os.path.exists(new_filename):
1026 old_file = new_filename+'.old'
1047 old_file = new_filename+'.old'
1027 if os.path.exists(old_file):
1048 if os.path.exists(old_file):
1028 os.remove(old_file)
1049 os.remove(old_file)
1029 os.rename(new_filename,old_file)
1050 os.rename(new_filename,old_file)
1030 shutil.copy(new_full_path,new_filename)
1051 shutil.copy(new_full_path,new_filename)
1031 else:
1052 else:
1032 raise ValueError,'unrecognized mode for install:',`mode`
1053 raise ValueError,'unrecognized mode for install:',`mode`
1033
1054
1034 # Fix line-endings to those native to each platform in the config
1055 # Fix line-endings to those native to each platform in the config
1035 # directory.
1056 # directory.
1036 try:
1057 try:
1037 os.chdir(ipythondir)
1058 os.chdir(ipythondir)
1038 except:
1059 except:
1039 print """
1060 print """
1040 Problem: changing to directory %s failed.
1061 Problem: changing to directory %s failed.
1041 Details:
1062 Details:
1042 %s
1063 %s
1043
1064
1044 Some configuration files may have incorrect line endings. This should not
1065 Some configuration files may have incorrect line endings. This should not
1045 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1066 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1046 wait()
1067 wait()
1047 else:
1068 else:
1048 for fname in glb('ipythonrc*'):
1069 for fname in glb('ipythonrc*'):
1049 try:
1070 try:
1050 native_line_ends(fname,backup=0)
1071 native_line_ends(fname,backup=0)
1051 except IOError:
1072 except IOError:
1052 pass
1073 pass
1053
1074
1054 if mode == 'install':
1075 if mode == 'install':
1055 print """
1076 print """
1056 Successful installation!
1077 Successful installation!
1057
1078
1058 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1079 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1059 IPython manual (there are both HTML and PDF versions supplied with the
1080 IPython manual (there are both HTML and PDF versions supplied with the
1060 distribution) to make sure that your system environment is properly configured
1081 distribution) to make sure that your system environment is properly configured
1061 to take advantage of IPython's features."""
1082 to take advantage of IPython's features."""
1062 else:
1083 else:
1063 print """
1084 print """
1064 Successful upgrade!
1085 Successful upgrade!
1065
1086
1066 All files in your directory:
1087 All files in your directory:
1067 %(ipythondir)s
1088 %(ipythondir)s
1068 which would have been overwritten by the upgrade were backed up with a .old
1089 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
1090 extension. If you had made particular customizations in those files you may
1070 want to merge them back into the new files.""" % locals()
1091 want to merge them back into the new files.""" % locals()
1071 wait()
1092 wait()
1072 os.chdir(cwd)
1093 os.chdir(cwd)
1073 # end user_setup()
1094 # end user_setup()
1074
1095
1075 def atexit_operations(self):
1096 def atexit_operations(self):
1076 """This will be executed at the time of exit.
1097 """This will be executed at the time of exit.
1077
1098
1078 Saving of persistent data should be performed here. """
1099 Saving of persistent data should be performed here. """
1079
1100
1101 #print '*** IPython exit cleanup ***' # dbg
1080 # input history
1102 # input history
1081 self.savehist()
1103 self.savehist()
1082
1104
1083 # Cleanup all tempfiles left around
1105 # Cleanup all tempfiles left around
1084 for tfile in self.tempfiles:
1106 for tfile in self.tempfiles:
1085 try:
1107 try:
1086 os.unlink(tfile)
1108 os.unlink(tfile)
1087 except OSError:
1109 except OSError:
1088 pass
1110 pass
1089
1111
1090 # save the "persistent data" catch-all dictionary
1112 # save the "persistent data" catch-all dictionary
1091 try:
1113 try:
1092 pickle.dump(self.persist, open(self.persist_fname,"w"))
1114 pickle.dump(self.persist, open(self.persist_fname,"w"))
1093 except:
1115 except:
1094 print "*** ERROR *** persistent data saving failed."
1116 print "*** ERROR *** persistent data saving failed."
1095
1117
1096 def savehist(self):
1118 def savehist(self):
1097 """Save input history to a file (via readline library)."""
1119 """Save input history to a file (via readline library)."""
1098 try:
1120 try:
1099 self.readline.write_history_file(self.histfile)
1121 self.readline.write_history_file(self.histfile)
1100 except:
1122 except:
1101 print 'Unable to save IPython command history to file: ' + \
1123 print 'Unable to save IPython command history to file: ' + \
1102 `self.histfile`
1124 `self.histfile`
1103
1125
1104 def pre_readline(self):
1126 def pre_readline(self):
1105 """readline hook to be used at the start of each line.
1127 """readline hook to be used at the start of each line.
1106
1128
1107 Currently it handles auto-indent only."""
1129 Currently it handles auto-indent only."""
1108
1130
1109 self.readline.insert_text(self.indent_current)
1131 self.readline.insert_text(self.indent_current)
1110
1132
1111 def init_readline(self):
1133 def init_readline(self):
1112 """Command history completion/saving/reloading."""
1134 """Command history completion/saving/reloading."""
1113 try:
1135 try:
1114 import readline
1136 import readline
1115 except ImportError:
1137 except ImportError:
1116 self.has_readline = 0
1138 self.has_readline = 0
1117 self.readline = None
1139 self.readline = None
1118 # no point in bugging windows users with this every time:
1140 # no point in bugging windows users with this every time:
1119 if os.name == 'posix':
1141 if os.name == 'posix':
1120 warn('Readline services not available on this platform.')
1142 warn('Readline services not available on this platform.')
1121 else:
1143 else:
1122 import atexit
1144 import atexit
1123 from IPython.completer import IPCompleter
1145 from IPython.completer import IPCompleter
1124 self.Completer = IPCompleter(self,
1146 self.Completer = IPCompleter(self,
1125 self.user_ns,
1147 self.user_ns,
1126 self.user_global_ns,
1148 self.user_global_ns,
1127 self.rc.readline_omit__names,
1149 self.rc.readline_omit__names,
1128 self.alias_table)
1150 self.alias_table)
1129
1151
1130 # Platform-specific configuration
1152 # Platform-specific configuration
1131 if os.name == 'nt':
1153 if os.name == 'nt':
1132 self.readline_startup_hook = readline.set_pre_input_hook
1154 self.readline_startup_hook = readline.set_pre_input_hook
1133 else:
1155 else:
1134 self.readline_startup_hook = readline.set_startup_hook
1156 self.readline_startup_hook = readline.set_startup_hook
1135
1157
1136 # Load user's initrc file (readline config)
1158 # Load user's initrc file (readline config)
1137 inputrc_name = os.environ.get('INPUTRC')
1159 inputrc_name = os.environ.get('INPUTRC')
1138 if inputrc_name is None:
1160 if inputrc_name is None:
1139 home_dir = get_home_dir()
1161 home_dir = get_home_dir()
1140 if home_dir is not None:
1162 if home_dir is not None:
1141 inputrc_name = os.path.join(home_dir,'.inputrc')
1163 inputrc_name = os.path.join(home_dir,'.inputrc')
1142 if os.path.isfile(inputrc_name):
1164 if os.path.isfile(inputrc_name):
1143 try:
1165 try:
1144 readline.read_init_file(inputrc_name)
1166 readline.read_init_file(inputrc_name)
1145 except:
1167 except:
1146 warn('Problems reading readline initialization file <%s>'
1168 warn('Problems reading readline initialization file <%s>'
1147 % inputrc_name)
1169 % inputrc_name)
1148
1170
1149 self.has_readline = 1
1171 self.has_readline = 1
1150 self.readline = readline
1172 self.readline = readline
1151 # save this in sys so embedded copies can restore it properly
1173 # save this in sys so embedded copies can restore it properly
1152 sys.ipcompleter = self.Completer.complete
1174 sys.ipcompleter = self.Completer.complete
1153 readline.set_completer(self.Completer.complete)
1175 readline.set_completer(self.Completer.complete)
1154
1176
1155 # Configure readline according to user's prefs
1177 # Configure readline according to user's prefs
1156 for rlcommand in self.rc.readline_parse_and_bind:
1178 for rlcommand in self.rc.readline_parse_and_bind:
1157 readline.parse_and_bind(rlcommand)
1179 readline.parse_and_bind(rlcommand)
1158
1180
1159 # remove some chars from the delimiters list
1181 # remove some chars from the delimiters list
1160 delims = readline.get_completer_delims()
1182 delims = readline.get_completer_delims()
1161 delims = delims.translate(string._idmap,
1183 delims = delims.translate(string._idmap,
1162 self.rc.readline_remove_delims)
1184 self.rc.readline_remove_delims)
1163 readline.set_completer_delims(delims)
1185 readline.set_completer_delims(delims)
1164 # otherwise we end up with a monster history after a while:
1186 # otherwise we end up with a monster history after a while:
1165 readline.set_history_length(1000)
1187 readline.set_history_length(1000)
1166 try:
1188 try:
1167 #print '*** Reading readline history' # dbg
1189 #print '*** Reading readline history' # dbg
1168 readline.read_history_file(self.histfile)
1190 readline.read_history_file(self.histfile)
1169 except IOError:
1191 except IOError:
1170 pass # It doesn't exist yet.
1192 pass # It doesn't exist yet.
1171
1193
1172 atexit.register(self.atexit_operations)
1194 atexit.register(self.atexit_operations)
1173 del atexit
1195 del atexit
1174
1196
1175 # Configure auto-indent for all platforms
1197 # Configure auto-indent for all platforms
1176 self.set_autoindent(self.rc.autoindent)
1198 self.set_autoindent(self.rc.autoindent)
1177
1199
1178 def _should_recompile(self,e):
1200 def _should_recompile(self,e):
1179 """Utility routine for edit_syntax_error"""
1201 """Utility routine for edit_syntax_error"""
1180
1202
1181 if e.filename in ('<ipython console>','<input>','<string>',
1203 if e.filename in ('<ipython console>','<input>','<string>',
1182 '<console>',None):
1204 '<console>',None):
1183
1205
1184 return False
1206 return False
1185 try:
1207 try:
1186 if not ask_yes_no('Return to editor to correct syntax error? '
1208 if not ask_yes_no('Return to editor to correct syntax error? '
1187 '[Y/n] ','y'):
1209 '[Y/n] ','y'):
1188 return False
1210 return False
1189 except EOFError:
1211 except EOFError:
1190 return False
1212 return False
1191
1213
1192 def int0(x):
1214 def int0(x):
1193 try:
1215 try:
1194 return int(x)
1216 return int(x)
1195 except TypeError:
1217 except TypeError:
1196 return 0
1218 return 0
1197 # always pass integer line and offset values to editor hook
1219 # always pass integer line and offset values to editor hook
1198 self.hooks.fix_error_editor(e.filename,
1220 self.hooks.fix_error_editor(e.filename,
1199 int0(e.lineno),int0(e.offset),e.msg)
1221 int0(e.lineno),int0(e.offset),e.msg)
1200 return True
1222 return True
1201
1223
1202 def edit_syntax_error(self):
1224 def edit_syntax_error(self):
1203 """The bottom half of the syntax error handler called in the main loop.
1225 """The bottom half of the syntax error handler called in the main loop.
1204
1226
1205 Loop until syntax error is fixed or user cancels.
1227 Loop until syntax error is fixed or user cancels.
1206 """
1228 """
1207
1229
1208 while self.SyntaxTB.last_syntax_error:
1230 while self.SyntaxTB.last_syntax_error:
1209 # copy and clear last_syntax_error
1231 # copy and clear last_syntax_error
1210 err = self.SyntaxTB.clear_err_state()
1232 err = self.SyntaxTB.clear_err_state()
1211 if not self._should_recompile(err):
1233 if not self._should_recompile(err):
1212 return
1234 return
1213 try:
1235 try:
1214 # may set last_syntax_error again if a SyntaxError is raised
1236 # may set last_syntax_error again if a SyntaxError is raised
1215 self.safe_execfile(err.filename,self.shell.user_ns)
1237 self.safe_execfile(err.filename,self.shell.user_ns)
1216 except:
1238 except:
1217 self.showtraceback()
1239 self.showtraceback()
1218 else:
1240 else:
1219 f = file(err.filename)
1241 f = file(err.filename)
1220 try:
1242 try:
1221 sys.displayhook(f.read())
1243 sys.displayhook(f.read())
1222 finally:
1244 finally:
1223 f.close()
1245 f.close()
1224
1246
1225 def showsyntaxerror(self, filename=None):
1247 def showsyntaxerror(self, filename=None):
1226 """Display the syntax error that just occurred.
1248 """Display the syntax error that just occurred.
1227
1249
1228 This doesn't display a stack trace because there isn't one.
1250 This doesn't display a stack trace because there isn't one.
1229
1251
1230 If a filename is given, it is stuffed in the exception instead
1252 If a filename is given, it is stuffed in the exception instead
1231 of what was there before (because Python's parser always uses
1253 of what was there before (because Python's parser always uses
1232 "<string>" when reading from a string).
1254 "<string>" when reading from a string).
1233 """
1255 """
1234 etype, value, last_traceback = sys.exc_info()
1256 etype, value, last_traceback = sys.exc_info()
1235 if filename and etype is SyntaxError:
1257 if filename and etype is SyntaxError:
1236 # Work hard to stuff the correct filename in the exception
1258 # Work hard to stuff the correct filename in the exception
1237 try:
1259 try:
1238 msg, (dummy_filename, lineno, offset, line) = value
1260 msg, (dummy_filename, lineno, offset, line) = value
1239 except:
1261 except:
1240 # Not the format we expect; leave it alone
1262 # Not the format we expect; leave it alone
1241 pass
1263 pass
1242 else:
1264 else:
1243 # Stuff in the right filename
1265 # Stuff in the right filename
1244 try:
1266 try:
1245 # Assume SyntaxError is a class exception
1267 # Assume SyntaxError is a class exception
1246 value = SyntaxError(msg, (filename, lineno, offset, line))
1268 value = SyntaxError(msg, (filename, lineno, offset, line))
1247 except:
1269 except:
1248 # If that failed, assume SyntaxError is a string
1270 # If that failed, assume SyntaxError is a string
1249 value = msg, (filename, lineno, offset, line)
1271 value = msg, (filename, lineno, offset, line)
1250 self.SyntaxTB(etype,value,[])
1272 self.SyntaxTB(etype,value,[])
1251
1273
1252 def debugger(self):
1274 def debugger(self):
1253 """Call the pdb debugger."""
1275 """Call the pdb debugger."""
1254
1276
1255 if not self.rc.pdb:
1277 if not self.rc.pdb:
1256 return
1278 return
1257 pdb.pm()
1279 pdb.pm()
1258
1280
1259 def showtraceback(self,exc_tuple = None,filename=None):
1281 def showtraceback(self,exc_tuple = None,filename=None):
1260 """Display the exception that just occurred."""
1282 """Display the exception that just occurred."""
1261
1283
1262 # Though this won't be called by syntax errors in the input line,
1284 # Though this won't be called by syntax errors in the input line,
1263 # there may be SyntaxError cases whith imported code.
1285 # there may be SyntaxError cases whith imported code.
1264 if exc_tuple is None:
1286 if exc_tuple is None:
1265 type, value, tb = sys.exc_info()
1287 type, value, tb = sys.exc_info()
1266 else:
1288 else:
1267 type, value, tb = exc_tuple
1289 type, value, tb = exc_tuple
1268 if type is SyntaxError:
1290 if type is SyntaxError:
1269 self.showsyntaxerror(filename)
1291 self.showsyntaxerror(filename)
1270 else:
1292 else:
1271 self.InteractiveTB()
1293 self.InteractiveTB()
1272 if self.InteractiveTB.call_pdb and self.has_readline:
1294 if self.InteractiveTB.call_pdb and self.has_readline:
1273 # pdb mucks up readline, fix it back
1295 # pdb mucks up readline, fix it back
1274 self.readline.set_completer(self.Completer.complete)
1296 self.readline.set_completer(self.Completer.complete)
1275
1297
1276 def mainloop(self,banner=None):
1298 def mainloop(self,banner=None):
1277 """Creates the local namespace and starts the mainloop.
1299 """Creates the local namespace and starts the mainloop.
1278
1300
1279 If an optional banner argument is given, it will override the
1301 If an optional banner argument is given, it will override the
1280 internally created default banner."""
1302 internally created default banner."""
1281
1303
1282 if self.rc.c: # Emulate Python's -c option
1304 if self.rc.c: # Emulate Python's -c option
1283 self.exec_init_cmd()
1305 self.exec_init_cmd()
1284 if banner is None:
1306 if banner is None:
1285 if self.rc.banner:
1307 if self.rc.banner:
1286 banner = self.BANNER+self.banner2
1308 banner = self.BANNER+self.banner2
1287 else:
1309 else:
1288 banner = ''
1310 banner = ''
1289 self.interact(banner)
1311 self.interact(banner)
1290
1312
1291 def exec_init_cmd(self):
1313 def exec_init_cmd(self):
1292 """Execute a command given at the command line.
1314 """Execute a command given at the command line.
1293
1315
1294 This emulates Python's -c option."""
1316 This emulates Python's -c option."""
1295
1317
1296 sys.argv = ['-c']
1318 sys.argv = ['-c']
1297 self.push(self.rc.c)
1319 self.push(self.rc.c)
1298
1320
1299 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1321 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1300 """Embeds IPython into a running python program.
1322 """Embeds IPython into a running python program.
1301
1323
1302 Input:
1324 Input:
1303
1325
1304 - header: An optional header message can be specified.
1326 - header: An optional header message can be specified.
1305
1327
1306 - local_ns, global_ns: working namespaces. If given as None, the
1328 - local_ns, global_ns: working namespaces. If given as None, the
1307 IPython-initialized one is updated with __main__.__dict__, so that
1329 IPython-initialized one is updated with __main__.__dict__, so that
1308 program variables become visible but user-specific configuration
1330 program variables become visible but user-specific configuration
1309 remains possible.
1331 remains possible.
1310
1332
1311 - stack_depth: specifies how many levels in the stack to go to
1333 - stack_depth: specifies how many levels in the stack to go to
1312 looking for namespaces (when local_ns and global_ns are None). This
1334 looking for namespaces (when local_ns and global_ns are None). This
1313 allows an intermediate caller to make sure that this function gets
1335 allows an intermediate caller to make sure that this function gets
1314 the namespace from the intended level in the stack. By default (0)
1336 the namespace from the intended level in the stack. By default (0)
1315 it will get its locals and globals from the immediate caller.
1337 it will get its locals and globals from the immediate caller.
1316
1338
1317 Warning: it's possible to use this in a program which is being run by
1339 Warning: it's possible to use this in a program which is being run by
1318 IPython itself (via %run), but some funny things will happen (a few
1340 IPython itself (via %run), but some funny things will happen (a few
1319 globals get overwritten). In the future this will be cleaned up, as
1341 globals get overwritten). In the future this will be cleaned up, as
1320 there is no fundamental reason why it can't work perfectly."""
1342 there is no fundamental reason why it can't work perfectly."""
1321
1343
1322 # Get locals and globals from caller
1344 # Get locals and globals from caller
1323 if local_ns is None or global_ns is None:
1345 if local_ns is None or global_ns is None:
1324 call_frame = sys._getframe(stack_depth).f_back
1346 call_frame = sys._getframe(stack_depth).f_back
1325
1347
1326 if local_ns is None:
1348 if local_ns is None:
1327 local_ns = call_frame.f_locals
1349 local_ns = call_frame.f_locals
1328 if global_ns is None:
1350 if global_ns is None:
1329 global_ns = call_frame.f_globals
1351 global_ns = call_frame.f_globals
1330
1352
1331 # Update namespaces and fire up interpreter
1353 # Update namespaces and fire up interpreter
1332
1354
1333 # The global one is easy, we can just throw it in
1355 # The global one is easy, we can just throw it in
1334 self.user_global_ns = global_ns
1356 self.user_global_ns = global_ns
1335
1357
1336 # but the user/local one is tricky: ipython needs it to store internal
1358 # but the user/local one is tricky: ipython needs it to store internal
1337 # data, but we also need the locals. We'll copy locals in the user
1359 # data, but we also need the locals. We'll copy locals in the user
1338 # one, but will track what got copied so we can delete them at exit.
1360 # one, but will track what got copied so we can delete them at exit.
1339 # This is so that a later embedded call doesn't see locals from a
1361 # This is so that a later embedded call doesn't see locals from a
1340 # previous call (which most likely existed in a separate scope).
1362 # previous call (which most likely existed in a separate scope).
1341 local_varnames = local_ns.keys()
1363 local_varnames = local_ns.keys()
1342 self.user_ns.update(local_ns)
1364 self.user_ns.update(local_ns)
1343
1365
1344 # Patch for global embedding to make sure that things don't overwrite
1366 # Patch for global embedding to make sure that things don't overwrite
1345 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1367 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1346 # FIXME. Test this a bit more carefully (the if.. is new)
1368 # FIXME. Test this a bit more carefully (the if.. is new)
1347 if local_ns is None and global_ns is None:
1369 if local_ns is None and global_ns is None:
1348 self.user_global_ns.update(__main__.__dict__)
1370 self.user_global_ns.update(__main__.__dict__)
1349
1371
1350 # make sure the tab-completer has the correct frame information, so it
1372 # make sure the tab-completer has the correct frame information, so it
1351 # actually completes using the frame's locals/globals
1373 # actually completes using the frame's locals/globals
1352 self.set_completer_frame()
1374 self.set_completer_frame()
1353
1375
1354 # before activating the interactive mode, we need to make sure that
1376 # before activating the interactive mode, we need to make sure that
1355 # all names in the builtin namespace needed by ipython point to
1377 # all names in the builtin namespace needed by ipython point to
1356 # ourselves, and not to other instances.
1378 # ourselves, and not to other instances.
1357 self.add_builtins()
1379 self.add_builtins()
1358
1380
1359 self.interact(header)
1381 self.interact(header)
1360
1382
1361 # now, purge out the user namespace from anything we might have added
1383 # now, purge out the user namespace from anything we might have added
1362 # from the caller's local namespace
1384 # from the caller's local namespace
1363 delvar = self.user_ns.pop
1385 delvar = self.user_ns.pop
1364 for var in local_varnames:
1386 for var in local_varnames:
1365 delvar(var,None)
1387 delvar(var,None)
1366 # and clean builtins we may have overridden
1388 # and clean builtins we may have overridden
1367 self.clean_builtins()
1389 self.clean_builtins()
1368
1390
1369 def interact(self, banner=None):
1391 def interact(self, banner=None):
1370 """Closely emulate the interactive Python console.
1392 """Closely emulate the interactive Python console.
1371
1393
1372 The optional banner argument specify the banner to print
1394 The optional banner argument specify the banner to print
1373 before the first interaction; by default it prints a banner
1395 before the first interaction; by default it prints a banner
1374 similar to the one printed by the real Python interpreter,
1396 similar to the one printed by the real Python interpreter,
1375 followed by the current class name in parentheses (so as not
1397 followed by the current class name in parentheses (so as not
1376 to confuse this with the real interpreter -- since it's so
1398 to confuse this with the real interpreter -- since it's so
1377 close!).
1399 close!).
1378
1400
1379 """
1401 """
1380 cprt = 'Type "copyright", "credits" or "license" for more information.'
1402 cprt = 'Type "copyright", "credits" or "license" for more information.'
1381 if banner is None:
1403 if banner is None:
1382 self.write("Python %s on %s\n%s\n(%s)\n" %
1404 self.write("Python %s on %s\n%s\n(%s)\n" %
1383 (sys.version, sys.platform, cprt,
1405 (sys.version, sys.platform, cprt,
1384 self.__class__.__name__))
1406 self.__class__.__name__))
1385 else:
1407 else:
1386 self.write(banner)
1408 self.write(banner)
1387
1409
1388 more = 0
1410 more = 0
1389
1411
1390 # Mark activity in the builtins
1412 # Mark activity in the builtins
1391 __builtin__.__dict__['__IPYTHON__active'] += 1
1413 __builtin__.__dict__['__IPYTHON__active'] += 1
1392
1414
1393 # exit_now is set by a call to %Exit or %Quit
1415 # exit_now is set by a call to %Exit or %Quit
1394 self.exit_now = False
1416 self.exit_now = False
1395 while not self.exit_now:
1417 while not self.exit_now:
1396
1418
1397 try:
1419 try:
1398 if more:
1420 if more:
1399 prompt = self.outputcache.prompt2
1421 prompt = self.outputcache.prompt2
1400 if self.autoindent:
1422 if self.autoindent:
1401 self.readline_startup_hook(self.pre_readline)
1423 self.readline_startup_hook(self.pre_readline)
1402 else:
1424 else:
1403 prompt = self.outputcache.prompt1
1425 prompt = self.outputcache.prompt1
1404 try:
1426 try:
1405 line = self.raw_input(prompt,more)
1427 line = self.raw_input(prompt,more)
1406 if self.autoindent:
1428 if self.autoindent:
1407 self.readline_startup_hook(None)
1429 self.readline_startup_hook(None)
1408 except EOFError:
1430 except EOFError:
1409 if self.autoindent:
1431 if self.autoindent:
1410 self.readline_startup_hook(None)
1432 self.readline_startup_hook(None)
1411 self.write("\n")
1433 self.write("\n")
1412 self.exit()
1434 self.exit()
1413 else:
1435 else:
1414 more = self.push(line)
1436 more = self.push(line)
1415
1437
1416 if (self.SyntaxTB.last_syntax_error and
1438 if (self.SyntaxTB.last_syntax_error and
1417 self.rc.autoedit_syntax):
1439 self.rc.autoedit_syntax):
1418 self.edit_syntax_error()
1440 self.edit_syntax_error()
1419
1441
1420 except KeyboardInterrupt:
1442 except KeyboardInterrupt:
1421 self.write("\nKeyboardInterrupt\n")
1443 self.write("\nKeyboardInterrupt\n")
1422 self.resetbuffer()
1444 self.resetbuffer()
1423 more = 0
1445 more = 0
1424 # keep cache in sync with the prompt counter:
1446 # keep cache in sync with the prompt counter:
1425 self.outputcache.prompt_count -= 1
1447 self.outputcache.prompt_count -= 1
1426
1448
1427 if self.autoindent:
1449 if self.autoindent:
1428 self.indent_current_nsp = 0
1450 self.indent_current_nsp = 0
1429 self.indent_current = ' '* self.indent_current_nsp
1451 self.indent_current = ' '* self.indent_current_nsp
1430
1452
1431 except bdb.BdbQuit:
1453 except bdb.BdbQuit:
1432 warn("The Python debugger has exited with a BdbQuit exception.\n"
1454 warn("The Python debugger has exited with a BdbQuit exception.\n"
1433 "Because of how pdb handles the stack, it is impossible\n"
1455 "Because of how pdb handles the stack, it is impossible\n"
1434 "for IPython to properly format this particular exception.\n"
1456 "for IPython to properly format this particular exception.\n"
1435 "IPython will resume normal operation.")
1457 "IPython will resume normal operation.")
1436
1458
1437 # We are off again...
1459 # We are off again...
1438 __builtin__.__dict__['__IPYTHON__active'] -= 1
1460 __builtin__.__dict__['__IPYTHON__active'] -= 1
1439
1461
1440 def excepthook(self, type, value, tb):
1462 def excepthook(self, type, value, tb):
1441 """One more defense for GUI apps that call sys.excepthook.
1463 """One more defense for GUI apps that call sys.excepthook.
1442
1464
1443 GUI frameworks like wxPython trap exceptions and call
1465 GUI frameworks like wxPython trap exceptions and call
1444 sys.excepthook themselves. I guess this is a feature that
1466 sys.excepthook themselves. I guess this is a feature that
1445 enables them to keep running after exceptions that would
1467 enables them to keep running after exceptions that would
1446 otherwise kill their mainloop. This is a bother for IPython
1468 otherwise kill their mainloop. This is a bother for IPython
1447 which excepts to catch all of the program exceptions with a try:
1469 which excepts to catch all of the program exceptions with a try:
1448 except: statement.
1470 except: statement.
1449
1471
1450 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1472 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1451 any app directly invokes sys.excepthook, it will look to the user like
1473 any app directly invokes sys.excepthook, it will look to the user like
1452 IPython crashed. In order to work around this, we can disable the
1474 IPython crashed. In order to work around this, we can disable the
1453 CrashHandler and replace it with this excepthook instead, which prints a
1475 CrashHandler and replace it with this excepthook instead, which prints a
1454 regular traceback using our InteractiveTB. In this fashion, apps which
1476 regular traceback using our InteractiveTB. In this fashion, apps which
1455 call sys.excepthook will generate a regular-looking exception from
1477 call sys.excepthook will generate a regular-looking exception from
1456 IPython, and the CrashHandler will only be triggered by real IPython
1478 IPython, and the CrashHandler will only be triggered by real IPython
1457 crashes.
1479 crashes.
1458
1480
1459 This hook should be used sparingly, only in places which are not likely
1481 This hook should be used sparingly, only in places which are not likely
1460 to be true IPython errors.
1482 to be true IPython errors.
1461 """
1483 """
1462
1484
1463 self.InteractiveTB(type, value, tb, tb_offset=0)
1485 self.InteractiveTB(type, value, tb, tb_offset=0)
1464 if self.InteractiveTB.call_pdb and self.has_readline:
1486 if self.InteractiveTB.call_pdb and self.has_readline:
1465 self.readline.set_completer(self.Completer.complete)
1487 self.readline.set_completer(self.Completer.complete)
1466
1488
1467 def call_alias(self,alias,rest=''):
1489 def call_alias(self,alias,rest=''):
1468 """Call an alias given its name and the rest of the line.
1490 """Call an alias given its name and the rest of the line.
1469
1491
1470 This function MUST be given a proper alias, because it doesn't make
1492 This function MUST be given a proper alias, because it doesn't make
1471 any checks when looking up into the alias table. The caller is
1493 any checks when looking up into the alias table. The caller is
1472 responsible for invoking it only with a valid alias."""
1494 responsible for invoking it only with a valid alias."""
1473
1495
1474 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1496 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1475 nargs,cmd = self.alias_table[alias]
1497 nargs,cmd = self.alias_table[alias]
1476 # Expand the %l special to be the user's input line
1498 # Expand the %l special to be the user's input line
1477 if cmd.find('%l') >= 0:
1499 if cmd.find('%l') >= 0:
1478 cmd = cmd.replace('%l',rest)
1500 cmd = cmd.replace('%l',rest)
1479 rest = ''
1501 rest = ''
1480 if nargs==0:
1502 if nargs==0:
1481 # Simple, argument-less aliases
1503 # Simple, argument-less aliases
1482 cmd = '%s %s' % (cmd,rest)
1504 cmd = '%s %s' % (cmd,rest)
1483 else:
1505 else:
1484 # Handle aliases with positional arguments
1506 # Handle aliases with positional arguments
1485 args = rest.split(None,nargs)
1507 args = rest.split(None,nargs)
1486 if len(args)< nargs:
1508 if len(args)< nargs:
1487 error('Alias <%s> requires %s arguments, %s given.' %
1509 error('Alias <%s> requires %s arguments, %s given.' %
1488 (alias,nargs,len(args)))
1510 (alias,nargs,len(args)))
1489 return
1511 return
1490 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1512 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1491 # Now call the macro, evaluating in the user's namespace
1513 # Now call the macro, evaluating in the user's namespace
1492 try:
1514 try:
1493 self.system(cmd)
1515 self.system(cmd)
1494 except:
1516 except:
1495 self.showtraceback()
1517 self.showtraceback()
1496
1518
1497 def autoindent_update(self,line):
1519 def autoindent_update(self,line):
1498 """Keep track of the indent level."""
1520 """Keep track of the indent level."""
1521
1499 if self.autoindent:
1522 if self.autoindent:
1500 if line:
1523 if line:
1501 ini_spaces = ini_spaces_re.match(line)
1524 self.indent_current_nsp = num_ini_spaces(line)
1502 if ini_spaces:
1503 nspaces = ini_spaces.end()
1504 else:
1505 nspaces = 0
1506 self.indent_current_nsp = nspaces
1507
1525
1508 if line[-1] == ':':
1526 if line[-1] == ':':
1509 self.indent_current_nsp += 4
1527 self.indent_current_nsp += 4
1510 elif dedent_re.match(line):
1528 elif dedent_re.match(line):
1511 self.indent_current_nsp -= 4
1529 self.indent_current_nsp -= 4
1512 else:
1530 else:
1513 self.indent_current_nsp = 0
1531 self.indent_current_nsp = 0
1514
1532
1515 # indent_current is the actual string to be inserted
1533 # indent_current is the actual string to be inserted
1516 # by the readline hooks for indentation
1534 # by the readline hooks for indentation
1517 self.indent_current = ' '* self.indent_current_nsp
1535 self.indent_current = ' '* self.indent_current_nsp
1518
1536
1519 def runlines(self,lines):
1537 def runlines(self,lines):
1520 """Run a string of one or more lines of source.
1538 """Run a string of one or more lines of source.
1521
1539
1522 This method is capable of running a string containing multiple source
1540 This method is capable of running a string containing multiple source
1523 lines, as if they had been entered at the IPython prompt. Since it
1541 lines, as if they had been entered at the IPython prompt. Since it
1524 exposes IPython's processing machinery, the given strings can contain
1542 exposes IPython's processing machinery, the given strings can contain
1525 magic calls (%magic), special shell access (!cmd), etc."""
1543 magic calls (%magic), special shell access (!cmd), etc."""
1526
1544
1527 # We must start with a clean buffer, in case this is run from an
1545 # We must start with a clean buffer, in case this is run from an
1528 # interactive IPython session (via a magic, for example).
1546 # interactive IPython session (via a magic, for example).
1529 self.resetbuffer()
1547 self.resetbuffer()
1530 lines = lines.split('\n')
1548 lines = lines.split('\n')
1531 more = 0
1549 more = 0
1532 for line in lines:
1550 for line in lines:
1533 # skip blank lines so we don't mess up the prompt counter, but do
1551 # skip blank lines so we don't mess up the prompt counter, but do
1534 # NOT skip even a blank line if we are in a code block (more is
1552 # NOT skip even a blank line if we are in a code block (more is
1535 # true)
1553 # true)
1536 if line or more:
1554 if line or more:
1537 more = self.push(self.prefilter(line,more))
1555 more = self.push(self.prefilter(line,more))
1538 # IPython's runsource returns None if there was an error
1556 # IPython's runsource returns None if there was an error
1539 # compiling the code. This allows us to stop processing right
1557 # compiling the code. This allows us to stop processing right
1540 # away, so the user gets the error message at the right place.
1558 # away, so the user gets the error message at the right place.
1541 if more is None:
1559 if more is None:
1542 break
1560 break
1543 # final newline in case the input didn't have it, so that the code
1561 # final newline in case the input didn't have it, so that the code
1544 # actually does get executed
1562 # actually does get executed
1545 if more:
1563 if more:
1546 self.push('\n')
1564 self.push('\n')
1547
1565
1548 def runsource(self, source, filename='<input>', symbol='single'):
1566 def runsource(self, source, filename='<input>', symbol='single'):
1549 """Compile and run some source in the interpreter.
1567 """Compile and run some source in the interpreter.
1550
1568
1551 Arguments are as for compile_command().
1569 Arguments are as for compile_command().
1552
1570
1553 One several things can happen:
1571 One several things can happen:
1554
1572
1555 1) The input is incorrect; compile_command() raised an
1573 1) The input is incorrect; compile_command() raised an
1556 exception (SyntaxError or OverflowError). A syntax traceback
1574 exception (SyntaxError or OverflowError). A syntax traceback
1557 will be printed by calling the showsyntaxerror() method.
1575 will be printed by calling the showsyntaxerror() method.
1558
1576
1559 2) The input is incomplete, and more input is required;
1577 2) The input is incomplete, and more input is required;
1560 compile_command() returned None. Nothing happens.
1578 compile_command() returned None. Nothing happens.
1561
1579
1562 3) The input is complete; compile_command() returned a code
1580 3) The input is complete; compile_command() returned a code
1563 object. The code is executed by calling self.runcode() (which
1581 object. The code is executed by calling self.runcode() (which
1564 also handles run-time exceptions, except for SystemExit).
1582 also handles run-time exceptions, except for SystemExit).
1565
1583
1566 The return value is:
1584 The return value is:
1567
1585
1568 - True in case 2
1586 - True in case 2
1569
1587
1570 - False in the other cases, unless an exception is raised, where
1588 - False in the other cases, unless an exception is raised, where
1571 None is returned instead. This can be used by external callers to
1589 None is returned instead. This can be used by external callers to
1572 know whether to continue feeding input or not.
1590 know whether to continue feeding input or not.
1573
1591
1574 The return value can be used to decide whether to use sys.ps1 or
1592 The return value can be used to decide whether to use sys.ps1 or
1575 sys.ps2 to prompt the next line."""
1593 sys.ps2 to prompt the next line."""
1576
1594
1577 try:
1595 try:
1578 code = self.compile(source,filename,symbol)
1596 code = self.compile(source,filename,symbol)
1579 except (OverflowError, SyntaxError, ValueError):
1597 except (OverflowError, SyntaxError, ValueError):
1580 # Case 1
1598 # Case 1
1581 self.showsyntaxerror(filename)
1599 self.showsyntaxerror(filename)
1582 return None
1600 return None
1583
1601
1584 if code is None:
1602 if code is None:
1585 # Case 2
1603 # Case 2
1586 return True
1604 return True
1587
1605
1588 # Case 3
1606 # Case 3
1589 # We store the code object so that threaded shells and
1607 # We store the code object so that threaded shells and
1590 # custom exception handlers can access all this info if needed.
1608 # custom exception handlers can access all this info if needed.
1591 # The source corresponding to this can be obtained from the
1609 # The source corresponding to this can be obtained from the
1592 # buffer attribute as '\n'.join(self.buffer).
1610 # buffer attribute as '\n'.join(self.buffer).
1593 self.code_to_run = code
1611 self.code_to_run = code
1594 # now actually execute the code object
1612 # now actually execute the code object
1595 if self.runcode(code) == 0:
1613 if self.runcode(code) == 0:
1596 return False
1614 return False
1597 else:
1615 else:
1598 return None
1616 return None
1599
1617
1600 def runcode(self,code_obj):
1618 def runcode(self,code_obj):
1601 """Execute a code object.
1619 """Execute a code object.
1602
1620
1603 When an exception occurs, self.showtraceback() is called to display a
1621 When an exception occurs, self.showtraceback() is called to display a
1604 traceback.
1622 traceback.
1605
1623
1606 Return value: a flag indicating whether the code to be run completed
1624 Return value: a flag indicating whether the code to be run completed
1607 successfully:
1625 successfully:
1608
1626
1609 - 0: successful execution.
1627 - 0: successful execution.
1610 - 1: an error occurred.
1628 - 1: an error occurred.
1611 """
1629 """
1612
1630
1613 # Set our own excepthook in case the user code tries to call it
1631 # Set our own excepthook in case the user code tries to call it
1614 # directly, so that the IPython crash handler doesn't get triggered
1632 # directly, so that the IPython crash handler doesn't get triggered
1615 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1633 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1616
1634
1617 # we save the original sys.excepthook in the instance, in case config
1635 # we save the original sys.excepthook in the instance, in case config
1618 # code (such as magics) needs access to it.
1636 # code (such as magics) needs access to it.
1619 self.sys_excepthook = old_excepthook
1637 self.sys_excepthook = old_excepthook
1620 outflag = 1 # happens in more places, so it's easier as default
1638 outflag = 1 # happens in more places, so it's easier as default
1621 try:
1639 try:
1622 try:
1640 try:
1623 # Embedded instances require separate global/local namespaces
1641 # Embedded instances require separate global/local namespaces
1624 # so they can see both the surrounding (local) namespace and
1642 # so they can see both the surrounding (local) namespace and
1625 # the module-level globals when called inside another function.
1643 # the module-level globals when called inside another function.
1626 if self.embedded:
1644 if self.embedded:
1627 exec code_obj in self.user_global_ns, self.user_ns
1645 exec code_obj in self.user_global_ns, self.user_ns
1628 # Normal (non-embedded) instances should only have a single
1646 # Normal (non-embedded) instances should only have a single
1629 # namespace for user code execution, otherwise functions won't
1647 # namespace for user code execution, otherwise functions won't
1630 # see interactive top-level globals.
1648 # see interactive top-level globals.
1631 else:
1649 else:
1632 exec code_obj in self.user_ns
1650 exec code_obj in self.user_ns
1633 finally:
1651 finally:
1634 # Reset our crash handler in place
1652 # Reset our crash handler in place
1635 sys.excepthook = old_excepthook
1653 sys.excepthook = old_excepthook
1636 except SystemExit:
1654 except SystemExit:
1637 self.resetbuffer()
1655 self.resetbuffer()
1638 self.showtraceback()
1656 self.showtraceback()
1639 warn("Type exit or quit to exit IPython "
1657 warn("Type exit or quit to exit IPython "
1640 "(%Exit or %Quit do so unconditionally).",level=1)
1658 "(%Exit or %Quit do so unconditionally).",level=1)
1641 except self.custom_exceptions:
1659 except self.custom_exceptions:
1642 etype,value,tb = sys.exc_info()
1660 etype,value,tb = sys.exc_info()
1643 self.CustomTB(etype,value,tb)
1661 self.CustomTB(etype,value,tb)
1644 except:
1662 except:
1645 self.showtraceback()
1663 self.showtraceback()
1646 else:
1664 else:
1647 outflag = 0
1665 outflag = 0
1648 if softspace(sys.stdout, 0):
1666 if softspace(sys.stdout, 0):
1649 print
1667 print
1650 # Flush out code object which has been run (and source)
1668 # Flush out code object which has been run (and source)
1651 self.code_to_run = None
1669 self.code_to_run = None
1652 return outflag
1670 return outflag
1653
1671
1654 def push(self, line):
1672 def push(self, line):
1655 """Push a line to the interpreter.
1673 """Push a line to the interpreter.
1656
1674
1657 The line should not have a trailing newline; it may have
1675 The line should not have a trailing newline; it may have
1658 internal newlines. The line is appended to a buffer and the
1676 internal newlines. The line is appended to a buffer and the
1659 interpreter's runsource() method is called with the
1677 interpreter's runsource() method is called with the
1660 concatenated contents of the buffer as source. If this
1678 concatenated contents of the buffer as source. If this
1661 indicates that the command was executed or invalid, the buffer
1679 indicates that the command was executed or invalid, the buffer
1662 is reset; otherwise, the command is incomplete, and the buffer
1680 is reset; otherwise, the command is incomplete, and the buffer
1663 is left as it was after the line was appended. The return
1681 is left as it was after the line was appended. The return
1664 value is 1 if more input is required, 0 if the line was dealt
1682 value is 1 if more input is required, 0 if the line was dealt
1665 with in some way (this is the same as runsource()).
1683 with in some way (this is the same as runsource()).
1666 """
1684 """
1667
1685
1668 # autoindent management should be done here, and not in the
1686 # autoindent management should be done here, and not in the
1669 # interactive loop, since that one is only seen by keyboard input. We
1687 # interactive loop, since that one is only seen by keyboard input. We
1670 # need this done correctly even for code run via runlines (which uses
1688 # need this done correctly even for code run via runlines (which uses
1671 # push).
1689 # push).
1672
1690
1673 #print 'push line: <%s>' % line # dbg
1691 #print 'push line: <%s>' % line # dbg
1674 self.autoindent_update(line)
1692 self.autoindent_update(line)
1675
1693
1676 self.buffer.append(line)
1694 self.buffer.append(line)
1677 more = self.runsource('\n'.join(self.buffer), self.filename)
1695 more = self.runsource('\n'.join(self.buffer), self.filename)
1678 if not more:
1696 if not more:
1679 self.resetbuffer()
1697 self.resetbuffer()
1680 return more
1698 return more
1681
1699
1682 def resetbuffer(self):
1700 def resetbuffer(self):
1683 """Reset the input buffer."""
1701 """Reset the input buffer."""
1684 self.buffer[:] = []
1702 self.buffer[:] = []
1685
1703
1686 def raw_input(self,prompt='',continue_prompt=False):
1704 def raw_input(self,prompt='',continue_prompt=False):
1687 """Write a prompt and read a line.
1705 """Write a prompt and read a line.
1688
1706
1689 The returned line does not include the trailing newline.
1707 The returned line does not include the trailing newline.
1690 When the user enters the EOF key sequence, EOFError is raised.
1708 When the user enters the EOF key sequence, EOFError is raised.
1691
1709
1692 Optional inputs:
1710 Optional inputs:
1693
1711
1694 - prompt(''): a string to be printed to prompt the user.
1712 - prompt(''): a string to be printed to prompt the user.
1695
1713
1696 - continue_prompt(False): whether this line is the first one or a
1714 - continue_prompt(False): whether this line is the first one or a
1697 continuation in a sequence of inputs.
1715 continuation in a sequence of inputs.
1698 """
1716 """
1699
1717
1700 line = raw_input_original(prompt)
1718 line = raw_input_original(prompt)
1701 # Try to be reasonably smart about not re-indenting pasted input more
1719 # Try to be reasonably smart about not re-indenting pasted input more
1702 # than necessary. We do this by trimming out the auto-indent initial
1720 # than necessary. We do this by trimming out the auto-indent initial
1703 # spaces, if the user's actual input started itself with whitespace.
1721 # spaces, if the user's actual input started itself with whitespace.
1704 if self.autoindent:
1722 #debugp('self.buffer[-1]')
1705 line2 = line[self.indent_current_nsp:]
1723 ## if self.autoindent:
1706 if line2[0:1] in (' ','\t'):
1724 ## try:
1707 line = line2
1725 ## prev_line = self.buffer[-1]
1726 ## except IndexError:
1727 ## prev_line = ''
1728 ## prev_indent = num_ini_spaces(prev_line)
1729 ## debugp('prev_indent')
1730 ## # Split the user's input
1731 ## line1 = line[:self.indent_current_nsp]
1732 ## line2 = line[self.indent_current_nsp:]
1733 ## if line1.isspace() and line2 and \
1734 ## num_ini_spaces(line2)==prev_indent:
1735 ## line = line2
1736 #debugp('line')
1737 #debugp('line1')
1738 #debugp('line2')
1739 ## if line1.isspace() and line2 and line2[0:1] in (' ','\t'):
1740 ## line = line2
1741 ## debugp('line')
1708 return self.prefilter(line,continue_prompt)
1742 return self.prefilter(line,continue_prompt)
1709
1743
1710 def split_user_input(self,line):
1744 def split_user_input(self,line):
1711 """Split user input into pre-char, function part and rest."""
1745 """Split user input into pre-char, function part and rest."""
1712
1746
1713 lsplit = self.line_split.match(line)
1747 lsplit = self.line_split.match(line)
1714 if lsplit is None: # no regexp match returns None
1748 if lsplit is None: # no regexp match returns None
1715 try:
1749 try:
1716 iFun,theRest = line.split(None,1)
1750 iFun,theRest = line.split(None,1)
1717 except ValueError:
1751 except ValueError:
1718 iFun,theRest = line,''
1752 iFun,theRest = line,''
1719 pre = re.match('^(\s*)(.*)',line).groups()[0]
1753 pre = re.match('^(\s*)(.*)',line).groups()[0]
1720 else:
1754 else:
1721 pre,iFun,theRest = lsplit.groups()
1755 pre,iFun,theRest = lsplit.groups()
1722
1756
1723 #print 'line:<%s>' % line # dbg
1757 #print 'line:<%s>' % line # dbg
1724 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1758 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1725 return pre,iFun.strip(),theRest
1759 return pre,iFun.strip(),theRest
1726
1760
1727 def _prefilter(self, line, continue_prompt):
1761 def _prefilter(self, line, continue_prompt):
1728 """Calls different preprocessors, depending on the form of line."""
1762 """Calls different preprocessors, depending on the form of line."""
1729
1763
1730 # All handlers *must* return a value, even if it's blank ('').
1764 # All handlers *must* return a value, even if it's blank ('').
1731
1765
1732 # Lines are NOT logged here. Handlers should process the line as
1766 # Lines are NOT logged here. Handlers should process the line as
1733 # needed, update the cache AND log it (so that the input cache array
1767 # needed, update the cache AND log it (so that the input cache array
1734 # stays synced).
1768 # stays synced).
1735
1769
1736 # This function is _very_ delicate, and since it's also the one which
1770 # This function is _very_ delicate, and since it's also the one which
1737 # determines IPython's response to user input, it must be as efficient
1771 # determines IPython's response to user input, it must be as efficient
1738 # as possible. For this reason it has _many_ returns in it, trying
1772 # as possible. For this reason it has _many_ returns in it, trying
1739 # always to exit as quickly as it can figure out what it needs to do.
1773 # always to exit as quickly as it can figure out what it needs to do.
1740
1774
1741 # This function is the main responsible for maintaining IPython's
1775 # This function is the main responsible for maintaining IPython's
1742 # behavior respectful of Python's semantics. So be _very_ careful if
1776 # behavior respectful of Python's semantics. So be _very_ careful if
1743 # making changes to anything here.
1777 # making changes to anything here.
1744
1778
1745 #.....................................................................
1779 #.....................................................................
1746 # Code begins
1780 # Code begins
1747
1781
1748 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1782 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1749
1783
1750 # save the line away in case we crash, so the post-mortem handler can
1784 # save the line away in case we crash, so the post-mortem handler can
1751 # record it
1785 # record it
1752 self._last_input_line = line
1786 self._last_input_line = line
1753
1787
1754 #print '***line: <%s>' % line # dbg
1788 #print '***line: <%s>' % line # dbg
1755
1789
1756 # the input history needs to track even empty lines
1790 # the input history needs to track even empty lines
1757 if not line.strip():
1791 if not line.strip():
1758 if not continue_prompt:
1792 if not continue_prompt:
1759 self.outputcache.prompt_count -= 1
1793 self.outputcache.prompt_count -= 1
1760 return self.handle_normal(line,continue_prompt)
1794 return self.handle_normal(line,continue_prompt)
1761 #return self.handle_normal('',continue_prompt)
1795 #return self.handle_normal('',continue_prompt)
1762
1796
1763 # print '***cont',continue_prompt # dbg
1797 # print '***cont',continue_prompt # dbg
1764 # special handlers are only allowed for single line statements
1798 # special handlers are only allowed for single line statements
1765 if continue_prompt and not self.rc.multi_line_specials:
1799 if continue_prompt and not self.rc.multi_line_specials:
1766 return self.handle_normal(line,continue_prompt)
1800 return self.handle_normal(line,continue_prompt)
1767
1801
1768 # For the rest, we need the structure of the input
1802 # For the rest, we need the structure of the input
1769 pre,iFun,theRest = self.split_user_input(line)
1803 pre,iFun,theRest = self.split_user_input(line)
1770 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1804 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1771
1805
1772 # First check for explicit escapes in the last/first character
1806 # First check for explicit escapes in the last/first character
1773 handler = None
1807 handler = None
1774 if line[-1] == self.ESC_HELP:
1808 if line[-1] == self.ESC_HELP:
1775 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1809 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1776 if handler is None:
1810 if handler is None:
1777 # look at the first character of iFun, NOT of line, so we skip
1811 # look at the first character of iFun, NOT of line, so we skip
1778 # leading whitespace in multiline input
1812 # leading whitespace in multiline input
1779 handler = self.esc_handlers.get(iFun[0:1])
1813 handler = self.esc_handlers.get(iFun[0:1])
1780 if handler is not None:
1814 if handler is not None:
1781 return handler(line,continue_prompt,pre,iFun,theRest)
1815 return handler(line,continue_prompt,pre,iFun,theRest)
1782 # Emacs ipython-mode tags certain input lines
1816 # Emacs ipython-mode tags certain input lines
1783 if line.endswith('# PYTHON-MODE'):
1817 if line.endswith('# PYTHON-MODE'):
1784 return self.handle_emacs(line,continue_prompt)
1818 return self.handle_emacs(line,continue_prompt)
1785
1819
1786 # Next, check if we can automatically execute this thing
1820 # Next, check if we can automatically execute this thing
1787
1821
1788 # Allow ! in multi-line statements if multi_line_specials is on:
1822 # Allow ! in multi-line statements if multi_line_specials is on:
1789 if continue_prompt and self.rc.multi_line_specials and \
1823 if continue_prompt and self.rc.multi_line_specials and \
1790 iFun.startswith(self.ESC_SHELL):
1824 iFun.startswith(self.ESC_SHELL):
1791 return self.handle_shell_escape(line,continue_prompt,
1825 return self.handle_shell_escape(line,continue_prompt,
1792 pre=pre,iFun=iFun,
1826 pre=pre,iFun=iFun,
1793 theRest=theRest)
1827 theRest=theRest)
1794
1828
1795 # Let's try to find if the input line is a magic fn
1829 # Let's try to find if the input line is a magic fn
1796 oinfo = None
1830 oinfo = None
1797 if hasattr(self,'magic_'+iFun):
1831 if hasattr(self,'magic_'+iFun):
1798 # WARNING: _ofind uses getattr(), so it can consume generators and
1832 # WARNING: _ofind uses getattr(), so it can consume generators and
1799 # cause other side effects.
1833 # cause other side effects.
1800 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1834 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1801 if oinfo['ismagic']:
1835 if oinfo['ismagic']:
1802 # Be careful not to call magics when a variable assignment is
1836 # Be careful not to call magics when a variable assignment is
1803 # being made (ls='hi', for example)
1837 # being made (ls='hi', for example)
1804 if self.rc.automagic and \
1838 if self.rc.automagic and \
1805 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1839 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1806 (self.rc.multi_line_specials or not continue_prompt):
1840 (self.rc.multi_line_specials or not continue_prompt):
1807 return self.handle_magic(line,continue_prompt,
1841 return self.handle_magic(line,continue_prompt,
1808 pre,iFun,theRest)
1842 pre,iFun,theRest)
1809 else:
1843 else:
1810 return self.handle_normal(line,continue_prompt)
1844 return self.handle_normal(line,continue_prompt)
1811
1845
1812 # If the rest of the line begins with an (in)equality, assginment or
1846 # If the rest of the line begins with an (in)equality, assginment or
1813 # function call, we should not call _ofind but simply execute it.
1847 # function call, we should not call _ofind but simply execute it.
1814 # This avoids spurious geattr() accesses on objects upon assignment.
1848 # This avoids spurious geattr() accesses on objects upon assignment.
1815 #
1849 #
1816 # It also allows users to assign to either alias or magic names true
1850 # It also allows users to assign to either alias or magic names true
1817 # python variables (the magic/alias systems always take second seat to
1851 # python variables (the magic/alias systems always take second seat to
1818 # true python code).
1852 # true python code).
1819 if theRest and theRest[0] in '!=()':
1853 if theRest and theRest[0] in '!=()':
1820 return self.handle_normal(line,continue_prompt)
1854 return self.handle_normal(line,continue_prompt)
1821
1855
1822 if oinfo is None:
1856 if oinfo is None:
1823 # let's try to ensure that _oinfo is ONLY called when autocall is
1857 # let's try to ensure that _oinfo is ONLY called when autocall is
1824 # on. Since it has inevitable potential side effects, at least
1858 # on. Since it has inevitable potential side effects, at least
1825 # having autocall off should be a guarantee to the user that no
1859 # having autocall off should be a guarantee to the user that no
1826 # weird things will happen.
1860 # weird things will happen.
1827
1861
1828 if self.rc.autocall:
1862 if self.rc.autocall:
1829 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1863 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1830 else:
1864 else:
1831 # in this case, all that's left is either an alias or
1865 # in this case, all that's left is either an alias or
1832 # processing the line normally.
1866 # processing the line normally.
1833 if iFun in self.alias_table:
1867 if iFun in self.alias_table:
1834 return self.handle_alias(line,continue_prompt,
1868 return self.handle_alias(line,continue_prompt,
1835 pre,iFun,theRest)
1869 pre,iFun,theRest)
1836 else:
1870 else:
1837 return self.handle_normal(line,continue_prompt)
1871 return self.handle_normal(line,continue_prompt)
1838
1872
1839 if not oinfo['found']:
1873 if not oinfo['found']:
1840 return self.handle_normal(line,continue_prompt)
1874 return self.handle_normal(line,continue_prompt)
1841 else:
1875 else:
1842 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1876 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1843 if oinfo['isalias']:
1877 if oinfo['isalias']:
1844 return self.handle_alias(line,continue_prompt,
1878 return self.handle_alias(line,continue_prompt,
1845 pre,iFun,theRest)
1879 pre,iFun,theRest)
1846
1880
1847 if self.rc.autocall and \
1881 if self.rc.autocall and \
1848 not self.re_exclude_auto.match(theRest) and \
1882 not self.re_exclude_auto.match(theRest) and \
1849 self.re_fun_name.match(iFun) and \
1883 self.re_fun_name.match(iFun) and \
1850 callable(oinfo['obj']) :
1884 callable(oinfo['obj']) :
1851 #print 'going auto' # dbg
1885 #print 'going auto' # dbg
1852 return self.handle_auto(line,continue_prompt,
1886 return self.handle_auto(line,continue_prompt,
1853 pre,iFun,theRest,oinfo['obj'])
1887 pre,iFun,theRest,oinfo['obj'])
1854 else:
1888 else:
1855 #print 'was callable?', callable(oinfo['obj']) # dbg
1889 #print 'was callable?', callable(oinfo['obj']) # dbg
1856 return self.handle_normal(line,continue_prompt)
1890 return self.handle_normal(line,continue_prompt)
1857
1891
1858 # If we get here, we have a normal Python line. Log and return.
1892 # If we get here, we have a normal Python line. Log and return.
1859 return self.handle_normal(line,continue_prompt)
1893 return self.handle_normal(line,continue_prompt)
1860
1894
1861 def _prefilter_dumb(self, line, continue_prompt):
1895 def _prefilter_dumb(self, line, continue_prompt):
1862 """simple prefilter function, for debugging"""
1896 """simple prefilter function, for debugging"""
1863 return self.handle_normal(line,continue_prompt)
1897 return self.handle_normal(line,continue_prompt)
1864
1898
1865 # Set the default prefilter() function (this can be user-overridden)
1899 # Set the default prefilter() function (this can be user-overridden)
1866 prefilter = _prefilter
1900 prefilter = _prefilter
1867
1901
1868 def handle_normal(self,line,continue_prompt=None,
1902 def handle_normal(self,line,continue_prompt=None,
1869 pre=None,iFun=None,theRest=None):
1903 pre=None,iFun=None,theRest=None):
1870 """Handle normal input lines. Use as a template for handlers."""
1904 """Handle normal input lines. Use as a template for handlers."""
1871
1905
1872 # With autoindent on, we need some way to exit the input loop, and I
1906 # With autoindent on, we need some way to exit the input loop, and I
1873 # don't want to force the user to have to backspace all the way to
1907 # don't want to force the user to have to backspace all the way to
1874 # clear the line. The rule will be in this case, that either two
1908 # clear the line. The rule will be in this case, that either two
1875 # lines of pure whitespace in a row, or a line of pure whitespace but
1909 # lines of pure whitespace in a row, or a line of pure whitespace but
1876 # of a size different to the indent level, will exit the input loop.
1910 # of a size different to the indent level, will exit the input loop.
1877
1911
1878 if (continue_prompt and self.autoindent and isspace(line) and
1912 if (continue_prompt and self.autoindent and line.isspace() and
1879 (line != self.indent_current or isspace(self.buffer[-1]))):
1913 (line != self.indent_current or (self.buffer[-1]).isspace() )):
1880 line = ''
1914 line = ''
1881
1915
1882 self.log(line,continue_prompt)
1916 self.log(line,continue_prompt)
1883 return line
1917 return line
1884
1918
1885 def handle_alias(self,line,continue_prompt=None,
1919 def handle_alias(self,line,continue_prompt=None,
1886 pre=None,iFun=None,theRest=None):
1920 pre=None,iFun=None,theRest=None):
1887 """Handle alias input lines. """
1921 """Handle alias input lines. """
1888
1922
1889 # pre is needed, because it carries the leading whitespace. Otherwise
1923 # pre is needed, because it carries the leading whitespace. Otherwise
1890 # aliases won't work in indented sections.
1924 # aliases won't work in indented sections.
1891 line_out = '%sipalias(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
1925 line_out = '%sipalias(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
1892 self.log(line_out,continue_prompt)
1926 self.log(line_out,continue_prompt)
1893 return line_out
1927 return line_out
1894
1928
1895 def handle_shell_escape(self, line, continue_prompt=None,
1929 def handle_shell_escape(self, line, continue_prompt=None,
1896 pre=None,iFun=None,theRest=None):
1930 pre=None,iFun=None,theRest=None):
1897 """Execute the line in a shell, empty return value"""
1931 """Execute the line in a shell, empty return value"""
1898
1932
1899 #print 'line in :', `line` # dbg
1933 #print 'line in :', `line` # dbg
1900 # Example of a special handler. Others follow a similar pattern.
1934 # Example of a special handler. Others follow a similar pattern.
1901 if line.lstrip().startswith('!!'):
1935 if line.lstrip().startswith('!!'):
1902 # rewrite iFun/theRest to properly hold the call to %sx and
1936 # rewrite iFun/theRest to properly hold the call to %sx and
1903 # the actual command to be executed, so handle_magic can work
1937 # the actual command to be executed, so handle_magic can work
1904 # correctly
1938 # correctly
1905 theRest = '%s %s' % (iFun[2:],theRest)
1939 theRest = '%s %s' % (iFun[2:],theRest)
1906 iFun = 'sx'
1940 iFun = 'sx'
1907 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1941 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1908 continue_prompt,pre,iFun,theRest)
1942 continue_prompt,pre,iFun,theRest)
1909 else:
1943 else:
1910 cmd=line.lstrip()[1:]
1944 cmd=line.lstrip()[1:]
1911 line_out = '%sipsystem(%s)' % (pre,make_quoted_expr(cmd))
1945 line_out = '%sipsystem(%s)' % (pre,make_quoted_expr(cmd))
1912 # update cache/log and return
1946 # update cache/log and return
1913 self.log(line_out,continue_prompt)
1947 self.log(line_out,continue_prompt)
1914 return line_out
1948 return line_out
1915
1949
1916 def handle_magic(self, line, continue_prompt=None,
1950 def handle_magic(self, line, continue_prompt=None,
1917 pre=None,iFun=None,theRest=None):
1951 pre=None,iFun=None,theRest=None):
1918 """Execute magic functions."""
1952 """Execute magic functions."""
1919
1953
1920
1954
1921 cmd = '%sipmagic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
1955 cmd = '%sipmagic(%s)' % (pre,make_quoted_expr(iFun + " " + theRest))
1922 self.log(cmd,continue_prompt)
1956 self.log(cmd,continue_prompt)
1923 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1957 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1924 return cmd
1958 return cmd
1925
1959
1926 def handle_auto(self, line, continue_prompt=None,
1960 def handle_auto(self, line, continue_prompt=None,
1927 pre=None,iFun=None,theRest=None,obj=None):
1961 pre=None,iFun=None,theRest=None,obj=None):
1928 """Hande lines which can be auto-executed, quoting if requested."""
1962 """Hande lines which can be auto-executed, quoting if requested."""
1929
1963
1930 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1964 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1931
1965
1932 # This should only be active for single-line input!
1966 # This should only be active for single-line input!
1933 if continue_prompt:
1967 if continue_prompt:
1934 self.log(line,continue_prompt)
1968 self.log(line,continue_prompt)
1935 return line
1969 return line
1936
1970
1937 auto_rewrite = True
1971 auto_rewrite = True
1938 if pre == self.ESC_QUOTE:
1972 if pre == self.ESC_QUOTE:
1939 # Auto-quote splitting on whitespace
1973 # Auto-quote splitting on whitespace
1940 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1974 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
1941 elif pre == self.ESC_QUOTE2:
1975 elif pre == self.ESC_QUOTE2:
1942 # Auto-quote whole string
1976 # Auto-quote whole string
1943 newcmd = '%s("%s")' % (iFun,theRest)
1977 newcmd = '%s("%s")' % (iFun,theRest)
1944 else:
1978 else:
1945 # Auto-paren.
1979 # Auto-paren.
1946 # We only apply it to argument-less calls if the autocall
1980 # We only apply it to argument-less calls if the autocall
1947 # parameter is set to 2. We only need to check that autocall is <
1981 # parameter is set to 2. We only need to check that autocall is <
1948 # 2, since this function isn't called unless it's at least 1.
1982 # 2, since this function isn't called unless it's at least 1.
1949 if not theRest and (self.rc.autocall < 2):
1983 if not theRest and (self.rc.autocall < 2):
1950 newcmd = '%s %s' % (iFun,theRest)
1984 newcmd = '%s %s' % (iFun,theRest)
1951 auto_rewrite = False
1985 auto_rewrite = False
1952 else:
1986 else:
1953 if theRest.startswith('['):
1987 if theRest.startswith('['):
1954 if hasattr(obj,'__getitem__'):
1988 if hasattr(obj,'__getitem__'):
1955 # Don't autocall in this case: item access for an object
1989 # Don't autocall in this case: item access for an object
1956 # which is BOTH callable and implements __getitem__.
1990 # which is BOTH callable and implements __getitem__.
1957 newcmd = '%s %s' % (iFun,theRest)
1991 newcmd = '%s %s' % (iFun,theRest)
1958 auto_rewrite = False
1992 auto_rewrite = False
1959 else:
1993 else:
1960 # if the object doesn't support [] access, go ahead and
1994 # if the object doesn't support [] access, go ahead and
1961 # autocall
1995 # autocall
1962 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1996 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1963 elif theRest.endswith(';'):
1997 elif theRest.endswith(';'):
1964 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1998 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
1965 else:
1999 else:
1966 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2000 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
1967
2001
1968 if auto_rewrite:
2002 if auto_rewrite:
1969 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
2003 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd
1970 # log what is now valid Python, not the actual user input (without the
2004 # log what is now valid Python, not the actual user input (without the
1971 # final newline)
2005 # final newline)
1972 self.log(newcmd,continue_prompt)
2006 self.log(newcmd,continue_prompt)
1973 return newcmd
2007 return newcmd
1974
2008
1975 def handle_help(self, line, continue_prompt=None,
2009 def handle_help(self, line, continue_prompt=None,
1976 pre=None,iFun=None,theRest=None):
2010 pre=None,iFun=None,theRest=None):
1977 """Try to get some help for the object.
2011 """Try to get some help for the object.
1978
2012
1979 obj? or ?obj -> basic information.
2013 obj? or ?obj -> basic information.
1980 obj?? or ??obj -> more details.
2014 obj?? or ??obj -> more details.
1981 """
2015 """
1982
2016
1983 # We need to make sure that we don't process lines which would be
2017 # We need to make sure that we don't process lines which would be
1984 # otherwise valid python, such as "x=1 # what?"
2018 # otherwise valid python, such as "x=1 # what?"
1985 try:
2019 try:
1986 codeop.compile_command(line)
2020 codeop.compile_command(line)
1987 except SyntaxError:
2021 except SyntaxError:
1988 # We should only handle as help stuff which is NOT valid syntax
2022 # We should only handle as help stuff which is NOT valid syntax
1989 if line[0]==self.ESC_HELP:
2023 if line[0]==self.ESC_HELP:
1990 line = line[1:]
2024 line = line[1:]
1991 elif line[-1]==self.ESC_HELP:
2025 elif line[-1]==self.ESC_HELP:
1992 line = line[:-1]
2026 line = line[:-1]
1993 self.log('#?'+line)
2027 self.log('#?'+line)
1994 if line:
2028 if line:
1995 self.magic_pinfo(line)
2029 self.magic_pinfo(line)
1996 else:
2030 else:
1997 page(self.usage,screen_lines=self.rc.screen_length)
2031 page(self.usage,screen_lines=self.rc.screen_length)
1998 return '' # Empty string is needed here!
2032 return '' # Empty string is needed here!
1999 except:
2033 except:
2000 # Pass any other exceptions through to the normal handler
2034 # Pass any other exceptions through to the normal handler
2001 return self.handle_normal(line,continue_prompt)
2035 return self.handle_normal(line,continue_prompt)
2002 else:
2036 else:
2003 # If the code compiles ok, we should handle it normally
2037 # If the code compiles ok, we should handle it normally
2004 return self.handle_normal(line,continue_prompt)
2038 return self.handle_normal(line,continue_prompt)
2005
2039
2006 def handle_emacs(self,line,continue_prompt=None,
2040 def handle_emacs(self,line,continue_prompt=None,
2007 pre=None,iFun=None,theRest=None):
2041 pre=None,iFun=None,theRest=None):
2008 """Handle input lines marked by python-mode."""
2042 """Handle input lines marked by python-mode."""
2009
2043
2010 # Currently, nothing is done. Later more functionality can be added
2044 # Currently, nothing is done. Later more functionality can be added
2011 # here if needed.
2045 # here if needed.
2012
2046
2013 # The input cache shouldn't be updated
2047 # The input cache shouldn't be updated
2014
2048
2015 return line
2049 return line
2016
2050
2017 def mktempfile(self,data=None):
2051 def mktempfile(self,data=None):
2018 """Make a new tempfile and return its filename.
2052 """Make a new tempfile and return its filename.
2019
2053
2020 This makes a call to tempfile.mktemp, but it registers the created
2054 This makes a call to tempfile.mktemp, but it registers the created
2021 filename internally so ipython cleans it up at exit time.
2055 filename internally so ipython cleans it up at exit time.
2022
2056
2023 Optional inputs:
2057 Optional inputs:
2024
2058
2025 - data(None): if data is given, it gets written out to the temp file
2059 - data(None): if data is given, it gets written out to the temp file
2026 immediately, and the file is closed again."""
2060 immediately, and the file is closed again."""
2027
2061
2028 filename = tempfile.mktemp('.py','ipython_edit_')
2062 filename = tempfile.mktemp('.py','ipython_edit_')
2029 self.tempfiles.append(filename)
2063 self.tempfiles.append(filename)
2030
2064
2031 if data:
2065 if data:
2032 tmp_file = open(filename,'w')
2066 tmp_file = open(filename,'w')
2033 tmp_file.write(data)
2067 tmp_file.write(data)
2034 tmp_file.close()
2068 tmp_file.close()
2035 return filename
2069 return filename
2036
2070
2037 def write(self,data):
2071 def write(self,data):
2038 """Write a string to the default output"""
2072 """Write a string to the default output"""
2039 Term.cout.write(data)
2073 Term.cout.write(data)
2040
2074
2041 def write_err(self,data):
2075 def write_err(self,data):
2042 """Write a string to the default error output"""
2076 """Write a string to the default error output"""
2043 Term.cerr.write(data)
2077 Term.cerr.write(data)
2044
2078
2045 def exit(self):
2079 def exit(self):
2046 """Handle interactive exit.
2080 """Handle interactive exit.
2047
2081
2048 This method sets the exit_now attribute."""
2082 This method sets the exit_now attribute."""
2049
2083
2050 if self.rc.confirm_exit:
2084 if self.rc.confirm_exit:
2051 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2085 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2052 self.exit_now = True
2086 self.exit_now = True
2053 else:
2087 else:
2054 self.exit_now = True
2088 self.exit_now = True
2055 return self.exit_now
2089 return self.exit_now
2056
2090
2057 def safe_execfile(self,fname,*where,**kw):
2091 def safe_execfile(self,fname,*where,**kw):
2058 fname = os.path.expanduser(fname)
2092 fname = os.path.expanduser(fname)
2059
2093
2060 # find things also in current directory
2094 # find things also in current directory
2061 dname = os.path.dirname(fname)
2095 dname = os.path.dirname(fname)
2062 if not sys.path.count(dname):
2096 if not sys.path.count(dname):
2063 sys.path.append(dname)
2097 sys.path.append(dname)
2064
2098
2065 try:
2099 try:
2066 xfile = open(fname)
2100 xfile = open(fname)
2067 except:
2101 except:
2068 print >> Term.cerr, \
2102 print >> Term.cerr, \
2069 'Could not open file <%s> for safe execution.' % fname
2103 'Could not open file <%s> for safe execution.' % fname
2070 return None
2104 return None
2071
2105
2072 kw.setdefault('islog',0)
2106 kw.setdefault('islog',0)
2073 kw.setdefault('quiet',1)
2107 kw.setdefault('quiet',1)
2074 kw.setdefault('exit_ignore',0)
2108 kw.setdefault('exit_ignore',0)
2075 first = xfile.readline()
2109 first = xfile.readline()
2076 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2110 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2077 xfile.close()
2111 xfile.close()
2078 # line by line execution
2112 # line by line execution
2079 if first.startswith(loghead) or kw['islog']:
2113 if first.startswith(loghead) or kw['islog']:
2080 print 'Loading log file <%s> one line at a time...' % fname
2114 print 'Loading log file <%s> one line at a time...' % fname
2081 if kw['quiet']:
2115 if kw['quiet']:
2082 stdout_save = sys.stdout
2116 stdout_save = sys.stdout
2083 sys.stdout = StringIO.StringIO()
2117 sys.stdout = StringIO.StringIO()
2084 try:
2118 try:
2085 globs,locs = where[0:2]
2119 globs,locs = where[0:2]
2086 except:
2120 except:
2087 try:
2121 try:
2088 globs = locs = where[0]
2122 globs = locs = where[0]
2089 except:
2123 except:
2090 globs = locs = globals()
2124 globs = locs = globals()
2091 badblocks = []
2125 badblocks = []
2092
2126
2093 # we also need to identify indented blocks of code when replaying
2127 # we also need to identify indented blocks of code when replaying
2094 # logs and put them together before passing them to an exec
2128 # logs and put them together before passing them to an exec
2095 # statement. This takes a bit of regexp and look-ahead work in the
2129 # statement. This takes a bit of regexp and look-ahead work in the
2096 # file. It's easiest if we swallow the whole thing in memory
2130 # file. It's easiest if we swallow the whole thing in memory
2097 # first, and manually walk through the lines list moving the
2131 # first, and manually walk through the lines list moving the
2098 # counter ourselves.
2132 # counter ourselves.
2099 indent_re = re.compile('\s+\S')
2133 indent_re = re.compile('\s+\S')
2100 xfile = open(fname)
2134 xfile = open(fname)
2101 filelines = xfile.readlines()
2135 filelines = xfile.readlines()
2102 xfile.close()
2136 xfile.close()
2103 nlines = len(filelines)
2137 nlines = len(filelines)
2104 lnum = 0
2138 lnum = 0
2105 while lnum < nlines:
2139 while lnum < nlines:
2106 line = filelines[lnum]
2140 line = filelines[lnum]
2107 lnum += 1
2141 lnum += 1
2108 # don't re-insert logger status info into cache
2142 # don't re-insert logger status info into cache
2109 if line.startswith('#log#'):
2143 if line.startswith('#log#'):
2110 continue
2144 continue
2111 else:
2145 else:
2112 # build a block of code (maybe a single line) for execution
2146 # build a block of code (maybe a single line) for execution
2113 block = line
2147 block = line
2114 try:
2148 try:
2115 next = filelines[lnum] # lnum has already incremented
2149 next = filelines[lnum] # lnum has already incremented
2116 except:
2150 except:
2117 next = None
2151 next = None
2118 while next and indent_re.match(next):
2152 while next and indent_re.match(next):
2119 block += next
2153 block += next
2120 lnum += 1
2154 lnum += 1
2121 try:
2155 try:
2122 next = filelines[lnum]
2156 next = filelines[lnum]
2123 except:
2157 except:
2124 next = None
2158 next = None
2125 # now execute the block of one or more lines
2159 # now execute the block of one or more lines
2126 try:
2160 try:
2127 exec block in globs,locs
2161 exec block in globs,locs
2128 except SystemExit:
2162 except SystemExit:
2129 pass
2163 pass
2130 except:
2164 except:
2131 badblocks.append(block.rstrip())
2165 badblocks.append(block.rstrip())
2132 if kw['quiet']: # restore stdout
2166 if kw['quiet']: # restore stdout
2133 sys.stdout.close()
2167 sys.stdout.close()
2134 sys.stdout = stdout_save
2168 sys.stdout = stdout_save
2135 print 'Finished replaying log file <%s>' % fname
2169 print 'Finished replaying log file <%s>' % fname
2136 if badblocks:
2170 if badblocks:
2137 print >> sys.stderr, ('\nThe following lines/blocks in file '
2171 print >> sys.stderr, ('\nThe following lines/blocks in file '
2138 '<%s> reported errors:' % fname)
2172 '<%s> reported errors:' % fname)
2139
2173
2140 for badline in badblocks:
2174 for badline in badblocks:
2141 print >> sys.stderr, badline
2175 print >> sys.stderr, badline
2142 else: # regular file execution
2176 else: # regular file execution
2143 try:
2177 try:
2144 execfile(fname,*where)
2178 execfile(fname,*where)
2145 except SyntaxError:
2179 except SyntaxError:
2146 etype,evalue = sys.exc_info()[:2]
2180 etype,evalue = sys.exc_info()[:2]
2147 self.SyntaxTB(etype,evalue,[])
2181 self.SyntaxTB(etype,evalue,[])
2148 warn('Failure executing file: <%s>' % fname)
2182 warn('Failure executing file: <%s>' % fname)
2149 except SystemExit,status:
2183 except SystemExit,status:
2150 if not kw['exit_ignore']:
2184 if not kw['exit_ignore']:
2151 self.InteractiveTB()
2185 self.InteractiveTB()
2152 warn('Failure executing file: <%s>' % fname)
2186 warn('Failure executing file: <%s>' % fname)
2153 except:
2187 except:
2154 self.InteractiveTB()
2188 self.InteractiveTB()
2155 warn('Failure executing file: <%s>' % fname)
2189 warn('Failure executing file: <%s>' % fname)
2156
2190
2157 #************************* end of file <iplib.py> *****************************
2191 #************************* 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
General Comments 0
You need to be logged in to leave comments. Login now