##// END OF EJS Templates
Prettified and hardened string/backslash quoting with ipsystem(), ipalias() and ...
vivainio -
Show More

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

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