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