##// END OF EJS Templates
* IPython/iplib.py (runsource): remove self.code_to_run_src attribute. I...
fperez -
Show More

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

@@ -1,887 +1,886 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """IPython Shell classes.
2 """IPython Shell classes.
3
3
4 All the matplotlib support code was co-developed with John Hunter,
4 All the matplotlib support code was co-developed with John Hunter,
5 matplotlib's author.
5 matplotlib's author.
6
6
7 $Id: Shell.py 634 2005-07-17 01:56:45Z tzanko $"""
7 $Id: Shell.py 703 2005-08-16 17:34:44Z fperez $"""
8
8
9 #*****************************************************************************
9 #*****************************************************************************
10 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
10 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #*****************************************************************************
14 #*****************************************************************************
15
15
16 from IPython import Release
16 from IPython import Release
17 __author__ = '%s <%s>' % Release.authors['Fernando']
17 __author__ = '%s <%s>' % Release.authors['Fernando']
18 __license__ = Release.license
18 __license__ = Release.license
19
19
20 # Code begins
20 # Code begins
21 import __main__
21 import __main__
22 import __builtin__
22 import __builtin__
23 import sys
23 import sys
24 import os
24 import os
25 import code
25 import code
26 import threading
26 import threading
27 import signal
27 import signal
28
28
29 import IPython
29 import IPython
30 from IPython.iplib import InteractiveShell
30 from IPython.iplib import InteractiveShell
31 from IPython.ipmaker import make_IPython
31 from IPython.ipmaker import make_IPython
32 from IPython.genutils import Term,warn,error,flag_calls
32 from IPython.genutils import Term,warn,error,flag_calls
33 from IPython.Struct import Struct
33 from IPython.Struct import Struct
34 from IPython.Magic import Magic
34 from IPython.Magic import Magic
35 from IPython import ultraTB
35 from IPython import ultraTB
36
36
37 # global flag to pass around information about Ctrl-C without exceptions
37 # global flag to pass around information about Ctrl-C without exceptions
38 KBINT = False
38 KBINT = False
39
39
40 # global flag to turn on/off Tk support.
40 # global flag to turn on/off Tk support.
41 USE_TK = False
41 USE_TK = False
42
42
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44 # This class is trivial now, but I want to have it in to publish a clean
44 # This class is trivial now, but I want to have it in to publish a clean
45 # interface. Later when the internals are reorganized, code that uses this
45 # interface. Later when the internals are reorganized, code that uses this
46 # shouldn't have to change.
46 # shouldn't have to change.
47
47
48 class IPShell:
48 class IPShell:
49 """Create an IPython instance."""
49 """Create an IPython instance."""
50
50
51 def __init__(self,argv=None,user_ns=None,debug=1,
51 def __init__(self,argv=None,user_ns=None,debug=1,
52 shell_class=InteractiveShell):
52 shell_class=InteractiveShell):
53 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
53 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
54 shell_class=shell_class)
54 shell_class=shell_class)
55
55
56 def mainloop(self,sys_exit=0,banner=None):
56 def mainloop(self,sys_exit=0,banner=None):
57 self.IP.mainloop(banner)
57 self.IP.mainloop(banner)
58 if sys_exit:
58 if sys_exit:
59 sys.exit()
59 sys.exit()
60
60
61 #-----------------------------------------------------------------------------
61 #-----------------------------------------------------------------------------
62 class IPShellEmbed:
62 class IPShellEmbed:
63 """Allow embedding an IPython shell into a running program.
63 """Allow embedding an IPython shell into a running program.
64
64
65 Instances of this class are callable, with the __call__ method being an
65 Instances of this class are callable, with the __call__ method being an
66 alias to the embed() method of an InteractiveShell instance.
66 alias to the embed() method of an InteractiveShell instance.
67
67
68 Usage (see also the example-embed.py file for a running example):
68 Usage (see also the example-embed.py file for a running example):
69
69
70 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
70 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
71
71
72 - argv: list containing valid command-line options for IPython, as they
72 - argv: list containing valid command-line options for IPython, as they
73 would appear in sys.argv[1:].
73 would appear in sys.argv[1:].
74
74
75 For example, the following command-line options:
75 For example, the following command-line options:
76
76
77 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
77 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
78
78
79 would be passed in the argv list as:
79 would be passed in the argv list as:
80
80
81 ['-prompt_in1','Input <\\#>','-colors','LightBG']
81 ['-prompt_in1','Input <\\#>','-colors','LightBG']
82
82
83 - banner: string which gets printed every time the interpreter starts.
83 - banner: string which gets printed every time the interpreter starts.
84
84
85 - exit_msg: string which gets printed every time the interpreter exits.
85 - exit_msg: string which gets printed every time the interpreter exits.
86
86
87 - rc_override: a dict or Struct of configuration options such as those
87 - rc_override: a dict or Struct of configuration options such as those
88 used by IPython. These options are read from your ~/.ipython/ipythonrc
88 used by IPython. These options are read from your ~/.ipython/ipythonrc
89 file when the Shell object is created. Passing an explicit rc_override
89 file when the Shell object is created. Passing an explicit rc_override
90 dict with any options you want allows you to override those values at
90 dict with any options you want allows you to override those values at
91 creation time without having to modify the file. This way you can create
91 creation time without having to modify the file. This way you can create
92 embeddable instances configured in any way you want without editing any
92 embeddable instances configured in any way you want without editing any
93 global files (thus keeping your interactive IPython configuration
93 global files (thus keeping your interactive IPython configuration
94 unchanged).
94 unchanged).
95
95
96 Then the ipshell instance can be called anywhere inside your code:
96 Then the ipshell instance can be called anywhere inside your code:
97
97
98 ipshell(header='') -> Opens up an IPython shell.
98 ipshell(header='') -> Opens up an IPython shell.
99
99
100 - header: string printed by the IPython shell upon startup. This can let
100 - header: string printed by the IPython shell upon startup. This can let
101 you know where in your code you are when dropping into the shell. Note
101 you know where in your code you are when dropping into the shell. Note
102 that 'banner' gets prepended to all calls, so header is used for
102 that 'banner' gets prepended to all calls, so header is used for
103 location-specific information.
103 location-specific information.
104
104
105 For more details, see the __call__ method below.
105 For more details, see the __call__ method below.
106
106
107 When the IPython shell is exited with Ctrl-D, normal program execution
107 When the IPython shell is exited with Ctrl-D, normal program execution
108 resumes.
108 resumes.
109
109
110 This functionality was inspired by a posting on comp.lang.python by cmkl
110 This functionality was inspired by a posting on comp.lang.python by cmkl
111 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
111 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
112 by the IDL stop/continue commands."""
112 by the IDL stop/continue commands."""
113
113
114 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None):
114 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None):
115 """Note that argv here is a string, NOT a list."""
115 """Note that argv here is a string, NOT a list."""
116 self.set_banner(banner)
116 self.set_banner(banner)
117 self.set_exit_msg(exit_msg)
117 self.set_exit_msg(exit_msg)
118 self.set_dummy_mode(0)
118 self.set_dummy_mode(0)
119
119
120 # sys.displayhook is a global, we need to save the user's original
120 # sys.displayhook is a global, we need to save the user's original
121 # Don't rely on __displayhook__, as the user may have changed that.
121 # Don't rely on __displayhook__, as the user may have changed that.
122 self.sys_displayhook_ori = sys.displayhook
122 self.sys_displayhook_ori = sys.displayhook
123
123
124 # save readline completer status
124 # save readline completer status
125 try:
125 try:
126 #print 'Save completer',sys.ipcompleter # dbg
126 #print 'Save completer',sys.ipcompleter # dbg
127 self.sys_ipcompleter_ori = sys.ipcompleter
127 self.sys_ipcompleter_ori = sys.ipcompleter
128 except:
128 except:
129 pass # not nested with IPython
129 pass # not nested with IPython
130
130
131 # FIXME. Passing user_ns breaks namespace handling.
131 # FIXME. Passing user_ns breaks namespace handling.
132 #self.IP = make_IPython(argv,user_ns=__main__.__dict__)
132 #self.IP = make_IPython(argv,user_ns=__main__.__dict__)
133 self.IP = make_IPython(argv,rc_override=rc_override,embedded=True)
133 self.IP = make_IPython(argv,rc_override=rc_override,embedded=True)
134
134
135 self.IP.name_space_init()
135 self.IP.name_space_init()
136 # mark this as an embedded instance so we know if we get a crash
136 # mark this as an embedded instance so we know if we get a crash
137 # post-mortem
137 # post-mortem
138 self.IP.rc.embedded = 1
138 self.IP.rc.embedded = 1
139 # copy our own displayhook also
139 # copy our own displayhook also
140 self.sys_displayhook_embed = sys.displayhook
140 self.sys_displayhook_embed = sys.displayhook
141 # and leave the system's display hook clean
141 # and leave the system's display hook clean
142 sys.displayhook = self.sys_displayhook_ori
142 sys.displayhook = self.sys_displayhook_ori
143 # don't use the ipython crash handler so that user exceptions aren't
143 # don't use the ipython crash handler so that user exceptions aren't
144 # trapped
144 # trapped
145 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
145 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
146 mode = self.IP.rc.xmode,
146 mode = self.IP.rc.xmode,
147 call_pdb = self.IP.rc.pdb)
147 call_pdb = self.IP.rc.pdb)
148 self.restore_system_completer()
148 self.restore_system_completer()
149
149
150 def restore_system_completer(self):
150 def restore_system_completer(self):
151 """Restores the readline completer which was in place.
151 """Restores the readline completer which was in place.
152
152
153 This allows embedded IPython within IPython not to disrupt the
153 This allows embedded IPython within IPython not to disrupt the
154 parent's completion.
154 parent's completion.
155 """
155 """
156
156
157 try:
157 try:
158 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
158 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
159 sys.ipcompleter = self.sys_ipcompleter_ori
159 sys.ipcompleter = self.sys_ipcompleter_ori
160 except:
160 except:
161 pass
161 pass
162
162
163 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
163 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
164 """Activate the interactive interpreter.
164 """Activate the interactive interpreter.
165
165
166 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
166 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
167 the interpreter shell with the given local and global namespaces, and
167 the interpreter shell with the given local and global namespaces, and
168 optionally print a header string at startup.
168 optionally print a header string at startup.
169
169
170 The shell can be globally activated/deactivated using the
170 The shell can be globally activated/deactivated using the
171 set/get_dummy_mode methods. This allows you to turn off a shell used
171 set/get_dummy_mode methods. This allows you to turn off a shell used
172 for debugging globally.
172 for debugging globally.
173
173
174 However, *each* time you call the shell you can override the current
174 However, *each* time you call the shell you can override the current
175 state of dummy_mode with the optional keyword parameter 'dummy'. For
175 state of dummy_mode with the optional keyword parameter 'dummy'. For
176 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
176 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
177 can still have a specific call work by making it as IPShell(dummy=0).
177 can still have a specific call work by making it as IPShell(dummy=0).
178
178
179 The optional keyword parameter dummy controls whether the call
179 The optional keyword parameter dummy controls whether the call
180 actually does anything. """
180 actually does anything. """
181
181
182 # Allow the dummy parameter to override the global __dummy_mode
182 # Allow the dummy parameter to override the global __dummy_mode
183 if dummy or (dummy != 0 and self.__dummy_mode):
183 if dummy or (dummy != 0 and self.__dummy_mode):
184 return
184 return
185
185
186 # Set global subsystems (display,completions) to our values
186 # Set global subsystems (display,completions) to our values
187 sys.displayhook = self.sys_displayhook_embed
187 sys.displayhook = self.sys_displayhook_embed
188 if self.IP.has_readline:
188 if self.IP.has_readline:
189 self.IP.readline.set_completer(self.IP.Completer.complete)
189 self.IP.readline.set_completer(self.IP.Completer.complete)
190
190
191 if self.banner and header:
191 if self.banner and header:
192 format = '%s\n%s\n'
192 format = '%s\n%s\n'
193 else:
193 else:
194 format = '%s%s\n'
194 format = '%s%s\n'
195 banner = format % (self.banner,header)
195 banner = format % (self.banner,header)
196
196
197 # Call the embedding code with a stack depth of 1 so it can skip over
197 # Call the embedding code with a stack depth of 1 so it can skip over
198 # our call and get the original caller's namespaces.
198 # our call and get the original caller's namespaces.
199 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
199 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
200
200
201 if self.exit_msg:
201 if self.exit_msg:
202 print self.exit_msg
202 print self.exit_msg
203
203
204 # Restore global systems (display, completion)
204 # Restore global systems (display, completion)
205 sys.displayhook = self.sys_displayhook_ori
205 sys.displayhook = self.sys_displayhook_ori
206 self.restore_system_completer()
206 self.restore_system_completer()
207
207
208 def set_dummy_mode(self,dummy):
208 def set_dummy_mode(self,dummy):
209 """Sets the embeddable shell's dummy mode parameter.
209 """Sets the embeddable shell's dummy mode parameter.
210
210
211 set_dummy_mode(dummy): dummy = 0 or 1.
211 set_dummy_mode(dummy): dummy = 0 or 1.
212
212
213 This parameter is persistent and makes calls to the embeddable shell
213 This parameter is persistent and makes calls to the embeddable shell
214 silently return without performing any action. This allows you to
214 silently return without performing any action. This allows you to
215 globally activate or deactivate a shell you're using with a single call.
215 globally activate or deactivate a shell you're using with a single call.
216
216
217 If you need to manually"""
217 If you need to manually"""
218
218
219 if dummy not in [0,1]:
219 if dummy not in [0,1]:
220 raise ValueError,'dummy parameter must be 0 or 1'
220 raise ValueError,'dummy parameter must be 0 or 1'
221 self.__dummy_mode = dummy
221 self.__dummy_mode = dummy
222
222
223 def get_dummy_mode(self):
223 def get_dummy_mode(self):
224 """Return the current value of the dummy mode parameter.
224 """Return the current value of the dummy mode parameter.
225 """
225 """
226 return self.__dummy_mode
226 return self.__dummy_mode
227
227
228 def set_banner(self,banner):
228 def set_banner(self,banner):
229 """Sets the global banner.
229 """Sets the global banner.
230
230
231 This banner gets prepended to every header printed when the shell
231 This banner gets prepended to every header printed when the shell
232 instance is called."""
232 instance is called."""
233
233
234 self.banner = banner
234 self.banner = banner
235
235
236 def set_exit_msg(self,exit_msg):
236 def set_exit_msg(self,exit_msg):
237 """Sets the global exit_msg.
237 """Sets the global exit_msg.
238
238
239 This exit message gets printed upon exiting every time the embedded
239 This exit message gets printed upon exiting every time the embedded
240 shell is called. It is None by default. """
240 shell is called. It is None by default. """
241
241
242 self.exit_msg = exit_msg
242 self.exit_msg = exit_msg
243
243
244 #-----------------------------------------------------------------------------
244 #-----------------------------------------------------------------------------
245 def sigint_handler (signum,stack_frame):
245 def sigint_handler (signum,stack_frame):
246 """Sigint handler for threaded apps.
246 """Sigint handler for threaded apps.
247
247
248 This is a horrible hack to pass information about SIGINT _without_ using
248 This is a horrible hack to pass information about SIGINT _without_ using
249 exceptions, since I haven't been able to properly manage cross-thread
249 exceptions, since I haven't been able to properly manage cross-thread
250 exceptions in GTK/WX. In fact, I don't think it can be done (or at least
250 exceptions in GTK/WX. In fact, I don't think it can be done (or at least
251 that's my understanding from a c.l.py thread where this was discussed)."""
251 that's my understanding from a c.l.py thread where this was discussed)."""
252
252
253 global KBINT
253 global KBINT
254
254
255 print '\nKeyboardInterrupt - Press <Enter> to continue.',
255 print '\nKeyboardInterrupt - Press <Enter> to continue.',
256 Term.cout.flush()
256 Term.cout.flush()
257 # Set global flag so that runsource can know that Ctrl-C was hit
257 # Set global flag so that runsource can know that Ctrl-C was hit
258 KBINT = True
258 KBINT = True
259
259
260 class MTInteractiveShell(InteractiveShell):
260 class MTInteractiveShell(InteractiveShell):
261 """Simple multi-threaded shell."""
261 """Simple multi-threaded shell."""
262
262
263 # Threading strategy taken from:
263 # Threading strategy taken from:
264 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
264 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
265 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
265 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
266 # from the pygtk mailing list, to avoid lockups with system calls.
266 # from the pygtk mailing list, to avoid lockups with system calls.
267
267
268 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
268 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
269 user_ns = None, banner2='',**kw):
269 user_ns = None, banner2='',**kw):
270 """Similar to the normal InteractiveShell, but with threading control"""
270 """Similar to the normal InteractiveShell, but with threading control"""
271
271
272 IPython.iplib.InteractiveShell.__init__(self,name,usage,rc,user_ns,banner2)
272 IPython.iplib.InteractiveShell.__init__(self,name,usage,rc,user_ns,banner2)
273
273
274 # Locking control variable
274 # Locking control variable
275 self.thread_ready = threading.Condition()
275 self.thread_ready = threading.Condition()
276
276
277 # Stuff to do at closing time
277 # Stuff to do at closing time
278 self._kill = False
278 self._kill = False
279 on_kill = kw.get('on_kill')
279 on_kill = kw.get('on_kill')
280 if on_kill is None:
280 if on_kill is None:
281 on_kill = []
281 on_kill = []
282 # Check that all things to kill are callable:
282 # Check that all things to kill are callable:
283 for t in on_kill:
283 for t in on_kill:
284 if not callable(t):
284 if not callable(t):
285 raise TypeError,'on_kill must be a list of callables'
285 raise TypeError,'on_kill must be a list of callables'
286 self.on_kill = on_kill
286 self.on_kill = on_kill
287
287
288 def runsource(self, source, filename="<input>", symbol="single"):
288 def runsource(self, source, filename="<input>", symbol="single"):
289 """Compile and run some source in the interpreter.
289 """Compile and run some source in the interpreter.
290
290
291 Modified version of code.py's runsource(), to handle threading issues.
291 Modified version of code.py's runsource(), to handle threading issues.
292 See the original for full docstring details."""
292 See the original for full docstring details."""
293
293
294 global KBINT
294 global KBINT
295
295
296 # If Ctrl-C was typed, we reset the flag and return right away
296 # If Ctrl-C was typed, we reset the flag and return right away
297 if KBINT:
297 if KBINT:
298 KBINT = False
298 KBINT = False
299 return False
299 return False
300
300
301 try:
301 try:
302 code = self.compile(source, filename, symbol)
302 code = self.compile(source, filename, symbol)
303 except (OverflowError, SyntaxError, ValueError):
303 except (OverflowError, SyntaxError, ValueError):
304 # Case 1
304 # Case 1
305 self.showsyntaxerror(filename)
305 self.showsyntaxerror(filename)
306 return False
306 return False
307
307
308 if code is None:
308 if code is None:
309 # Case 2
309 # Case 2
310 return True
310 return True
311
311
312 # Case 3
312 # Case 3
313 # Store code in self, so the execution thread can handle it
313 # Store code in self, so the execution thread can handle it
314 self.thread_ready.acquire()
314 self.thread_ready.acquire()
315 self.code_to_run_src = source
316 self.code_to_run = code
315 self.code_to_run = code
317 self.thread_ready.wait() # Wait until processed in timeout interval
316 self.thread_ready.wait() # Wait until processed in timeout interval
318 self.thread_ready.release()
317 self.thread_ready.release()
319
318
320 return False
319 return False
321
320
322 def runcode(self):
321 def runcode(self):
323 """Execute a code object.
322 """Execute a code object.
324
323
325 Multithreaded wrapper around IPython's runcode()."""
324 Multithreaded wrapper around IPython's runcode()."""
326
325
327 # lock thread-protected stuff
326 # lock thread-protected stuff
328 self.thread_ready.acquire()
327 self.thread_ready.acquire()
329
328
330 # Install sigint handler
329 # Install sigint handler
331 try:
330 try:
332 signal.signal(signal.SIGINT, sigint_handler)
331 signal.signal(signal.SIGINT, sigint_handler)
333 except SystemError:
332 except SystemError:
334 # This happens under Windows, which seems to have all sorts
333 # This happens under Windows, which seems to have all sorts
335 # of problems with signal handling. Oh well...
334 # of problems with signal handling. Oh well...
336 pass
335 pass
337
336
338 if self._kill:
337 if self._kill:
339 print >>Term.cout, 'Closing threads...',
338 print >>Term.cout, 'Closing threads...',
340 Term.cout.flush()
339 Term.cout.flush()
341 for tokill in self.on_kill:
340 for tokill in self.on_kill:
342 tokill()
341 tokill()
343 print >>Term.cout, 'Done.'
342 print >>Term.cout, 'Done.'
344
343
345 # Run pending code by calling parent class
344 # Run pending code by calling parent class
346 if self.code_to_run is not None:
345 if self.code_to_run is not None:
347 self.thread_ready.notify()
346 self.thread_ready.notify()
348 InteractiveShell.runcode(self,self.code_to_run)
347 InteractiveShell.runcode(self,self.code_to_run)
349
348
350 # We're done with thread-protected variables
349 # We're done with thread-protected variables
351 self.thread_ready.release()
350 self.thread_ready.release()
352 # This MUST return true for gtk threading to work
351 # This MUST return true for gtk threading to work
353 return True
352 return True
354
353
355 def kill (self):
354 def kill (self):
356 """Kill the thread, returning when it has been shut down."""
355 """Kill the thread, returning when it has been shut down."""
357 self.thread_ready.acquire()
356 self.thread_ready.acquire()
358 self._kill = True
357 self._kill = True
359 self.thread_ready.release()
358 self.thread_ready.release()
360
359
361 class MatplotlibShellBase:
360 class MatplotlibShellBase:
362 """Mixin class to provide the necessary modifications to regular IPython
361 """Mixin class to provide the necessary modifications to regular IPython
363 shell classes for matplotlib support.
362 shell classes for matplotlib support.
364
363
365 Given Python's MRO, this should be used as the FIRST class in the
364 Given Python's MRO, this should be used as the FIRST class in the
366 inheritance hierarchy, so that it overrides the relevant methods."""
365 inheritance hierarchy, so that it overrides the relevant methods."""
367
366
368 def _matplotlib_config(self,name):
367 def _matplotlib_config(self,name):
369 """Return various items needed to setup the user's shell with matplotlib"""
368 """Return various items needed to setup the user's shell with matplotlib"""
370
369
371 # Initialize matplotlib to interactive mode always
370 # Initialize matplotlib to interactive mode always
372 import matplotlib
371 import matplotlib
373 from matplotlib import backends
372 from matplotlib import backends
374 matplotlib.interactive(True)
373 matplotlib.interactive(True)
375
374
376 def use(arg):
375 def use(arg):
377 """IPython wrapper for matplotlib's backend switcher.
376 """IPython wrapper for matplotlib's backend switcher.
378
377
379 In interactive use, we can not allow switching to a different
378 In interactive use, we can not allow switching to a different
380 interactive backend, since thread conflicts will most likely crash
379 interactive backend, since thread conflicts will most likely crash
381 the python interpreter. This routine does a safety check first,
380 the python interpreter. This routine does a safety check first,
382 and refuses to perform a dangerous switch. It still allows
381 and refuses to perform a dangerous switch. It still allows
383 switching to non-interactive backends."""
382 switching to non-interactive backends."""
384
383
385 if arg in backends.interactive_bk and arg != self.mpl_backend:
384 if arg in backends.interactive_bk and arg != self.mpl_backend:
386 m=('invalid matplotlib backend switch.\n'
385 m=('invalid matplotlib backend switch.\n'
387 'This script attempted to switch to the interactive '
386 'This script attempted to switch to the interactive '
388 'backend: `%s`\n'
387 'backend: `%s`\n'
389 'Your current choice of interactive backend is: `%s`\n\n'
388 'Your current choice of interactive backend is: `%s`\n\n'
390 'Switching interactive matplotlib backends at runtime\n'
389 'Switching interactive matplotlib backends at runtime\n'
391 'would crash the python interpreter, '
390 'would crash the python interpreter, '
392 'and IPython has blocked it.\n\n'
391 'and IPython has blocked it.\n\n'
393 'You need to either change your choice of matplotlib backend\n'
392 'You need to either change your choice of matplotlib backend\n'
394 'by editing your .matplotlibrc file, or run this script as a \n'
393 'by editing your .matplotlibrc file, or run this script as a \n'
395 'standalone file from the command line, not using IPython.\n' %
394 'standalone file from the command line, not using IPython.\n' %
396 (arg,self.mpl_backend) )
395 (arg,self.mpl_backend) )
397 raise RuntimeError, m
396 raise RuntimeError, m
398 else:
397 else:
399 self.mpl_use(arg)
398 self.mpl_use(arg)
400 self.mpl_use._called = True
399 self.mpl_use._called = True
401
400
402 self.matplotlib = matplotlib
401 self.matplotlib = matplotlib
403 self.mpl_backend = matplotlib.rcParams['backend']
402 self.mpl_backend = matplotlib.rcParams['backend']
404
403
405 # we also need to block switching of interactive backends by use()
404 # we also need to block switching of interactive backends by use()
406 self.mpl_use = matplotlib.use
405 self.mpl_use = matplotlib.use
407 self.mpl_use._called = False
406 self.mpl_use._called = False
408 # overwrite the original matplotlib.use with our wrapper
407 # overwrite the original matplotlib.use with our wrapper
409 matplotlib.use = use
408 matplotlib.use = use
410
409
411
410
412 # This must be imported last in the matplotlib series, after
411 # This must be imported last in the matplotlib series, after
413 # backend/interactivity choices have been made
412 # backend/interactivity choices have been made
414 try:
413 try:
415 import matplotlib.pylab as pylab
414 import matplotlib.pylab as pylab
416 self.pylab = pylab
415 self.pylab = pylab
417 self.pylab_name = 'pylab'
416 self.pylab_name = 'pylab'
418 except ImportError:
417 except ImportError:
419 import matplotlib.matlab as matlab
418 import matplotlib.matlab as matlab
420 self.pylab = matlab
419 self.pylab = matlab
421 self.pylab_name = 'matlab'
420 self.pylab_name = 'matlab'
422
421
423 self.pylab.show._needmain = False
422 self.pylab.show._needmain = False
424 # We need to detect at runtime whether show() is called by the user.
423 # We need to detect at runtime whether show() is called by the user.
425 # For this, we wrap it into a decorator which adds a 'called' flag.
424 # For this, we wrap it into a decorator which adds a 'called' flag.
426 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
425 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
427
426
428 # Build a user namespace initialized with matplotlib/matlab features.
427 # Build a user namespace initialized with matplotlib/matlab features.
429 user_ns = {'__name__':'__main__',
428 user_ns = {'__name__':'__main__',
430 '__builtins__' : __builtin__ }
429 '__builtins__' : __builtin__ }
431
430
432 # Be careful not to remove the final \n in the code string below, or
431 # Be careful not to remove the final \n in the code string below, or
433 # things will break badly with py22 (I think it's a python bug, 2.3 is
432 # things will break badly with py22 (I think it's a python bug, 2.3 is
434 # OK).
433 # OK).
435 pname = self.pylab_name # Python can't interpolate dotted var names
434 pname = self.pylab_name # Python can't interpolate dotted var names
436 exec ("import matplotlib\n"
435 exec ("import matplotlib\n"
437 "import matplotlib.%(pname)s as %(pname)s\n"
436 "import matplotlib.%(pname)s as %(pname)s\n"
438 "from matplotlib.%(pname)s import *\n" % locals()) in user_ns
437 "from matplotlib.%(pname)s import *\n" % locals()) in user_ns
439
438
440 # Build matplotlib info banner
439 # Build matplotlib info banner
441 b="""
440 b="""
442 Welcome to pylab, a matplotlib-based Python environment.
441 Welcome to pylab, a matplotlib-based Python environment.
443 For more information, type 'help(pylab)'.
442 For more information, type 'help(pylab)'.
444 """
443 """
445 return user_ns,b
444 return user_ns,b
446
445
447 def mplot_exec(self,fname,*where,**kw):
446 def mplot_exec(self,fname,*where,**kw):
448 """Execute a matplotlib script.
447 """Execute a matplotlib script.
449
448
450 This is a call to execfile(), but wrapped in safeties to properly
449 This is a call to execfile(), but wrapped in safeties to properly
451 handle interactive rendering and backend switching."""
450 handle interactive rendering and backend switching."""
452
451
453 #print '*** Matplotlib runner ***' # dbg
452 #print '*** Matplotlib runner ***' # dbg
454 # turn off rendering until end of script
453 # turn off rendering until end of script
455 isInteractive = self.matplotlib.rcParams['interactive']
454 isInteractive = self.matplotlib.rcParams['interactive']
456 self.matplotlib.interactive(False)
455 self.matplotlib.interactive(False)
457 self.safe_execfile(fname,*where,**kw)
456 self.safe_execfile(fname,*where,**kw)
458 self.matplotlib.interactive(isInteractive)
457 self.matplotlib.interactive(isInteractive)
459 # make rendering call now, if the user tried to do it
458 # make rendering call now, if the user tried to do it
460 if self.pylab.draw_if_interactive.called:
459 if self.pylab.draw_if_interactive.called:
461 self.pylab.draw()
460 self.pylab.draw()
462 self.pylab.draw_if_interactive.called = False
461 self.pylab.draw_if_interactive.called = False
463
462
464 # if a backend switch was performed, reverse it now
463 # if a backend switch was performed, reverse it now
465 if self.mpl_use._called:
464 if self.mpl_use._called:
466 self.matplotlib.rcParams['backend'] = self.mpl_backend
465 self.matplotlib.rcParams['backend'] = self.mpl_backend
467
466
468 def magic_run(self,parameter_s=''):
467 def magic_run(self,parameter_s=''):
469 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
468 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
470
469
471 # Fix the docstring so users see the original as well
470 # Fix the docstring so users see the original as well
472 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
471 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
473 "\n *** Modified %run for Matplotlib,"
472 "\n *** Modified %run for Matplotlib,"
474 " with proper interactive handling ***")
473 " with proper interactive handling ***")
475
474
476 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
475 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
477 # and multithreaded. Note that these are meant for internal use, the IPShell*
476 # and multithreaded. Note that these are meant for internal use, the IPShell*
478 # classes below are the ones meant for public consumption.
477 # classes below are the ones meant for public consumption.
479
478
480 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
479 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
481 """Single-threaded shell with matplotlib support."""
480 """Single-threaded shell with matplotlib support."""
482
481
483 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
482 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
484 user_ns = None, **kw):
483 user_ns = None, **kw):
485 user_ns,b2 = self._matplotlib_config(name)
484 user_ns,b2 = self._matplotlib_config(name)
486 InteractiveShell.__init__(self,name,usage,rc,user_ns,banner2=b2,**kw)
485 InteractiveShell.__init__(self,name,usage,rc,user_ns,banner2=b2,**kw)
487
486
488 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
487 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
489 """Multi-threaded shell with matplotlib support."""
488 """Multi-threaded shell with matplotlib support."""
490
489
491 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
490 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
492 user_ns = None, **kw):
491 user_ns = None, **kw):
493 user_ns,b2 = self._matplotlib_config(name)
492 user_ns,b2 = self._matplotlib_config(name)
494 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,banner2=b2,**kw)
493 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,banner2=b2,**kw)
495
494
496 #-----------------------------------------------------------------------------
495 #-----------------------------------------------------------------------------
497 # Utility functions for the different GUI enabled IPShell* classes.
496 # Utility functions for the different GUI enabled IPShell* classes.
498
497
499 def get_tk():
498 def get_tk():
500 """Tries to import Tkinter and returns a withdrawn Tkinter root
499 """Tries to import Tkinter and returns a withdrawn Tkinter root
501 window. If Tkinter is already imported or not available, this
500 window. If Tkinter is already imported or not available, this
502 returns None. This function calls `hijack_tk` underneath.
501 returns None. This function calls `hijack_tk` underneath.
503 """
502 """
504 if not USE_TK or sys.modules.has_key('Tkinter'):
503 if not USE_TK or sys.modules.has_key('Tkinter'):
505 return None
504 return None
506 else:
505 else:
507 try:
506 try:
508 import Tkinter
507 import Tkinter
509 except ImportError:
508 except ImportError:
510 return None
509 return None
511 else:
510 else:
512 hijack_tk()
511 hijack_tk()
513 r = Tkinter.Tk()
512 r = Tkinter.Tk()
514 r.withdraw()
513 r.withdraw()
515 return r
514 return r
516
515
517 def hijack_tk():
516 def hijack_tk():
518 """Modifies Tkinter's mainloop with a dummy so when a module calls
517 """Modifies Tkinter's mainloop with a dummy so when a module calls
519 mainloop, it does not block.
518 mainloop, it does not block.
520
519
521 """
520 """
522 def misc_mainloop(self, n=0):
521 def misc_mainloop(self, n=0):
523 pass
522 pass
524 def tkinter_mainloop(n=0):
523 def tkinter_mainloop(n=0):
525 pass
524 pass
526
525
527 import Tkinter
526 import Tkinter
528 Tkinter.Misc.mainloop = misc_mainloop
527 Tkinter.Misc.mainloop = misc_mainloop
529 Tkinter.mainloop = tkinter_mainloop
528 Tkinter.mainloop = tkinter_mainloop
530
529
531 def update_tk(tk):
530 def update_tk(tk):
532 """Updates the Tkinter event loop. This is typically called from
531 """Updates the Tkinter event loop. This is typically called from
533 the respective WX or GTK mainloops.
532 the respective WX or GTK mainloops.
534 """
533 """
535 if tk:
534 if tk:
536 tk.update()
535 tk.update()
537
536
538 def hijack_wx():
537 def hijack_wx():
539 """Modifies wxPython's MainLoop with a dummy so user code does not
538 """Modifies wxPython's MainLoop with a dummy so user code does not
540 block IPython. The hijacked mainloop function is returned.
539 block IPython. The hijacked mainloop function is returned.
541 """
540 """
542 def dummy_mainloop(*args, **kw):
541 def dummy_mainloop(*args, **kw):
543 pass
542 pass
544 import wxPython
543 import wxPython
545 ver = wxPython.__version__
544 ver = wxPython.__version__
546 orig_mainloop = None
545 orig_mainloop = None
547 if ver[:3] >= '2.5':
546 if ver[:3] >= '2.5':
548 import wx
547 import wx
549 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
548 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
550 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
549 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
551 else: raise AttributeError('Could not find wx core module')
550 else: raise AttributeError('Could not find wx core module')
552 orig_mainloop = core.PyApp_MainLoop
551 orig_mainloop = core.PyApp_MainLoop
553 core.PyApp_MainLoop = dummy_mainloop
552 core.PyApp_MainLoop = dummy_mainloop
554 elif ver[:3] == '2.4':
553 elif ver[:3] == '2.4':
555 orig_mainloop = wxPython.wxc.wxPyApp_MainLoop
554 orig_mainloop = wxPython.wxc.wxPyApp_MainLoop
556 wxPython.wxc.wxPyApp_MainLoop = dummy_mainloop
555 wxPython.wxc.wxPyApp_MainLoop = dummy_mainloop
557 else:
556 else:
558 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
557 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
559 return orig_mainloop
558 return orig_mainloop
560
559
561 def hijack_gtk():
560 def hijack_gtk():
562 """Modifies pyGTK's mainloop with a dummy so user code does not
561 """Modifies pyGTK's mainloop with a dummy so user code does not
563 block IPython. This function returns the original `gtk.mainloop`
562 block IPython. This function returns the original `gtk.mainloop`
564 function that has been hijacked.
563 function that has been hijacked.
565
564
566 NOTE: Make sure you import this *AFTER* you call
565 NOTE: Make sure you import this *AFTER* you call
567 pygtk.require(...).
566 pygtk.require(...).
568 """
567 """
569 def dummy_mainloop(*args, **kw):
568 def dummy_mainloop(*args, **kw):
570 pass
569 pass
571 import gtk
570 import gtk
572 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
571 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
573 else: orig_mainloop = gtk.mainloop
572 else: orig_mainloop = gtk.mainloop
574 gtk.mainloop = dummy_mainloop
573 gtk.mainloop = dummy_mainloop
575 gtk.main = dummy_mainloop
574 gtk.main = dummy_mainloop
576 return orig_mainloop
575 return orig_mainloop
577
576
578 #-----------------------------------------------------------------------------
577 #-----------------------------------------------------------------------------
579 # The IPShell* classes below are the ones meant to be run by external code as
578 # The IPShell* classes below are the ones meant to be run by external code as
580 # IPython instances. Note that unless a specific threading strategy is
579 # IPython instances. Note that unless a specific threading strategy is
581 # desired, the factory function start() below should be used instead (it
580 # desired, the factory function start() below should be used instead (it
582 # selects the proper threaded class).
581 # selects the proper threaded class).
583
582
584 class IPShellGTK(threading.Thread):
583 class IPShellGTK(threading.Thread):
585 """Run a gtk mainloop() in a separate thread.
584 """Run a gtk mainloop() in a separate thread.
586
585
587 Python commands can be passed to the thread where they will be executed.
586 Python commands can be passed to the thread where they will be executed.
588 This is implemented by periodically checking for passed code using a
587 This is implemented by periodically checking for passed code using a
589 GTK timeout callback."""
588 GTK timeout callback."""
590
589
591 TIMEOUT = 100 # Millisecond interval between timeouts.
590 TIMEOUT = 100 # Millisecond interval between timeouts.
592
591
593 def __init__(self,argv=None,user_ns=None,debug=1,
592 def __init__(self,argv=None,user_ns=None,debug=1,
594 shell_class=MTInteractiveShell):
593 shell_class=MTInteractiveShell):
595
594
596 import pygtk
595 import pygtk
597 pygtk.require("2.0")
596 pygtk.require("2.0")
598 import gtk
597 import gtk
599
598
600 self.gtk = gtk
599 self.gtk = gtk
601 self.gtk_mainloop = hijack_gtk()
600 self.gtk_mainloop = hijack_gtk()
602
601
603 # Allows us to use both Tk and GTK.
602 # Allows us to use both Tk and GTK.
604 self.tk = get_tk()
603 self.tk = get_tk()
605
604
606 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
605 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
607 else: mainquit = self.gtk.mainquit
606 else: mainquit = self.gtk.mainquit
608
607
609 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
608 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
610 shell_class=shell_class,
609 shell_class=shell_class,
611 on_kill=[mainquit])
610 on_kill=[mainquit])
612 threading.Thread.__init__(self)
611 threading.Thread.__init__(self)
613
612
614 def run(self):
613 def run(self):
615 self.IP.mainloop()
614 self.IP.mainloop()
616 self.IP.kill()
615 self.IP.kill()
617
616
618 def mainloop(self):
617 def mainloop(self):
619
618
620 if self.gtk.pygtk_version >= (2,4,0):
619 if self.gtk.pygtk_version >= (2,4,0):
621 import gobject
620 import gobject
622 gobject.timeout_add(self.TIMEOUT, self.on_timer)
621 gobject.timeout_add(self.TIMEOUT, self.on_timer)
623 else:
622 else:
624 self.gtk.timeout_add(self.TIMEOUT, self.on_timer)
623 self.gtk.timeout_add(self.TIMEOUT, self.on_timer)
625
624
626 if sys.platform != 'win32':
625 if sys.platform != 'win32':
627 try:
626 try:
628 if self.gtk.gtk_version[0] >= 2:
627 if self.gtk.gtk_version[0] >= 2:
629 self.gtk.threads_init()
628 self.gtk.threads_init()
630 except AttributeError:
629 except AttributeError:
631 pass
630 pass
632 except RuntimeError:
631 except RuntimeError:
633 error('Your pyGTK likely has not been compiled with '
632 error('Your pyGTK likely has not been compiled with '
634 'threading support.\n'
633 'threading support.\n'
635 'The exception printout is below.\n'
634 'The exception printout is below.\n'
636 'You can either rebuild pyGTK with threads, or '
635 'You can either rebuild pyGTK with threads, or '
637 'try using \n'
636 'try using \n'
638 'matplotlib with a different backend (like Tk or WX).\n'
637 'matplotlib with a different backend (like Tk or WX).\n'
639 'Note that matplotlib will most likely not work in its '
638 'Note that matplotlib will most likely not work in its '
640 'current state!')
639 'current state!')
641 self.IP.InteractiveTB()
640 self.IP.InteractiveTB()
642 self.start()
641 self.start()
643 self.gtk.threads_enter()
642 self.gtk.threads_enter()
644 self.gtk_mainloop()
643 self.gtk_mainloop()
645 self.gtk.threads_leave()
644 self.gtk.threads_leave()
646 self.join()
645 self.join()
647
646
648 def on_timer(self):
647 def on_timer(self):
649 update_tk(self.tk)
648 update_tk(self.tk)
650 return self.IP.runcode()
649 return self.IP.runcode()
651
650
652
651
653 class IPShellWX(threading.Thread):
652 class IPShellWX(threading.Thread):
654 """Run a wx mainloop() in a separate thread.
653 """Run a wx mainloop() in a separate thread.
655
654
656 Python commands can be passed to the thread where they will be executed.
655 Python commands can be passed to the thread where they will be executed.
657 This is implemented by periodically checking for passed code using a
656 This is implemented by periodically checking for passed code using a
658 GTK timeout callback."""
657 GTK timeout callback."""
659
658
660 TIMEOUT = 100 # Millisecond interval between timeouts.
659 TIMEOUT = 100 # Millisecond interval between timeouts.
661
660
662 def __init__(self,argv=None,user_ns=None,debug=1,
661 def __init__(self,argv=None,user_ns=None,debug=1,
663 shell_class=MTInteractiveShell):
662 shell_class=MTInteractiveShell):
664
663
665 import wxPython.wx as wx
664 import wxPython.wx as wx
666
665
667 threading.Thread.__init__(self)
666 threading.Thread.__init__(self)
668 self.wx = wx
667 self.wx = wx
669 self.wx_mainloop = hijack_wx()
668 self.wx_mainloop = hijack_wx()
670
669
671 # Allows us to use both Tk and GTK.
670 # Allows us to use both Tk and GTK.
672 self.tk = get_tk()
671 self.tk = get_tk()
673
672
674 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
673 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
675 shell_class=shell_class,
674 shell_class=shell_class,
676 on_kill=[self.wxexit])
675 on_kill=[self.wxexit])
677 self.app = None
676 self.app = None
678
677
679 def wxexit(self, *args):
678 def wxexit(self, *args):
680 if self.app is not None:
679 if self.app is not None:
681 self.app.agent.timer.Stop()
680 self.app.agent.timer.Stop()
682 self.app.ExitMainLoop()
681 self.app.ExitMainLoop()
683
682
684 def run(self):
683 def run(self):
685 self.IP.mainloop()
684 self.IP.mainloop()
686 self.IP.kill()
685 self.IP.kill()
687
686
688 def mainloop(self):
687 def mainloop(self):
689
688
690 self.start()
689 self.start()
691
690
692 class TimerAgent(self.wx.wxMiniFrame):
691 class TimerAgent(self.wx.wxMiniFrame):
693 wx = self.wx
692 wx = self.wx
694 IP = self.IP
693 IP = self.IP
695 tk = self.tk
694 tk = self.tk
696 def __init__(self, parent, interval):
695 def __init__(self, parent, interval):
697 style = self.wx.wxDEFAULT_FRAME_STYLE | self.wx.wxTINY_CAPTION_HORIZ
696 style = self.wx.wxDEFAULT_FRAME_STYLE | self.wx.wxTINY_CAPTION_HORIZ
698 self.wx.wxMiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
697 self.wx.wxMiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
699 size=(100, 100),style=style)
698 size=(100, 100),style=style)
700 self.Show(False)
699 self.Show(False)
701 self.interval = interval
700 self.interval = interval
702 self.timerId = self.wx.wxNewId()
701 self.timerId = self.wx.wxNewId()
703
702
704 def StartWork(self):
703 def StartWork(self):
705 self.timer = self.wx.wxTimer(self, self.timerId)
704 self.timer = self.wx.wxTimer(self, self.timerId)
706 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
705 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
707 self.timer.Start(self.interval)
706 self.timer.Start(self.interval)
708
707
709 def OnTimer(self, event):
708 def OnTimer(self, event):
710 update_tk(self.tk)
709 update_tk(self.tk)
711 self.IP.runcode()
710 self.IP.runcode()
712
711
713 class App(self.wx.wxApp):
712 class App(self.wx.wxApp):
714 wx = self.wx
713 wx = self.wx
715 TIMEOUT = self.TIMEOUT
714 TIMEOUT = self.TIMEOUT
716 def OnInit(self):
715 def OnInit(self):
717 'Create the main window and insert the custom frame'
716 'Create the main window and insert the custom frame'
718 self.agent = TimerAgent(None, self.TIMEOUT)
717 self.agent = TimerAgent(None, self.TIMEOUT)
719 self.agent.Show(self.wx.false)
718 self.agent.Show(self.wx.false)
720 self.agent.StartWork()
719 self.agent.StartWork()
721 return self.wx.true
720 return self.wx.true
722
721
723 self.app = App(redirect=False)
722 self.app = App(redirect=False)
724 self.wx_mainloop(self.app)
723 self.wx_mainloop(self.app)
725 self.join()
724 self.join()
726
725
727
726
728 class IPShellQt(threading.Thread):
727 class IPShellQt(threading.Thread):
729 """Run a Qt event loop in a separate thread.
728 """Run a Qt event loop in a separate thread.
730
729
731 Python commands can be passed to the thread where they will be executed.
730 Python commands can be passed to the thread where they will be executed.
732 This is implemented by periodically checking for passed code using a
731 This is implemented by periodically checking for passed code using a
733 Qt timer / slot."""
732 Qt timer / slot."""
734
733
735 TIMEOUT = 100 # Millisecond interval between timeouts.
734 TIMEOUT = 100 # Millisecond interval between timeouts.
736
735
737 def __init__(self,argv=None,user_ns=None,debug=0,
736 def __init__(self,argv=None,user_ns=None,debug=0,
738 shell_class=MTInteractiveShell):
737 shell_class=MTInteractiveShell):
739
738
740 import qt
739 import qt
741
740
742 class newQApplication:
741 class newQApplication:
743 def __init__( self ):
742 def __init__( self ):
744 self.QApplication = qt.QApplication
743 self.QApplication = qt.QApplication
745
744
746 def __call__( *args, **kwargs ):
745 def __call__( *args, **kwargs ):
747 return qt.qApp
746 return qt.qApp
748
747
749 def exec_loop( *args, **kwargs ):
748 def exec_loop( *args, **kwargs ):
750 pass
749 pass
751
750
752 def __getattr__( self, name ):
751 def __getattr__( self, name ):
753 return getattr( self.QApplication, name )
752 return getattr( self.QApplication, name )
754
753
755 qt.QApplication = newQApplication()
754 qt.QApplication = newQApplication()
756
755
757 # Allows us to use both Tk and QT.
756 # Allows us to use both Tk and QT.
758 self.tk = get_tk()
757 self.tk = get_tk()
759
758
760 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
759 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
761 shell_class=shell_class,
760 shell_class=shell_class,
762 on_kill=[qt.qApp.exit])
761 on_kill=[qt.qApp.exit])
763
762
764 threading.Thread.__init__(self)
763 threading.Thread.__init__(self)
765
764
766 def run(self):
765 def run(self):
767 #sys.excepthook = self.IP.excepthook # dbg
766 #sys.excepthook = self.IP.excepthook # dbg
768 self.IP.mainloop()
767 self.IP.mainloop()
769 self.IP.kill()
768 self.IP.kill()
770
769
771 def mainloop(self):
770 def mainloop(self):
772 import qt, sys
771 import qt, sys
773 if qt.QApplication.startingUp():
772 if qt.QApplication.startingUp():
774 a = qt.QApplication.QApplication( sys.argv )
773 a = qt.QApplication.QApplication( sys.argv )
775 self.timer = qt.QTimer()
774 self.timer = qt.QTimer()
776 qt.QObject.connect( self.timer, qt.SIGNAL( 'timeout()' ), self.on_timer )
775 qt.QObject.connect( self.timer, qt.SIGNAL( 'timeout()' ), self.on_timer )
777
776
778 self.start()
777 self.start()
779 self.timer.start( self.TIMEOUT, True )
778 self.timer.start( self.TIMEOUT, True )
780 while True:
779 while True:
781 if self.IP._kill: break
780 if self.IP._kill: break
782 qt.qApp.exec_loop()
781 qt.qApp.exec_loop()
783 self.join()
782 self.join()
784
783
785 def on_timer(self):
784 def on_timer(self):
786 update_tk(self.tk)
785 update_tk(self.tk)
787 result = self.IP.runcode()
786 result = self.IP.runcode()
788 self.timer.start( self.TIMEOUT, True )
787 self.timer.start( self.TIMEOUT, True )
789 return result
788 return result
790
789
791 # A set of matplotlib public IPython shell classes, for single-threaded
790 # A set of matplotlib public IPython shell classes, for single-threaded
792 # (Tk* and FLTK* backends) and multithreaded (GTK* and WX* backends) use.
791 # (Tk* and FLTK* backends) and multithreaded (GTK* and WX* backends) use.
793 class IPShellMatplotlib(IPShell):
792 class IPShellMatplotlib(IPShell):
794 """Subclass IPShell with MatplotlibShell as the internal shell.
793 """Subclass IPShell with MatplotlibShell as the internal shell.
795
794
796 Single-threaded class, meant for the Tk* and FLTK* backends.
795 Single-threaded class, meant for the Tk* and FLTK* backends.
797
796
798 Having this on a separate class simplifies the external driver code."""
797 Having this on a separate class simplifies the external driver code."""
799
798
800 def __init__(self,argv=None,user_ns=None,debug=1):
799 def __init__(self,argv=None,user_ns=None,debug=1):
801 IPShell.__init__(self,argv,user_ns,debug,shell_class=MatplotlibShell)
800 IPShell.__init__(self,argv,user_ns,debug,shell_class=MatplotlibShell)
802
801
803 class IPShellMatplotlibGTK(IPShellGTK):
802 class IPShellMatplotlibGTK(IPShellGTK):
804 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
803 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
805
804
806 Multi-threaded class, meant for the GTK* backends."""
805 Multi-threaded class, meant for the GTK* backends."""
807
806
808 def __init__(self,argv=None,user_ns=None,debug=1):
807 def __init__(self,argv=None,user_ns=None,debug=1):
809 IPShellGTK.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
808 IPShellGTK.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
810
809
811 class IPShellMatplotlibWX(IPShellWX):
810 class IPShellMatplotlibWX(IPShellWX):
812 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
811 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
813
812
814 Multi-threaded class, meant for the WX* backends."""
813 Multi-threaded class, meant for the WX* backends."""
815
814
816 def __init__(self,argv=None,user_ns=None,debug=1):
815 def __init__(self,argv=None,user_ns=None,debug=1):
817 IPShellWX.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
816 IPShellWX.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
818
817
819 class IPShellMatplotlibQt(IPShellQt):
818 class IPShellMatplotlibQt(IPShellQt):
820 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
819 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
821
820
822 Multi-threaded class, meant for the Qt* backends."""
821 Multi-threaded class, meant for the Qt* backends."""
823
822
824 def __init__(self,argv=None,user_ns=None,debug=1):
823 def __init__(self,argv=None,user_ns=None,debug=1):
825 IPShellQt.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
824 IPShellQt.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
826
825
827 #-----------------------------------------------------------------------------
826 #-----------------------------------------------------------------------------
828 # Factory functions to actually start the proper thread-aware shell
827 # Factory functions to actually start the proper thread-aware shell
829
828
830 def _matplotlib_shell_class():
829 def _matplotlib_shell_class():
831 """Factory function to handle shell class selection for matplotlib.
830 """Factory function to handle shell class selection for matplotlib.
832
831
833 The proper shell class to use depends on the matplotlib backend, since
832 The proper shell class to use depends on the matplotlib backend, since
834 each backend requires a different threading strategy."""
833 each backend requires a different threading strategy."""
835
834
836 try:
835 try:
837 import matplotlib
836 import matplotlib
838 except ImportError:
837 except ImportError:
839 error('matplotlib could NOT be imported! Starting normal IPython.')
838 error('matplotlib could NOT be imported! Starting normal IPython.')
840 sh_class = IPShell
839 sh_class = IPShell
841 else:
840 else:
842 backend = matplotlib.rcParams['backend']
841 backend = matplotlib.rcParams['backend']
843 if backend.startswith('GTK'):
842 if backend.startswith('GTK'):
844 sh_class = IPShellMatplotlibGTK
843 sh_class = IPShellMatplotlibGTK
845 elif backend.startswith('WX'):
844 elif backend.startswith('WX'):
846 sh_class = IPShellMatplotlibWX
845 sh_class = IPShellMatplotlibWX
847 elif backend.startswith('Qt'):
846 elif backend.startswith('Qt'):
848 sh_class = IPShellMatplotlibQt
847 sh_class = IPShellMatplotlibQt
849 else:
848 else:
850 sh_class = IPShellMatplotlib
849 sh_class = IPShellMatplotlib
851 #print 'Using %s with the %s backend.' % (sh_class,backend) # dbg
850 #print 'Using %s with the %s backend.' % (sh_class,backend) # dbg
852 return sh_class
851 return sh_class
853
852
854 # This is the one which should be called by external code.
853 # This is the one which should be called by external code.
855 def start():
854 def start():
856 """Return a running shell instance, dealing with threading options.
855 """Return a running shell instance, dealing with threading options.
857
856
858 This is a factory function which will instantiate the proper IPython shell
857 This is a factory function which will instantiate the proper IPython shell
859 based on the user's threading choice. Such a selector is needed because
858 based on the user's threading choice. Such a selector is needed because
860 different GUI toolkits require different thread handling details."""
859 different GUI toolkits require different thread handling details."""
861
860
862 global USE_TK
861 global USE_TK
863 # Crude sys.argv hack to extract the threading options.
862 # Crude sys.argv hack to extract the threading options.
864 if len(sys.argv) > 1:
863 if len(sys.argv) > 1:
865 if len(sys.argv) > 2:
864 if len(sys.argv) > 2:
866 arg2 = sys.argv[2]
865 arg2 = sys.argv[2]
867 if arg2.endswith('-tk'):
866 if arg2.endswith('-tk'):
868 USE_TK = True
867 USE_TK = True
869 arg1 = sys.argv[1]
868 arg1 = sys.argv[1]
870 if arg1.endswith('-gthread'):
869 if arg1.endswith('-gthread'):
871 shell = IPShellGTK
870 shell = IPShellGTK
872 elif arg1.endswith( '-qthread' ):
871 elif arg1.endswith( '-qthread' ):
873 shell = IPShellQt
872 shell = IPShellQt
874 elif arg1.endswith('-wthread'):
873 elif arg1.endswith('-wthread'):
875 shell = IPShellWX
874 shell = IPShellWX
876 elif arg1.endswith('-pylab'):
875 elif arg1.endswith('-pylab'):
877 shell = _matplotlib_shell_class()
876 shell = _matplotlib_shell_class()
878 else:
877 else:
879 shell = IPShell
878 shell = IPShell
880 else:
879 else:
881 shell = IPShell
880 shell = IPShell
882 return shell()
881 return shell()
883
882
884 # Some aliases for backwards compatibility
883 # Some aliases for backwards compatibility
885 IPythonShell = IPShell
884 IPythonShell = IPShell
886 IPythonShellEmbed = IPShellEmbed
885 IPythonShellEmbed = IPShellEmbed
887 #************************ End of file <Shell.py> ***************************
886 #************************ End of file <Shell.py> ***************************
@@ -1,1520 +1,1521 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 645 2005-07-19 01:59:26Z fperez $"""
8 $Id: genutils.py 703 2005-08-16 17:34:44Z 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
18
17 from IPython import Release
19 from IPython import Release
18 __author__ = '%s <%s>' % Release.authors['Fernando']
20 __author__ = '%s <%s>' % Release.authors['Fernando']
19 __license__ = Release.license
21 __license__ = Release.license
20
22
21 #****************************************************************************
23 #****************************************************************************
22 # required modules
24 # required modules
23 import __main__
25 import __main__
24 import types,commands,time,sys,os,re,shutil
26 import types,commands,time,sys,os,re,shutil
25 import tempfile
27 import tempfile
26 import codecs
27 from IPython.Itpl import Itpl,itpl,printpl
28 from IPython.Itpl import Itpl,itpl,printpl
28 from IPython import DPyGetOpt
29 from IPython import DPyGetOpt
29
30
30 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
31 # Build objects which appeared in Python 2.3 for 2.2, to make ipython
31 # 2.2-friendly
32 # 2.2-friendly
32 try:
33 try:
33 basestring
34 basestring
34 except NameError:
35 except NameError:
35 import types
36 import types
36 basestring = (types.StringType, types.UnicodeType)
37 basestring = (types.StringType, types.UnicodeType)
37 True = 1==1
38 True = 1==1
38 False = 1==0
39 False = 1==0
39
40
40 def enumerate(obj):
41 def enumerate(obj):
41 i = -1
42 i = -1
42 for item in obj:
43 for item in obj:
43 i += 1
44 i += 1
44 yield i, item
45 yield i, item
45
46
46 # add these to the builtin namespace, so that all modules find them
47 # add these to the builtin namespace, so that all modules find them
47 import __builtin__
48 import __builtin__
48 __builtin__.basestring = basestring
49 __builtin__.basestring = basestring
49 __builtin__.True = True
50 __builtin__.True = True
50 __builtin__.False = False
51 __builtin__.False = False
51 __builtin__.enumerate = enumerate
52 __builtin__.enumerate = enumerate
52
53
53 #****************************************************************************
54 #****************************************************************************
54 # Exceptions
55 # Exceptions
55 class Error(Exception):
56 class Error(Exception):
56 """Base class for exceptions in this module."""
57 """Base class for exceptions in this module."""
57 pass
58 pass
58
59
59 #----------------------------------------------------------------------------
60 #----------------------------------------------------------------------------
60 class IOStream:
61 class IOStream:
61 def __init__(self,stream,fallback):
62 def __init__(self,stream,fallback):
62 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
63 if not hasattr(stream,'write') or not hasattr(stream,'flush'):
63 stream = fallback
64 stream = fallback
64 self.stream = stream
65 self.stream = stream
65 self._swrite = stream.write
66 self._swrite = stream.write
66 self.flush = stream.flush
67 self.flush = stream.flush
67
68
68 def write(self,data):
69 def write(self,data):
69 try:
70 try:
70 self._swrite(data)
71 self._swrite(data)
71 except:
72 except:
72 try:
73 try:
73 # print handles some unicode issues which may trip a plain
74 # print handles some unicode issues which may trip a plain
74 # write() call. Attempt to emulate write() by using a
75 # write() call. Attempt to emulate write() by using a
75 # trailing comma
76 # trailing comma
76 print >> self.stream, data,
77 print >> self.stream, data,
77 except:
78 except:
78 # if we get here, something is seriously broken.
79 # if we get here, something is seriously broken.
79 print >> sys.stderr, \
80 print >> sys.stderr, \
80 'ERROR - failed to write data to stream:', stream
81 'ERROR - failed to write data to stream:', stream
81
82
82 class IOTerm:
83 class IOTerm:
83 """ Term holds the file or file-like objects for handling I/O operations.
84 """ Term holds the file or file-like objects for handling I/O operations.
84
85
85 These are normally just sys.stdin, sys.stdout and sys.stderr but for
86 These are normally just sys.stdin, sys.stdout and sys.stderr but for
86 Windows they can can replaced to allow editing the strings before they are
87 Windows they can can replaced to allow editing the strings before they are
87 displayed."""
88 displayed."""
88
89
89 # In the future, having IPython channel all its I/O operations through
90 # In the future, having IPython channel all its I/O operations through
90 # this class will make it easier to embed it into other environments which
91 # this class will make it easier to embed it into other environments which
91 # are not a normal terminal (such as a GUI-based shell)
92 # are not a normal terminal (such as a GUI-based shell)
92 def __init__(self,cin=None,cout=None,cerr=None):
93 def __init__(self,cin=None,cout=None,cerr=None):
93 self.cin = IOStream(cin,sys.stdin)
94 self.cin = IOStream(cin,sys.stdin)
94 self.cout = IOStream(cout,sys.stdout)
95 self.cout = IOStream(cout,sys.stdout)
95 self.cerr = IOStream(cerr,sys.stderr)
96 self.cerr = IOStream(cerr,sys.stderr)
96
97
97 # Global variable to be used for all I/O
98 # Global variable to be used for all I/O
98 Term = IOTerm()
99 Term = IOTerm()
99
100
100 # Windows-specific code to load Gary Bishop's readline and configure it
101 # Windows-specific code to load Gary Bishop's readline and configure it
101 # automatically for the users
102 # automatically for the users
102 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
103 # Note: os.name on cygwin returns posix, so this should only pick up 'native'
103 # windows. Cygwin returns 'cygwin' for sys.platform.
104 # windows. Cygwin returns 'cygwin' for sys.platform.
104 if os.name == 'nt':
105 if os.name == 'nt':
105 try:
106 try:
106 import readline
107 import readline
107 except ImportError:
108 except ImportError:
108 pass
109 pass
109 else:
110 else:
110 try:
111 try:
111 _out = readline.GetOutputFile()
112 _out = readline.GetOutputFile()
112 except AttributeError:
113 except AttributeError:
113 pass
114 pass
114 else:
115 else:
115 # Remake Term to use the readline i/o facilities
116 # Remake Term to use the readline i/o facilities
116 Term = IOTerm(cout=_out,cerr=_out)
117 Term = IOTerm(cout=_out,cerr=_out)
117 del _out
118 del _out
118
119
119 #****************************************************************************
120 #****************************************************************************
120 # Generic warning/error printer, used by everything else
121 # Generic warning/error printer, used by everything else
121 def warn(msg,level=2,exit_val=1):
122 def warn(msg,level=2,exit_val=1):
122 """Standard warning printer. Gives formatting consistency.
123 """Standard warning printer. Gives formatting consistency.
123
124
124 Output is sent to Term.cerr (sys.stderr by default).
125 Output is sent to Term.cerr (sys.stderr by default).
125
126
126 Options:
127 Options:
127
128
128 -level(2): allows finer control:
129 -level(2): allows finer control:
129 0 -> Do nothing, dummy function.
130 0 -> Do nothing, dummy function.
130 1 -> Print message.
131 1 -> Print message.
131 2 -> Print 'WARNING:' + message. (Default level).
132 2 -> Print 'WARNING:' + message. (Default level).
132 3 -> Print 'ERROR:' + message.
133 3 -> Print 'ERROR:' + message.
133 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
134 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val).
134
135
135 -exit_val (1): exit value returned by sys.exit() for a level 4
136 -exit_val (1): exit value returned by sys.exit() for a level 4
136 warning. Ignored for all other levels."""
137 warning. Ignored for all other levels."""
137
138
138 if level>0:
139 if level>0:
139 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
140 header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
140 print >> Term.cerr, '%s%s' % (header[level],msg)
141 print >> Term.cerr, '%s%s' % (header[level],msg)
141 if level == 4:
142 if level == 4:
142 print >> Term.cerr,'Exiting.\n'
143 print >> Term.cerr,'Exiting.\n'
143 sys.exit(exit_val)
144 sys.exit(exit_val)
144
145
145 def info(msg):
146 def info(msg):
146 """Equivalent to warn(msg,level=1)."""
147 """Equivalent to warn(msg,level=1)."""
147
148
148 warn(msg,level=1)
149 warn(msg,level=1)
149
150
150 def error(msg):
151 def error(msg):
151 """Equivalent to warn(msg,level=3)."""
152 """Equivalent to warn(msg,level=3)."""
152
153
153 warn(msg,level=3)
154 warn(msg,level=3)
154
155
155 def fatal(msg,exit_val=1):
156 def fatal(msg,exit_val=1):
156 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
157 """Equivalent to warn(msg,exit_val=exit_val,level=4)."""
157
158
158 warn(msg,exit_val=exit_val,level=4)
159 warn(msg,exit_val=exit_val,level=4)
159
160
160 #----------------------------------------------------------------------------
161 #----------------------------------------------------------------------------
161 StringTypes = types.StringTypes
162 StringTypes = types.StringTypes
162
163
163 # Basic timing functionality
164 # Basic timing functionality
164
165
165 # If possible (Unix), use the resource module instead of time.clock()
166 # If possible (Unix), use the resource module instead of time.clock()
166 try:
167 try:
167 import resource
168 import resource
168 def clock():
169 def clock():
169 """clock() -> floating point number
170 """clock() -> floating point number
170
171
171 Return the CPU time in seconds (user time only, system time is
172 Return the CPU time in seconds (user time only, system time is
172 ignored) since the start of the process. This is done via a call to
173 ignored) since the start of the process. This is done via a call to
173 resource.getrusage, so it avoids the wraparound problems in
174 resource.getrusage, so it avoids the wraparound problems in
174 time.clock()."""
175 time.clock()."""
175
176
176 return resource.getrusage(resource.RUSAGE_SELF)[0]
177 return resource.getrusage(resource.RUSAGE_SELF)[0]
177
178
178 def clock2():
179 def clock2():
179 """clock2() -> (t_user,t_system)
180 """clock2() -> (t_user,t_system)
180
181
181 Similar to clock(), but return a tuple of user/system times."""
182 Similar to clock(), but return a tuple of user/system times."""
182 return resource.getrusage(resource.RUSAGE_SELF)[:2]
183 return resource.getrusage(resource.RUSAGE_SELF)[:2]
183
184
184 except ImportError:
185 except ImportError:
185 clock = time.clock
186 clock = time.clock
186 def clock2():
187 def clock2():
187 """Under windows, system CPU time can't be measured.
188 """Under windows, system CPU time can't be measured.
188
189
189 This just returns clock() and zero."""
190 This just returns clock() and zero."""
190 return time.clock(),0.0
191 return time.clock(),0.0
191
192
192 def timings_out(reps,func,*args,**kw):
193 def timings_out(reps,func,*args,**kw):
193 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
194 """timings_out(reps,func,*args,**kw) -> (t_total,t_per_call,output)
194
195
195 Execute a function reps times, return a tuple with the elapsed total
196 Execute a function reps times, return a tuple with the elapsed total
196 CPU time in seconds, the time per call and the function's output.
197 CPU time in seconds, the time per call and the function's output.
197
198
198 Under Unix, the return value is the sum of user+system time consumed by
199 Under Unix, the return value is the sum of user+system time consumed by
199 the process, computed via the resource module. This prevents problems
200 the process, computed via the resource module. This prevents problems
200 related to the wraparound effect which the time.clock() function has.
201 related to the wraparound effect which the time.clock() function has.
201
202
202 Under Windows the return value is in wall clock seconds. See the
203 Under Windows the return value is in wall clock seconds. See the
203 documentation for the time module for more details."""
204 documentation for the time module for more details."""
204
205
205 reps = int(reps)
206 reps = int(reps)
206 assert reps >=1, 'reps must be >= 1'
207 assert reps >=1, 'reps must be >= 1'
207 if reps==1:
208 if reps==1:
208 start = clock()
209 start = clock()
209 out = func(*args,**kw)
210 out = func(*args,**kw)
210 tot_time = clock()-start
211 tot_time = clock()-start
211 else:
212 else:
212 rng = xrange(reps-1) # the last time is executed separately to store output
213 rng = xrange(reps-1) # the last time is executed separately to store output
213 start = clock()
214 start = clock()
214 for dummy in rng: func(*args,**kw)
215 for dummy in rng: func(*args,**kw)
215 out = func(*args,**kw) # one last time
216 out = func(*args,**kw) # one last time
216 tot_time = clock()-start
217 tot_time = clock()-start
217 av_time = tot_time / reps
218 av_time = tot_time / reps
218 return tot_time,av_time,out
219 return tot_time,av_time,out
219
220
220 def timings(reps,func,*args,**kw):
221 def timings(reps,func,*args,**kw):
221 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
222 """timings(reps,func,*args,**kw) -> (t_total,t_per_call)
222
223
223 Execute a function reps times, return a tuple with the elapsed total CPU
224 Execute a function reps times, return a tuple with the elapsed total CPU
224 time in seconds and the time per call. These are just the first two values
225 time in seconds and the time per call. These are just the first two values
225 in timings_out()."""
226 in timings_out()."""
226
227
227 return timings_out(reps,func,*args,**kw)[0:2]
228 return timings_out(reps,func,*args,**kw)[0:2]
228
229
229 def timing(func,*args,**kw):
230 def timing(func,*args,**kw):
230 """timing(func,*args,**kw) -> t_total
231 """timing(func,*args,**kw) -> t_total
231
232
232 Execute a function once, return the elapsed total CPU time in
233 Execute a function once, return the elapsed total CPU time in
233 seconds. This is just the first value in timings_out()."""
234 seconds. This is just the first value in timings_out()."""
234
235
235 return timings_out(1,func,*args,**kw)[0]
236 return timings_out(1,func,*args,**kw)[0]
236
237
237 #****************************************************************************
238 #****************************************************************************
238 # file and system
239 # file and system
239
240
240 def system(cmd,verbose=0,debug=0,header=''):
241 def system(cmd,verbose=0,debug=0,header=''):
241 """Execute a system command, return its exit status.
242 """Execute a system command, return its exit status.
242
243
243 Options:
244 Options:
244
245
245 - verbose (0): print the command to be executed.
246 - verbose (0): print the command to be executed.
246
247
247 - debug (0): only print, do not actually execute.
248 - debug (0): only print, do not actually execute.
248
249
249 - header (''): Header to print on screen prior to the executed command (it
250 - header (''): Header to print on screen prior to the executed command (it
250 is only prepended to the command, no newlines are added).
251 is only prepended to the command, no newlines are added).
251
252
252 Note: a stateful version of this function is available through the
253 Note: a stateful version of this function is available through the
253 SystemExec class."""
254 SystemExec class."""
254
255
255 stat = 0
256 stat = 0
256 if verbose or debug: print header+cmd
257 if verbose or debug: print header+cmd
257 sys.stdout.flush()
258 sys.stdout.flush()
258 if not debug: stat = os.system(cmd)
259 if not debug: stat = os.system(cmd)
259 return stat
260 return stat
260
261
261 def shell(cmd,verbose=0,debug=0,header=''):
262 def shell(cmd,verbose=0,debug=0,header=''):
262 """Execute a command in the system shell, always return None.
263 """Execute a command in the system shell, always return None.
263
264
264 Options:
265 Options:
265
266
266 - verbose (0): print the command to be executed.
267 - verbose (0): print the command to be executed.
267
268
268 - debug (0): only print, do not actually execute.
269 - debug (0): only print, do not actually execute.
269
270
270 - header (''): Header to print on screen prior to the executed command (it
271 - header (''): Header to print on screen prior to the executed command (it
271 is only prepended to the command, no newlines are added).
272 is only prepended to the command, no newlines are added).
272
273
273 Note: this is similar to genutils.system(), but it returns None so it can
274 Note: this is similar to genutils.system(), but it returns None so it can
274 be conveniently used in interactive loops without getting the return value
275 be conveniently used in interactive loops without getting the return value
275 (typically 0) printed many times."""
276 (typically 0) printed many times."""
276
277
277 stat = 0
278 stat = 0
278 if verbose or debug: print header+cmd
279 if verbose or debug: print header+cmd
279 # flush stdout so we don't mangle python's buffering
280 # flush stdout so we don't mangle python's buffering
280 sys.stdout.flush()
281 sys.stdout.flush()
281 if not debug:
282 if not debug:
282 os.system(cmd)
283 os.system(cmd)
283
284
284 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
285 def getoutput(cmd,verbose=0,debug=0,header='',split=0):
285 """Dummy substitute for perl's backquotes.
286 """Dummy substitute for perl's backquotes.
286
287
287 Executes a command and returns the output.
288 Executes a command and returns the output.
288
289
289 Accepts the same arguments as system(), plus:
290 Accepts the same arguments as system(), plus:
290
291
291 - split(0): if true, the output is returned as a list split on newlines.
292 - split(0): if true, the output is returned as a list split on newlines.
292
293
293 Note: a stateful version of this function is available through the
294 Note: a stateful version of this function is available through the
294 SystemExec class."""
295 SystemExec class."""
295
296
296 if verbose or debug: print header+cmd
297 if verbose or debug: print header+cmd
297 if not debug:
298 if not debug:
298 output = commands.getoutput(cmd)
299 output = commands.getoutput(cmd)
299 if split:
300 if split:
300 return output.split('\n')
301 return output.split('\n')
301 else:
302 else:
302 return output
303 return output
303
304
304 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
305 def getoutputerror(cmd,verbose=0,debug=0,header='',split=0):
305 """Return (standard output,standard error) of executing cmd in a shell.
306 """Return (standard output,standard error) of executing cmd in a shell.
306
307
307 Accepts the same arguments as system(), plus:
308 Accepts the same arguments as system(), plus:
308
309
309 - split(0): if true, each of stdout/err is returned as a list split on
310 - split(0): if true, each of stdout/err is returned as a list split on
310 newlines.
311 newlines.
311
312
312 Note: a stateful version of this function is available through the
313 Note: a stateful version of this function is available through the
313 SystemExec class."""
314 SystemExec class."""
314
315
315 if verbose or debug: print header+cmd
316 if verbose or debug: print header+cmd
316 if not cmd:
317 if not cmd:
317 if split:
318 if split:
318 return [],[]
319 return [],[]
319 else:
320 else:
320 return '',''
321 return '',''
321 if not debug:
322 if not debug:
322 pin,pout,perr = os.popen3(cmd)
323 pin,pout,perr = os.popen3(cmd)
323 tout = pout.read().rstrip()
324 tout = pout.read().rstrip()
324 terr = perr.read().rstrip()
325 terr = perr.read().rstrip()
325 pin.close()
326 pin.close()
326 pout.close()
327 pout.close()
327 perr.close()
328 perr.close()
328 if split:
329 if split:
329 return tout.split('\n'),terr.split('\n')
330 return tout.split('\n'),terr.split('\n')
330 else:
331 else:
331 return tout,terr
332 return tout,terr
332
333
333 # for compatibility with older naming conventions
334 # for compatibility with older naming conventions
334 xsys = system
335 xsys = system
335 bq = getoutput
336 bq = getoutput
336
337
337 class SystemExec:
338 class SystemExec:
338 """Access the system and getoutput functions through a stateful interface.
339 """Access the system and getoutput functions through a stateful interface.
339
340
340 Note: here we refer to the system and getoutput functions from this
341 Note: here we refer to the system and getoutput functions from this
341 library, not the ones from the standard python library.
342 library, not the ones from the standard python library.
342
343
343 This class offers the system and getoutput functions as methods, but the
344 This class offers the system and getoutput functions as methods, but the
344 verbose, debug and header parameters can be set for the instance (at
345 verbose, debug and header parameters can be set for the instance (at
345 creation time or later) so that they don't need to be specified on each
346 creation time or later) so that they don't need to be specified on each
346 call.
347 call.
347
348
348 For efficiency reasons, there's no way to override the parameters on a
349 For efficiency reasons, there's no way to override the parameters on a
349 per-call basis other than by setting instance attributes. If you need
350 per-call basis other than by setting instance attributes. If you need
350 local overrides, it's best to directly call system() or getoutput().
351 local overrides, it's best to directly call system() or getoutput().
351
352
352 The following names are provided as alternate options:
353 The following names are provided as alternate options:
353 - xsys: alias to system
354 - xsys: alias to system
354 - bq: alias to getoutput
355 - bq: alias to getoutput
355
356
356 An instance can then be created as:
357 An instance can then be created as:
357 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
358 >>> sysexec = SystemExec(verbose=1,debug=0,header='Calling: ')
358
359
359 And used as:
360 And used as:
360 >>> sysexec.xsys('pwd')
361 >>> sysexec.xsys('pwd')
361 >>> dirlist = sysexec.bq('ls -l')
362 >>> dirlist = sysexec.bq('ls -l')
362 """
363 """
363
364
364 def __init__(self,verbose=0,debug=0,header='',split=0):
365 def __init__(self,verbose=0,debug=0,header='',split=0):
365 """Specify the instance's values for verbose, debug and header."""
366 """Specify the instance's values for verbose, debug and header."""
366 setattr_list(self,'verbose debug header split')
367 setattr_list(self,'verbose debug header split')
367
368
368 def system(self,cmd):
369 def system(self,cmd):
369 """Stateful interface to system(), with the same keyword parameters."""
370 """Stateful interface to system(), with the same keyword parameters."""
370
371
371 system(cmd,self.verbose,self.debug,self.header)
372 system(cmd,self.verbose,self.debug,self.header)
372
373
373 def shell(self,cmd):
374 def shell(self,cmd):
374 """Stateful interface to shell(), with the same keyword parameters."""
375 """Stateful interface to shell(), with the same keyword parameters."""
375
376
376 shell(cmd,self.verbose,self.debug,self.header)
377 shell(cmd,self.verbose,self.debug,self.header)
377
378
378 xsys = system # alias
379 xsys = system # alias
379
380
380 def getoutput(self,cmd):
381 def getoutput(self,cmd):
381 """Stateful interface to getoutput()."""
382 """Stateful interface to getoutput()."""
382
383
383 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
384 return getoutput(cmd,self.verbose,self.debug,self.header,self.split)
384
385
385 def getoutputerror(self,cmd):
386 def getoutputerror(self,cmd):
386 """Stateful interface to getoutputerror()."""
387 """Stateful interface to getoutputerror()."""
387
388
388 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
389 return getoutputerror(cmd,self.verbose,self.debug,self.header,self.split)
389
390
390 bq = getoutput # alias
391 bq = getoutput # alias
391
392
392 #-----------------------------------------------------------------------------
393 #-----------------------------------------------------------------------------
393 def mutex_opts(dict,ex_op):
394 def mutex_opts(dict,ex_op):
394 """Check for presence of mutually exclusive keys in a dict.
395 """Check for presence of mutually exclusive keys in a dict.
395
396
396 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
397 Call: mutex_opts(dict,[[op1a,op1b],[op2a,op2b]...]"""
397 for op1,op2 in ex_op:
398 for op1,op2 in ex_op:
398 if op1 in dict and op2 in dict:
399 if op1 in dict and op2 in dict:
399 raise ValueError,'\n*** ERROR in Arguments *** '\
400 raise ValueError,'\n*** ERROR in Arguments *** '\
400 'Options '+op1+' and '+op2+' are mutually exclusive.'
401 'Options '+op1+' and '+op2+' are mutually exclusive.'
401
402
402 #-----------------------------------------------------------------------------
403 #-----------------------------------------------------------------------------
403 def filefind(fname,alt_dirs = None):
404 def filefind(fname,alt_dirs = None):
404 """Return the given filename either in the current directory, if it
405 """Return the given filename either in the current directory, if it
405 exists, or in a specified list of directories.
406 exists, or in a specified list of directories.
406
407
407 ~ expansion is done on all file and directory names.
408 ~ expansion is done on all file and directory names.
408
409
409 Upon an unsuccessful search, raise an IOError exception."""
410 Upon an unsuccessful search, raise an IOError exception."""
410
411
411 if alt_dirs is None:
412 if alt_dirs is None:
412 try:
413 try:
413 alt_dirs = get_home_dir()
414 alt_dirs = get_home_dir()
414 except HomeDirError:
415 except HomeDirError:
415 alt_dirs = os.getcwd()
416 alt_dirs = os.getcwd()
416 search = [fname] + list_strings(alt_dirs)
417 search = [fname] + list_strings(alt_dirs)
417 search = map(os.path.expanduser,search)
418 search = map(os.path.expanduser,search)
418 #print 'search list for',fname,'list:',search # dbg
419 #print 'search list for',fname,'list:',search # dbg
419 fname = search[0]
420 fname = search[0]
420 if os.path.isfile(fname):
421 if os.path.isfile(fname):
421 return fname
422 return fname
422 for direc in search[1:]:
423 for direc in search[1:]:
423 testname = os.path.join(direc,fname)
424 testname = os.path.join(direc,fname)
424 #print 'testname',testname # dbg
425 #print 'testname',testname # dbg
425 if os.path.isfile(testname):
426 if os.path.isfile(testname):
426 return testname
427 return testname
427 raise IOError,'File' + `fname` + \
428 raise IOError,'File' + `fname` + \
428 ' not found in current or supplied directories:' + `alt_dirs`
429 ' not found in current or supplied directories:' + `alt_dirs`
429
430
430 #----------------------------------------------------------------------------
431 #----------------------------------------------------------------------------
431 def target_outdated(target,deps):
432 def target_outdated(target,deps):
432 """Determine whether a target is out of date.
433 """Determine whether a target is out of date.
433
434
434 target_outdated(target,deps) -> 1/0
435 target_outdated(target,deps) -> 1/0
435
436
436 deps: list of filenames which MUST exist.
437 deps: list of filenames which MUST exist.
437 target: single filename which may or may not exist.
438 target: single filename which may or may not exist.
438
439
439 If target doesn't exist or is older than any file listed in deps, return
440 If target doesn't exist or is older than any file listed in deps, return
440 true, otherwise return false.
441 true, otherwise return false.
441 """
442 """
442 try:
443 try:
443 target_time = os.path.getmtime(target)
444 target_time = os.path.getmtime(target)
444 except os.error:
445 except os.error:
445 return 1
446 return 1
446 for dep in deps:
447 for dep in deps:
447 dep_time = os.path.getmtime(dep)
448 dep_time = os.path.getmtime(dep)
448 if dep_time > target_time:
449 if dep_time > target_time:
449 #print "For target",target,"Dep failed:",dep # dbg
450 #print "For target",target,"Dep failed:",dep # dbg
450 #print "times (dep,tar):",dep_time,target_time # dbg
451 #print "times (dep,tar):",dep_time,target_time # dbg
451 return 1
452 return 1
452 return 0
453 return 0
453
454
454 #-----------------------------------------------------------------------------
455 #-----------------------------------------------------------------------------
455 def target_update(target,deps,cmd):
456 def target_update(target,deps,cmd):
456 """Update a target with a given command given a list of dependencies.
457 """Update a target with a given command given a list of dependencies.
457
458
458 target_update(target,deps,cmd) -> runs cmd if target is outdated.
459 target_update(target,deps,cmd) -> runs cmd if target is outdated.
459
460
460 This is just a wrapper around target_outdated() which calls the given
461 This is just a wrapper around target_outdated() which calls the given
461 command if target is outdated."""
462 command if target is outdated."""
462
463
463 if target_outdated(target,deps):
464 if target_outdated(target,deps):
464 xsys(cmd)
465 xsys(cmd)
465
466
466 #----------------------------------------------------------------------------
467 #----------------------------------------------------------------------------
467 def unquote_ends(istr):
468 def unquote_ends(istr):
468 """Remove a single pair of quotes from the endpoints of a string."""
469 """Remove a single pair of quotes from the endpoints of a string."""
469
470
470 if not istr:
471 if not istr:
471 return istr
472 return istr
472 if (istr[0]=="'" and istr[-1]=="'") or \
473 if (istr[0]=="'" and istr[-1]=="'") or \
473 (istr[0]=='"' and istr[-1]=='"'):
474 (istr[0]=='"' and istr[-1]=='"'):
474 return istr[1:-1]
475 return istr[1:-1]
475 else:
476 else:
476 return istr
477 return istr
477
478
478 #----------------------------------------------------------------------------
479 #----------------------------------------------------------------------------
479 def process_cmdline(argv,names=[],defaults={},usage=''):
480 def process_cmdline(argv,names=[],defaults={},usage=''):
480 """ Process command-line options and arguments.
481 """ Process command-line options and arguments.
481
482
482 Arguments:
483 Arguments:
483
484
484 - argv: list of arguments, typically sys.argv.
485 - argv: list of arguments, typically sys.argv.
485
486
486 - names: list of option names. See DPyGetOpt docs for details on options
487 - names: list of option names. See DPyGetOpt docs for details on options
487 syntax.
488 syntax.
488
489
489 - defaults: dict of default values.
490 - defaults: dict of default values.
490
491
491 - usage: optional usage notice to print if a wrong argument is passed.
492 - usage: optional usage notice to print if a wrong argument is passed.
492
493
493 Return a dict of options and a list of free arguments."""
494 Return a dict of options and a list of free arguments."""
494
495
495 getopt = DPyGetOpt.DPyGetOpt()
496 getopt = DPyGetOpt.DPyGetOpt()
496 getopt.setIgnoreCase(0)
497 getopt.setIgnoreCase(0)
497 getopt.parseConfiguration(names)
498 getopt.parseConfiguration(names)
498
499
499 try:
500 try:
500 getopt.processArguments(argv)
501 getopt.processArguments(argv)
501 except:
502 except:
502 print usage
503 print usage
503 warn(`sys.exc_value`,level=4)
504 warn(`sys.exc_value`,level=4)
504
505
505 defaults.update(getopt.optionValues)
506 defaults.update(getopt.optionValues)
506 args = getopt.freeValues
507 args = getopt.freeValues
507
508
508 return defaults,args
509 return defaults,args
509
510
510 #----------------------------------------------------------------------------
511 #----------------------------------------------------------------------------
511 def optstr2types(ostr):
512 def optstr2types(ostr):
512 """Convert a string of option names to a dict of type mappings.
513 """Convert a string of option names to a dict of type mappings.
513
514
514 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
515 optstr2types(str) -> {None:'string_opts',int:'int_opts',float:'float_opts'}
515
516
516 This is used to get the types of all the options in a string formatted
517 This is used to get the types of all the options in a string formatted
517 with the conventions of DPyGetOpt. The 'type' None is used for options
518 with the conventions of DPyGetOpt. The 'type' None is used for options
518 which are strings (they need no further conversion). This function's main
519 which are strings (they need no further conversion). This function's main
519 use is to get a typemap for use with read_dict().
520 use is to get a typemap for use with read_dict().
520 """
521 """
521
522
522 typeconv = {None:'',int:'',float:''}
523 typeconv = {None:'',int:'',float:''}
523 typemap = {'s':None,'i':int,'f':float}
524 typemap = {'s':None,'i':int,'f':float}
524 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
525 opt_re = re.compile(r'([\w]*)([^:=]*:?=?)([sif]?)')
525
526
526 for w in ostr.split():
527 for w in ostr.split():
527 oname,alias,otype = opt_re.match(w).groups()
528 oname,alias,otype = opt_re.match(w).groups()
528 if otype == '' or alias == '!': # simple switches are integers too
529 if otype == '' or alias == '!': # simple switches are integers too
529 otype = 'i'
530 otype = 'i'
530 typeconv[typemap[otype]] += oname + ' '
531 typeconv[typemap[otype]] += oname + ' '
531 return typeconv
532 return typeconv
532
533
533 #----------------------------------------------------------------------------
534 #----------------------------------------------------------------------------
534 def read_dict(filename,type_conv=None,**opt):
535 def read_dict(filename,type_conv=None,**opt):
535
536
536 """Read a dictionary of key=value pairs from an input file, optionally
537 """Read a dictionary of key=value pairs from an input file, optionally
537 performing conversions on the resulting values.
538 performing conversions on the resulting values.
538
539
539 read_dict(filename,type_conv,**opt) -> dict
540 read_dict(filename,type_conv,**opt) -> dict
540
541
541 Only one value per line is accepted, the format should be
542 Only one value per line is accepted, the format should be
542 # optional comments are ignored
543 # optional comments are ignored
543 key value\n
544 key value\n
544
545
545 Args:
546 Args:
546
547
547 - type_conv: A dictionary specifying which keys need to be converted to
548 - type_conv: A dictionary specifying which keys need to be converted to
548 which types. By default all keys are read as strings. This dictionary
549 which types. By default all keys are read as strings. This dictionary
549 should have as its keys valid conversion functions for strings
550 should have as its keys valid conversion functions for strings
550 (int,long,float,complex, or your own). The value for each key
551 (int,long,float,complex, or your own). The value for each key
551 (converter) should be a whitespace separated string containing the names
552 (converter) should be a whitespace separated string containing the names
552 of all the entries in the file to be converted using that function. For
553 of all the entries in the file to be converted using that function. For
553 keys to be left alone, use None as the conversion function (only needed
554 keys to be left alone, use None as the conversion function (only needed
554 with purge=1, see below).
555 with purge=1, see below).
555
556
556 - opt: dictionary with extra options as below (default in parens)
557 - opt: dictionary with extra options as below (default in parens)
557
558
558 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
559 purge(0): if set to 1, all keys *not* listed in type_conv are purged out
559 of the dictionary to be returned. If purge is going to be used, the
560 of the dictionary to be returned. If purge is going to be used, the
560 set of keys to be left as strings also has to be explicitly specified
561 set of keys to be left as strings also has to be explicitly specified
561 using the (non-existent) conversion function None.
562 using the (non-existent) conversion function None.
562
563
563 fs(None): field separator. This is the key/value separator to be used
564 fs(None): field separator. This is the key/value separator to be used
564 when parsing the file. The None default means any whitespace [behavior
565 when parsing the file. The None default means any whitespace [behavior
565 of string.split()].
566 of string.split()].
566
567
567 strip(0): if 1, strip string values of leading/trailinig whitespace.
568 strip(0): if 1, strip string values of leading/trailinig whitespace.
568
569
569 warn(1): warning level if requested keys are not found in file.
570 warn(1): warning level if requested keys are not found in file.
570 - 0: silently ignore.
571 - 0: silently ignore.
571 - 1: inform but proceed.
572 - 1: inform but proceed.
572 - 2: raise KeyError exception.
573 - 2: raise KeyError exception.
573
574
574 no_empty(0): if 1, remove keys with whitespace strings as a value.
575 no_empty(0): if 1, remove keys with whitespace strings as a value.
575
576
576 unique([]): list of keys (or space separated string) which can't be
577 unique([]): list of keys (or space separated string) which can't be
577 repeated. If one such key is found in the file, each new instance
578 repeated. If one such key is found in the file, each new instance
578 overwrites the previous one. For keys not listed here, the behavior is
579 overwrites the previous one. For keys not listed here, the behavior is
579 to make a list of all appearances.
580 to make a list of all appearances.
580
581
581 Example:
582 Example:
582 If the input file test.ini has:
583 If the input file test.ini has:
583 i 3
584 i 3
584 x 4.5
585 x 4.5
585 y 5.5
586 y 5.5
586 s hi ho
587 s hi ho
587 Then:
588 Then:
588
589
589 >>> type_conv={int:'i',float:'x',None:'s'}
590 >>> type_conv={int:'i',float:'x',None:'s'}
590 >>> read_dict('test.ini')
591 >>> read_dict('test.ini')
591 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
592 {'i': '3', 's': 'hi ho', 'x': '4.5', 'y': '5.5'}
592 >>> read_dict('test.ini',type_conv)
593 >>> read_dict('test.ini',type_conv)
593 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
594 {'i': 3, 's': 'hi ho', 'x': 4.5, 'y': '5.5'}
594 >>> read_dict('test.ini',type_conv,purge=1)
595 >>> read_dict('test.ini',type_conv,purge=1)
595 {'i': 3, 's': 'hi ho', 'x': 4.5}
596 {'i': 3, 's': 'hi ho', 'x': 4.5}
596 """
597 """
597
598
598 # starting config
599 # starting config
599 opt.setdefault('purge',0)
600 opt.setdefault('purge',0)
600 opt.setdefault('fs',None) # field sep defaults to any whitespace
601 opt.setdefault('fs',None) # field sep defaults to any whitespace
601 opt.setdefault('strip',0)
602 opt.setdefault('strip',0)
602 opt.setdefault('warn',1)
603 opt.setdefault('warn',1)
603 opt.setdefault('no_empty',0)
604 opt.setdefault('no_empty',0)
604 opt.setdefault('unique','')
605 opt.setdefault('unique','')
605 if type(opt['unique']) in StringTypes:
606 if type(opt['unique']) in StringTypes:
606 unique_keys = qw(opt['unique'])
607 unique_keys = qw(opt['unique'])
607 elif type(opt['unique']) in (types.TupleType,types.ListType):
608 elif type(opt['unique']) in (types.TupleType,types.ListType):
608 unique_keys = opt['unique']
609 unique_keys = opt['unique']
609 else:
610 else:
610 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
611 raise ValueError, 'Unique keys must be given as a string, List or Tuple'
611
612
612 dict = {}
613 dict = {}
613 # first read in table of values as strings
614 # first read in table of values as strings
614 file = open(filename,'r')
615 file = open(filename,'r')
615 for line in file.readlines():
616 for line in file.readlines():
616 line = line.strip()
617 line = line.strip()
617 if len(line) and line[0]=='#': continue
618 if len(line) and line[0]=='#': continue
618 if len(line)>0:
619 if len(line)>0:
619 lsplit = line.split(opt['fs'],1)
620 lsplit = line.split(opt['fs'],1)
620 try:
621 try:
621 key,val = lsplit
622 key,val = lsplit
622 except ValueError:
623 except ValueError:
623 key,val = lsplit[0],''
624 key,val = lsplit[0],''
624 key = key.strip()
625 key = key.strip()
625 if opt['strip']: val = val.strip()
626 if opt['strip']: val = val.strip()
626 if val == "''" or val == '""': val = ''
627 if val == "''" or val == '""': val = ''
627 if opt['no_empty'] and (val=='' or val.isspace()):
628 if opt['no_empty'] and (val=='' or val.isspace()):
628 continue
629 continue
629 # if a key is found more than once in the file, build a list
630 # if a key is found more than once in the file, build a list
630 # unless it's in the 'unique' list. In that case, last found in file
631 # unless it's in the 'unique' list. In that case, last found in file
631 # takes precedence. User beware.
632 # takes precedence. User beware.
632 try:
633 try:
633 if dict[key] and key in unique_keys:
634 if dict[key] and key in unique_keys:
634 dict[key] = val
635 dict[key] = val
635 elif type(dict[key]) is types.ListType:
636 elif type(dict[key]) is types.ListType:
636 dict[key].append(val)
637 dict[key].append(val)
637 else:
638 else:
638 dict[key] = [dict[key],val]
639 dict[key] = [dict[key],val]
639 except KeyError:
640 except KeyError:
640 dict[key] = val
641 dict[key] = val
641 # purge if requested
642 # purge if requested
642 if opt['purge']:
643 if opt['purge']:
643 accepted_keys = qwflat(type_conv.values())
644 accepted_keys = qwflat(type_conv.values())
644 for key in dict.keys():
645 for key in dict.keys():
645 if key in accepted_keys: continue
646 if key in accepted_keys: continue
646 del(dict[key])
647 del(dict[key])
647 # now convert if requested
648 # now convert if requested
648 if type_conv==None: return dict
649 if type_conv==None: return dict
649 conversions = type_conv.keys()
650 conversions = type_conv.keys()
650 try: conversions.remove(None)
651 try: conversions.remove(None)
651 except: pass
652 except: pass
652 for convert in conversions:
653 for convert in conversions:
653 for val in qw(type_conv[convert]):
654 for val in qw(type_conv[convert]):
654 try:
655 try:
655 dict[val] = convert(dict[val])
656 dict[val] = convert(dict[val])
656 except KeyError,e:
657 except KeyError,e:
657 if opt['warn'] == 0:
658 if opt['warn'] == 0:
658 pass
659 pass
659 elif opt['warn'] == 1:
660 elif opt['warn'] == 1:
660 print >>sys.stderr, 'Warning: key',val,\
661 print >>sys.stderr, 'Warning: key',val,\
661 'not found in file',filename
662 'not found in file',filename
662 elif opt['warn'] == 2:
663 elif opt['warn'] == 2:
663 raise KeyError,e
664 raise KeyError,e
664 else:
665 else:
665 raise ValueError,'Warning level must be 0,1 or 2'
666 raise ValueError,'Warning level must be 0,1 or 2'
666
667
667 return dict
668 return dict
668
669
669 #----------------------------------------------------------------------------
670 #----------------------------------------------------------------------------
670 def flag_calls(func):
671 def flag_calls(func):
671 """Wrap a function to detect and flag when it gets called.
672 """Wrap a function to detect and flag when it gets called.
672
673
673 This is a decorator which takes a function and wraps it in a function with
674 This is a decorator which takes a function and wraps it in a function with
674 a 'called' attribute. wrapper.called is initialized to False.
675 a 'called' attribute. wrapper.called is initialized to False.
675
676
676 The wrapper.called attribute is set to False right before each call to the
677 The wrapper.called attribute is set to False right before each call to the
677 wrapped function, so if the call fails it remains False. After the call
678 wrapped function, so if the call fails it remains False. After the call
678 completes, wrapper.called is set to True and the output is returned.
679 completes, wrapper.called is set to True and the output is returned.
679
680
680 Testing for truth in wrapper.called allows you to determine if a call to
681 Testing for truth in wrapper.called allows you to determine if a call to
681 func() was attempted and succeeded."""
682 func() was attempted and succeeded."""
682
683
683 def wrapper(*args,**kw):
684 def wrapper(*args,**kw):
684 wrapper.called = False
685 wrapper.called = False
685 out = func(*args,**kw)
686 out = func(*args,**kw)
686 wrapper.called = True
687 wrapper.called = True
687 return out
688 return out
688
689
689 wrapper.called = False
690 wrapper.called = False
690 wrapper.__doc__ = func.__doc__
691 wrapper.__doc__ = func.__doc__
691 return wrapper
692 return wrapper
692
693
693 #----------------------------------------------------------------------------
694 #----------------------------------------------------------------------------
694 class HomeDirError(Error):
695 class HomeDirError(Error):
695 pass
696 pass
696
697
697 def get_home_dir():
698 def get_home_dir():
698 """Return the closest possible equivalent to a 'home' directory.
699 """Return the closest possible equivalent to a 'home' directory.
699
700
700 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
701 We first try $HOME. Absent that, on NT it's $HOMEDRIVE\$HOMEPATH.
701
702
702 Currently only Posix and NT are implemented, a HomeDirError exception is
703 Currently only Posix and NT are implemented, a HomeDirError exception is
703 raised for all other OSes. """
704 raised for all other OSes. """
704
705
705 isdir = os.path.isdir
706 isdir = os.path.isdir
706 env = os.environ
707 env = os.environ
707 try:
708 try:
708 homedir = env['HOME']
709 homedir = env['HOME']
709 if not isdir(homedir):
710 if not isdir(homedir):
710 # in case a user stuck some string which does NOT resolve to a
711 # in case a user stuck some string which does NOT resolve to a
711 # valid path, it's as good as if we hadn't foud it
712 # valid path, it's as good as if we hadn't foud it
712 raise KeyError
713 raise KeyError
713 return homedir
714 return homedir
714 except KeyError:
715 except KeyError:
715 if os.name == 'posix':
716 if os.name == 'posix':
716 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
717 raise HomeDirError,'undefined $HOME, IPython can not proceed.'
717 elif os.name == 'nt':
718 elif os.name == 'nt':
718 # For some strange reason, win9x returns 'nt' for os.name.
719 # For some strange reason, win9x returns 'nt' for os.name.
719 try:
720 try:
720 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
721 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
721 if not isdir(homedir):
722 if not isdir(homedir):
722 homedir = os.path.join(env['USERPROFILE'])
723 homedir = os.path.join(env['USERPROFILE'])
723 if not isdir(homedir):
724 if not isdir(homedir):
724 raise HomeDirError
725 raise HomeDirError
725 return homedir
726 return homedir
726 except:
727 except:
727 try:
728 try:
728 # Use the registry to get the 'My Documents' folder.
729 # Use the registry to get the 'My Documents' folder.
729 import _winreg as wreg
730 import _winreg as wreg
730 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
731 key = wreg.OpenKey(wreg.HKEY_CURRENT_USER,
731 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
732 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
732 homedir = wreg.QueryValueEx(key,'Personal')[0]
733 homedir = wreg.QueryValueEx(key,'Personal')[0]
733 key.Close()
734 key.Close()
734 return homedir
735 return homedir
735 except:
736 except:
736 return 'C:\\'
737 return 'C:\\'
737 elif os.name == 'dos':
738 elif os.name == 'dos':
738 # Desperate, may do absurd things in classic MacOS. May work under DOS.
739 # Desperate, may do absurd things in classic MacOS. May work under DOS.
739 return 'C:\\'
740 return 'C:\\'
740 else:
741 else:
741 raise HomeDirError,'support for your operating system not implemented.'
742 raise HomeDirError,'support for your operating system not implemented.'
742
743
743 #****************************************************************************
744 #****************************************************************************
744 # strings and text
745 # strings and text
745
746
746 class LSString(str):
747 class LSString(str):
747 """String derivative with a special access attributes.
748 """String derivative with a special access attributes.
748
749
749 These are normal strings, but with the special attributes:
750 These are normal strings, but with the special attributes:
750
751
751 .l (or .list) : value as list (split on newlines).
752 .l (or .list) : value as list (split on newlines).
752 .n (or .nlstr): original value (the string itself).
753 .n (or .nlstr): original value (the string itself).
753 .s (or .spstr): value as whitespace-separated string.
754 .s (or .spstr): value as whitespace-separated string.
754
755
755 Any values which require transformations are computed only once and
756 Any values which require transformations are computed only once and
756 cached.
757 cached.
757
758
758 Such strings are very useful to efficiently interact with the shell, which
759 Such strings are very useful to efficiently interact with the shell, which
759 typically only understands whitespace-separated options for commands."""
760 typically only understands whitespace-separated options for commands."""
760
761
761 def get_list(self):
762 def get_list(self):
762 try:
763 try:
763 return self.__list
764 return self.__list
764 except AttributeError:
765 except AttributeError:
765 self.__list = self.split('\n')
766 self.__list = self.split('\n')
766 return self.__list
767 return self.__list
767
768
768 l = list = property(get_list)
769 l = list = property(get_list)
769
770
770 def get_spstr(self):
771 def get_spstr(self):
771 try:
772 try:
772 return self.__spstr
773 return self.__spstr
773 except AttributeError:
774 except AttributeError:
774 self.__spstr = self.replace('\n',' ')
775 self.__spstr = self.replace('\n',' ')
775 return self.__spstr
776 return self.__spstr
776
777
777 s = spstr = property(get_spstr)
778 s = spstr = property(get_spstr)
778
779
779 def get_nlstr(self):
780 def get_nlstr(self):
780 return self
781 return self
781
782
782 n = nlstr = property(get_nlstr)
783 n = nlstr = property(get_nlstr)
783
784
784 class SList(list):
785 class SList(list):
785 """List derivative with a special access attributes.
786 """List derivative with a special access attributes.
786
787
787 These are normal lists, but with the special attributes:
788 These are normal lists, but with the special attributes:
788
789
789 .l (or .list) : value as list (the list itself).
790 .l (or .list) : value as list (the list itself).
790 .n (or .nlstr): value as a string, joined on newlines.
791 .n (or .nlstr): value as a string, joined on newlines.
791 .s (or .spstr): value as a string, joined on spaces.
792 .s (or .spstr): value as a string, joined on spaces.
792
793
793 Any values which require transformations are computed only once and
794 Any values which require transformations are computed only once and
794 cached."""
795 cached."""
795
796
796 def get_list(self):
797 def get_list(self):
797 return self
798 return self
798
799
799 l = list = property(get_list)
800 l = list = property(get_list)
800
801
801 def get_spstr(self):
802 def get_spstr(self):
802 try:
803 try:
803 return self.__spstr
804 return self.__spstr
804 except AttributeError:
805 except AttributeError:
805 self.__spstr = ' '.join(self)
806 self.__spstr = ' '.join(self)
806 return self.__spstr
807 return self.__spstr
807
808
808 s = spstr = property(get_spstr)
809 s = spstr = property(get_spstr)
809
810
810 def get_nlstr(self):
811 def get_nlstr(self):
811 try:
812 try:
812 return self.__nlstr
813 return self.__nlstr
813 except AttributeError:
814 except AttributeError:
814 self.__nlstr = '\n'.join(self)
815 self.__nlstr = '\n'.join(self)
815 return self.__nlstr
816 return self.__nlstr
816
817
817 n = nlstr = property(get_nlstr)
818 n = nlstr = property(get_nlstr)
818
819
819 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
820 def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
820 """Take multiple lines of input.
821 """Take multiple lines of input.
821
822
822 A list with each line of input as a separate element is returned when a
823 A list with each line of input as a separate element is returned when a
823 termination string is entered (defaults to a single '.'). Input can also
824 termination string is entered (defaults to a single '.'). Input can also
824 terminate via EOF (^D in Unix, ^Z-RET in Windows).
825 terminate via EOF (^D in Unix, ^Z-RET in Windows).
825
826
826 Lines of input which end in \\ are joined into single entries (and a
827 Lines of input which end in \\ are joined into single entries (and a
827 secondary continuation prompt is issued as long as the user terminates
828 secondary continuation prompt is issued as long as the user terminates
828 lines with \\). This allows entering very long strings which are still
829 lines with \\). This allows entering very long strings which are still
829 meant to be treated as single entities.
830 meant to be treated as single entities.
830 """
831 """
831
832
832 try:
833 try:
833 if header:
834 if header:
834 header += '\n'
835 header += '\n'
835 lines = [raw_input(header + ps1)]
836 lines = [raw_input(header + ps1)]
836 except EOFError:
837 except EOFError:
837 return []
838 return []
838 terminate = [terminate_str]
839 terminate = [terminate_str]
839 try:
840 try:
840 while lines[-1:] != terminate:
841 while lines[-1:] != terminate:
841 new_line = raw_input(ps1)
842 new_line = raw_input(ps1)
842 while new_line.endswith('\\'):
843 while new_line.endswith('\\'):
843 new_line = new_line[:-1] + raw_input(ps2)
844 new_line = new_line[:-1] + raw_input(ps2)
844 lines.append(new_line)
845 lines.append(new_line)
845
846
846 return lines[:-1] # don't return the termination command
847 return lines[:-1] # don't return the termination command
847 except EOFError:
848 except EOFError:
848 print
849 print
849 return lines
850 return lines
850
851
851 #----------------------------------------------------------------------------
852 #----------------------------------------------------------------------------
852 def raw_input_ext(prompt='', ps2='... '):
853 def raw_input_ext(prompt='', ps2='... '):
853 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
854 """Similar to raw_input(), but accepts extended lines if input ends with \\."""
854
855
855 line = raw_input(prompt)
856 line = raw_input(prompt)
856 while line.endswith('\\'):
857 while line.endswith('\\'):
857 line = line[:-1] + raw_input(ps2)
858 line = line[:-1] + raw_input(ps2)
858 return line
859 return line
859
860
860 #----------------------------------------------------------------------------
861 #----------------------------------------------------------------------------
861 def ask_yes_no(prompt,default=None):
862 def ask_yes_no(prompt,default=None):
862 """Asks a question and returns an integer 1/0 (y/n) answer.
863 """Asks a question and returns an integer 1/0 (y/n) answer.
863
864
864 If default is given (one of 'y','n'), it is used if the user input is
865 If default is given (one of 'y','n'), it is used if the user input is
865 empty. Otherwise the question is repeated until an answer is given.
866 empty. Otherwise the question is repeated until an answer is given.
866 If EOF occurs 20 times consecutively, the default answer is assumed,
867 If EOF occurs 20 times consecutively, the default answer is assumed,
867 or if there is no default, an exception is raised to prevent infinite
868 or if there is no default, an exception is raised to prevent infinite
868 loops.
869 loops.
869
870
870 Valid answers are: y/yes/n/no (match is not case sensitive)."""
871 Valid answers are: y/yes/n/no (match is not case sensitive)."""
871
872
872 answers = {'y':1,'n':0,'yes':1,'no':0}
873 answers = {'y':1,'n':0,'yes':1,'no':0}
873 ans = None
874 ans = None
874 eofs, max_eofs = 0, 20
875 eofs, max_eofs = 0, 20
875 while ans not in answers.keys():
876 while ans not in answers.keys():
876 try:
877 try:
877 ans = raw_input(prompt+' ').lower()
878 ans = raw_input(prompt+' ').lower()
878 if not ans: # response was an empty string
879 if not ans: # response was an empty string
879 ans = default
880 ans = default
880 eofs = 0
881 eofs = 0
881 except (EOFError,KeyboardInterrupt):
882 except (EOFError,KeyboardInterrupt):
882 eofs = eofs + 1
883 eofs = eofs + 1
883 if eofs >= max_eofs:
884 if eofs >= max_eofs:
884 if default in answers.keys():
885 if default in answers.keys():
885 ans = default
886 ans = default
886 else:
887 else:
887 raise
888 raise
888
889
889 return answers[ans]
890 return answers[ans]
890
891
891 #----------------------------------------------------------------------------
892 #----------------------------------------------------------------------------
892 class EvalDict:
893 class EvalDict:
893 """
894 """
894 Emulate a dict which evaluates its contents in the caller's frame.
895 Emulate a dict which evaluates its contents in the caller's frame.
895
896
896 Usage:
897 Usage:
897 >>>number = 19
898 >>>number = 19
898 >>>text = "python"
899 >>>text = "python"
899 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
900 >>>print "%(text.capitalize())s %(number/9.0).1f rules!" % EvalDict()
900 """
901 """
901
902
902 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
903 # This version is due to sismex01@hebmex.com on c.l.py, and is basically a
903 # modified (shorter) version of:
904 # modified (shorter) version of:
904 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
905 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66018 by
905 # Skip Montanaro (skip@pobox.com).
906 # Skip Montanaro (skip@pobox.com).
906
907
907 def __getitem__(self, name):
908 def __getitem__(self, name):
908 frame = sys._getframe(1)
909 frame = sys._getframe(1)
909 return eval(name, frame.f_globals, frame.f_locals)
910 return eval(name, frame.f_globals, frame.f_locals)
910
911
911 EvalString = EvalDict # for backwards compatibility
912 EvalString = EvalDict # for backwards compatibility
912 #----------------------------------------------------------------------------
913 #----------------------------------------------------------------------------
913 def qw(words,flat=0,sep=None,maxsplit=-1):
914 def qw(words,flat=0,sep=None,maxsplit=-1):
914 """Similar to Perl's qw() operator, but with some more options.
915 """Similar to Perl's qw() operator, but with some more options.
915
916
916 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
917 qw(words,flat=0,sep=' ',maxsplit=-1) -> words.split(sep,maxsplit)
917
918
918 words can also be a list itself, and with flat=1, the output will be
919 words can also be a list itself, and with flat=1, the output will be
919 recursively flattened. Examples:
920 recursively flattened. Examples:
920
921
921 >>> qw('1 2')
922 >>> qw('1 2')
922 ['1', '2']
923 ['1', '2']
923 >>> qw(['a b','1 2',['m n','p q']])
924 >>> qw(['a b','1 2',['m n','p q']])
924 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
925 [['a', 'b'], ['1', '2'], [['m', 'n'], ['p', 'q']]]
925 >>> qw(['a b','1 2',['m n','p q']],flat=1)
926 >>> qw(['a b','1 2',['m n','p q']],flat=1)
926 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
927 ['a', 'b', '1', '2', 'm', 'n', 'p', 'q'] """
927
928
928 if type(words) in StringTypes:
929 if type(words) in StringTypes:
929 return [word.strip() for word in words.split(sep,maxsplit)
930 return [word.strip() for word in words.split(sep,maxsplit)
930 if word and not word.isspace() ]
931 if word and not word.isspace() ]
931 if flat:
932 if flat:
932 return flatten(map(qw,words,[1]*len(words)))
933 return flatten(map(qw,words,[1]*len(words)))
933 return map(qw,words)
934 return map(qw,words)
934
935
935 #----------------------------------------------------------------------------
936 #----------------------------------------------------------------------------
936 def qwflat(words,sep=None,maxsplit=-1):
937 def qwflat(words,sep=None,maxsplit=-1):
937 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
938 """Calls qw(words) in flat mode. It's just a convenient shorthand."""
938 return qw(words,1,sep,maxsplit)
939 return qw(words,1,sep,maxsplit)
939
940
940 #-----------------------------------------------------------------------------
941 #-----------------------------------------------------------------------------
941 def list_strings(arg):
942 def list_strings(arg):
942 """Always return a list of strings, given a string or list of strings
943 """Always return a list of strings, given a string or list of strings
943 as input."""
944 as input."""
944
945
945 if type(arg) in StringTypes: return [arg]
946 if type(arg) in StringTypes: return [arg]
946 else: return arg
947 else: return arg
947
948
948 #----------------------------------------------------------------------------
949 #----------------------------------------------------------------------------
949 def grep(pat,list,case=1):
950 def grep(pat,list,case=1):
950 """Simple minded grep-like function.
951 """Simple minded grep-like function.
951 grep(pat,list) returns occurrences of pat in list, None on failure.
952 grep(pat,list) returns occurrences of pat in list, None on failure.
952
953
953 It only does simple string matching, with no support for regexps. Use the
954 It only does simple string matching, with no support for regexps. Use the
954 option case=0 for case-insensitive matching."""
955 option case=0 for case-insensitive matching."""
955
956
956 # This is pretty crude. At least it should implement copying only references
957 # This is pretty crude. At least it should implement copying only references
957 # to the original data in case it's big. Now it copies the data for output.
958 # to the original data in case it's big. Now it copies the data for output.
958 out=[]
959 out=[]
959 if case:
960 if case:
960 for term in list:
961 for term in list:
961 if term.find(pat)>-1: out.append(term)
962 if term.find(pat)>-1: out.append(term)
962 else:
963 else:
963 lpat=pat.lower()
964 lpat=pat.lower()
964 for term in list:
965 for term in list:
965 if term.lower().find(lpat)>-1: out.append(term)
966 if term.lower().find(lpat)>-1: out.append(term)
966
967
967 if len(out): return out
968 if len(out): return out
968 else: return None
969 else: return None
969
970
970 #----------------------------------------------------------------------------
971 #----------------------------------------------------------------------------
971 def dgrep(pat,*opts):
972 def dgrep(pat,*opts):
972 """Return grep() on dir()+dir(__builtins__).
973 """Return grep() on dir()+dir(__builtins__).
973
974
974 A very common use of grep() when working interactively."""
975 A very common use of grep() when working interactively."""
975
976
976 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
977 return grep(pat,dir(__main__)+dir(__main__.__builtins__),*opts)
977
978
978 #----------------------------------------------------------------------------
979 #----------------------------------------------------------------------------
979 def idgrep(pat):
980 def idgrep(pat):
980 """Case-insensitive dgrep()"""
981 """Case-insensitive dgrep()"""
981
982
982 return dgrep(pat,0)
983 return dgrep(pat,0)
983
984
984 #----------------------------------------------------------------------------
985 #----------------------------------------------------------------------------
985 def igrep(pat,list):
986 def igrep(pat,list):
986 """Synonym for case-insensitive grep."""
987 """Synonym for case-insensitive grep."""
987
988
988 return grep(pat,list,case=0)
989 return grep(pat,list,case=0)
989
990
990 #----------------------------------------------------------------------------
991 #----------------------------------------------------------------------------
991 def indent(str,nspaces=4,ntabs=0):
992 def indent(str,nspaces=4,ntabs=0):
992 """Indent a string a given number of spaces or tabstops.
993 """Indent a string a given number of spaces or tabstops.
993
994
994 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
995 indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
995 """
996 """
996 if str is None:
997 if str is None:
997 return
998 return
998 ind = '\t'*ntabs+' '*nspaces
999 ind = '\t'*ntabs+' '*nspaces
999 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1000 outstr = '%s%s' % (ind,str.replace(os.linesep,os.linesep+ind))
1000 if outstr.endswith(os.linesep+ind):
1001 if outstr.endswith(os.linesep+ind):
1001 return outstr[:-len(ind)]
1002 return outstr[:-len(ind)]
1002 else:
1003 else:
1003 return outstr
1004 return outstr
1004
1005
1005 #-----------------------------------------------------------------------------
1006 #-----------------------------------------------------------------------------
1006 def native_line_ends(filename,backup=1):
1007 def native_line_ends(filename,backup=1):
1007 """Convert (in-place) a file to line-ends native to the current OS.
1008 """Convert (in-place) a file to line-ends native to the current OS.
1008
1009
1009 If the optional backup argument is given as false, no backup of the
1010 If the optional backup argument is given as false, no backup of the
1010 original file is left. """
1011 original file is left. """
1011
1012
1012 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1013 backup_suffixes = {'posix':'~','dos':'.bak','nt':'.bak','mac':'.bak'}
1013
1014
1014 bak_filename = filename + backup_suffixes[os.name]
1015 bak_filename = filename + backup_suffixes[os.name]
1015
1016
1016 original = open(filename).read()
1017 original = open(filename).read()
1017 shutil.copy2(filename,bak_filename)
1018 shutil.copy2(filename,bak_filename)
1018 try:
1019 try:
1019 new = open(filename,'wb')
1020 new = open(filename,'wb')
1020 new.write(os.linesep.join(original.splitlines()))
1021 new.write(os.linesep.join(original.splitlines()))
1021 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1022 new.write(os.linesep) # ALWAYS put an eol at the end of the file
1022 new.close()
1023 new.close()
1023 except:
1024 except:
1024 os.rename(bak_filename,filename)
1025 os.rename(bak_filename,filename)
1025 if not backup:
1026 if not backup:
1026 try:
1027 try:
1027 os.remove(bak_filename)
1028 os.remove(bak_filename)
1028 except:
1029 except:
1029 pass
1030 pass
1030
1031
1031 #----------------------------------------------------------------------------
1032 #----------------------------------------------------------------------------
1032 def get_pager_cmd(pager_cmd = None):
1033 def get_pager_cmd(pager_cmd = None):
1033 """Return a pager command.
1034 """Return a pager command.
1034
1035
1035 Makes some attempts at finding an OS-correct one."""
1036 Makes some attempts at finding an OS-correct one."""
1036
1037
1037 if os.name == 'posix':
1038 if os.name == 'posix':
1038 default_pager_cmd = 'less -r' # -r for color control sequences
1039 default_pager_cmd = 'less -r' # -r for color control sequences
1039 elif os.name in ['nt','dos']:
1040 elif os.name in ['nt','dos']:
1040 default_pager_cmd = 'type'
1041 default_pager_cmd = 'type'
1041
1042
1042 if pager_cmd is None:
1043 if pager_cmd is None:
1043 try:
1044 try:
1044 pager_cmd = os.environ['PAGER']
1045 pager_cmd = os.environ['PAGER']
1045 except:
1046 except:
1046 pager_cmd = default_pager_cmd
1047 pager_cmd = default_pager_cmd
1047 return pager_cmd
1048 return pager_cmd
1048
1049
1049 #-----------------------------------------------------------------------------
1050 #-----------------------------------------------------------------------------
1050 def get_pager_start(pager,start):
1051 def get_pager_start(pager,start):
1051 """Return the string for paging files with an offset.
1052 """Return the string for paging files with an offset.
1052
1053
1053 This is the '+N' argument which less and more (under Unix) accept.
1054 This is the '+N' argument which less and more (under Unix) accept.
1054 """
1055 """
1055
1056
1056 if pager in ['less','more']:
1057 if pager in ['less','more']:
1057 if start:
1058 if start:
1058 start_string = '+' + str(start)
1059 start_string = '+' + str(start)
1059 else:
1060 else:
1060 start_string = ''
1061 start_string = ''
1061 else:
1062 else:
1062 start_string = ''
1063 start_string = ''
1063 return start_string
1064 return start_string
1064
1065
1065 #----------------------------------------------------------------------------
1066 #----------------------------------------------------------------------------
1066 def page_dumb(strng,start=0,screen_lines=25):
1067 def page_dumb(strng,start=0,screen_lines=25):
1067 """Very dumb 'pager' in Python, for when nothing else works.
1068 """Very dumb 'pager' in Python, for when nothing else works.
1068
1069
1069 Only moves forward, same interface as page(), except for pager_cmd and
1070 Only moves forward, same interface as page(), except for pager_cmd and
1070 mode."""
1071 mode."""
1071
1072
1072 out_ln = strng.splitlines()[start:]
1073 out_ln = strng.splitlines()[start:]
1073 screens = chop(out_ln,screen_lines-1)
1074 screens = chop(out_ln,screen_lines-1)
1074 if len(screens) == 1:
1075 if len(screens) == 1:
1075 print >>Term.cout, os.linesep.join(screens[0])
1076 print >>Term.cout, os.linesep.join(screens[0])
1076 else:
1077 else:
1077 for scr in screens[0:-1]:
1078 for scr in screens[0:-1]:
1078 print >>Term.cout, os.linesep.join(scr)
1079 print >>Term.cout, os.linesep.join(scr)
1079 ans = raw_input('---Return to continue, q to quit--- ')
1080 ans = raw_input('---Return to continue, q to quit--- ')
1080 if ans.lower().startswith('q'):
1081 if ans.lower().startswith('q'):
1081 return
1082 return
1082 print >>Term.cout, os.linesep.join(screens[-1])
1083 print >>Term.cout, os.linesep.join(screens[-1])
1083
1084
1084 #----------------------------------------------------------------------------
1085 #----------------------------------------------------------------------------
1085 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1086 def page(strng,start=0,screen_lines=0,pager_cmd = None):
1086 """Print a string, piping through a pager after a certain length.
1087 """Print a string, piping through a pager after a certain length.
1087
1088
1088 The screen_lines parameter specifies the number of *usable* lines of your
1089 The screen_lines parameter specifies the number of *usable* lines of your
1089 terminal screen (total lines minus lines you need to reserve to show other
1090 terminal screen (total lines minus lines you need to reserve to show other
1090 information).
1091 information).
1091
1092
1092 If you set screen_lines to a number <=0, page() will try to auto-determine
1093 If you set screen_lines to a number <=0, page() will try to auto-determine
1093 your screen size and will only use up to (screen_size+screen_lines) for
1094 your screen size and will only use up to (screen_size+screen_lines) for
1094 printing, paging after that. That is, if you want auto-detection but need
1095 printing, paging after that. That is, if you want auto-detection but need
1095 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1096 to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for
1096 auto-detection without any lines reserved simply use screen_lines = 0.
1097 auto-detection without any lines reserved simply use screen_lines = 0.
1097
1098
1098 If a string won't fit in the allowed lines, it is sent through the
1099 If a string won't fit in the allowed lines, it is sent through the
1099 specified pager command. If none given, look for PAGER in the environment,
1100 specified pager command. If none given, look for PAGER in the environment,
1100 and ultimately default to less.
1101 and ultimately default to less.
1101
1102
1102 If no system pager works, the string is sent through a 'dumb pager'
1103 If no system pager works, the string is sent through a 'dumb pager'
1103 written in python, very simplistic.
1104 written in python, very simplistic.
1104 """
1105 """
1105
1106
1106 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1107 # Ugly kludge, but calling curses.initscr() flat out crashes in emacs
1107 TERM = os.environ.get('TERM','dumb')
1108 TERM = os.environ.get('TERM','dumb')
1108 if TERM in ['dumb','emacs'] and os.name != 'nt':
1109 if TERM in ['dumb','emacs'] and os.name != 'nt':
1109 print strng
1110 print strng
1110 return
1111 return
1111 # chop off the topmost part of the string we don't want to see
1112 # chop off the topmost part of the string we don't want to see
1112 str_lines = strng.split(os.linesep)[start:]
1113 str_lines = strng.split(os.linesep)[start:]
1113 str_toprint = os.linesep.join(str_lines)
1114 str_toprint = os.linesep.join(str_lines)
1114 num_newlines = len(str_lines)
1115 num_newlines = len(str_lines)
1115 len_str = len(str_toprint)
1116 len_str = len(str_toprint)
1116
1117
1117 # Dumb heuristics to guesstimate number of on-screen lines the string
1118 # Dumb heuristics to guesstimate number of on-screen lines the string
1118 # takes. Very basic, but good enough for docstrings in reasonable
1119 # takes. Very basic, but good enough for docstrings in reasonable
1119 # terminals. If someone later feels like refining it, it's not hard.
1120 # terminals. If someone later feels like refining it, it's not hard.
1120 numlines = max(num_newlines,int(len_str/80)+1)
1121 numlines = max(num_newlines,int(len_str/80)+1)
1121
1122
1122 screen_lines_def = 25 # default value if we can't auto-determine
1123 screen_lines_def = 25 # default value if we can't auto-determine
1123
1124
1124 # auto-determine screen size
1125 # auto-determine screen size
1125 if screen_lines <= 0:
1126 if screen_lines <= 0:
1126 if TERM=='xterm':
1127 if TERM=='xterm':
1127 try:
1128 try:
1128 import curses
1129 import curses
1129 if hasattr(curses,'initscr'):
1130 if hasattr(curses,'initscr'):
1130 use_curses = 1
1131 use_curses = 1
1131 else:
1132 else:
1132 use_curses = 0
1133 use_curses = 0
1133 except ImportError:
1134 except ImportError:
1134 use_curses = 0
1135 use_curses = 0
1135 else:
1136 else:
1136 # curses causes problems on many terminals other than xterm.
1137 # curses causes problems on many terminals other than xterm.
1137 use_curses = 0
1138 use_curses = 0
1138 if use_curses:
1139 if use_curses:
1139 scr = curses.initscr()
1140 scr = curses.initscr()
1140 screen_lines_real,screen_cols = scr.getmaxyx()
1141 screen_lines_real,screen_cols = scr.getmaxyx()
1141 curses.endwin()
1142 curses.endwin()
1142 screen_lines += screen_lines_real
1143 screen_lines += screen_lines_real
1143 #print '***Screen size:',screen_lines_real,'lines x',\
1144 #print '***Screen size:',screen_lines_real,'lines x',\
1144 #screen_cols,'columns.' # dbg
1145 #screen_cols,'columns.' # dbg
1145 else:
1146 else:
1146 screen_lines += screen_lines_def
1147 screen_lines += screen_lines_def
1147
1148
1148 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1149 #print 'numlines',numlines,'screenlines',screen_lines # dbg
1149 if numlines <= screen_lines :
1150 if numlines <= screen_lines :
1150 #print '*** normal print' # dbg
1151 #print '*** normal print' # dbg
1151 print >>Term.cout, str_toprint
1152 print >>Term.cout, str_toprint
1152 else:
1153 else:
1153 # Try to open pager and default to internal one if that fails.
1154 # Try to open pager and default to internal one if that fails.
1154 # All failure modes are tagged as 'retval=1', to match the return
1155 # All failure modes are tagged as 'retval=1', to match the return
1155 # value of a failed system command. If any intermediate attempt
1156 # value of a failed system command. If any intermediate attempt
1156 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1157 # sets retval to 1, at the end we resort to our own page_dumb() pager.
1157 pager_cmd = get_pager_cmd(pager_cmd)
1158 pager_cmd = get_pager_cmd(pager_cmd)
1158 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1159 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1159 if os.name == 'nt':
1160 if os.name == 'nt':
1160 if pager_cmd.startswith('type'):
1161 if pager_cmd.startswith('type'):
1161 # The default WinXP 'type' command is failing on complex strings.
1162 # The default WinXP 'type' command is failing on complex strings.
1162 retval = 1
1163 retval = 1
1163 else:
1164 else:
1164 tmpname = tempfile.mktemp('.txt')
1165 tmpname = tempfile.mktemp('.txt')
1165 tmpfile = file(tmpname,'wt')
1166 tmpfile = file(tmpname,'wt')
1166 tmpfile.write(strng)
1167 tmpfile.write(strng)
1167 tmpfile.close()
1168 tmpfile.close()
1168 cmd = "%s < %s" % (pager_cmd,tmpname)
1169 cmd = "%s < %s" % (pager_cmd,tmpname)
1169 if os.system(cmd):
1170 if os.system(cmd):
1170 retval = 1
1171 retval = 1
1171 else:
1172 else:
1172 retval = None
1173 retval = None
1173 os.remove(tmpname)
1174 os.remove(tmpname)
1174 else:
1175 else:
1175 try:
1176 try:
1176 retval = None
1177 retval = None
1177 # if I use popen4, things hang. No idea why.
1178 # if I use popen4, things hang. No idea why.
1178 #pager,shell_out = os.popen4(pager_cmd)
1179 #pager,shell_out = os.popen4(pager_cmd)
1179 pager = os.popen(pager_cmd,'w')
1180 pager = os.popen(pager_cmd,'w')
1180 pager.write(strng)
1181 pager.write(strng)
1181 pager.close()
1182 pager.close()
1182 retval = pager.close() # success returns None
1183 retval = pager.close() # success returns None
1183 except IOError,msg: # broken pipe when user quits
1184 except IOError,msg: # broken pipe when user quits
1184 if msg.args == (32,'Broken pipe'):
1185 if msg.args == (32,'Broken pipe'):
1185 retval = None
1186 retval = None
1186 else:
1187 else:
1187 retval = 1
1188 retval = 1
1188 except OSError:
1189 except OSError:
1189 # Other strange problems, sometimes seen in Win2k/cygwin
1190 # Other strange problems, sometimes seen in Win2k/cygwin
1190 retval = 1
1191 retval = 1
1191 if retval is not None:
1192 if retval is not None:
1192 page_dumb(strng,screen_lines=screen_lines)
1193 page_dumb(strng,screen_lines=screen_lines)
1193
1194
1194 #----------------------------------------------------------------------------
1195 #----------------------------------------------------------------------------
1195 def page_file(fname,start = 0, pager_cmd = None):
1196 def page_file(fname,start = 0, pager_cmd = None):
1196 """Page a file, using an optional pager command and starting line.
1197 """Page a file, using an optional pager command and starting line.
1197 """
1198 """
1198
1199
1199 pager_cmd = get_pager_cmd(pager_cmd)
1200 pager_cmd = get_pager_cmd(pager_cmd)
1200 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1201 pager_cmd += ' ' + get_pager_start(pager_cmd,start)
1201
1202
1202 try:
1203 try:
1203 if os.environ['TERM'] in ['emacs','dumb']:
1204 if os.environ['TERM'] in ['emacs','dumb']:
1204 raise EnvironmentError
1205 raise EnvironmentError
1205 xsys(pager_cmd + ' ' + fname)
1206 xsys(pager_cmd + ' ' + fname)
1206 except:
1207 except:
1207 try:
1208 try:
1208 if start > 0:
1209 if start > 0:
1209 start -= 1
1210 start -= 1
1210 page(open(fname).read(),start)
1211 page(open(fname).read(),start)
1211 except:
1212 except:
1212 print 'Unable to show file',`fname`
1213 print 'Unable to show file',`fname`
1213
1214
1214 #----------------------------------------------------------------------------
1215 #----------------------------------------------------------------------------
1215 def snip_print(str,width = 75,print_full = 0,header = ''):
1216 def snip_print(str,width = 75,print_full = 0,header = ''):
1216 """Print a string snipping the midsection to fit in width.
1217 """Print a string snipping the midsection to fit in width.
1217
1218
1218 print_full: mode control:
1219 print_full: mode control:
1219 - 0: only snip long strings
1220 - 0: only snip long strings
1220 - 1: send to page() directly.
1221 - 1: send to page() directly.
1221 - 2: snip long strings and ask for full length viewing with page()
1222 - 2: snip long strings and ask for full length viewing with page()
1222 Return 1 if snipping was necessary, 0 otherwise."""
1223 Return 1 if snipping was necessary, 0 otherwise."""
1223
1224
1224 if print_full == 1:
1225 if print_full == 1:
1225 page(header+str)
1226 page(header+str)
1226 return 0
1227 return 0
1227
1228
1228 print header,
1229 print header,
1229 if len(str) < width:
1230 if len(str) < width:
1230 print str
1231 print str
1231 snip = 0
1232 snip = 0
1232 else:
1233 else:
1233 whalf = int((width -5)/2)
1234 whalf = int((width -5)/2)
1234 print str[:whalf] + ' <...> ' + str[-whalf:]
1235 print str[:whalf] + ' <...> ' + str[-whalf:]
1235 snip = 1
1236 snip = 1
1236 if snip and print_full == 2:
1237 if snip and print_full == 2:
1237 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1238 if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y':
1238 page(str)
1239 page(str)
1239 return snip
1240 return snip
1240
1241
1241 #****************************************************************************
1242 #****************************************************************************
1242 # lists, dicts and structures
1243 # lists, dicts and structures
1243
1244
1244 def belong(candidates,checklist):
1245 def belong(candidates,checklist):
1245 """Check whether a list of items appear in a given list of options.
1246 """Check whether a list of items appear in a given list of options.
1246
1247
1247 Returns a list of 1 and 0, one for each candidate given."""
1248 Returns a list of 1 and 0, one for each candidate given."""
1248
1249
1249 return [x in checklist for x in candidates]
1250 return [x in checklist for x in candidates]
1250
1251
1251 #----------------------------------------------------------------------------
1252 #----------------------------------------------------------------------------
1252 def uniq_stable(elems):
1253 def uniq_stable(elems):
1253 """uniq_stable(elems) -> list
1254 """uniq_stable(elems) -> list
1254
1255
1255 Return from an iterable, a list of all the unique elements in the input,
1256 Return from an iterable, a list of all the unique elements in the input,
1256 but maintaining the order in which they first appear.
1257 but maintaining the order in which they first appear.
1257
1258
1258 A naive solution to this problem which just makes a dictionary with the
1259 A naive solution to this problem which just makes a dictionary with the
1259 elements as keys fails to respect the stability condition, since
1260 elements as keys fails to respect the stability condition, since
1260 dictionaries are unsorted by nature.
1261 dictionaries are unsorted by nature.
1261
1262
1262 Note: All elements in the input must be valid dictionary keys for this
1263 Note: All elements in the input must be valid dictionary keys for this
1263 routine to work, as it internally uses a dictionary for efficiency
1264 routine to work, as it internally uses a dictionary for efficiency
1264 reasons."""
1265 reasons."""
1265
1266
1266 unique = []
1267 unique = []
1267 unique_dict = {}
1268 unique_dict = {}
1268 for nn in elems:
1269 for nn in elems:
1269 if nn not in unique_dict:
1270 if nn not in unique_dict:
1270 unique.append(nn)
1271 unique.append(nn)
1271 unique_dict[nn] = None
1272 unique_dict[nn] = None
1272 return unique
1273 return unique
1273
1274
1274 #----------------------------------------------------------------------------
1275 #----------------------------------------------------------------------------
1275 class NLprinter:
1276 class NLprinter:
1276 """Print an arbitrarily nested list, indicating index numbers.
1277 """Print an arbitrarily nested list, indicating index numbers.
1277
1278
1278 An instance of this class called nlprint is available and callable as a
1279 An instance of this class called nlprint is available and callable as a
1279 function.
1280 function.
1280
1281
1281 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1282 nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent'
1282 and using 'sep' to separate the index from the value. """
1283 and using 'sep' to separate the index from the value. """
1283
1284
1284 def __init__(self):
1285 def __init__(self):
1285 self.depth = 0
1286 self.depth = 0
1286
1287
1287 def __call__(self,lst,pos='',**kw):
1288 def __call__(self,lst,pos='',**kw):
1288 """Prints the nested list numbering levels."""
1289 """Prints the nested list numbering levels."""
1289 kw.setdefault('indent',' ')
1290 kw.setdefault('indent',' ')
1290 kw.setdefault('sep',': ')
1291 kw.setdefault('sep',': ')
1291 kw.setdefault('start',0)
1292 kw.setdefault('start',0)
1292 kw.setdefault('stop',len(lst))
1293 kw.setdefault('stop',len(lst))
1293 # we need to remove start and stop from kw so they don't propagate
1294 # we need to remove start and stop from kw so they don't propagate
1294 # into a recursive call for a nested list.
1295 # into a recursive call for a nested list.
1295 start = kw['start']; del kw['start']
1296 start = kw['start']; del kw['start']
1296 stop = kw['stop']; del kw['stop']
1297 stop = kw['stop']; del kw['stop']
1297 if self.depth == 0 and 'header' in kw.keys():
1298 if self.depth == 0 and 'header' in kw.keys():
1298 print kw['header']
1299 print kw['header']
1299
1300
1300 for idx in range(start,stop):
1301 for idx in range(start,stop):
1301 elem = lst[idx]
1302 elem = lst[idx]
1302 if type(elem)==type([]):
1303 if type(elem)==type([]):
1303 self.depth += 1
1304 self.depth += 1
1304 self.__call__(elem,itpl('$pos$idx,'),**kw)
1305 self.__call__(elem,itpl('$pos$idx,'),**kw)
1305 self.depth -= 1
1306 self.depth -= 1
1306 else:
1307 else:
1307 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1308 printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem')
1308
1309
1309 nlprint = NLprinter()
1310 nlprint = NLprinter()
1310 #----------------------------------------------------------------------------
1311 #----------------------------------------------------------------------------
1311 def all_belong(candidates,checklist):
1312 def all_belong(candidates,checklist):
1312 """Check whether a list of items ALL appear in a given list of options.
1313 """Check whether a list of items ALL appear in a given list of options.
1313
1314
1314 Returns a single 1 or 0 value."""
1315 Returns a single 1 or 0 value."""
1315
1316
1316 return 1-(0 in [x in checklist for x in candidates])
1317 return 1-(0 in [x in checklist for x in candidates])
1317
1318
1318 #----------------------------------------------------------------------------
1319 #----------------------------------------------------------------------------
1319 def sort_compare(lst1,lst2,inplace = 1):
1320 def sort_compare(lst1,lst2,inplace = 1):
1320 """Sort and compare two lists.
1321 """Sort and compare two lists.
1321
1322
1322 By default it does it in place, thus modifying the lists. Use inplace = 0
1323 By default it does it in place, thus modifying the lists. Use inplace = 0
1323 to avoid that (at the cost of temporary copy creation)."""
1324 to avoid that (at the cost of temporary copy creation)."""
1324 if not inplace:
1325 if not inplace:
1325 lst1 = lst1[:]
1326 lst1 = lst1[:]
1326 lst2 = lst2[:]
1327 lst2 = lst2[:]
1327 lst1.sort(); lst2.sort()
1328 lst1.sort(); lst2.sort()
1328 return lst1 == lst2
1329 return lst1 == lst2
1329
1330
1330 #----------------------------------------------------------------------------
1331 #----------------------------------------------------------------------------
1331 def mkdict(**kwargs):
1332 def mkdict(**kwargs):
1332 """Return a dict from a keyword list.
1333 """Return a dict from a keyword list.
1333
1334
1334 It's just syntactic sugar for making ditcionary creation more convenient:
1335 It's just syntactic sugar for making ditcionary creation more convenient:
1335 # the standard way
1336 # the standard way
1336 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1337 >>>data = { 'red' : 1, 'green' : 2, 'blue' : 3 }
1337 # a cleaner way
1338 # a cleaner way
1338 >>>data = dict(red=1, green=2, blue=3)
1339 >>>data = dict(red=1, green=2, blue=3)
1339
1340
1340 If you need more than this, look at the Struct() class."""
1341 If you need more than this, look at the Struct() class."""
1341
1342
1342 return kwargs
1343 return kwargs
1343
1344
1344 #----------------------------------------------------------------------------
1345 #----------------------------------------------------------------------------
1345 def list2dict(lst):
1346 def list2dict(lst):
1346 """Takes a list of (key,value) pairs and turns it into a dict."""
1347 """Takes a list of (key,value) pairs and turns it into a dict."""
1347
1348
1348 dic = {}
1349 dic = {}
1349 for k,v in lst: dic[k] = v
1350 for k,v in lst: dic[k] = v
1350 return dic
1351 return dic
1351
1352
1352 #----------------------------------------------------------------------------
1353 #----------------------------------------------------------------------------
1353 def list2dict2(lst,default=''):
1354 def list2dict2(lst,default=''):
1354 """Takes a list and turns it into a dict.
1355 """Takes a list and turns it into a dict.
1355 Much slower than list2dict, but more versatile. This version can take
1356 Much slower than list2dict, but more versatile. This version can take
1356 lists with sublists of arbitrary length (including sclars)."""
1357 lists with sublists of arbitrary length (including sclars)."""
1357
1358
1358 dic = {}
1359 dic = {}
1359 for elem in lst:
1360 for elem in lst:
1360 if type(elem) in (types.ListType,types.TupleType):
1361 if type(elem) in (types.ListType,types.TupleType):
1361 size = len(elem)
1362 size = len(elem)
1362 if size == 0:
1363 if size == 0:
1363 pass
1364 pass
1364 elif size == 1:
1365 elif size == 1:
1365 dic[elem] = default
1366 dic[elem] = default
1366 else:
1367 else:
1367 k,v = elem[0], elem[1:]
1368 k,v = elem[0], elem[1:]
1368 if len(v) == 1: v = v[0]
1369 if len(v) == 1: v = v[0]
1369 dic[k] = v
1370 dic[k] = v
1370 else:
1371 else:
1371 dic[elem] = default
1372 dic[elem] = default
1372 return dic
1373 return dic
1373
1374
1374 #----------------------------------------------------------------------------
1375 #----------------------------------------------------------------------------
1375 def flatten(seq):
1376 def flatten(seq):
1376 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1377 """Flatten a list of lists (NOT recursive, only works for 2d lists)."""
1377
1378
1378 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1379 # bug in python??? (YES. Fixed in 2.2, let's leave the kludgy fix in).
1379
1380
1380 # if the x=0 isn't made, a *global* variable x is left over after calling
1381 # if the x=0 isn't made, a *global* variable x is left over after calling
1381 # this function, with the value of the last element in the return
1382 # this function, with the value of the last element in the return
1382 # list. This does seem like a bug big time to me.
1383 # list. This does seem like a bug big time to me.
1383
1384
1384 # the problem is fixed with the x=0, which seems to force the creation of
1385 # the problem is fixed with the x=0, which seems to force the creation of
1385 # a local name
1386 # a local name
1386
1387
1387 x = 0
1388 x = 0
1388 return [x for subseq in seq for x in subseq]
1389 return [x for subseq in seq for x in subseq]
1389
1390
1390 #----------------------------------------------------------------------------
1391 #----------------------------------------------------------------------------
1391 def get_slice(seq,start=0,stop=None,step=1):
1392 def get_slice(seq,start=0,stop=None,step=1):
1392 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1393 """Get a slice of a sequence with variable step. Specify start,stop,step."""
1393 if stop == None:
1394 if stop == None:
1394 stop = len(seq)
1395 stop = len(seq)
1395 item = lambda i: seq[i]
1396 item = lambda i: seq[i]
1396 return map(item,xrange(start,stop,step))
1397 return map(item,xrange(start,stop,step))
1397
1398
1398 #----------------------------------------------------------------------------
1399 #----------------------------------------------------------------------------
1399 def chop(seq,size):
1400 def chop(seq,size):
1400 """Chop a sequence into chunks of the given size."""
1401 """Chop a sequence into chunks of the given size."""
1401 chunk = lambda i: seq[i:i+size]
1402 chunk = lambda i: seq[i:i+size]
1402 return map(chunk,xrange(0,len(seq),size))
1403 return map(chunk,xrange(0,len(seq),size))
1403
1404
1404 #----------------------------------------------------------------------------
1405 #----------------------------------------------------------------------------
1405 def with(object, **args):
1406 def with(object, **args):
1406 """Set multiple attributes for an object, similar to Pascal's with.
1407 """Set multiple attributes for an object, similar to Pascal's with.
1407
1408
1408 Example:
1409 Example:
1409 with(jim,
1410 with(jim,
1410 born = 1960,
1411 born = 1960,
1411 haircolour = 'Brown',
1412 haircolour = 'Brown',
1412 eyecolour = 'Green')
1413 eyecolour = 'Green')
1413
1414
1414 Credit: Greg Ewing, in
1415 Credit: Greg Ewing, in
1415 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1416 http://mail.python.org/pipermail/python-list/2001-May/040703.html"""
1416
1417
1417 object.__dict__.update(args)
1418 object.__dict__.update(args)
1418
1419
1419 #----------------------------------------------------------------------------
1420 #----------------------------------------------------------------------------
1420 def setattr_list(obj,alist,nspace = None):
1421 def setattr_list(obj,alist,nspace = None):
1421 """Set a list of attributes for an object taken from a namespace.
1422 """Set a list of attributes for an object taken from a namespace.
1422
1423
1423 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1424 setattr_list(obj,alist,nspace) -> sets in obj all the attributes listed in
1424 alist with their values taken from nspace, which must be a dict (something
1425 alist with their values taken from nspace, which must be a dict (something
1425 like locals() will often do) If nspace isn't given, locals() of the
1426 like locals() will often do) If nspace isn't given, locals() of the
1426 *caller* is used, so in most cases you can omit it.
1427 *caller* is used, so in most cases you can omit it.
1427
1428
1428 Note that alist can be given as a string, which will be automatically
1429 Note that alist can be given as a string, which will be automatically
1429 split into a list on whitespace. If given as a list, it must be a list of
1430 split into a list on whitespace. If given as a list, it must be a list of
1430 *strings* (the variable names themselves), not of variables."""
1431 *strings* (the variable names themselves), not of variables."""
1431
1432
1432 # this grabs the local variables from the *previous* call frame -- that is
1433 # this grabs the local variables from the *previous* call frame -- that is
1433 # the locals from the function that called setattr_list().
1434 # the locals from the function that called setattr_list().
1434 # - snipped from weave.inline()
1435 # - snipped from weave.inline()
1435 if nspace is None:
1436 if nspace is None:
1436 call_frame = sys._getframe().f_back
1437 call_frame = sys._getframe().f_back
1437 nspace = call_frame.f_locals
1438 nspace = call_frame.f_locals
1438
1439
1439 if type(alist) in StringTypes:
1440 if type(alist) in StringTypes:
1440 alist = alist.split()
1441 alist = alist.split()
1441 for attr in alist:
1442 for attr in alist:
1442 val = eval(attr,nspace)
1443 val = eval(attr,nspace)
1443 setattr(obj,attr,val)
1444 setattr(obj,attr,val)
1444
1445
1445 #----------------------------------------------------------------------------
1446 #----------------------------------------------------------------------------
1446 def getattr_list(obj,alist,*args):
1447 def getattr_list(obj,alist,*args):
1447 """getattr_list(obj,alist[, default]) -> attribute list.
1448 """getattr_list(obj,alist[, default]) -> attribute list.
1448
1449
1449 Get a list of named attributes for an object. When a default argument is
1450 Get a list of named attributes for an object. When a default argument is
1450 given, it is returned when the attribute doesn't exist; without it, an
1451 given, it is returned when the attribute doesn't exist; without it, an
1451 exception is raised in that case.
1452 exception is raised in that case.
1452
1453
1453 Note that alist can be given as a string, which will be automatically
1454 Note that alist can be given as a string, which will be automatically
1454 split into a list on whitespace. If given as a list, it must be a list of
1455 split into a list on whitespace. If given as a list, it must be a list of
1455 *strings* (the variable names themselves), not of variables."""
1456 *strings* (the variable names themselves), not of variables."""
1456
1457
1457 if type(alist) in StringTypes:
1458 if type(alist) in StringTypes:
1458 alist = alist.split()
1459 alist = alist.split()
1459 if args:
1460 if args:
1460 if len(args)==1:
1461 if len(args)==1:
1461 default = args[0]
1462 default = args[0]
1462 return map(lambda attr: getattr(obj,attr,default),alist)
1463 return map(lambda attr: getattr(obj,attr,default),alist)
1463 else:
1464 else:
1464 raise ValueError,'getattr_list() takes only one optional argument'
1465 raise ValueError,'getattr_list() takes only one optional argument'
1465 else:
1466 else:
1466 return map(lambda attr: getattr(obj,attr),alist)
1467 return map(lambda attr: getattr(obj,attr),alist)
1467
1468
1468 #----------------------------------------------------------------------------
1469 #----------------------------------------------------------------------------
1469 def map_method(method,object_list,*argseq,**kw):
1470 def map_method(method,object_list,*argseq,**kw):
1470 """map_method(method,object_list,*args,**kw) -> list
1471 """map_method(method,object_list,*args,**kw) -> list
1471
1472
1472 Return a list of the results of applying the methods to the items of the
1473 Return a list of the results of applying the methods to the items of the
1473 argument sequence(s). If more than one sequence is given, the method is
1474 argument sequence(s). If more than one sequence is given, the method is
1474 called with an argument list consisting of the corresponding item of each
1475 called with an argument list consisting of the corresponding item of each
1475 sequence. All sequences must be of the same length.
1476 sequence. All sequences must be of the same length.
1476
1477
1477 Keyword arguments are passed verbatim to all objects called.
1478 Keyword arguments are passed verbatim to all objects called.
1478
1479
1479 This is Python code, so it's not nearly as fast as the builtin map()."""
1480 This is Python code, so it's not nearly as fast as the builtin map()."""
1480
1481
1481 out_list = []
1482 out_list = []
1482 idx = 0
1483 idx = 0
1483 for object in object_list:
1484 for object in object_list:
1484 try:
1485 try:
1485 handler = getattr(object, method)
1486 handler = getattr(object, method)
1486 except AttributeError:
1487 except AttributeError:
1487 out_list.append(None)
1488 out_list.append(None)
1488 else:
1489 else:
1489 if argseq:
1490 if argseq:
1490 args = map(lambda lst:lst[idx],argseq)
1491 args = map(lambda lst:lst[idx],argseq)
1491 #print 'ob',object,'hand',handler,'ar',args # dbg
1492 #print 'ob',object,'hand',handler,'ar',args # dbg
1492 out_list.append(handler(args,**kw))
1493 out_list.append(handler(args,**kw))
1493 else:
1494 else:
1494 out_list.append(handler(**kw))
1495 out_list.append(handler(**kw))
1495 idx += 1
1496 idx += 1
1496 return out_list
1497 return out_list
1497
1498
1498 #----------------------------------------------------------------------------
1499 #----------------------------------------------------------------------------
1499 # Proposed popitem() extension, written as a method
1500 # Proposed popitem() extension, written as a method
1500
1501
1501 class NotGiven: pass
1502 class NotGiven: pass
1502
1503
1503 def popkey(dct,key,default=NotGiven):
1504 def popkey(dct,key,default=NotGiven):
1504 """Return dct[key] and delete dct[key].
1505 """Return dct[key] and delete dct[key].
1505
1506
1506 If default is given, return it if dct[key] doesn't exist, otherwise raise
1507 If default is given, return it if dct[key] doesn't exist, otherwise raise
1507 KeyError. """
1508 KeyError. """
1508
1509
1509 try:
1510 try:
1510 val = dct[key]
1511 val = dct[key]
1511 except KeyError:
1512 except KeyError:
1512 if default is NotGiven:
1513 if default is NotGiven:
1513 raise
1514 raise
1514 else:
1515 else:
1515 return default
1516 return default
1516 else:
1517 else:
1517 del dct[key]
1518 del dct[key]
1518 return val
1519 return val
1519 #*************************** end of file <genutils.py> **********************
1520 #*************************** end of file <genutils.py> **********************
1520
1521
@@ -1,1999 +1,2004 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 638 2005-07-18 03:01:41Z fperez $
9 $Id: iplib.py 703 2005-08-16 17:34:44Z 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-2004 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2004 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, much of that class has been copied
20 # Python standard library. Over time, much 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. The Python License (sec. 2) allows for this, but it's always
22 # subclassing. The Python License (sec. 2) allows for this, but it's always
23 # nice to acknowledge credit where credit is due.
23 # nice to acknowledge credit where credit is due.
24 #*****************************************************************************
24 #*****************************************************************************
25
25
26 #****************************************************************************
26 #****************************************************************************
27 # Modules and globals
27 # Modules and globals
28
28
29 from __future__ import generators # for 2.2 backwards-compatibility
29 from __future__ import generators # for 2.2 backwards-compatibility
30
30
31 from IPython import Release
31 from IPython import Release
32 __author__ = '%s <%s>\n%s <%s>' % \
32 __author__ = '%s <%s>\n%s <%s>' % \
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
34 __license__ = Release.license
34 __license__ = Release.license
35 __version__ = Release.version
35 __version__ = Release.version
36
36
37 # Python standard modules
37 # Python standard modules
38 import __main__
38 import __main__
39 import __builtin__
39 import __builtin__
40 import exceptions
40 import exceptions
41 import keyword
41 import keyword
42 import new
42 import new
43 import os, sys, shutil
43 import os, sys, shutil
44 import code, glob, types, re
44 import code, glob, types, re
45 import string, StringIO
45 import string, StringIO
46 import inspect, pydoc
46 import inspect, pydoc
47 import bdb, pdb
47 import bdb, pdb
48 import UserList # don't subclass list so this works with Python2.1
48 import UserList # don't subclass list so this works with Python2.1
49 from pprint import pprint, pformat
49 from pprint import pprint, pformat
50 import cPickle as pickle
50 import cPickle as pickle
51 import traceback
51 import traceback
52
52
53 # IPython's own modules
53 # IPython's own modules
54 import IPython
54 import IPython
55 from IPython import OInspect,PyColorize,ultraTB
55 from IPython import OInspect,PyColorize,ultraTB
56 from IPython.ultraTB import ColorScheme,ColorSchemeTable # too long names
56 from IPython.ultraTB import ColorScheme,ColorSchemeTable # too long names
57 from IPython.Logger import Logger
57 from IPython.Logger import Logger
58 from IPython.Magic import Magic,magic2python,shlex_split
58 from IPython.Magic import Magic,magic2python,shlex_split
59 from IPython.usage import cmd_line_usage,interactive_usage
59 from IPython.usage import cmd_line_usage,interactive_usage
60 from IPython.Struct import Struct
60 from IPython.Struct import Struct
61 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
61 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
62 from IPython.FakeModule import FakeModule
62 from IPython.FakeModule import FakeModule
63 from IPython.background_jobs import BackgroundJobManager
63 from IPython.background_jobs import BackgroundJobManager
64 from IPython.genutils import *
64 from IPython.genutils import *
65
65
66 # Global pointer to the running
66 # Global pointer to the running
67
67
68 # store the builtin raw_input globally, and use this always, in case user code
68 # store the builtin raw_input globally, and use this always, in case user code
69 # overwrites it (like wx.py.PyShell does)
69 # overwrites it (like wx.py.PyShell does)
70 raw_input_original = raw_input
70 raw_input_original = raw_input
71
71
72 #****************************************************************************
72 #****************************************************************************
73 # Some utility function definitions
73 # Some utility function definitions
74
74
75 class Bunch: pass
75 class Bunch: pass
76
76
77 def esc_quotes(strng):
77 def esc_quotes(strng):
78 """Return the input string with single and double quotes escaped out"""
78 """Return the input string with single and double quotes escaped out"""
79
79
80 return strng.replace('"','\\"').replace("'","\\'")
80 return strng.replace('"','\\"').replace("'","\\'")
81
81
82 def import_fail_info(mod_name,fns=None):
82 def import_fail_info(mod_name,fns=None):
83 """Inform load failure for a module."""
83 """Inform load failure for a module."""
84
84
85 if fns == None:
85 if fns == None:
86 warn("Loading of %s failed.\n" % (mod_name,))
86 warn("Loading of %s failed.\n" % (mod_name,))
87 else:
87 else:
88 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
88 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
89
89
90 def qw_lol(indata):
90 def qw_lol(indata):
91 """qw_lol('a b') -> [['a','b']],
91 """qw_lol('a b') -> [['a','b']],
92 otherwise it's just a call to qw().
92 otherwise it's just a call to qw().
93
93
94 We need this to make sure the modules_some keys *always* end up as a
94 We need this to make sure the modules_some keys *always* end up as a
95 list of lists."""
95 list of lists."""
96
96
97 if type(indata) in StringTypes:
97 if type(indata) in StringTypes:
98 return [qw(indata)]
98 return [qw(indata)]
99 else:
99 else:
100 return qw(indata)
100 return qw(indata)
101
101
102 def ipmagic(arg_s):
102 def ipmagic(arg_s):
103 """Call a magic function by name.
103 """Call a magic function by name.
104
104
105 Input: a string containing the name of the magic function to call and any
105 Input: a string containing the name of the magic function to call and any
106 additional arguments to be passed to the magic.
106 additional arguments to be passed to the magic.
107
107
108 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
108 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
109 prompt:
109 prompt:
110
110
111 In[1]: %name -opt foo bar
111 In[1]: %name -opt foo bar
112
112
113 To call a magic without arguments, simply use ipmagic('name').
113 To call a magic without arguments, simply use ipmagic('name').
114
114
115 This provides a proper Python function to call IPython's magics in any
115 This provides a proper Python function to call IPython's magics in any
116 valid Python code you can type at the interpreter, including loops and
116 valid Python code you can type at the interpreter, including loops and
117 compound statements. It is added by IPython to the Python builtin
117 compound statements. It is added by IPython to the Python builtin
118 namespace upon initialization."""
118 namespace upon initialization."""
119
119
120 args = arg_s.split(' ',1)
120 args = arg_s.split(' ',1)
121 magic_name = args[0]
121 magic_name = args[0]
122 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
122 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
123 magic_name = magic_name[1:]
123 magic_name = magic_name[1:]
124 try:
124 try:
125 magic_args = args[1]
125 magic_args = args[1]
126 except IndexError:
126 except IndexError:
127 magic_args = ''
127 magic_args = ''
128 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
128 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
129 if fn is None:
129 if fn is None:
130 error("Magic function `%s` not found." % magic_name)
130 error("Magic function `%s` not found." % magic_name)
131 else:
131 else:
132 magic_args = __IPYTHON__.var_expand(magic_args)
132 magic_args = __IPYTHON__.var_expand(magic_args)
133 return fn(magic_args)
133 return fn(magic_args)
134
134
135 def ipalias(arg_s):
135 def ipalias(arg_s):
136 """Call an alias by name.
136 """Call an alias by name.
137
137
138 Input: a string containing the name of the alias to call and any
138 Input: a string containing the name of the alias to call and any
139 additional arguments to be passed to the magic.
139 additional arguments to be passed to the magic.
140
140
141 ipalias('name -opt foo bar') is equivalent to typing at the ipython
141 ipalias('name -opt foo bar') is equivalent to typing at the ipython
142 prompt:
142 prompt:
143
143
144 In[1]: name -opt foo bar
144 In[1]: name -opt foo bar
145
145
146 To call an alias without arguments, simply use ipalias('name').
146 To call an alias without arguments, simply use ipalias('name').
147
147
148 This provides a proper Python function to call IPython's aliases in any
148 This provides a proper Python function to call IPython's aliases in any
149 valid Python code you can type at the interpreter, including loops and
149 valid Python code you can type at the interpreter, including loops and
150 compound statements. It is added by IPython to the Python builtin
150 compound statements. It is added by IPython to the Python builtin
151 namespace upon initialization."""
151 namespace upon initialization."""
152
152
153 args = arg_s.split(' ',1)
153 args = arg_s.split(' ',1)
154 alias_name = args[0]
154 alias_name = args[0]
155 try:
155 try:
156 alias_args = args[1]
156 alias_args = args[1]
157 except IndexError:
157 except IndexError:
158 alias_args = ''
158 alias_args = ''
159 if alias_name in __IPYTHON__.alias_table:
159 if alias_name in __IPYTHON__.alias_table:
160 __IPYTHON__.call_alias(alias_name,alias_args)
160 __IPYTHON__.call_alias(alias_name,alias_args)
161 else:
161 else:
162 error("Alias `%s` not found." % alias_name)
162 error("Alias `%s` not found." % alias_name)
163
163
164 #-----------------------------------------------------------------------------
164 #-----------------------------------------------------------------------------
165 # Local use classes
165 # Local use classes
166 try:
166 try:
167 from IPython import FlexCompleter
167 from IPython import FlexCompleter
168
168
169 class MagicCompleter(FlexCompleter.Completer):
169 class MagicCompleter(FlexCompleter.Completer):
170 """Extension of the completer class to work on %-prefixed lines."""
170 """Extension of the completer class to work on %-prefixed lines."""
171
171
172 def __init__(self,shell,namespace=None,omit__names=0,alias_table=None):
172 def __init__(self,shell,namespace=None,omit__names=0,alias_table=None):
173 """MagicCompleter() -> completer
173 """MagicCompleter() -> completer
174
174
175 Return a completer object suitable for use by the readline library
175 Return a completer object suitable for use by the readline library
176 via readline.set_completer().
176 via readline.set_completer().
177
177
178 Inputs:
178 Inputs:
179
179
180 - shell: a pointer to the ipython shell itself. This is needed
180 - shell: a pointer to the ipython shell itself. This is needed
181 because this completer knows about magic functions, and those can
181 because this completer knows about magic functions, and those can
182 only be accessed via the ipython instance.
182 only be accessed via the ipython instance.
183
183
184 - namespace: an optional dict where completions are performed.
184 - namespace: an optional dict where completions are performed.
185
185
186 - The optional omit__names parameter sets the completer to omit the
186 - The optional omit__names parameter sets the completer to omit the
187 'magic' names (__magicname__) for python objects unless the text
187 'magic' names (__magicname__) for python objects unless the text
188 to be completed explicitly starts with one or more underscores.
188 to be completed explicitly starts with one or more underscores.
189
189
190 - If alias_table is supplied, it should be a dictionary of aliases
190 - If alias_table is supplied, it should be a dictionary of aliases
191 to complete. """
191 to complete. """
192
192
193 FlexCompleter.Completer.__init__(self,namespace)
193 FlexCompleter.Completer.__init__(self,namespace)
194 self.magic_prefix = shell.name+'.magic_'
194 self.magic_prefix = shell.name+'.magic_'
195 self.magic_escape = shell.ESC_MAGIC
195 self.magic_escape = shell.ESC_MAGIC
196 self.readline = FlexCompleter.readline
196 self.readline = FlexCompleter.readline
197 delims = self.readline.get_completer_delims()
197 delims = self.readline.get_completer_delims()
198 delims = delims.replace(self.magic_escape,'')
198 delims = delims.replace(self.magic_escape,'')
199 self.readline.set_completer_delims(delims)
199 self.readline.set_completer_delims(delims)
200 self.get_line_buffer = self.readline.get_line_buffer
200 self.get_line_buffer = self.readline.get_line_buffer
201 self.omit__names = omit__names
201 self.omit__names = omit__names
202 self.merge_completions = shell.rc.readline_merge_completions
202 self.merge_completions = shell.rc.readline_merge_completions
203
203
204 if alias_table is None:
204 if alias_table is None:
205 alias_table = {}
205 alias_table = {}
206 self.alias_table = alias_table
206 self.alias_table = alias_table
207 # Regexp to split filenames with spaces in them
207 # Regexp to split filenames with spaces in them
208 self.space_name_re = re.compile(r'([^\\] )')
208 self.space_name_re = re.compile(r'([^\\] )')
209 # Hold a local ref. to glob.glob for speed
209 # Hold a local ref. to glob.glob for speed
210 self.glob = glob.glob
210 self.glob = glob.glob
211 # Special handling of backslashes needed in win32 platforms
211 # Special handling of backslashes needed in win32 platforms
212 if sys.platform == "win32":
212 if sys.platform == "win32":
213 self.clean_glob = self._clean_glob_win32
213 self.clean_glob = self._clean_glob_win32
214 else:
214 else:
215 self.clean_glob = self._clean_glob
215 self.clean_glob = self._clean_glob
216 self.matchers = [self.python_matches,
216 self.matchers = [self.python_matches,
217 self.file_matches,
217 self.file_matches,
218 self.alias_matches,
218 self.alias_matches,
219 self.python_func_kw_matches]
219 self.python_func_kw_matches]
220
220
221 # Code contributed by Alex Schmolck, for ipython/emacs integration
221 # Code contributed by Alex Schmolck, for ipython/emacs integration
222 def all_completions(self, text):
222 def all_completions(self, text):
223 """Return all possible completions for the benefit of emacs."""
223 """Return all possible completions for the benefit of emacs."""
224
224
225 completions = []
225 completions = []
226 try:
226 try:
227 for i in xrange(sys.maxint):
227 for i in xrange(sys.maxint):
228 res = self.complete(text, i)
228 res = self.complete(text, i)
229
229
230 if not res: break
230 if not res: break
231
231
232 completions.append(res)
232 completions.append(res)
233 #XXX workaround for ``notDefined.<tab>``
233 #XXX workaround for ``notDefined.<tab>``
234 except NameError:
234 except NameError:
235 pass
235 pass
236 return completions
236 return completions
237 # /end Alex Schmolck code.
237 # /end Alex Schmolck code.
238
238
239 def _clean_glob(self,text):
239 def _clean_glob(self,text):
240 return self.glob("%s*" % text)
240 return self.glob("%s*" % text)
241
241
242 def _clean_glob_win32(self,text):
242 def _clean_glob_win32(self,text):
243 return [f.replace("\\","/")
243 return [f.replace("\\","/")
244 for f in self.glob("%s*" % text)]
244 for f in self.glob("%s*" % text)]
245
245
246 def file_matches(self, text):
246 def file_matches(self, text):
247 """Match filneames, expanding ~USER type strings.
247 """Match filneames, expanding ~USER type strings.
248
248
249 Most of the seemingly convoluted logic in this completer is an
249 Most of the seemingly convoluted logic in this completer is an
250 attempt to handle filenames with spaces in them. And yet it's not
250 attempt to handle filenames with spaces in them. And yet it's not
251 quite perfect, because Python's readline doesn't expose all of the
251 quite perfect, because Python's readline doesn't expose all of the
252 GNU readline details needed for this to be done correctly.
252 GNU readline details needed for this to be done correctly.
253
253
254 For a filename with a space in it, the printed completions will be
254 For a filename with a space in it, the printed completions will be
255 only the parts after what's already been typed (instead of the
255 only the parts after what's already been typed (instead of the
256 full completions, as is normally done). I don't think with the
256 full completions, as is normally done). I don't think with the
257 current (as of Python 2.3) Python readline it's possible to do
257 current (as of Python 2.3) Python readline it's possible to do
258 better."""
258 better."""
259
259
260 #print 'Completer->file_matches: <%s>' % text # dbg
260 #print 'Completer->file_matches: <%s>' % text # dbg
261
261
262 # chars that require escaping with backslash - i.e. chars
262 # chars that require escaping with backslash - i.e. chars
263 # that readline treats incorrectly as delimiters, but we
263 # that readline treats incorrectly as delimiters, but we
264 # don't want to treat as delimiters in filename matching
264 # don't want to treat as delimiters in filename matching
265 # when escaped with backslash
265 # when escaped with backslash
266
266
267 protectables = ' ()[]{}'
267 protectables = ' ()[]{}'
268
268
269 def protect_filename(s):
269 def protect_filename(s):
270 return "".join([(ch in protectables and '\\' + ch or ch)
270 return "".join([(ch in protectables and '\\' + ch or ch)
271 for ch in s])
271 for ch in s])
272
272
273 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
273 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
274 open_quotes = 0 # track strings with open quotes
274 open_quotes = 0 # track strings with open quotes
275 try:
275 try:
276 lsplit = shlex_split(lbuf)[-1]
276 lsplit = shlex_split(lbuf)[-1]
277 except ValueError:
277 except ValueError:
278 # typically an unmatched ", or backslash without escaped char.
278 # typically an unmatched ", or backslash without escaped char.
279 if lbuf.count('"')==1:
279 if lbuf.count('"')==1:
280 open_quotes = 1
280 open_quotes = 1
281 lsplit = lbuf.split('"')[-1]
281 lsplit = lbuf.split('"')[-1]
282 elif lbuf.count("'")==1:
282 elif lbuf.count("'")==1:
283 open_quotes = 1
283 open_quotes = 1
284 lsplit = lbuf.split("'")[-1]
284 lsplit = lbuf.split("'")[-1]
285 else:
285 else:
286 return None
286 return None
287 except IndexError:
287 except IndexError:
288 # tab pressed on empty line
288 # tab pressed on empty line
289 lsplit = ""
289 lsplit = ""
290
290
291 if lsplit != protect_filename(lsplit):
291 if lsplit != protect_filename(lsplit):
292 # if protectables are found, do matching on the whole escaped
292 # if protectables are found, do matching on the whole escaped
293 # name
293 # name
294 has_protectables = 1
294 has_protectables = 1
295 text0,text = text,lsplit
295 text0,text = text,lsplit
296 else:
296 else:
297 has_protectables = 0
297 has_protectables = 0
298 text = os.path.expanduser(text)
298 text = os.path.expanduser(text)
299
299
300 if text == "":
300 if text == "":
301 return [protect_filename(f) for f in self.glob("*")]
301 return [protect_filename(f) for f in self.glob("*")]
302
302
303 m0 = self.clean_glob(text.replace('\\',''))
303 m0 = self.clean_glob(text.replace('\\',''))
304 if has_protectables:
304 if has_protectables:
305 # If we had protectables, we need to revert our changes to the
305 # If we had protectables, we need to revert our changes to the
306 # beginning of filename so that we don't double-write the part
306 # beginning of filename so that we don't double-write the part
307 # of the filename we have so far
307 # of the filename we have so far
308 len_lsplit = len(lsplit)
308 len_lsplit = len(lsplit)
309 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
309 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
310 else:
310 else:
311 if open_quotes:
311 if open_quotes:
312 # if we have a string with an open quote, we don't need to
312 # if we have a string with an open quote, we don't need to
313 # protect the names at all (and we _shouldn't_, as it
313 # protect the names at all (and we _shouldn't_, as it
314 # would cause bugs when the filesystem call is made).
314 # would cause bugs when the filesystem call is made).
315 matches = m0
315 matches = m0
316 else:
316 else:
317 matches = [protect_filename(f) for f in m0]
317 matches = [protect_filename(f) for f in m0]
318 if len(matches) == 1 and os.path.isdir(matches[0]):
318 if len(matches) == 1 and os.path.isdir(matches[0]):
319 # Takes care of links to directories also. Use '/'
319 # Takes care of links to directories also. Use '/'
320 # explicitly, even under Windows, so that name completions
320 # explicitly, even under Windows, so that name completions
321 # don't end up escaped.
321 # don't end up escaped.
322 matches[0] += '/'
322 matches[0] += '/'
323 return matches
323 return matches
324
324
325 def alias_matches(self, text):
325 def alias_matches(self, text):
326 """Match internal system aliases"""
326 """Match internal system aliases"""
327 #print 'Completer->alias_matches:',text # dbg
327 #print 'Completer->alias_matches:',text # dbg
328 text = os.path.expanduser(text)
328 text = os.path.expanduser(text)
329 aliases = self.alias_table.keys()
329 aliases = self.alias_table.keys()
330 if text == "":
330 if text == "":
331 return aliases
331 return aliases
332 else:
332 else:
333 return [alias for alias in aliases if alias.startswith(text)]
333 return [alias for alias in aliases if alias.startswith(text)]
334
334
335 def python_matches(self,text):
335 def python_matches(self,text):
336 """Match attributes or global python names"""
336 """Match attributes or global python names"""
337 #print 'Completer->python_matches' # dbg
337 #print 'Completer->python_matches' # dbg
338 if "." in text:
338 if "." in text:
339 try:
339 try:
340 matches = self.attr_matches(text)
340 matches = self.attr_matches(text)
341 if text.endswith('.') and self.omit__names:
341 if text.endswith('.') and self.omit__names:
342 if self.omit__names == 1:
342 if self.omit__names == 1:
343 # true if txt is _not_ a __ name, false otherwise:
343 # true if txt is _not_ a __ name, false otherwise:
344 no__name = (lambda txt:
344 no__name = (lambda txt:
345 re.match(r'.*\.__.*?__',txt) is None)
345 re.match(r'.*\.__.*?__',txt) is None)
346 else:
346 else:
347 # true if txt is _not_ a _ name, false otherwise:
347 # true if txt is _not_ a _ name, false otherwise:
348 no__name = (lambda txt:
348 no__name = (lambda txt:
349 re.match(r'.*\._.*?',txt) is None)
349 re.match(r'.*\._.*?',txt) is None)
350 matches = filter(no__name, matches)
350 matches = filter(no__name, matches)
351 except NameError:
351 except NameError:
352 # catches <undefined attributes>.<tab>
352 # catches <undefined attributes>.<tab>
353 matches = []
353 matches = []
354 else:
354 else:
355 matches = self.global_matches(text)
355 matches = self.global_matches(text)
356 # this is so completion finds magics when automagic is on:
356 # this is so completion finds magics when automagic is on:
357 if matches == [] and not text.startswith(os.sep):
357 if matches == [] and not text.startswith(os.sep):
358 matches = self.attr_matches(self.magic_prefix+text)
358 matches = self.attr_matches(self.magic_prefix+text)
359 return matches
359 return matches
360
360
361 def _default_arguments(self, obj):
361 def _default_arguments(self, obj):
362 """Return the list of default arguments of obj if it is callable,
362 """Return the list of default arguments of obj if it is callable,
363 or empty list otherwise."""
363 or empty list otherwise."""
364
364
365 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
365 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
366 # for classes, check for __init__,__new__
366 # for classes, check for __init__,__new__
367 if inspect.isclass(obj):
367 if inspect.isclass(obj):
368 obj = (getattr(obj,'__init__',None) or
368 obj = (getattr(obj,'__init__',None) or
369 getattr(obj,'__new__',None))
369 getattr(obj,'__new__',None))
370 # for all others, check if they are __call__able
370 # for all others, check if they are __call__able
371 elif hasattr(obj, '__call__'):
371 elif hasattr(obj, '__call__'):
372 obj = obj.__call__
372 obj = obj.__call__
373 # XXX: is there a way to handle the builtins ?
373 # XXX: is there a way to handle the builtins ?
374 try:
374 try:
375 args,_,_1,defaults = inspect.getargspec(obj)
375 args,_,_1,defaults = inspect.getargspec(obj)
376 if defaults:
376 if defaults:
377 return args[-len(defaults):]
377 return args[-len(defaults):]
378 except TypeError: pass
378 except TypeError: pass
379 return []
379 return []
380
380
381 def python_func_kw_matches(self,text):
381 def python_func_kw_matches(self,text):
382 """Match named parameters (kwargs) of the last open function"""
382 """Match named parameters (kwargs) of the last open function"""
383
383
384 if "." in text: # a parameter cannot be dotted
384 if "." in text: # a parameter cannot be dotted
385 return []
385 return []
386 try: regexp = self.__funcParamsRegex
386 try: regexp = self.__funcParamsRegex
387 except AttributeError:
387 except AttributeError:
388 regexp = self.__funcParamsRegex = re.compile(r'''
388 regexp = self.__funcParamsRegex = re.compile(r'''
389 '.*?' | # single quoted strings or
389 '.*?' | # single quoted strings or
390 ".*?" | # double quoted strings or
390 ".*?" | # double quoted strings or
391 \w+ | # identifier
391 \w+ | # identifier
392 \S # other characters
392 \S # other characters
393 ''', re.VERBOSE | re.DOTALL)
393 ''', re.VERBOSE | re.DOTALL)
394 # 1. find the nearest identifier that comes before an unclosed
394 # 1. find the nearest identifier that comes before an unclosed
395 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
395 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
396 tokens = regexp.findall(self.get_line_buffer())
396 tokens = regexp.findall(self.get_line_buffer())
397 tokens.reverse()
397 tokens.reverse()
398 iterTokens = iter(tokens); openPar = 0
398 iterTokens = iter(tokens); openPar = 0
399 for token in iterTokens:
399 for token in iterTokens:
400 if token == ')':
400 if token == ')':
401 openPar -= 1
401 openPar -= 1
402 elif token == '(':
402 elif token == '(':
403 openPar += 1
403 openPar += 1
404 if openPar > 0:
404 if openPar > 0:
405 # found the last unclosed parenthesis
405 # found the last unclosed parenthesis
406 break
406 break
407 else:
407 else:
408 return []
408 return []
409 # 2. Concatenate any dotted names (e.g. "foo.bar" for "foo.bar(x, pa" )
409 # 2. Concatenate any dotted names (e.g. "foo.bar" for "foo.bar(x, pa" )
410 ids = []
410 ids = []
411 isId = re.compile(r'\w+$').match
411 isId = re.compile(r'\w+$').match
412 while True:
412 while True:
413 try:
413 try:
414 ids.append(iterTokens.next())
414 ids.append(iterTokens.next())
415 if not isId(ids[-1]):
415 if not isId(ids[-1]):
416 ids.pop(); break
416 ids.pop(); break
417 if not iterTokens.next() == '.':
417 if not iterTokens.next() == '.':
418 break
418 break
419 except StopIteration:
419 except StopIteration:
420 break
420 break
421 # lookup the candidate callable matches either using global_matches
421 # lookup the candidate callable matches either using global_matches
422 # or attr_matches for dotted names
422 # or attr_matches for dotted names
423 if len(ids) == 1:
423 if len(ids) == 1:
424 callableMatches = self.global_matches(ids[0])
424 callableMatches = self.global_matches(ids[0])
425 else:
425 else:
426 callableMatches = self.attr_matches('.'.join(ids[::-1]))
426 callableMatches = self.attr_matches('.'.join(ids[::-1]))
427 argMatches = []
427 argMatches = []
428 for callableMatch in callableMatches:
428 for callableMatch in callableMatches:
429 try: namedArgs = self._default_arguments(eval(callableMatch,
429 try: namedArgs = self._default_arguments(eval(callableMatch,
430 self.namespace))
430 self.namespace))
431 except: continue
431 except: continue
432 for namedArg in namedArgs:
432 for namedArg in namedArgs:
433 if namedArg.startswith(text):
433 if namedArg.startswith(text):
434 argMatches.append("%s=" %namedArg)
434 argMatches.append("%s=" %namedArg)
435 return argMatches
435 return argMatches
436
436
437 def complete(self, text, state):
437 def complete(self, text, state):
438 """Return the next possible completion for 'text'.
438 """Return the next possible completion for 'text'.
439
439
440 This is called successively with state == 0, 1, 2, ... until it
440 This is called successively with state == 0, 1, 2, ... until it
441 returns None. The completion should begin with 'text'. """
441 returns None. The completion should begin with 'text'. """
442
442
443 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
443 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
444 magic_escape = self.magic_escape
444 magic_escape = self.magic_escape
445 magic_prefix = self.magic_prefix
445 magic_prefix = self.magic_prefix
446
446
447 try:
447 try:
448 if text.startswith(magic_escape):
448 if text.startswith(magic_escape):
449 text = text.replace(magic_escape,magic_prefix)
449 text = text.replace(magic_escape,magic_prefix)
450 elif text.startswith('~'):
450 elif text.startswith('~'):
451 text = os.path.expanduser(text)
451 text = os.path.expanduser(text)
452 if state == 0:
452 if state == 0:
453 # Extend the list of completions with the results of each
453 # Extend the list of completions with the results of each
454 # matcher, so we return results to the user from all
454 # matcher, so we return results to the user from all
455 # namespaces.
455 # namespaces.
456 if self.merge_completions:
456 if self.merge_completions:
457 self.matches = []
457 self.matches = []
458 for matcher in self.matchers:
458 for matcher in self.matchers:
459 self.matches.extend(matcher(text))
459 self.matches.extend(matcher(text))
460 else:
460 else:
461 for matcher in self.matchers:
461 for matcher in self.matchers:
462 self.matches = matcher(text)
462 self.matches = matcher(text)
463 if self.matches:
463 if self.matches:
464 break
464 break
465
465
466 try:
466 try:
467 return self.matches[state].replace(magic_prefix,magic_escape)
467 return self.matches[state].replace(magic_prefix,magic_escape)
468 except IndexError:
468 except IndexError:
469 return None
469 return None
470 except:
470 except:
471 # If completion fails, don't annoy the user.
471 # If completion fails, don't annoy the user.
472 pass
472 pass
473
473
474 except ImportError:
474 except ImportError:
475 pass # no readline support
475 pass # no readline support
476
476
477 except KeyError:
477 except KeyError:
478 pass # Windows doesn't set TERM, it doesn't matter
478 pass # Windows doesn't set TERM, it doesn't matter
479
479
480
480
481 class InputList(UserList.UserList):
481 class InputList(UserList.UserList):
482 """Class to store user input.
482 """Class to store user input.
483
483
484 It's basically a list, but slices return a string instead of a list, thus
484 It's basically a list, but slices return a string instead of a list, thus
485 allowing things like (assuming 'In' is an instance):
485 allowing things like (assuming 'In' is an instance):
486
486
487 exec In[4:7]
487 exec In[4:7]
488
488
489 or
489 or
490
490
491 exec In[5:9] + In[14] + In[21:25]"""
491 exec In[5:9] + In[14] + In[21:25]"""
492
492
493 def __getslice__(self,i,j):
493 def __getslice__(self,i,j):
494 return ''.join(UserList.UserList.__getslice__(self,i,j))
494 return ''.join(UserList.UserList.__getslice__(self,i,j))
495
495
496 #****************************************************************************
496 #****************************************************************************
497 # Local use exceptions
497 # Local use exceptions
498 class SpaceInInput(exceptions.Exception):
498 class SpaceInInput(exceptions.Exception):
499 pass
499 pass
500
500
501 #****************************************************************************
501 #****************************************************************************
502 # Main IPython class
502 # Main IPython class
503
503
504 class InteractiveShell(code.InteractiveConsole, Logger, Magic):
504 class InteractiveShell(code.InteractiveConsole, Logger, Magic):
505 """An enhanced console for Python."""
505 """An enhanced console for Python."""
506
506
507 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
507 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
508 user_ns = None,banner2='',
508 user_ns = None,banner2='',
509 custom_exceptions=((),None)):
509 custom_exceptions=((),None)):
510
510
511 # Put a reference to self in builtins so that any form of embedded or
511 # Put a reference to self in builtins so that any form of embedded or
512 # imported code can test for being inside IPython.
512 # imported code can test for being inside IPython.
513 __builtin__.__IPYTHON__ = self
513 __builtin__.__IPYTHON__ = self
514
514
515 # And load into builtins ipmagic/ipalias as well
515 # And load into builtins ipmagic/ipalias as well
516 __builtin__.ipmagic = ipmagic
516 __builtin__.ipmagic = ipmagic
517 __builtin__.ipalias = ipalias
517 __builtin__.ipalias = ipalias
518
518
519 # Add to __builtin__ other parts of IPython's public API
519 # Add to __builtin__ other parts of IPython's public API
520 __builtin__.ip_set_hook = self.set_hook
520 __builtin__.ip_set_hook = self.set_hook
521
521
522 # Keep in the builtins a flag for when IPython is active. We set it
522 # Keep in the builtins a flag for when IPython is active. We set it
523 # with setdefault so that multiple nested IPythons don't clobber one
523 # with setdefault so that multiple nested IPythons don't clobber one
524 # another. Each will increase its value by one upon being activated,
524 # another. Each will increase its value by one upon being activated,
525 # which also gives us a way to determine the nesting level.
525 # which also gives us a way to determine the nesting level.
526 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
526 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
527
527
528 # Inform the user of ipython's fast exit magics.
528 # Inform the user of ipython's fast exit magics.
529 _exit = ' Use %Exit or %Quit to exit without confirmation.'
529 _exit = ' Use %Exit or %Quit to exit without confirmation.'
530 __builtin__.exit += _exit
530 __builtin__.exit += _exit
531 __builtin__.quit += _exit
531 __builtin__.quit += _exit
532
532
533 # Create the namespace where the user will operate:
533 # Create the namespace where the user will operate:
534
534
535 # FIXME. For some strange reason, __builtins__ is showing up at user
535 # FIXME. For some strange reason, __builtins__ is showing up at user
536 # level as a dict instead of a module. This is a manual fix, but I
536 # level as a dict instead of a module. This is a manual fix, but I
537 # should really track down where the problem is coming from. Alex
537 # should really track down where the problem is coming from. Alex
538 # Schmolck reported this problem first.
538 # Schmolck reported this problem first.
539
539
540 # A useful post by Alex Martelli on this topic:
540 # A useful post by Alex Martelli on this topic:
541 # Re: inconsistent value from __builtins__
541 # Re: inconsistent value from __builtins__
542 # Von: Alex Martelli <aleaxit@yahoo.com>
542 # Von: Alex Martelli <aleaxit@yahoo.com>
543 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
543 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
544 # Gruppen: comp.lang.python
544 # Gruppen: comp.lang.python
545 # Referenzen: 1
545 # Referenzen: 1
546
546
547 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
547 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
548 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
548 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
549 # > <type 'dict'>
549 # > <type 'dict'>
550 # > >>> print type(__builtins__)
550 # > >>> print type(__builtins__)
551 # > <type 'module'>
551 # > <type 'module'>
552 # > Is this difference in return value intentional?
552 # > Is this difference in return value intentional?
553
553
554 # Well, it's documented that '__builtins__' can be either a dictionary
554 # Well, it's documented that '__builtins__' can be either a dictionary
555 # or a module, and it's been that way for a long time. Whether it's
555 # or a module, and it's been that way for a long time. Whether it's
556 # intentional (or sensible), I don't know. In any case, the idea is that
556 # intentional (or sensible), I don't know. In any case, the idea is that
557 # if you need to access the built-in namespace directly, you should start
557 # if you need to access the built-in namespace directly, you should start
558 # with "import __builtin__" (note, no 's') which will definitely give you
558 # with "import __builtin__" (note, no 's') which will definitely give you
559 # a module. Yeah, it's somewhat confusing:-(.
559 # a module. Yeah, it's somewhat confusing:-(.
560
560
561 if user_ns is None:
561 if user_ns is None:
562 # Set __name__ to __main__ to better match the behavior of the
562 # Set __name__ to __main__ to better match the behavior of the
563 # normal interpreter.
563 # normal interpreter.
564 self.user_ns = {'__name__' :'__main__',
564 self.user_ns = {'__name__' :'__main__',
565 '__builtins__' : __builtin__,
565 '__builtins__' : __builtin__,
566 }
566 }
567 else:
567 else:
568 self.user_ns = user_ns
568 self.user_ns = user_ns
569
569
570 # The user namespace MUST have a pointer to the shell itself.
570 # The user namespace MUST have a pointer to the shell itself.
571 self.user_ns[name] = self
571 self.user_ns[name] = self
572
572
573 # We need to insert into sys.modules something that looks like a
573 # We need to insert into sys.modules something that looks like a
574 # module but which accesses the IPython namespace, for shelve and
574 # module but which accesses the IPython namespace, for shelve and
575 # pickle to work interactively. Normally they rely on getting
575 # pickle to work interactively. Normally they rely on getting
576 # everything out of __main__, but for embedding purposes each IPython
576 # everything out of __main__, but for embedding purposes each IPython
577 # instance has its own private namespace, so we can't go shoving
577 # instance has its own private namespace, so we can't go shoving
578 # everything into __main__.
578 # everything into __main__.
579
579
580 try:
580 try:
581 main_name = self.user_ns['__name__']
581 main_name = self.user_ns['__name__']
582 except KeyError:
582 except KeyError:
583 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
583 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
584 else:
584 else:
585 #print "pickle hack in place" # dbg
585 #print "pickle hack in place" # dbg
586 sys.modules[main_name] = FakeModule(self.user_ns)
586 sys.modules[main_name] = FakeModule(self.user_ns)
587
587
588 # List of input with multi-line handling.
588 # List of input with multi-line handling.
589 # Fill its zero entry, user counter starts at 1
589 # Fill its zero entry, user counter starts at 1
590 self.input_hist = InputList(['\n'])
590 self.input_hist = InputList(['\n'])
591
591
592 # list of visited directories
592 # list of visited directories
593 self.dir_hist = [os.getcwd()]
593 self.dir_hist = [os.getcwd()]
594
594
595 # dict of output history
595 # dict of output history
596 self.output_hist = {}
596 self.output_hist = {}
597
597
598 # dict of names to be treated as system aliases. Each entry in the
598 # dict of names to be treated as system aliases. Each entry in the
599 # alias table must be a 2-tuple of the form (N,name), where N is the
599 # alias table must be a 2-tuple of the form (N,name), where N is the
600 # number of positional arguments of the alias.
600 # number of positional arguments of the alias.
601 self.alias_table = {}
601 self.alias_table = {}
602
602
603 # dict of things NOT to alias (keywords and builtins)
603 # dict of things NOT to alias (keywords and builtins)
604 self.no_alias = {}
604 self.no_alias = {}
605 for key in keyword.kwlist:
605 for key in keyword.kwlist:
606 self.no_alias[key] = 1
606 self.no_alias[key] = 1
607 self.no_alias.update(__builtin__.__dict__)
607 self.no_alias.update(__builtin__.__dict__)
608
608
609 # make global variables for user access to these
609 # make global variables for user access to these
610 self.user_ns['_ih'] = self.input_hist
610 self.user_ns['_ih'] = self.input_hist
611 self.user_ns['_oh'] = self.output_hist
611 self.user_ns['_oh'] = self.output_hist
612 self.user_ns['_dh'] = self.dir_hist
612 self.user_ns['_dh'] = self.dir_hist
613
613
614 # user aliases to input and output histories
614 # user aliases to input and output histories
615 self.user_ns['In'] = self.input_hist
615 self.user_ns['In'] = self.input_hist
616 self.user_ns['Out'] = self.output_hist
616 self.user_ns['Out'] = self.output_hist
617
617
618 # Store the actual shell's name
618 # Store the actual shell's name
619 self.name = name
619 self.name = name
620
620
621 # Object variable to store code object waiting execution. This is
621 # Object variable to store code object waiting execution. This is
622 # used mainly by the multithreaded shells, but it can come in handy in
622 # used mainly by the multithreaded shells, but it can come in handy in
623 # other situations. No need to use a Queue here, since it's a single
623 # other situations. No need to use a Queue here, since it's a single
624 # item which gets cleared once run.
624 # item which gets cleared once run.
625 self.code_to_run = None
625 self.code_to_run = None
626 self.code_to_run_src = '' # corresponding source
627
626
628 # Job manager (for jobs run as background threads)
627 # Job manager (for jobs run as background threads)
629 self.jobs = BackgroundJobManager()
628 self.jobs = BackgroundJobManager()
630 # Put the job manager into builtins so it's always there.
629 # Put the job manager into builtins so it's always there.
631 __builtin__.jobs = self.jobs
630 __builtin__.jobs = self.jobs
632
631
633 # escapes for automatic behavior on the command line
632 # escapes for automatic behavior on the command line
634 self.ESC_SHELL = '!'
633 self.ESC_SHELL = '!'
635 self.ESC_HELP = '?'
634 self.ESC_HELP = '?'
636 self.ESC_MAGIC = '%'
635 self.ESC_MAGIC = '%'
637 self.ESC_QUOTE = ','
636 self.ESC_QUOTE = ','
638 self.ESC_QUOTE2 = ';'
637 self.ESC_QUOTE2 = ';'
639 self.ESC_PAREN = '/'
638 self.ESC_PAREN = '/'
640
639
641 # And their associated handlers
640 # And their associated handlers
642 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
641 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
643 self.ESC_QUOTE:self.handle_auto,
642 self.ESC_QUOTE:self.handle_auto,
644 self.ESC_QUOTE2:self.handle_auto,
643 self.ESC_QUOTE2:self.handle_auto,
645 self.ESC_MAGIC:self.handle_magic,
644 self.ESC_MAGIC:self.handle_magic,
646 self.ESC_HELP:self.handle_help,
645 self.ESC_HELP:self.handle_help,
647 self.ESC_SHELL:self.handle_shell_escape,
646 self.ESC_SHELL:self.handle_shell_escape,
648 }
647 }
649
648
650 # class initializations
649 # class initializations
651 code.InteractiveConsole.__init__(self,locals = self.user_ns)
650 code.InteractiveConsole.__init__(self,locals = self.user_ns)
652 Logger.__init__(self,log_ns = self.user_ns)
651 Logger.__init__(self,log_ns = self.user_ns)
653 Magic.__init__(self,self)
652 Magic.__init__(self,self)
654
653
655 # an ugly hack to get a pointer to the shell, so I can start writing
654 # an ugly hack to get a pointer to the shell, so I can start writing
656 # magic code via this pointer instead of the current mixin salad.
655 # magic code via this pointer instead of the current mixin salad.
657 Magic.set_shell(self,self)
656 Magic.set_shell(self,self)
658
657
659 # hooks holds pointers used for user-side customizations
658 # hooks holds pointers used for user-side customizations
660 self.hooks = Struct()
659 self.hooks = Struct()
661
660
662 # Set all default hooks, defined in the IPython.hooks module.
661 # Set all default hooks, defined in the IPython.hooks module.
663 hooks = IPython.hooks
662 hooks = IPython.hooks
664 for hook_name in hooks.__all__:
663 for hook_name in hooks.__all__:
665 self.set_hook(hook_name,getattr(hooks,hook_name))
664 self.set_hook(hook_name,getattr(hooks,hook_name))
666
665
667 # Flag to mark unconditional exit
666 # Flag to mark unconditional exit
668 self.exit_now = False
667 self.exit_now = False
669
668
670 self.usage_min = """\
669 self.usage_min = """\
671 An enhanced console for Python.
670 An enhanced console for Python.
672 Some of its features are:
671 Some of its features are:
673 - Readline support if the readline library is present.
672 - Readline support if the readline library is present.
674 - Tab completion in the local namespace.
673 - Tab completion in the local namespace.
675 - Logging of input, see command-line options.
674 - Logging of input, see command-line options.
676 - System shell escape via ! , eg !ls.
675 - System shell escape via ! , eg !ls.
677 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
676 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
678 - Keeps track of locally defined variables via %who, %whos.
677 - Keeps track of locally defined variables via %who, %whos.
679 - Show object information with a ? eg ?x or x? (use ?? for more info).
678 - Show object information with a ? eg ?x or x? (use ?? for more info).
680 """
679 """
681 if usage: self.usage = usage
680 if usage: self.usage = usage
682 else: self.usage = self.usage_min
681 else: self.usage = self.usage_min
683
682
684 # Storage
683 # Storage
685 self.rc = rc # This will hold all configuration information
684 self.rc = rc # This will hold all configuration information
686 self.inputcache = []
685 self.inputcache = []
687 self._boundcache = []
686 self._boundcache = []
688 self.pager = 'less'
687 self.pager = 'less'
689 # temporary files used for various purposes. Deleted at exit.
688 # temporary files used for various purposes. Deleted at exit.
690 self.tempfiles = []
689 self.tempfiles = []
691
690
692 # for pushd/popd management
691 # for pushd/popd management
693 try:
692 try:
694 self.home_dir = get_home_dir()
693 self.home_dir = get_home_dir()
695 except HomeDirError,msg:
694 except HomeDirError,msg:
696 fatal(msg)
695 fatal(msg)
697
696
698 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
697 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
699
698
700 # Functions to call the underlying shell.
699 # Functions to call the underlying shell.
701
700
702 # utility to expand user variables via Itpl
701 # utility to expand user variables via Itpl
703 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
702 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
704 self.user_ns))
703 self.user_ns))
705 # The first is similar to os.system, but it doesn't return a value,
704 # The first is similar to os.system, but it doesn't return a value,
706 # and it allows interpolation of variables in the user's namespace.
705 # and it allows interpolation of variables in the user's namespace.
707 self.system = lambda cmd: shell(self.var_expand(cmd),
706 self.system = lambda cmd: shell(self.var_expand(cmd),
708 header='IPython system call: ',
707 header='IPython system call: ',
709 verbose=self.rc.system_verbose)
708 verbose=self.rc.system_verbose)
710 # These are for getoutput and getoutputerror:
709 # These are for getoutput and getoutputerror:
711 self.getoutput = lambda cmd: \
710 self.getoutput = lambda cmd: \
712 getoutput(self.var_expand(cmd),
711 getoutput(self.var_expand(cmd),
713 header='IPython system call: ',
712 header='IPython system call: ',
714 verbose=self.rc.system_verbose)
713 verbose=self.rc.system_verbose)
715 self.getoutputerror = lambda cmd: \
714 self.getoutputerror = lambda cmd: \
716 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
715 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
717 self.user_ns)),
716 self.user_ns)),
718 header='IPython system call: ',
717 header='IPython system call: ',
719 verbose=self.rc.system_verbose)
718 verbose=self.rc.system_verbose)
720
719
721 # RegExp for splitting line contents into pre-char//first
720 # RegExp for splitting line contents into pre-char//first
722 # word-method//rest. For clarity, each group in on one line.
721 # word-method//rest. For clarity, each group in on one line.
723
722
724 # WARNING: update the regexp if the above escapes are changed, as they
723 # WARNING: update the regexp if the above escapes are changed, as they
725 # are hardwired in.
724 # are hardwired in.
726
725
727 # Don't get carried away with trying to make the autocalling catch too
726 # Don't get carried away with trying to make the autocalling catch too
728 # much: it's better to be conservative rather than to trigger hidden
727 # much: it's better to be conservative rather than to trigger hidden
729 # evals() somewhere and end up causing side effects.
728 # evals() somewhere and end up causing side effects.
730
729
731 self.line_split = re.compile(r'^([\s*,;/])'
730 self.line_split = re.compile(r'^([\s*,;/])'
732 r'([\?\w\.]+\w*\s*)'
731 r'([\?\w\.]+\w*\s*)'
733 r'(\(?.*$)')
732 r'(\(?.*$)')
734
733
735 # Original re, keep around for a while in case changes break something
734 # Original re, keep around for a while in case changes break something
736 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
735 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
737 # r'(\s*[\?\w\.]+\w*\s*)'
736 # r'(\s*[\?\w\.]+\w*\s*)'
738 # r'(\(?.*$)')
737 # r'(\(?.*$)')
739
738
740 # RegExp to identify potential function names
739 # RegExp to identify potential function names
741 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
740 self.re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
742 # RegExp to exclude strings with this start from autocalling
741 # RegExp to exclude strings with this start from autocalling
743 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
742 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
744 # try to catch also methods for stuff in lists/tuples/dicts: off
743 # try to catch also methods for stuff in lists/tuples/dicts: off
745 # (experimental). For this to work, the line_split regexp would need
744 # (experimental). For this to work, the line_split regexp would need
746 # to be modified so it wouldn't break things at '['. That line is
745 # to be modified so it wouldn't break things at '['. That line is
747 # nasty enough that I shouldn't change it until I can test it _well_.
746 # nasty enough that I shouldn't change it until I can test it _well_.
748 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
747 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
749
748
750 # keep track of where we started running (mainly for crash post-mortem)
749 # keep track of where we started running (mainly for crash post-mortem)
751 self.starting_dir = os.getcwd()
750 self.starting_dir = os.getcwd()
752
751
753 # Attributes for Logger mixin class, make defaults here
752 # Attributes for Logger mixin class, make defaults here
754 self._dolog = 0
753 self._dolog = 0
755 self.LOG = ''
754 self.LOG = ''
756 self.LOGDEF = '.InteractiveShell.log'
755 self.LOGDEF = '.InteractiveShell.log'
757 self.LOGMODE = 'over'
756 self.LOGMODE = 'over'
758 self.LOGHEAD = Itpl(
757 self.LOGHEAD = Itpl(
759 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
758 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
760 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
759 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
761 #log# opts = $self.rc.opts
760 #log# opts = $self.rc.opts
762 #log# args = $self.rc.args
761 #log# args = $self.rc.args
763 #log# It is safe to make manual edits below here.
762 #log# It is safe to make manual edits below here.
764 #log#-----------------------------------------------------------------------
763 #log#-----------------------------------------------------------------------
765 """)
764 """)
766 # Various switches which can be set
765 # Various switches which can be set
767 self.CACHELENGTH = 5000 # this is cheap, it's just text
766 self.CACHELENGTH = 5000 # this is cheap, it's just text
768 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
767 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
769 self.banner2 = banner2
768 self.banner2 = banner2
770
769
771 # TraceBack handlers:
770 # TraceBack handlers:
772 # Need two, one for syntax errors and one for other exceptions.
771 # Need two, one for syntax errors and one for other exceptions.
773 self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor')
772 self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor')
774 # This one is initialized with an offset, meaning we always want to
773 # This one is initialized with an offset, meaning we always want to
775 # remove the topmost item in the traceback, which is our own internal
774 # remove the topmost item in the traceback, which is our own internal
776 # code. Valid modes: ['Plain','Context','Verbose']
775 # code. Valid modes: ['Plain','Context','Verbose']
777 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
776 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
778 color_scheme='NoColor',
777 color_scheme='NoColor',
779 tb_offset = 1)
778 tb_offset = 1)
780 # and add any custom exception handlers the user may have specified
779 # and add any custom exception handlers the user may have specified
781 self.set_custom_exc(*custom_exceptions)
780 self.set_custom_exc(*custom_exceptions)
782
781
783 # Object inspector
782 # Object inspector
784 ins_colors = OInspect.InspectColors
783 ins_colors = OInspect.InspectColors
785 code_colors = PyColorize.ANSICodeColors
784 code_colors = PyColorize.ANSICodeColors
786 self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor')
785 self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor')
787 self.autoindent = 0
786 self.autoindent = 0
788
787
789 # Make some aliases automatically
788 # Make some aliases automatically
790 # Prepare list of shell aliases to auto-define
789 # Prepare list of shell aliases to auto-define
791 if os.name == 'posix':
790 if os.name == 'posix':
792 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
791 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
793 'mv mv -i','rm rm -i','cp cp -i',
792 'mv mv -i','rm rm -i','cp cp -i',
794 'cat cat','less less','clear clear',
793 'cat cat','less less','clear clear',
795 # a better ls
794 # a better ls
796 'ls ls -F',
795 'ls ls -F',
797 # long ls
796 # long ls
798 'll ls -lF',
797 'll ls -lF',
799 # color ls
798 # color ls
800 'lc ls -F -o --color',
799 'lc ls -F -o --color',
801 # ls normal files only
800 # ls normal files only
802 'lf ls -F -o --color %l | grep ^-',
801 'lf ls -F -o --color %l | grep ^-',
803 # ls symbolic links
802 # ls symbolic links
804 'lk ls -F -o --color %l | grep ^l',
803 'lk ls -F -o --color %l | grep ^l',
805 # directories or links to directories,
804 # directories or links to directories,
806 'ldir ls -F -o --color %l | grep /$',
805 'ldir ls -F -o --color %l | grep /$',
807 # things which are executable
806 # things which are executable
808 'lx ls -F -o --color %l | grep ^-..x',
807 'lx ls -F -o --color %l | grep ^-..x',
809 )
808 )
810 elif os.name in ['nt','dos']:
809 elif os.name in ['nt','dos']:
811 auto_alias = ('dir dir /on', 'ls dir /on',
810 auto_alias = ('dir dir /on', 'ls dir /on',
812 'ddir dir /ad /on', 'ldir dir /ad /on',
811 'ddir dir /ad /on', 'ldir dir /ad /on',
813 'mkdir mkdir','rmdir rmdir','echo echo',
812 'mkdir mkdir','rmdir rmdir','echo echo',
814 'ren ren','cls cls','copy copy')
813 'ren ren','cls cls','copy copy')
815 else:
814 else:
816 auto_alias = ()
815 auto_alias = ()
817 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
816 self.auto_alias = map(lambda s:s.split(None,1),auto_alias)
818 # Call the actual (public) initializer
817 # Call the actual (public) initializer
819 self.init_auto_alias()
818 self.init_auto_alias()
820 # end __init__
819 # end __init__
821
820
822 def set_hook(self,name,hook):
821 def set_hook(self,name,hook):
823 """set_hook(name,hook) -> sets an internal IPython hook.
822 """set_hook(name,hook) -> sets an internal IPython hook.
824
823
825 IPython exposes some of its internal API as user-modifiable hooks. By
824 IPython exposes some of its internal API as user-modifiable hooks. By
826 resetting one of these hooks, you can modify IPython's behavior to
825 resetting one of these hooks, you can modify IPython's behavior to
827 call at runtime your own routines."""
826 call at runtime your own routines."""
828
827
829 # At some point in the future, this should validate the hook before it
828 # At some point in the future, this should validate the hook before it
830 # accepts it. Probably at least check that the hook takes the number
829 # accepts it. Probably at least check that the hook takes the number
831 # of args it's supposed to.
830 # of args it's supposed to.
832 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
831 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
833
832
834 def set_custom_exc(self,exc_tuple,handler):
833 def set_custom_exc(self,exc_tuple,handler):
835 """set_custom_exc(exc_tuple,handler)
834 """set_custom_exc(exc_tuple,handler)
836
835
837 Set a custom exception handler, which will be called if any of the
836 Set a custom exception handler, which will be called if any of the
838 exceptions in exc_tuple occur in the mainloop (specifically, in the
837 exceptions in exc_tuple occur in the mainloop (specifically, in the
839 runcode() method.
838 runcode() method.
840
839
841 Inputs:
840 Inputs:
842
841
843 - exc_tuple: a *tuple* of valid exceptions to call the defined
842 - exc_tuple: a *tuple* of valid exceptions to call the defined
844 handler for. It is very important that you use a tuple, and NOT A
843 handler for. It is very important that you use a tuple, and NOT A
845 LIST here, because of the way Python's except statement works. If
844 LIST here, because of the way Python's except statement works. If
846 you only want to trap a single exception, use a singleton tuple:
845 you only want to trap a single exception, use a singleton tuple:
847
846
848 exc_tuple == (MyCustomException,)
847 exc_tuple == (MyCustomException,)
849
848
850 - handler: this must be defined as a function with the following
849 - handler: this must be defined as a function with the following
851 basic interface: def my_handler(self,etype,value,tb).
850 basic interface: def my_handler(self,etype,value,tb).
852
851
853 This will be made into an instance method (via new.instancemethod)
852 This will be made into an instance method (via new.instancemethod)
854 of IPython itself, and it will be called if any of the exceptions
853 of IPython itself, and it will be called if any of the exceptions
855 listed in the exc_tuple are caught. If the handler is None, an
854 listed in the exc_tuple are caught. If the handler is None, an
856 internal basic one is used, which just prints basic info.
855 internal basic one is used, which just prints basic info.
857
856
858 WARNING: by putting in your own exception handler into IPython's main
857 WARNING: by putting in your own exception handler into IPython's main
859 execution loop, you run a very good chance of nasty crashes. This
858 execution loop, you run a very good chance of nasty crashes. This
860 facility should only be used if you really know what you are doing."""
859 facility should only be used if you really know what you are doing."""
861
860
862 assert type(exc_tuple)==type(()) , \
861 assert type(exc_tuple)==type(()) , \
863 "The custom exceptions must be given AS A TUPLE."
862 "The custom exceptions must be given AS A TUPLE."
864
863
865 def dummy_handler(self,etype,value,tb):
864 def dummy_handler(self,etype,value,tb):
866 print '*** Simple custom exception handler ***'
865 print '*** Simple custom exception handler ***'
867 print 'Exception type :',etype
866 print 'Exception type :',etype
868 print 'Exception value:',value
867 print 'Exception value:',value
869 print 'Traceback :',tb
868 print 'Traceback :',tb
870 print 'Source code :',self.code_to_run_src
869 print 'Source code :','\n'.join(self.buffer)
871
870
872 if handler is None: handler = dummy_handler
871 if handler is None: handler = dummy_handler
873
872
874 self.CustomTB = new.instancemethod(handler,self,self.__class__)
873 self.CustomTB = new.instancemethod(handler,self,self.__class__)
875 self.custom_exceptions = exc_tuple
874 self.custom_exceptions = exc_tuple
876
875
877 def set_custom_completer(self,completer,pos=0):
876 def set_custom_completer(self,completer,pos=0):
878 """set_custom_completer(completer,pos=0)
877 """set_custom_completer(completer,pos=0)
879
878
880 Adds a new custom completer function.
879 Adds a new custom completer function.
881
880
882 The position argument (defaults to 0) is the index in the completers
881 The position argument (defaults to 0) is the index in the completers
883 list where you want the completer to be inserted."""
882 list where you want the completer to be inserted."""
884
883
885 newcomp = new.instancemethod(completer,self.Completer,
884 newcomp = new.instancemethod(completer,self.Completer,
886 self.Completer.__class__)
885 self.Completer.__class__)
887 self.Completer.matchers.insert(pos,newcomp)
886 self.Completer.matchers.insert(pos,newcomp)
888
887
889 def post_config_initialization(self):
888 def post_config_initialization(self):
890 """Post configuration init method
889 """Post configuration init method
891
890
892 This is called after the configuration files have been processed to
891 This is called after the configuration files have been processed to
893 'finalize' the initialization."""
892 'finalize' the initialization."""
894
893
895 # dynamic data that survives through sessions
894 # dynamic data that survives through sessions
896 # XXX make the filename a config option?
895 # XXX make the filename a config option?
897 persist_base = 'persist'
896 persist_base = 'persist'
898 if self.rc.profile:
897 if self.rc.profile:
899 persist_base += '_%s' % self.rc.profile
898 persist_base += '_%s' % self.rc.profile
900 self.persist_fname = os.path.join(self.rc.ipythondir,persist_base)
899 self.persist_fname = os.path.join(self.rc.ipythondir,persist_base)
901
900
902 try:
901 try:
903 self.persist = pickle.load(file(self.persist_fname))
902 self.persist = pickle.load(file(self.persist_fname))
904 except:
903 except:
905 self.persist = {}
904 self.persist = {}
906
905
907 def init_auto_alias(self):
906 def init_auto_alias(self):
908 """Define some aliases automatically.
907 """Define some aliases automatically.
909
908
910 These are ALL parameter-less aliases"""
909 These are ALL parameter-less aliases"""
911 for alias,cmd in self.auto_alias:
910 for alias,cmd in self.auto_alias:
912 self.alias_table[alias] = (0,cmd)
911 self.alias_table[alias] = (0,cmd)
913
912
914 def alias_table_validate(self,verbose=0):
913 def alias_table_validate(self,verbose=0):
915 """Update information about the alias table.
914 """Update information about the alias table.
916
915
917 In particular, make sure no Python keywords/builtins are in it."""
916 In particular, make sure no Python keywords/builtins are in it."""
918
917
919 no_alias = self.no_alias
918 no_alias = self.no_alias
920 for k in self.alias_table.keys():
919 for k in self.alias_table.keys():
921 if k in no_alias:
920 if k in no_alias:
922 del self.alias_table[k]
921 del self.alias_table[k]
923 if verbose:
922 if verbose:
924 print ("Deleting alias <%s>, it's a Python "
923 print ("Deleting alias <%s>, it's a Python "
925 "keyword or builtin." % k)
924 "keyword or builtin." % k)
926
925
927 def set_autoindent(self,value=None):
926 def set_autoindent(self,value=None):
928 """Set the autoindent flag, checking for readline support.
927 """Set the autoindent flag, checking for readline support.
929
928
930 If called with no arguments, it acts as a toggle."""
929 If called with no arguments, it acts as a toggle."""
931
930
932 if not self.has_readline:
931 if not self.has_readline:
933 if os.name == 'posix':
932 if os.name == 'posix':
934 warn("The auto-indent feature requires the readline library")
933 warn("The auto-indent feature requires the readline library")
935 self.autoindent = 0
934 self.autoindent = 0
936 return
935 return
937 if value is None:
936 if value is None:
938 self.autoindent = not self.autoindent
937 self.autoindent = not self.autoindent
939 else:
938 else:
940 self.autoindent = value
939 self.autoindent = value
941
940
942 def rc_set_toggle(self,rc_field,value=None):
941 def rc_set_toggle(self,rc_field,value=None):
943 """Set or toggle a field in IPython's rc config. structure.
942 """Set or toggle a field in IPython's rc config. structure.
944
943
945 If called with no arguments, it acts as a toggle.
944 If called with no arguments, it acts as a toggle.
946
945
947 If called with a non-existent field, the resulting AttributeError
946 If called with a non-existent field, the resulting AttributeError
948 exception will propagate out."""
947 exception will propagate out."""
949
948
950 rc_val = getattr(self.rc,rc_field)
949 rc_val = getattr(self.rc,rc_field)
951 if value is None:
950 if value is None:
952 value = not rc_val
951 value = not rc_val
953 setattr(self.rc,rc_field,value)
952 setattr(self.rc,rc_field,value)
954
953
955 def user_setup(self,ipythondir,rc_suffix,mode='install'):
954 def user_setup(self,ipythondir,rc_suffix,mode='install'):
956 """Install the user configuration directory.
955 """Install the user configuration directory.
957
956
958 Can be called when running for the first time or to upgrade the user's
957 Can be called when running for the first time or to upgrade the user's
959 .ipython/ directory with the mode parameter. Valid modes are 'install'
958 .ipython/ directory with the mode parameter. Valid modes are 'install'
960 and 'upgrade'."""
959 and 'upgrade'."""
961
960
962 def wait():
961 def wait():
963 try:
962 try:
964 raw_input("Please press <RETURN> to start IPython.")
963 raw_input("Please press <RETURN> to start IPython.")
965 except EOFError:
964 except EOFError:
966 print >> Term.cout
965 print >> Term.cout
967 print '*'*70
966 print '*'*70
968
967
969 cwd = os.getcwd() # remember where we started
968 cwd = os.getcwd() # remember where we started
970 glb = glob.glob
969 glb = glob.glob
971 print '*'*70
970 print '*'*70
972 if mode == 'install':
971 if mode == 'install':
973 print \
972 print \
974 """Welcome to IPython. I will try to create a personal configuration directory
973 """Welcome to IPython. I will try to create a personal configuration directory
975 where you can customize many aspects of IPython's functionality in:\n"""
974 where you can customize many aspects of IPython's functionality in:\n"""
976 else:
975 else:
977 print 'I am going to upgrade your configuration in:'
976 print 'I am going to upgrade your configuration in:'
978
977
979 print ipythondir
978 print ipythondir
980
979
981 rcdirend = os.path.join('IPython','UserConfig')
980 rcdirend = os.path.join('IPython','UserConfig')
982 cfg = lambda d: os.path.join(d,rcdirend)
981 cfg = lambda d: os.path.join(d,rcdirend)
983 try:
982 try:
984 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
983 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
985 except IOError:
984 except IOError:
986 warning = """
985 warning = """
987 Installation error. IPython's directory was not found.
986 Installation error. IPython's directory was not found.
988
987
989 Check the following:
988 Check the following:
990
989
991 The ipython/IPython directory should be in a directory belonging to your
990 The ipython/IPython directory should be in a directory belonging to your
992 PYTHONPATH environment variable (that is, it should be in a directory
991 PYTHONPATH environment variable (that is, it should be in a directory
993 belonging to sys.path). You can copy it explicitly there or just link to it.
992 belonging to sys.path). You can copy it explicitly there or just link to it.
994
993
995 IPython will proceed with builtin defaults.
994 IPython will proceed with builtin defaults.
996 """
995 """
997 warn(warning)
996 warn(warning)
998 wait()
997 wait()
999 return
998 return
1000
999
1001 if mode == 'install':
1000 if mode == 'install':
1002 try:
1001 try:
1003 shutil.copytree(rcdir,ipythondir)
1002 shutil.copytree(rcdir,ipythondir)
1004 os.chdir(ipythondir)
1003 os.chdir(ipythondir)
1005 rc_files = glb("ipythonrc*")
1004 rc_files = glb("ipythonrc*")
1006 for rc_file in rc_files:
1005 for rc_file in rc_files:
1007 os.rename(rc_file,rc_file+rc_suffix)
1006 os.rename(rc_file,rc_file+rc_suffix)
1008 except:
1007 except:
1009 warning = """
1008 warning = """
1010
1009
1011 There was a problem with the installation:
1010 There was a problem with the installation:
1012 %s
1011 %s
1013 Try to correct it or contact the developers if you think it's a bug.
1012 Try to correct it or contact the developers if you think it's a bug.
1014 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1013 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1015 warn(warning)
1014 warn(warning)
1016 wait()
1015 wait()
1017 return
1016 return
1018
1017
1019 elif mode == 'upgrade':
1018 elif mode == 'upgrade':
1020 try:
1019 try:
1021 os.chdir(ipythondir)
1020 os.chdir(ipythondir)
1022 except:
1021 except:
1023 print """
1022 print """
1024 Can not upgrade: changing to directory %s failed. Details:
1023 Can not upgrade: changing to directory %s failed. Details:
1025 %s
1024 %s
1026 """ % (ipythondir,sys.exc_info()[1])
1025 """ % (ipythondir,sys.exc_info()[1])
1027 wait()
1026 wait()
1028 return
1027 return
1029 else:
1028 else:
1030 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1029 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1031 for new_full_path in sources:
1030 for new_full_path in sources:
1032 new_filename = os.path.basename(new_full_path)
1031 new_filename = os.path.basename(new_full_path)
1033 if new_filename.startswith('ipythonrc'):
1032 if new_filename.startswith('ipythonrc'):
1034 new_filename = new_filename + rc_suffix
1033 new_filename = new_filename + rc_suffix
1035 # The config directory should only contain files, skip any
1034 # The config directory should only contain files, skip any
1036 # directories which may be there (like CVS)
1035 # directories which may be there (like CVS)
1037 if os.path.isdir(new_full_path):
1036 if os.path.isdir(new_full_path):
1038 continue
1037 continue
1039 if os.path.exists(new_filename):
1038 if os.path.exists(new_filename):
1040 old_file = new_filename+'.old'
1039 old_file = new_filename+'.old'
1041 if os.path.exists(old_file):
1040 if os.path.exists(old_file):
1042 os.remove(old_file)
1041 os.remove(old_file)
1043 os.rename(new_filename,old_file)
1042 os.rename(new_filename,old_file)
1044 shutil.copy(new_full_path,new_filename)
1043 shutil.copy(new_full_path,new_filename)
1045 else:
1044 else:
1046 raise ValueError,'unrecognized mode for install:',`mode`
1045 raise ValueError,'unrecognized mode for install:',`mode`
1047
1046
1048 # Fix line-endings to those native to each platform in the config
1047 # Fix line-endings to those native to each platform in the config
1049 # directory.
1048 # directory.
1050 try:
1049 try:
1051 os.chdir(ipythondir)
1050 os.chdir(ipythondir)
1052 except:
1051 except:
1053 print """
1052 print """
1054 Problem: changing to directory %s failed.
1053 Problem: changing to directory %s failed.
1055 Details:
1054 Details:
1056 %s
1055 %s
1057
1056
1058 Some configuration files may have incorrect line endings. This should not
1057 Some configuration files may have incorrect line endings. This should not
1059 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1058 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1060 wait()
1059 wait()
1061 else:
1060 else:
1062 for fname in glb('ipythonrc*'):
1061 for fname in glb('ipythonrc*'):
1063 try:
1062 try:
1064 native_line_ends(fname,backup=0)
1063 native_line_ends(fname,backup=0)
1065 except IOError:
1064 except IOError:
1066 pass
1065 pass
1067
1066
1068 if mode == 'install':
1067 if mode == 'install':
1069 print """
1068 print """
1070 Successful installation!
1069 Successful installation!
1071
1070
1072 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1071 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1073 IPython manual (there are both HTML and PDF versions supplied with the
1072 IPython manual (there are both HTML and PDF versions supplied with the
1074 distribution) to make sure that your system environment is properly configured
1073 distribution) to make sure that your system environment is properly configured
1075 to take advantage of IPython's features."""
1074 to take advantage of IPython's features."""
1076 else:
1075 else:
1077 print """
1076 print """
1078 Successful upgrade!
1077 Successful upgrade!
1079
1078
1080 All files in your directory:
1079 All files in your directory:
1081 %(ipythondir)s
1080 %(ipythondir)s
1082 which would have been overwritten by the upgrade were backed up with a .old
1081 which would have been overwritten by the upgrade were backed up with a .old
1083 extension. If you had made particular customizations in those files you may
1082 extension. If you had made particular customizations in those files you may
1084 want to merge them back into the new files.""" % locals()
1083 want to merge them back into the new files.""" % locals()
1085 wait()
1084 wait()
1086 os.chdir(cwd)
1085 os.chdir(cwd)
1087 # end user_setup()
1086 # end user_setup()
1088
1087
1089 def atexit_operations(self):
1088 def atexit_operations(self):
1090 """This will be executed at the time of exit.
1089 """This will be executed at the time of exit.
1091
1090
1092 Saving of persistent data should be performed here. """
1091 Saving of persistent data should be performed here. """
1093
1092
1094 # input history
1093 # input history
1095 self.savehist()
1094 self.savehist()
1096
1095
1097 # Cleanup all tempfiles left around
1096 # Cleanup all tempfiles left around
1098 for tfile in self.tempfiles:
1097 for tfile in self.tempfiles:
1099 try:
1098 try:
1100 os.unlink(tfile)
1099 os.unlink(tfile)
1101 except OSError:
1100 except OSError:
1102 pass
1101 pass
1103
1102
1104 # save the "persistent data" catch-all dictionary
1103 # save the "persistent data" catch-all dictionary
1105 try:
1104 try:
1106 pickle.dump(self.persist, open(self.persist_fname,"w"))
1105 pickle.dump(self.persist, open(self.persist_fname,"w"))
1107 except:
1106 except:
1108 print "*** ERROR *** persistent data saving failed."
1107 print "*** ERROR *** persistent data saving failed."
1109
1108
1110 def savehist(self):
1109 def savehist(self):
1111 """Save input history to a file (via readline library)."""
1110 """Save input history to a file (via readline library)."""
1112 try:
1111 try:
1113 self.readline.write_history_file(self.histfile)
1112 self.readline.write_history_file(self.histfile)
1114 except:
1113 except:
1115 print 'Unable to save IPython command history to file: ' + \
1114 print 'Unable to save IPython command history to file: ' + \
1116 `self.histfile`
1115 `self.histfile`
1117
1116
1118 def pre_readline(self):
1117 def pre_readline(self):
1119 """readline hook to be used at the start of each line.
1118 """readline hook to be used at the start of each line.
1120
1119
1121 Currently it handles auto-indent only."""
1120 Currently it handles auto-indent only."""
1122
1121
1123 self.readline.insert_text(' '* self.readline_indent)
1122 self.readline.insert_text(' '* self.readline_indent)
1124
1123
1125 def init_readline(self):
1124 def init_readline(self):
1126 """Command history completion/saving/reloading."""
1125 """Command history completion/saving/reloading."""
1127 try:
1126 try:
1128 import readline
1127 import readline
1129 self.Completer = MagicCompleter(self,
1128 self.Completer = MagicCompleter(self,
1130 self.user_ns,
1129 self.user_ns,
1131 self.rc.readline_omit__names,
1130 self.rc.readline_omit__names,
1132 self.alias_table)
1131 self.alias_table)
1133 except ImportError,NameError:
1132 except ImportError,NameError:
1134 # If FlexCompleter failed to import, MagicCompleter won't be
1133 # If FlexCompleter failed to import, MagicCompleter won't be
1135 # defined. This can happen because of a problem with readline
1134 # defined. This can happen because of a problem with readline
1136 self.has_readline = 0
1135 self.has_readline = 0
1137 # no point in bugging windows users with this every time:
1136 # no point in bugging windows users with this every time:
1138 if os.name == 'posix':
1137 if os.name == 'posix':
1139 warn('Readline services not available on this platform.')
1138 warn('Readline services not available on this platform.')
1140 else:
1139 else:
1141 import atexit
1140 import atexit
1142
1141
1143 # Platform-specific configuration
1142 # Platform-specific configuration
1144 if os.name == 'nt':
1143 if os.name == 'nt':
1145 # readline under Windows modifies the default exit behavior
1144 # readline under Windows modifies the default exit behavior
1146 # from being Ctrl-Z/Return to the Unix Ctrl-D one.
1145 # from being Ctrl-Z/Return to the Unix Ctrl-D one.
1147 __builtin__.exit = __builtin__.quit = \
1146 __builtin__.exit = __builtin__.quit = \
1148 ('Use Ctrl-D (i.e. EOF) to exit. '
1147 ('Use Ctrl-D (i.e. EOF) to exit. '
1149 'Use %Exit or %Quit to exit without confirmation.')
1148 'Use %Exit or %Quit to exit without confirmation.')
1150 self.readline_startup_hook = readline.set_pre_input_hook
1149 self.readline_startup_hook = readline.set_pre_input_hook
1151 else:
1150 else:
1152 self.readline_startup_hook = readline.set_startup_hook
1151 self.readline_startup_hook = readline.set_startup_hook
1153
1152
1154 # Load user's initrc file (readline config)
1153 # Load user's initrc file (readline config)
1155 inputrc_name = os.environ.get('INPUTRC')
1154 inputrc_name = os.environ.get('INPUTRC')
1156 if inputrc_name is None:
1155 if inputrc_name is None:
1157 home_dir = get_home_dir()
1156 home_dir = get_home_dir()
1158 if home_dir is not None:
1157 if home_dir is not None:
1159 inputrc_name = os.path.join(home_dir,'.inputrc')
1158 inputrc_name = os.path.join(home_dir,'.inputrc')
1160 if os.path.isfile(inputrc_name):
1159 if os.path.isfile(inputrc_name):
1161 try:
1160 try:
1162 readline.read_init_file(inputrc_name)
1161 readline.read_init_file(inputrc_name)
1163 except:
1162 except:
1164 warn('Problems reading readline initialization file <%s>'
1163 warn('Problems reading readline initialization file <%s>'
1165 % inputrc_name)
1164 % inputrc_name)
1166
1165
1167 self.has_readline = 1
1166 self.has_readline = 1
1168 self.readline = readline
1167 self.readline = readline
1169 self.readline_indent = 0 # for auto-indenting via readline
1168 self.readline_indent = 0 # for auto-indenting via readline
1170 # save this in sys so embedded copies can restore it properly
1169 # save this in sys so embedded copies can restore it properly
1171 sys.ipcompleter = self.Completer.complete
1170 sys.ipcompleter = self.Completer.complete
1172 readline.set_completer(self.Completer.complete)
1171 readline.set_completer(self.Completer.complete)
1173
1172
1174 # Configure readline according to user's prefs
1173 # Configure readline according to user's prefs
1175 for rlcommand in self.rc.readline_parse_and_bind:
1174 for rlcommand in self.rc.readline_parse_and_bind:
1176 readline.parse_and_bind(rlcommand)
1175 readline.parse_and_bind(rlcommand)
1177
1176
1178 # remove some chars from the delimiters list
1177 # remove some chars from the delimiters list
1179 delims = readline.get_completer_delims()
1178 delims = readline.get_completer_delims()
1180 delims = delims.translate(string._idmap,
1179 delims = delims.translate(string._idmap,
1181 self.rc.readline_remove_delims)
1180 self.rc.readline_remove_delims)
1182 readline.set_completer_delims(delims)
1181 readline.set_completer_delims(delims)
1183 # otherwise we end up with a monster history after a while:
1182 # otherwise we end up with a monster history after a while:
1184 readline.set_history_length(1000)
1183 readline.set_history_length(1000)
1185 try:
1184 try:
1186 #print '*** Reading readline history' # dbg
1185 #print '*** Reading readline history' # dbg
1187 readline.read_history_file(self.histfile)
1186 readline.read_history_file(self.histfile)
1188 except IOError:
1187 except IOError:
1189 pass # It doesn't exist yet.
1188 pass # It doesn't exist yet.
1190
1189
1191 atexit.register(self.atexit_operations)
1190 atexit.register(self.atexit_operations)
1192 del atexit
1191 del atexit
1193
1192
1194 # Configure auto-indent for all platforms
1193 # Configure auto-indent for all platforms
1195 self.set_autoindent(self.rc.autoindent)
1194 self.set_autoindent(self.rc.autoindent)
1196
1195
1197 def showsyntaxerror(self, filename=None):
1196 def showsyntaxerror(self, filename=None):
1198 """Display the syntax error that just occurred.
1197 """Display the syntax error that just occurred.
1199
1198
1200 This doesn't display a stack trace because there isn't one.
1199 This doesn't display a stack trace because there isn't one.
1201
1200
1202 If a filename is given, it is stuffed in the exception instead
1201 If a filename is given, it is stuffed in the exception instead
1203 of what was there before (because Python's parser always uses
1202 of what was there before (because Python's parser always uses
1204 "<string>" when reading from a string).
1203 "<string>" when reading from a string).
1205 """
1204 """
1206 type, value, sys.last_traceback = sys.exc_info()
1205 type, value, sys.last_traceback = sys.exc_info()
1207 sys.last_type = type
1206 sys.last_type = type
1208 sys.last_value = value
1207 sys.last_value = value
1209 if filename and type is SyntaxError:
1208 if filename and type is SyntaxError:
1210 # Work hard to stuff the correct filename in the exception
1209 # Work hard to stuff the correct filename in the exception
1211 try:
1210 try:
1212 msg, (dummy_filename, lineno, offset, line) = value
1211 msg, (dummy_filename, lineno, offset, line) = value
1213 except:
1212 except:
1214 # Not the format we expect; leave it alone
1213 # Not the format we expect; leave it alone
1215 pass
1214 pass
1216 else:
1215 else:
1217 # Stuff in the right filename
1216 # Stuff in the right filename
1218 try:
1217 try:
1219 # Assume SyntaxError is a class exception
1218 # Assume SyntaxError is a class exception
1220 value = SyntaxError(msg, (filename, lineno, offset, line))
1219 value = SyntaxError(msg, (filename, lineno, offset, line))
1221 except:
1220 except:
1222 # If that failed, assume SyntaxError is a string
1221 # If that failed, assume SyntaxError is a string
1223 value = msg, (filename, lineno, offset, line)
1222 value = msg, (filename, lineno, offset, line)
1224 self.SyntaxTB(type,value,[])
1223 self.SyntaxTB(type,value,[])
1225
1224
1226 def debugger(self):
1225 def debugger(self):
1227 """Call the pdb debugger."""
1226 """Call the pdb debugger."""
1228
1227
1229 if not self.rc.pdb:
1228 if not self.rc.pdb:
1230 return
1229 return
1231 pdb.pm()
1230 pdb.pm()
1232
1231
1233 def showtraceback(self,exc_tuple = None):
1232 def showtraceback(self,exc_tuple = None):
1234 """Display the exception that just occurred."""
1233 """Display the exception that just occurred."""
1235
1234
1236 # Though this won't be called by syntax errors in the input line,
1235 # Though this won't be called by syntax errors in the input line,
1237 # there may be SyntaxError cases whith imported code.
1236 # there may be SyntaxError cases whith imported code.
1238 if exc_tuple is None:
1237 if exc_tuple is None:
1239 type, value, tb = sys.exc_info()
1238 type, value, tb = sys.exc_info()
1240 else:
1239 else:
1241 type, value, tb = exc_tuple
1240 type, value, tb = exc_tuple
1242 if type is SyntaxError:
1241 if type is SyntaxError:
1243 self.showsyntaxerror()
1242 self.showsyntaxerror()
1244 else:
1243 else:
1245 sys.last_type = type
1244 sys.last_type = type
1246 sys.last_value = value
1245 sys.last_value = value
1247 sys.last_traceback = tb
1246 sys.last_traceback = tb
1248 self.InteractiveTB()
1247 self.InteractiveTB()
1249 if self.InteractiveTB.call_pdb and self.has_readline:
1248 if self.InteractiveTB.call_pdb and self.has_readline:
1250 # pdb mucks up readline, fix it back
1249 # pdb mucks up readline, fix it back
1251 self.readline.set_completer(self.Completer.complete)
1250 self.readline.set_completer(self.Completer.complete)
1252
1251
1253 def update_cache(self, line):
1252 def update_cache(self, line):
1254 """puts line into cache"""
1253 """puts line into cache"""
1255 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1254 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1256 if len(self.inputcache) >= self.CACHELENGTH:
1255 if len(self.inputcache) >= self.CACHELENGTH:
1257 self.inputcache.pop() # This not :-)
1256 self.inputcache.pop() # This not :-)
1258
1257
1259 def name_space_init(self):
1258 def name_space_init(self):
1260 """Create local namespace."""
1259 """Create local namespace."""
1261 # We want this to be a method to facilitate embedded initialization.
1260 # We want this to be a method to facilitate embedded initialization.
1262 code.InteractiveConsole.__init__(self,self.user_ns)
1261 code.InteractiveConsole.__init__(self,self.user_ns)
1263
1262
1264 def mainloop(self,banner=None):
1263 def mainloop(self,banner=None):
1265 """Creates the local namespace and starts the mainloop.
1264 """Creates the local namespace and starts the mainloop.
1266
1265
1267 If an optional banner argument is given, it will override the
1266 If an optional banner argument is given, it will override the
1268 internally created default banner."""
1267 internally created default banner."""
1269
1268
1270 self.name_space_init()
1269 self.name_space_init()
1271 if self.rc.c: # Emulate Python's -c option
1270 if self.rc.c: # Emulate Python's -c option
1272 self.exec_init_cmd()
1271 self.exec_init_cmd()
1273 if banner is None:
1272 if banner is None:
1274 if self.rc.banner:
1273 if self.rc.banner:
1275 banner = self.BANNER+self.banner2
1274 banner = self.BANNER+self.banner2
1276 else:
1275 else:
1277 banner = ''
1276 banner = ''
1278 self.interact(banner)
1277 self.interact(banner)
1279
1278
1280 def exec_init_cmd(self):
1279 def exec_init_cmd(self):
1281 """Execute a command given at the command line.
1280 """Execute a command given at the command line.
1282
1281
1283 This emulates Python's -c option."""
1282 This emulates Python's -c option."""
1284
1283
1285 sys.argv = ['-c']
1284 sys.argv = ['-c']
1286 self.push(self.rc.c)
1285 self.push(self.rc.c)
1287
1286
1288 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1287 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1289 """Embeds IPython into a running python program.
1288 """Embeds IPython into a running python program.
1290
1289
1291 Input:
1290 Input:
1292
1291
1293 - header: An optional header message can be specified.
1292 - header: An optional header message can be specified.
1294
1293
1295 - local_ns, global_ns: working namespaces. If given as None, the
1294 - local_ns, global_ns: working namespaces. If given as None, the
1296 IPython-initialized one is updated with __main__.__dict__, so that
1295 IPython-initialized one is updated with __main__.__dict__, so that
1297 program variables become visible but user-specific configuration
1296 program variables become visible but user-specific configuration
1298 remains possible.
1297 remains possible.
1299
1298
1300 - stack_depth: specifies how many levels in the stack to go to
1299 - stack_depth: specifies how many levels in the stack to go to
1301 looking for namespaces (when local_ns and global_ns are None). This
1300 looking for namespaces (when local_ns and global_ns are None). This
1302 allows an intermediate caller to make sure that this function gets
1301 allows an intermediate caller to make sure that this function gets
1303 the namespace from the intended level in the stack. By default (0)
1302 the namespace from the intended level in the stack. By default (0)
1304 it will get its locals and globals from the immediate caller.
1303 it will get its locals and globals from the immediate caller.
1305
1304
1306 Warning: it's possible to use this in a program which is being run by
1305 Warning: it's possible to use this in a program which is being run by
1307 IPython itself (via %run), but some funny things will happen (a few
1306 IPython itself (via %run), but some funny things will happen (a few
1308 globals get overwritten). In the future this will be cleaned up, as
1307 globals get overwritten). In the future this will be cleaned up, as
1309 there is no fundamental reason why it can't work perfectly."""
1308 there is no fundamental reason why it can't work perfectly."""
1310
1309
1311 # Patch for global embedding to make sure that things don't overwrite
1310 # Patch for global embedding to make sure that things don't overwrite
1312 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1311 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1313 # FIXME. Test this a bit more carefully (the if.. is new)
1312 # FIXME. Test this a bit more carefully (the if.. is new)
1314 if local_ns is None and global_ns is None:
1313 if local_ns is None and global_ns is None:
1315 self.user_ns.update(__main__.__dict__)
1314 self.user_ns.update(__main__.__dict__)
1316
1315
1317 # Get locals and globals from caller
1316 # Get locals and globals from caller
1318 if local_ns is None or global_ns is None:
1317 if local_ns is None or global_ns is None:
1319 call_frame = sys._getframe(stack_depth).f_back
1318 call_frame = sys._getframe(stack_depth).f_back
1320
1319
1321 if local_ns is None:
1320 if local_ns is None:
1322 local_ns = call_frame.f_locals
1321 local_ns = call_frame.f_locals
1323 if global_ns is None:
1322 if global_ns is None:
1324 global_ns = call_frame.f_globals
1323 global_ns = call_frame.f_globals
1325
1324
1326 # Update namespaces and fire up interpreter
1325 # Update namespaces and fire up interpreter
1327 self.user_ns.update(local_ns)
1326 self.user_ns.update(local_ns)
1328 self.interact(header)
1327 self.interact(header)
1329
1328
1330 # Remove locals from namespace
1329 # Remove locals from namespace
1331 for k in local_ns:
1330 for k in local_ns:
1332 del self.user_ns[k]
1331 del self.user_ns[k]
1333
1332
1334 def interact(self, banner=None):
1333 def interact(self, banner=None):
1335 """Closely emulate the interactive Python console.
1334 """Closely emulate the interactive Python console.
1336
1335
1337 The optional banner argument specify the banner to print
1336 The optional banner argument specify the banner to print
1338 before the first interaction; by default it prints a banner
1337 before the first interaction; by default it prints a banner
1339 similar to the one printed by the real Python interpreter,
1338 similar to the one printed by the real Python interpreter,
1340 followed by the current class name in parentheses (so as not
1339 followed by the current class name in parentheses (so as not
1341 to confuse this with the real interpreter -- since it's so
1340 to confuse this with the real interpreter -- since it's so
1342 close!).
1341 close!).
1343
1342
1344 """
1343 """
1345 cprt = 'Type "copyright", "credits" or "license" for more information.'
1344 cprt = 'Type "copyright", "credits" or "license" for more information.'
1346 if banner is None:
1345 if banner is None:
1347 self.write("Python %s on %s\n%s\n(%s)\n" %
1346 self.write("Python %s on %s\n%s\n(%s)\n" %
1348 (sys.version, sys.platform, cprt,
1347 (sys.version, sys.platform, cprt,
1349 self.__class__.__name__))
1348 self.__class__.__name__))
1350 else:
1349 else:
1351 self.write(banner)
1350 self.write(banner)
1352
1351
1353 more = 0
1352 more = 0
1354
1353
1355 # Mark activity in the builtins
1354 # Mark activity in the builtins
1356 __builtin__.__dict__['__IPYTHON__active'] += 1
1355 __builtin__.__dict__['__IPYTHON__active'] += 1
1357
1356
1358 # exit_now is set by a call to %Exit or %Quit
1357 # exit_now is set by a call to %Exit or %Quit
1359 while not self.exit_now:
1358 while not self.exit_now:
1360 try:
1359 try:
1361 if more:
1360 if more:
1362 prompt = self.outputcache.prompt2
1361 prompt = self.outputcache.prompt2
1363 if self.autoindent:
1362 if self.autoindent:
1364 self.readline_startup_hook(self.pre_readline)
1363 self.readline_startup_hook(self.pre_readline)
1365 else:
1364 else:
1366 prompt = self.outputcache.prompt1
1365 prompt = self.outputcache.prompt1
1367 try:
1366 try:
1368 line = self.raw_input(prompt)
1367 line = self.raw_input(prompt)
1369 if self.autoindent:
1368 if self.autoindent:
1370 self.readline_startup_hook(None)
1369 self.readline_startup_hook(None)
1371 except EOFError:
1370 except EOFError:
1372 if self.autoindent:
1371 if self.autoindent:
1373 self.readline_startup_hook(None)
1372 self.readline_startup_hook(None)
1374 self.write("\n")
1373 self.write("\n")
1375 if self.rc.confirm_exit:
1374 if self.rc.confirm_exit:
1376 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1375 if ask_yes_no('Do you really want to exit ([y]/n)?','y'):
1377 break
1376 break
1378 else:
1377 else:
1379 break
1378 break
1380 else:
1379 else:
1381 more = self.push(line)
1380 more = self.push(line)
1382 # Auto-indent management
1381 # Auto-indent management
1383 if self.autoindent:
1382 if self.autoindent:
1384 if line:
1383 if line:
1385 ini_spaces = re.match('^(\s+)',line)
1384 ini_spaces = re.match('^(\s+)',line)
1386 if ini_spaces:
1385 if ini_spaces:
1387 nspaces = ini_spaces.end()
1386 nspaces = ini_spaces.end()
1388 else:
1387 else:
1389 nspaces = 0
1388 nspaces = 0
1390 self.readline_indent = nspaces
1389 self.readline_indent = nspaces
1391
1390
1392 if line[-1] == ':':
1391 if line[-1] == ':':
1393 self.readline_indent += 4
1392 self.readline_indent += 4
1394 elif re.match(r'^\s+raise|^\s+return',line):
1393 elif re.match(r'^\s+raise|^\s+return',line):
1395 self.readline_indent -= 4
1394 self.readline_indent -= 4
1396 else:
1395 else:
1397 self.readline_indent = 0
1396 self.readline_indent = 0
1398
1397
1399 except KeyboardInterrupt:
1398 except KeyboardInterrupt:
1400 self.write("\nKeyboardInterrupt\n")
1399 self.write("\nKeyboardInterrupt\n")
1401 self.resetbuffer()
1400 self.resetbuffer()
1402 more = 0
1401 more = 0
1403 # keep cache in sync with the prompt counter:
1402 # keep cache in sync with the prompt counter:
1404 self.outputcache.prompt_count -= 1
1403 self.outputcache.prompt_count -= 1
1405
1404
1406 if self.autoindent:
1405 if self.autoindent:
1407 self.readline_indent = 0
1406 self.readline_indent = 0
1408
1407
1409 except bdb.BdbQuit:
1408 except bdb.BdbQuit:
1410 warn("The Python debugger has exited with a BdbQuit exception.\n"
1409 warn("The Python debugger has exited with a BdbQuit exception.\n"
1411 "Because of how pdb handles the stack, it is impossible\n"
1410 "Because of how pdb handles the stack, it is impossible\n"
1412 "for IPython to properly format this particular exception.\n"
1411 "for IPython to properly format this particular exception.\n"
1413 "IPython will resume normal operation.")
1412 "IPython will resume normal operation.")
1414
1413
1415 # We are off again...
1414 # We are off again...
1416 __builtin__.__dict__['__IPYTHON__active'] -= 1
1415 __builtin__.__dict__['__IPYTHON__active'] -= 1
1417
1416
1418 def excepthook(self, type, value, tb):
1417 def excepthook(self, type, value, tb):
1419 """One more defense for GUI apps that call sys.excepthook.
1418 """One more defense for GUI apps that call sys.excepthook.
1420
1419
1421 GUI frameworks like wxPython trap exceptions and call
1420 GUI frameworks like wxPython trap exceptions and call
1422 sys.excepthook themselves. I guess this is a feature that
1421 sys.excepthook themselves. I guess this is a feature that
1423 enables them to keep running after exceptions that would
1422 enables them to keep running after exceptions that would
1424 otherwise kill their mainloop. This is a bother for IPython
1423 otherwise kill their mainloop. This is a bother for IPython
1425 which excepts to catch all of the program exceptions with a try:
1424 which excepts to catch all of the program exceptions with a try:
1426 except: statement.
1425 except: statement.
1427
1426
1428 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1427 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1429 any app directly invokes sys.excepthook, it will look to the user like
1428 any app directly invokes sys.excepthook, it will look to the user like
1430 IPython crashed. In order to work around this, we can disable the
1429 IPython crashed. In order to work around this, we can disable the
1431 CrashHandler and replace it with this excepthook instead, which prints a
1430 CrashHandler and replace it with this excepthook instead, which prints a
1432 regular traceback using our InteractiveTB. In this fashion, apps which
1431 regular traceback using our InteractiveTB. In this fashion, apps which
1433 call sys.excepthook will generate a regular-looking exception from
1432 call sys.excepthook will generate a regular-looking exception from
1434 IPython, and the CrashHandler will only be triggered by real IPython
1433 IPython, and the CrashHandler will only be triggered by real IPython
1435 crashes.
1434 crashes.
1436
1435
1437 This hook should be used sparingly, only in places which are not likely
1436 This hook should be used sparingly, only in places which are not likely
1438 to be true IPython errors.
1437 to be true IPython errors.
1439 """
1438 """
1440
1439
1441 self.InteractiveTB(type, value, tb, tb_offset=0)
1440 self.InteractiveTB(type, value, tb, tb_offset=0)
1442 if self.InteractiveTB.call_pdb and self.has_readline:
1441 if self.InteractiveTB.call_pdb and self.has_readline:
1443 self.readline.set_completer(self.Completer.complete)
1442 self.readline.set_completer(self.Completer.complete)
1444
1443
1445 def call_alias(self,alias,rest=''):
1444 def call_alias(self,alias,rest=''):
1446 """Call an alias given its name and the rest of the line.
1445 """Call an alias given its name and the rest of the line.
1447
1446
1448 This function MUST be given a proper alias, because it doesn't make
1447 This function MUST be given a proper alias, because it doesn't make
1449 any checks when looking up into the alias table. The caller is
1448 any checks when looking up into the alias table. The caller is
1450 responsible for invoking it only with a valid alias."""
1449 responsible for invoking it only with a valid alias."""
1451
1450
1452 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1451 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1453 nargs,cmd = self.alias_table[alias]
1452 nargs,cmd = self.alias_table[alias]
1454 # Expand the %l special to be the user's input line
1453 # Expand the %l special to be the user's input line
1455 if cmd.find('%l') >= 0:
1454 if cmd.find('%l') >= 0:
1456 cmd = cmd.replace('%l',rest)
1455 cmd = cmd.replace('%l',rest)
1457 rest = ''
1456 rest = ''
1458 if nargs==0:
1457 if nargs==0:
1459 # Simple, argument-less aliases
1458 # Simple, argument-less aliases
1460 cmd = '%s %s' % (cmd,rest)
1459 cmd = '%s %s' % (cmd,rest)
1461 else:
1460 else:
1462 # Handle aliases with positional arguments
1461 # Handle aliases with positional arguments
1463 args = rest.split(None,nargs)
1462 args = rest.split(None,nargs)
1464 if len(args)< nargs:
1463 if len(args)< nargs:
1465 error('Alias <%s> requires %s arguments, %s given.' %
1464 error('Alias <%s> requires %s arguments, %s given.' %
1466 (alias,nargs,len(args)))
1465 (alias,nargs,len(args)))
1467 return
1466 return
1468 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1467 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1469 # Now call the macro, evaluating in the user's namespace
1468 # Now call the macro, evaluating in the user's namespace
1470 try:
1469 try:
1471 self.system(cmd)
1470 self.system(cmd)
1472 except:
1471 except:
1473 self.showtraceback()
1472 self.showtraceback()
1474
1473
1475 def runlines(self,lines):
1474 def runlines(self,lines):
1476 """Run a string of one or more lines of source.
1475 """Run a string of one or more lines of source.
1477
1476
1478 This method is capable of running a string containing multiple source
1477 This method is capable of running a string containing multiple source
1479 lines, as if they had been entered at the IPython prompt. Since it
1478 lines, as if they had been entered at the IPython prompt. Since it
1480 exposes IPython's processing machinery, the given strings can contain
1479 exposes IPython's processing machinery, the given strings can contain
1481 magic calls (%magic), special shell access (!cmd), etc."""
1480 magic calls (%magic), special shell access (!cmd), etc."""
1482
1481
1483 # We must start with a clean buffer, in case this is run from an
1482 # We must start with a clean buffer, in case this is run from an
1484 # interactive IPython session (via a magic, for example).
1483 # interactive IPython session (via a magic, for example).
1485 self.resetbuffer()
1484 self.resetbuffer()
1486 lines = lines.split('\n')
1485 lines = lines.split('\n')
1487 more = 0
1486 more = 0
1488 for line in lines:
1487 for line in lines:
1489 # skip blank lines so we don't mess up the prompt counter, but do
1488 # skip blank lines so we don't mess up the prompt counter, but do
1490 # NOT skip even a blank line if we are in a code block (more is
1489 # NOT skip even a blank line if we are in a code block (more is
1491 # true)
1490 # true)
1492 if line or more:
1491 if line or more:
1493 more = self.push((self.prefilter(line,more)))
1492 more = self.push((self.prefilter(line,more)))
1494 # IPython's runsource returns None if there was an error
1493 # IPython's runsource returns None if there was an error
1495 # compiling the code. This allows us to stop processing right
1494 # compiling the code. This allows us to stop processing right
1496 # away, so the user gets the error message at the right place.
1495 # away, so the user gets the error message at the right place.
1497 if more is None:
1496 if more is None:
1498 break
1497 break
1499 # final newline in case the input didn't have it, so that the code
1498 # final newline in case the input didn't have it, so that the code
1500 # actually does get executed
1499 # actually does get executed
1501 if more:
1500 if more:
1502 self.push('\n')
1501 self.push('\n')
1503
1502
1504 def runsource(self, source, filename="<input>", symbol="single"):
1503 def runsource(self, source, filename="<input>", symbol="single"):
1505 """Compile and run some source in the interpreter.
1504 """Compile and run some source in the interpreter.
1506
1505
1507 Arguments are as for compile_command().
1506 Arguments are as for compile_command().
1508
1507
1509 One several things can happen:
1508 One several things can happen:
1510
1509
1511 1) The input is incorrect; compile_command() raised an
1510 1) The input is incorrect; compile_command() raised an
1512 exception (SyntaxError or OverflowError). A syntax traceback
1511 exception (SyntaxError or OverflowError). A syntax traceback
1513 will be printed by calling the showsyntaxerror() method.
1512 will be printed by calling the showsyntaxerror() method.
1514
1513
1515 2) The input is incomplete, and more input is required;
1514 2) The input is incomplete, and more input is required;
1516 compile_command() returned None. Nothing happens.
1515 compile_command() returned None. Nothing happens.
1517
1516
1518 3) The input is complete; compile_command() returned a code
1517 3) The input is complete; compile_command() returned a code
1519 object. The code is executed by calling self.runcode() (which
1518 object. The code is executed by calling self.runcode() (which
1520 also handles run-time exceptions, except for SystemExit).
1519 also handles run-time exceptions, except for SystemExit).
1521
1520
1522 The return value is:
1521 The return value is:
1523
1522
1524 - True in case 2
1523 - True in case 2
1525
1524
1526 - False in the other cases, unless an exception is raised, where
1525 - False in the other cases, unless an exception is raised, where
1527 None is returned instead. This can be used by external callers to
1526 None is returned instead. This can be used by external callers to
1528 know whether to continue feeding input or not.
1527 know whether to continue feeding input or not.
1529
1528
1530 The return value can be used to decide whether to use sys.ps1 or
1529 The return value can be used to decide whether to use sys.ps1 or
1531 sys.ps2 to prompt the next line."""
1530 sys.ps2 to prompt the next line."""
1531
1532 try:
1532 try:
1533 code = self.compile(source, filename, symbol)
1533 code = self.compile(source, filename, symbol)
1534 except (OverflowError, SyntaxError, ValueError):
1534 except (OverflowError, SyntaxError, ValueError):
1535 # Case 1
1535 # Case 1
1536 self.showsyntaxerror(filename)
1536 self.showsyntaxerror(filename)
1537 return None
1537 return None
1538
1538
1539 if code is None:
1539 if code is None:
1540 # Case 2
1540 # Case 2
1541 return True
1541 return True
1542
1542
1543 # Case 3
1543 # Case 3
1544 # We store the code source and object so that threaded shells and
1544 # We store the code object so that threaded shells and
1545 # custom exception handlers can access all this info if needed.
1545 # custom exception handlers can access all this info if needed.
1546 self.code_to_run_src = source
1546 # The source corresponding to this can be obtained from the
1547 # buffer attribute as '\n'.join(self.buffer).
1547 self.code_to_run = code
1548 self.code_to_run = code
1548 # now actually execute the code object
1549 # now actually execute the code object
1549 if self.runcode(code) == 0:
1550 if self.runcode(code) == 0:
1550 return False
1551 return False
1551 else:
1552 else:
1552 return None
1553 return None
1553
1554
1554 def runcode(self,code_obj):
1555 def runcode(self,code_obj):
1555 """Execute a code object.
1556 """Execute a code object.
1556
1557
1557 When an exception occurs, self.showtraceback() is called to display a
1558 When an exception occurs, self.showtraceback() is called to display a
1558 traceback.
1559 traceback.
1559
1560
1560 Return value: a flag indicating whether the code to be run completed
1561 Return value: a flag indicating whether the code to be run completed
1561 successfully:
1562 successfully:
1562
1563
1563 - 0: successful execution.
1564 - 0: successful execution.
1564 - 1: an error occurred.
1565 - 1: an error occurred.
1565 """
1566 """
1566
1567
1567 # Set our own excepthook in case the user code tries to call it
1568 # Set our own excepthook in case the user code tries to call it
1568 # directly, so that the IPython crash handler doesn't get triggered
1569 # directly, so that the IPython crash handler doesn't get triggered
1569 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1570 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1570 outflag = 1 # happens in more places, so it's easier as default
1571 outflag = 1 # happens in more places, so it's easier as default
1571 try:
1572 try:
1572 try:
1573 try:
1573 exec code_obj in self.locals
1574 exec code_obj in self.locals
1574 finally:
1575 finally:
1575 # Reset our crash handler in place
1576 # Reset our crash handler in place
1576 sys.excepthook = old_excepthook
1577 sys.excepthook = old_excepthook
1577 except SystemExit:
1578 except SystemExit:
1578 self.resetbuffer()
1579 self.resetbuffer()
1579 self.showtraceback()
1580 self.showtraceback()
1580 warn( __builtin__.exit,level=1)
1581 warn( __builtin__.exit,level=1)
1581 except self.custom_exceptions:
1582 except self.custom_exceptions:
1582 etype,value,tb = sys.exc_info()
1583 etype,value,tb = sys.exc_info()
1583 self.CustomTB(etype,value,tb)
1584 self.CustomTB(etype,value,tb)
1584 except:
1585 except:
1585 self.showtraceback()
1586 self.showtraceback()
1586 else:
1587 else:
1587 outflag = 0
1588 outflag = 0
1588 if code.softspace(sys.stdout, 0):
1589 if code.softspace(sys.stdout, 0):
1589 print
1590 print
1590 # Flush out code object which has been run (and source)
1591 # Flush out code object which has been run (and source)
1591 self.code_to_run = None
1592 self.code_to_run = None
1592 self.code_to_run_src = ''
1593 return outflag
1593 return outflag
1594
1594
1595 def raw_input(self, prompt=""):
1595 def raw_input(self, prompt=""):
1596 """Write a prompt and read a line.
1596 """Write a prompt and read a line.
1597
1597
1598 The returned line does not include the trailing newline.
1598 The returned line does not include the trailing newline.
1599 When the user enters the EOF key sequence, EOFError is raised.
1599 When the user enters the EOF key sequence, EOFError is raised.
1600
1600
1601 The base implementation uses the built-in function
1601 The base implementation uses the built-in function
1602 raw_input(); a subclass may replace this with a different
1602 raw_input(); a subclass may replace this with a different
1603 implementation.
1603 implementation.
1604 """
1604 """
1605 return self.prefilter(raw_input_original(prompt),
1605 return self.prefilter(raw_input_original(prompt),
1606 prompt==self.outputcache.prompt2)
1606 prompt==self.outputcache.prompt2)
1607
1607
1608 def split_user_input(self,line):
1608 def split_user_input(self,line):
1609 """Split user input into pre-char, function part and rest."""
1609 """Split user input into pre-char, function part and rest."""
1610
1610
1611 lsplit = self.line_split.match(line)
1611 lsplit = self.line_split.match(line)
1612 if lsplit is None: # no regexp match returns None
1612 if lsplit is None: # no regexp match returns None
1613 try:
1613 try:
1614 iFun,theRest = line.split(None,1)
1614 iFun,theRest = line.split(None,1)
1615 except ValueError:
1615 except ValueError:
1616 iFun,theRest = line,''
1616 iFun,theRest = line,''
1617 pre = re.match('^(\s*)(.*)',line).groups()[0]
1617 pre = re.match('^(\s*)(.*)',line).groups()[0]
1618 else:
1618 else:
1619 pre,iFun,theRest = lsplit.groups()
1619 pre,iFun,theRest = lsplit.groups()
1620
1620
1621 #print 'line:<%s>' % line # dbg
1621 #print 'line:<%s>' % line # dbg
1622 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1622 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun.strip(),theRest) # dbg
1623 return pre,iFun.strip(),theRest
1623 return pre,iFun.strip(),theRest
1624
1624
1625 def _prefilter(self, line, continue_prompt):
1625 def _prefilter(self, line, continue_prompt):
1626 """Calls different preprocessors, depending on the form of line."""
1626 """Calls different preprocessors, depending on the form of line."""
1627
1627
1628 # All handlers *must* return a value, even if it's blank ('').
1628 # All handlers *must* return a value, even if it's blank ('').
1629
1629
1630 # Lines are NOT logged here. Handlers should process the line as
1630 # Lines are NOT logged here. Handlers should process the line as
1631 # needed, update the cache AND log it (so that the input cache array
1631 # needed, update the cache AND log it (so that the input cache array
1632 # stays synced).
1632 # stays synced).
1633
1633
1634 # This function is _very_ delicate, and since it's also the one which
1634 # This function is _very_ delicate, and since it's also the one which
1635 # determines IPython's response to user input, it must be as efficient
1635 # determines IPython's response to user input, it must be as efficient
1636 # as possible. For this reason it has _many_ returns in it, trying
1636 # as possible. For this reason it has _many_ returns in it, trying
1637 # always to exit as quickly as it can figure out what it needs to do.
1637 # always to exit as quickly as it can figure out what it needs to do.
1638
1638
1639 # This function is the main responsible for maintaining IPython's
1639 # This function is the main responsible for maintaining IPython's
1640 # behavior respectful of Python's semantics. So be _very_ careful if
1640 # behavior respectful of Python's semantics. So be _very_ careful if
1641 # making changes to anything here.
1641 # making changes to anything here.
1642
1642
1643 #.....................................................................
1643 #.....................................................................
1644 # Code begins
1644 # Code begins
1645
1645
1646 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1646 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1647
1647
1648 # save the line away in case we crash, so the post-mortem handler can
1648 # save the line away in case we crash, so the post-mortem handler can
1649 # record it
1649 # record it
1650 self._last_input_line = line
1650 self._last_input_line = line
1651
1651
1652 #print '***line: <%s>' % line # dbg
1652 #print '***line: <%s>' % line # dbg
1653
1653
1654 # the input history needs to track even empty lines
1654 # the input history needs to track even empty lines
1655 if not line.strip():
1655 if not line.strip():
1656 if not continue_prompt:
1656 if not continue_prompt:
1657 self.outputcache.prompt_count -= 1
1657 self.outputcache.prompt_count -= 1
1658 return self.handle_normal('',continue_prompt)
1658 return self.handle_normal('',continue_prompt)
1659
1659
1660 # print '***cont',continue_prompt # dbg
1660 # print '***cont',continue_prompt # dbg
1661 # special handlers are only allowed for single line statements
1661 # special handlers are only allowed for single line statements
1662 if continue_prompt and not self.rc.multi_line_specials:
1662 if continue_prompt and not self.rc.multi_line_specials:
1663 return self.handle_normal(line,continue_prompt)
1663 return self.handle_normal(line,continue_prompt)
1664
1664
1665 # For the rest, we need the structure of the input
1665 # For the rest, we need the structure of the input
1666 pre,iFun,theRest = self.split_user_input(line)
1666 pre,iFun,theRest = self.split_user_input(line)
1667 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1667 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1668
1668
1669 # First check for explicit escapes in the last/first character
1669 # First check for explicit escapes in the last/first character
1670 handler = None
1670 handler = None
1671 if line[-1] == self.ESC_HELP:
1671 if line[-1] == self.ESC_HELP:
1672 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1672 handler = self.esc_handlers.get(line[-1]) # the ? can be at the end
1673 if handler is None:
1673 if handler is None:
1674 # look at the first character of iFun, NOT of line, so we skip
1674 # look at the first character of iFun, NOT of line, so we skip
1675 # leading whitespace in multiline input
1675 # leading whitespace in multiline input
1676 handler = self.esc_handlers.get(iFun[0:1])
1676 handler = self.esc_handlers.get(iFun[0:1])
1677 if handler is not None:
1677 if handler is not None:
1678 return handler(line,continue_prompt,pre,iFun,theRest)
1678 return handler(line,continue_prompt,pre,iFun,theRest)
1679 # Emacs ipython-mode tags certain input lines
1679 # Emacs ipython-mode tags certain input lines
1680 if line.endswith('# PYTHON-MODE'):
1680 if line.endswith('# PYTHON-MODE'):
1681 return self.handle_emacs(line,continue_prompt)
1681 return self.handle_emacs(line,continue_prompt)
1682
1682
1683 # Next, check if we can automatically execute this thing
1683 # Next, check if we can automatically execute this thing
1684
1684
1685 # Allow ! in multi-line statements if multi_line_specials is on:
1685 # Allow ! in multi-line statements if multi_line_specials is on:
1686 if continue_prompt and self.rc.multi_line_specials and \
1686 if continue_prompt and self.rc.multi_line_specials and \
1687 iFun.startswith(self.ESC_SHELL):
1687 iFun.startswith(self.ESC_SHELL):
1688 return self.handle_shell_escape(line,continue_prompt,
1688 return self.handle_shell_escape(line,continue_prompt,
1689 pre=pre,iFun=iFun,
1689 pre=pre,iFun=iFun,
1690 theRest=theRest)
1690 theRest=theRest)
1691
1691
1692 # Let's try to find if the input line is a magic fn
1692 # Let's try to find if the input line is a magic fn
1693 oinfo = None
1693 oinfo = None
1694 if hasattr(self,'magic_'+iFun):
1694 if hasattr(self,'magic_'+iFun):
1695 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1695 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1696 if oinfo['ismagic']:
1696 if oinfo['ismagic']:
1697 # Be careful not to call magics when a variable assignment is
1697 # Be careful not to call magics when a variable assignment is
1698 # being made (ls='hi', for example)
1698 # being made (ls='hi', for example)
1699 if self.rc.automagic and \
1699 if self.rc.automagic and \
1700 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1700 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1701 (self.rc.multi_line_specials or not continue_prompt):
1701 (self.rc.multi_line_specials or not continue_prompt):
1702 return self.handle_magic(line,continue_prompt,
1702 return self.handle_magic(line,continue_prompt,
1703 pre,iFun,theRest)
1703 pre,iFun,theRest)
1704 else:
1704 else:
1705 return self.handle_normal(line,continue_prompt)
1705 return self.handle_normal(line,continue_prompt)
1706
1706
1707 # If the rest of the line begins with an (in)equality, assginment or
1707 # If the rest of the line begins with an (in)equality, assginment or
1708 # function call, we should not call _ofind but simply execute it.
1708 # function call, we should not call _ofind but simply execute it.
1709 # This avoids spurious geattr() accesses on objects upon assignment.
1709 # This avoids spurious geattr() accesses on objects upon assignment.
1710 #
1710 #
1711 # It also allows users to assign to either alias or magic names true
1711 # It also allows users to assign to either alias or magic names true
1712 # python variables (the magic/alias systems always take second seat to
1712 # python variables (the magic/alias systems always take second seat to
1713 # true python code).
1713 # true python code).
1714 if theRest and theRest[0] in '!=()':
1714 if theRest and theRest[0] in '!=()':
1715 return self.handle_normal(line,continue_prompt)
1715 return self.handle_normal(line,continue_prompt)
1716
1716
1717 if oinfo is None:
1717 if oinfo is None:
1718 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1718 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1719
1719
1720 if not oinfo['found']:
1720 if not oinfo['found']:
1721 return self.handle_normal(line,continue_prompt)
1721 return self.handle_normal(line,continue_prompt)
1722 else:
1722 else:
1723 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1723 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1724 if oinfo['isalias']:
1724 if oinfo['isalias']:
1725 return self.handle_alias(line,continue_prompt,
1725 return self.handle_alias(line,continue_prompt,
1726 pre,iFun,theRest)
1726 pre,iFun,theRest)
1727
1727
1728 if self.rc.autocall and \
1728 if self.rc.autocall and \
1729 not self.re_exclude_auto.match(theRest) and \
1729 not self.re_exclude_auto.match(theRest) and \
1730 self.re_fun_name.match(iFun) and \
1730 self.re_fun_name.match(iFun) and \
1731 callable(oinfo['obj']) :
1731 callable(oinfo['obj']) :
1732 #print 'going auto' # dbg
1732 #print 'going auto' # dbg
1733 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1733 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1734 else:
1734 else:
1735 #print 'was callable?', callable(oinfo['obj']) # dbg
1735 #print 'was callable?', callable(oinfo['obj']) # dbg
1736 return self.handle_normal(line,continue_prompt)
1736 return self.handle_normal(line,continue_prompt)
1737
1737
1738 # If we get here, we have a normal Python line. Log and return.
1738 # If we get here, we have a normal Python line. Log and return.
1739 return self.handle_normal(line,continue_prompt)
1739 return self.handle_normal(line,continue_prompt)
1740
1740
1741 def _prefilter_dumb(self, line, continue_prompt):
1741 def _prefilter_dumb(self, line, continue_prompt):
1742 """simple prefilter function, for debugging"""
1742 """simple prefilter function, for debugging"""
1743 return self.handle_normal(line,continue_prompt)
1743 return self.handle_normal(line,continue_prompt)
1744
1744
1745 # Set the default prefilter() function (this can be user-overridden)
1745 # Set the default prefilter() function (this can be user-overridden)
1746 prefilter = _prefilter
1746 prefilter = _prefilter
1747
1747
1748 def handle_normal(self,line,continue_prompt=None,
1748 def handle_normal(self,line,continue_prompt=None,
1749 pre=None,iFun=None,theRest=None):
1749 pre=None,iFun=None,theRest=None):
1750 """Handle normal input lines. Use as a template for handlers."""
1750 """Handle normal input lines. Use as a template for handlers."""
1751
1751
1752 self.log(line,continue_prompt)
1752 self.log(line,continue_prompt)
1753 self.update_cache(line)
1753 self.update_cache(line)
1754 return line
1754 return line
1755
1755
1756 def handle_alias(self,line,continue_prompt=None,
1756 def handle_alias(self,line,continue_prompt=None,
1757 pre=None,iFun=None,theRest=None):
1757 pre=None,iFun=None,theRest=None):
1758 """Handle alias input lines. """
1758 """Handle alias input lines. """
1759
1759
1760 theRest = esc_quotes(theRest)
1760 theRest = esc_quotes(theRest)
1761 line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1761 line_out = "%s%s.call_alias('%s','%s')" % (pre,self.name,iFun,theRest)
1762 self.log(line_out,continue_prompt)
1762 self.log(line_out,continue_prompt)
1763 self.update_cache(line_out)
1763 self.update_cache(line_out)
1764 return line_out
1764 return line_out
1765
1765
1766 def handle_shell_escape(self, line, continue_prompt=None,
1766 def handle_shell_escape(self, line, continue_prompt=None,
1767 pre=None,iFun=None,theRest=None):
1767 pre=None,iFun=None,theRest=None):
1768 """Execute the line in a shell, empty return value"""
1768 """Execute the line in a shell, empty return value"""
1769
1769
1770 #print 'line in :', `line` # dbg
1770 # Example of a special handler. Others follow a similar pattern.
1771 # Example of a special handler. Others follow a similar pattern.
1771 if continue_prompt: # multi-line statements
1772 if continue_prompt: # multi-line statements
1772 if iFun.startswith('!!'):
1773 if iFun.startswith('!!'):
1773 print 'SyntaxError: !! is not allowed in multiline statements'
1774 print 'SyntaxError: !! is not allowed in multiline statements'
1774 return pre
1775 return pre
1775 else:
1776 else:
1776 cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
1777 cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
1777 line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1778 line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1779 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1778 else: # single-line input
1780 else: # single-line input
1779 if line.startswith('!!'):
1781 if line.startswith('!!'):
1780 # rewrite iFun/theRest to properly hold the call to %sx and
1782 # rewrite iFun/theRest to properly hold the call to %sx and
1781 # the actual command to be executed, so handle_magic can work
1783 # the actual command to be executed, so handle_magic can work
1782 # correctly
1784 # correctly
1783 theRest = '%s %s' % (iFun[2:],theRest)
1785 theRest = '%s %s' % (iFun[2:],theRest)
1784 iFun = 'sx'
1786 iFun = 'sx'
1785 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1787 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1786 continue_prompt,pre,iFun,theRest)
1788 continue_prompt,pre,iFun,theRest)
1787 else:
1789 else:
1788 cmd = esc_quotes(line[1:])
1790 cmd = esc_quotes(line[1:])
1789 line_out = '%s.system("%s")' % (self.name,cmd)
1791 line_out = '%s.system("%s")' % (self.name,cmd)
1792 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1790 # update cache/log and return
1793 # update cache/log and return
1791 self.log(line_out,continue_prompt)
1794 self.log(line_out,continue_prompt)
1792 self.update_cache(line_out) # readline cache gets normal line
1795 self.update_cache(line_out) # readline cache gets normal line
1796 #print 'line out r:', `line_out` # dbg
1797 #print 'line out s:', line_out # dbg
1793 return line_out
1798 return line_out
1794
1799
1795 def handle_magic(self, line, continue_prompt=None,
1800 def handle_magic(self, line, continue_prompt=None,
1796 pre=None,iFun=None,theRest=None):
1801 pre=None,iFun=None,theRest=None):
1797 """Execute magic functions.
1802 """Execute magic functions.
1798
1803
1799 Also log them with a prepended # so the log is clean Python."""
1804 Also log them with a prepended # so the log is clean Python."""
1800
1805
1801 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1806 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1802 self.log(cmd,continue_prompt)
1807 self.log(cmd,continue_prompt)
1803 self.update_cache(line)
1808 self.update_cache(line)
1804 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1809 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1805 return cmd
1810 return cmd
1806
1811
1807 def handle_auto(self, line, continue_prompt=None,
1812 def handle_auto(self, line, continue_prompt=None,
1808 pre=None,iFun=None,theRest=None):
1813 pre=None,iFun=None,theRest=None):
1809 """Hande lines which can be auto-executed, quoting if requested."""
1814 """Hande lines which can be auto-executed, quoting if requested."""
1810
1815
1811 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1816 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1812
1817
1813 # This should only be active for single-line input!
1818 # This should only be active for single-line input!
1814 if continue_prompt:
1819 if continue_prompt:
1815 return line
1820 return line
1816
1821
1817 if pre == self.ESC_QUOTE:
1822 if pre == self.ESC_QUOTE:
1818 # Auto-quote splitting on whitespace
1823 # Auto-quote splitting on whitespace
1819 newcmd = '%s("%s")\n' % (iFun,'", "'.join(theRest.split()) )
1824 newcmd = '%s("%s")\n' % (iFun,'", "'.join(theRest.split()) )
1820 elif pre == self.ESC_QUOTE2:
1825 elif pre == self.ESC_QUOTE2:
1821 # Auto-quote whole string
1826 # Auto-quote whole string
1822 newcmd = '%s("%s")\n' % (iFun,theRest)
1827 newcmd = '%s("%s")\n' % (iFun,theRest)
1823 else:
1828 else:
1824 # Auto-paren
1829 # Auto-paren
1825 if theRest[0:1] in ('=','['):
1830 if theRest[0:1] in ('=','['):
1826 # Don't autocall in these cases. They can be either
1831 # Don't autocall in these cases. They can be either
1827 # rebindings of an existing callable's name, or item access
1832 # rebindings of an existing callable's name, or item access
1828 # for an object which is BOTH callable and implements
1833 # for an object which is BOTH callable and implements
1829 # __getitem__.
1834 # __getitem__.
1830 return '%s %s\n' % (iFun,theRest)
1835 return '%s %s\n' % (iFun,theRest)
1831 if theRest.endswith(';'):
1836 if theRest.endswith(';'):
1832 newcmd = '%s(%s);\n' % (iFun.rstrip(),theRest[:-1])
1837 newcmd = '%s(%s);\n' % (iFun.rstrip(),theRest[:-1])
1833 else:
1838 else:
1834 newcmd = '%s(%s)\n' % (iFun.rstrip(),theRest)
1839 newcmd = '%s(%s)\n' % (iFun.rstrip(),theRest)
1835
1840
1836 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd,
1841 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd,
1837 # log what is now valid Python, not the actual user input (without the
1842 # log what is now valid Python, not the actual user input (without the
1838 # final newline)
1843 # final newline)
1839 self.log(newcmd.strip(),continue_prompt)
1844 self.log(newcmd.strip(),continue_prompt)
1840 return newcmd
1845 return newcmd
1841
1846
1842 def handle_help(self, line, continue_prompt=None,
1847 def handle_help(self, line, continue_prompt=None,
1843 pre=None,iFun=None,theRest=None):
1848 pre=None,iFun=None,theRest=None):
1844 """Try to get some help for the object.
1849 """Try to get some help for the object.
1845
1850
1846 obj? or ?obj -> basic information.
1851 obj? or ?obj -> basic information.
1847 obj?? or ??obj -> more details.
1852 obj?? or ??obj -> more details.
1848 """
1853 """
1849
1854
1850 # We need to make sure that we don't process lines which would be
1855 # We need to make sure that we don't process lines which would be
1851 # otherwise valid python, such as "x=1 # what?"
1856 # otherwise valid python, such as "x=1 # what?"
1852 try:
1857 try:
1853 code.compile_command(line)
1858 code.compile_command(line)
1854 except SyntaxError:
1859 except SyntaxError:
1855 # We should only handle as help stuff which is NOT valid syntax
1860 # We should only handle as help stuff which is NOT valid syntax
1856 if line[0]==self.ESC_HELP:
1861 if line[0]==self.ESC_HELP:
1857 line = line[1:]
1862 line = line[1:]
1858 elif line[-1]==self.ESC_HELP:
1863 elif line[-1]==self.ESC_HELP:
1859 line = line[:-1]
1864 line = line[:-1]
1860 self.log('#?'+line)
1865 self.log('#?'+line)
1861 self.update_cache(line)
1866 self.update_cache(line)
1862 if line:
1867 if line:
1863 self.magic_pinfo(line)
1868 self.magic_pinfo(line)
1864 else:
1869 else:
1865 page(self.usage,screen_lines=self.rc.screen_length)
1870 page(self.usage,screen_lines=self.rc.screen_length)
1866 return '' # Empty string is needed here!
1871 return '' # Empty string is needed here!
1867 except:
1872 except:
1868 # Pass any other exceptions through to the normal handler
1873 # Pass any other exceptions through to the normal handler
1869 return self.handle_normal(line,continue_prompt)
1874 return self.handle_normal(line,continue_prompt)
1870 else:
1875 else:
1871 # If the code compiles ok, we should handle it normally
1876 # If the code compiles ok, we should handle it normally
1872 return self.handle_normal(line,continue_prompt)
1877 return self.handle_normal(line,continue_prompt)
1873
1878
1874 def handle_emacs(self,line,continue_prompt=None,
1879 def handle_emacs(self,line,continue_prompt=None,
1875 pre=None,iFun=None,theRest=None):
1880 pre=None,iFun=None,theRest=None):
1876 """Handle input lines marked by python-mode."""
1881 """Handle input lines marked by python-mode."""
1877
1882
1878 # Currently, nothing is done. Later more functionality can be added
1883 # Currently, nothing is done. Later more functionality can be added
1879 # here if needed.
1884 # here if needed.
1880
1885
1881 # The input cache shouldn't be updated
1886 # The input cache shouldn't be updated
1882
1887
1883 return line
1888 return line
1884
1889
1885 def write(self,data):
1890 def write(self,data):
1886 """Write a string to the default output"""
1891 """Write a string to the default output"""
1887 Term.cout.write(data)
1892 Term.cout.write(data)
1888
1893
1889 def write_err(self,data):
1894 def write_err(self,data):
1890 """Write a string to the default error output"""
1895 """Write a string to the default error output"""
1891 Term.cerr.write(data)
1896 Term.cerr.write(data)
1892
1897
1893 def safe_execfile(self,fname,*where,**kw):
1898 def safe_execfile(self,fname,*where,**kw):
1894 fname = os.path.expanduser(fname)
1899 fname = os.path.expanduser(fname)
1895
1900
1896 # find things also in current directory
1901 # find things also in current directory
1897 dname = os.path.dirname(fname)
1902 dname = os.path.dirname(fname)
1898 if not sys.path.count(dname):
1903 if not sys.path.count(dname):
1899 sys.path.append(dname)
1904 sys.path.append(dname)
1900
1905
1901 try:
1906 try:
1902 xfile = open(fname)
1907 xfile = open(fname)
1903 except:
1908 except:
1904 print >> Term.cerr, \
1909 print >> Term.cerr, \
1905 'Could not open file <%s> for safe execution.' % fname
1910 'Could not open file <%s> for safe execution.' % fname
1906 return None
1911 return None
1907
1912
1908 kw.setdefault('islog',0)
1913 kw.setdefault('islog',0)
1909 kw.setdefault('quiet',1)
1914 kw.setdefault('quiet',1)
1910 kw.setdefault('exit_ignore',0)
1915 kw.setdefault('exit_ignore',0)
1911 first = xfile.readline()
1916 first = xfile.readline()
1912 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
1917 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
1913 xfile.close()
1918 xfile.close()
1914 # line by line execution
1919 # line by line execution
1915 if first.startswith(_LOGHEAD) or kw['islog']:
1920 if first.startswith(_LOGHEAD) or kw['islog']:
1916 print 'Loading log file <%s> one line at a time...' % fname
1921 print 'Loading log file <%s> one line at a time...' % fname
1917 if kw['quiet']:
1922 if kw['quiet']:
1918 stdout_save = sys.stdout
1923 stdout_save = sys.stdout
1919 sys.stdout = StringIO.StringIO()
1924 sys.stdout = StringIO.StringIO()
1920 try:
1925 try:
1921 globs,locs = where[0:2]
1926 globs,locs = where[0:2]
1922 except:
1927 except:
1923 try:
1928 try:
1924 globs = locs = where[0]
1929 globs = locs = where[0]
1925 except:
1930 except:
1926 globs = locs = globals()
1931 globs = locs = globals()
1927 badblocks = []
1932 badblocks = []
1928
1933
1929 # we also need to identify indented blocks of code when replaying
1934 # we also need to identify indented blocks of code when replaying
1930 # logs and put them together before passing them to an exec
1935 # logs and put them together before passing them to an exec
1931 # statement. This takes a bit of regexp and look-ahead work in the
1936 # statement. This takes a bit of regexp and look-ahead work in the
1932 # file. It's easiest if we swallow the whole thing in memory
1937 # file. It's easiest if we swallow the whole thing in memory
1933 # first, and manually walk through the lines list moving the
1938 # first, and manually walk through the lines list moving the
1934 # counter ourselves.
1939 # counter ourselves.
1935 indent_re = re.compile('\s+\S')
1940 indent_re = re.compile('\s+\S')
1936 xfile = open(fname)
1941 xfile = open(fname)
1937 filelines = xfile.readlines()
1942 filelines = xfile.readlines()
1938 xfile.close()
1943 xfile.close()
1939 nlines = len(filelines)
1944 nlines = len(filelines)
1940 lnum = 0
1945 lnum = 0
1941 while lnum < nlines:
1946 while lnum < nlines:
1942 line = filelines[lnum]
1947 line = filelines[lnum]
1943 lnum += 1
1948 lnum += 1
1944 # don't re-insert logger status info into cache
1949 # don't re-insert logger status info into cache
1945 if line.startswith('#log#'):
1950 if line.startswith('#log#'):
1946 continue
1951 continue
1947 elif line.startswith('#%s'% self.ESC_MAGIC):
1952 elif line.startswith('#%s'% self.ESC_MAGIC):
1948 self.update_cache(line[1:])
1953 self.update_cache(line[1:])
1949 line = magic2python(line)
1954 line = magic2python(line)
1950 elif line.startswith('#!'):
1955 elif line.startswith('#!'):
1951 self.update_cache(line[1:])
1956 self.update_cache(line[1:])
1952 else:
1957 else:
1953 # build a block of code (maybe a single line) for execution
1958 # build a block of code (maybe a single line) for execution
1954 block = line
1959 block = line
1955 try:
1960 try:
1956 next = filelines[lnum] # lnum has already incremented
1961 next = filelines[lnum] # lnum has already incremented
1957 except:
1962 except:
1958 next = None
1963 next = None
1959 while next and indent_re.match(next):
1964 while next and indent_re.match(next):
1960 block += next
1965 block += next
1961 lnum += 1
1966 lnum += 1
1962 try:
1967 try:
1963 next = filelines[lnum]
1968 next = filelines[lnum]
1964 except:
1969 except:
1965 next = None
1970 next = None
1966 # now execute the block of one or more lines
1971 # now execute the block of one or more lines
1967 try:
1972 try:
1968 exec block in globs,locs
1973 exec block in globs,locs
1969 self.update_cache(block.rstrip())
1974 self.update_cache(block.rstrip())
1970 except SystemExit:
1975 except SystemExit:
1971 pass
1976 pass
1972 except:
1977 except:
1973 badblocks.append(block.rstrip())
1978 badblocks.append(block.rstrip())
1974 if kw['quiet']: # restore stdout
1979 if kw['quiet']: # restore stdout
1975 sys.stdout.close()
1980 sys.stdout.close()
1976 sys.stdout = stdout_save
1981 sys.stdout = stdout_save
1977 print 'Finished replaying log file <%s>' % fname
1982 print 'Finished replaying log file <%s>' % fname
1978 if badblocks:
1983 if badblocks:
1979 print >> sys.stderr, \
1984 print >> sys.stderr, \
1980 '\nThe following lines/blocks in file <%s> reported errors:' \
1985 '\nThe following lines/blocks in file <%s> reported errors:' \
1981 % fname
1986 % fname
1982 for badline in badblocks:
1987 for badline in badblocks:
1983 print >> sys.stderr, badline
1988 print >> sys.stderr, badline
1984 else: # regular file execution
1989 else: # regular file execution
1985 try:
1990 try:
1986 execfile(fname,*where)
1991 execfile(fname,*where)
1987 except SyntaxError:
1992 except SyntaxError:
1988 etype, evalue = sys.exc_info()[0:2]
1993 etype, evalue = sys.exc_info()[0:2]
1989 self.SyntaxTB(etype,evalue,[])
1994 self.SyntaxTB(etype,evalue,[])
1990 warn('Failure executing file: <%s>' % fname)
1995 warn('Failure executing file: <%s>' % fname)
1991 except SystemExit,status:
1996 except SystemExit,status:
1992 if not kw['exit_ignore']:
1997 if not kw['exit_ignore']:
1993 self.InteractiveTB()
1998 self.InteractiveTB()
1994 warn('Failure executing file: <%s>' % fname)
1999 warn('Failure executing file: <%s>' % fname)
1995 except:
2000 except:
1996 self.InteractiveTB()
2001 self.InteractiveTB()
1997 warn('Failure executing file: <%s>' % fname)
2002 warn('Failure executing file: <%s>' % fname)
1998
2003
1999 #************************* end of file <iplib.py> *****************************
2004 #************************* end of file <iplib.py> *****************************
@@ -1,859 +1,860 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 ultraTB.py -- Spice up your tracebacks!
3 ultraTB.py -- Spice up your tracebacks!
4
4
5 * ColorTB
5 * ColorTB
6 I've always found it a bit hard to visually parse tracebacks in Python. The
6 I've always found it a bit hard to visually parse tracebacks in Python. The
7 ColorTB class is a solution to that problem. It colors the different parts of a
7 ColorTB class is a solution to that problem. It colors the different parts of a
8 traceback in a manner similar to what you would expect from a syntax-highlighting
8 traceback in a manner similar to what you would expect from a syntax-highlighting
9 text editor.
9 text editor.
10
10
11 Installation instructions for ColorTB:
11 Installation instructions for ColorTB:
12 import sys,ultraTB
12 import sys,ultraTB
13 sys.excepthook = ultraTB.ColorTB()
13 sys.excepthook = ultraTB.ColorTB()
14
14
15 * VerboseTB
15 * VerboseTB
16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
16 I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds
17 of useful info when a traceback occurs. Ping originally had it spit out HTML
17 of useful info when a traceback occurs. Ping originally had it spit out HTML
18 and intended it for CGI programmers, but why should they have all the fun? I
18 and intended it for CGI programmers, but why should they have all the fun? I
19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
19 altered it to spit out colored text to the terminal. It's a bit overwhelming,
20 but kind of neat, and maybe useful for long-running programs that you believe
20 but kind of neat, and maybe useful for long-running programs that you believe
21 are bug-free. If a crash *does* occur in that type of program you want details.
21 are bug-free. If a crash *does* occur in that type of program you want details.
22 Give it a shot--you'll love it or you'll hate it.
22 Give it a shot--you'll love it or you'll hate it.
23
23
24 Note:
24 Note:
25
25
26 The Verbose mode prints the variables currently visible where the exception
26 The Verbose mode prints the variables currently visible where the exception
27 happened (shortening their strings if too long). This can potentially be
27 happened (shortening their strings if too long). This can potentially be
28 very slow, if you happen to have a huge data structure whose string
28 very slow, if you happen to have a huge data structure whose string
29 representation is complex to compute. Your computer may appear to freeze for
29 representation is complex to compute. Your computer may appear to freeze for
30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
30 a while with cpu usage at 100%. If this occurs, you can cancel the traceback
31 with Ctrl-C (maybe hitting it more than once).
31 with Ctrl-C (maybe hitting it more than once).
32
32
33 If you encounter this kind of situation often, you may want to use the
33 If you encounter this kind of situation often, you may want to use the
34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
34 Verbose_novars mode instead of the regular Verbose, which avoids formatting
35 variables (but otherwise includes the information and context given by
35 variables (but otherwise includes the information and context given by
36 Verbose).
36 Verbose).
37
37
38
38
39 Installation instructions for ColorTB:
39 Installation instructions for ColorTB:
40 import sys,ultraTB
40 import sys,ultraTB
41 sys.excepthook = ultraTB.VerboseTB()
41 sys.excepthook = ultraTB.VerboseTB()
42
42
43 Note: Much of the code in this module was lifted verbatim from the standard
43 Note: Much of the code in this module was lifted verbatim from the standard
44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
44 library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'.
45
45
46 * Color schemes
46 * Color schemes
47 The colors are defined in the class TBTools through the use of the
47 The colors are defined in the class TBTools through the use of the
48 ColorSchemeTable class. Currently the following exist:
48 ColorSchemeTable class. Currently the following exist:
49
49
50 - NoColor: allows all of this module to be used in any terminal (the color
50 - NoColor: allows all of this module to be used in any terminal (the color
51 escapes are just dummy blank strings).
51 escapes are just dummy blank strings).
52
52
53 - Linux: is meant to look good in a terminal like the Linux console (black
53 - Linux: is meant to look good in a terminal like the Linux console (black
54 or very dark background).
54 or very dark background).
55
55
56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
56 - LightBG: similar to Linux but swaps dark/light colors to be more readable
57 in light background terminals.
57 in light background terminals.
58
58
59 You can implement other color schemes easily, the syntax is fairly
59 You can implement other color schemes easily, the syntax is fairly
60 self-explanatory. Please send back new schemes you develop to the author for
60 self-explanatory. Please send back new schemes you develop to the author for
61 possible inclusion in future releases.
61 possible inclusion in future releases.
62
62
63 $Id: ultraTB.py 636 2005-07-17 03:11:11Z fperez $"""
63 $Id: ultraTB.py 703 2005-08-16 17:34:44Z fperez $"""
64
64
65 #*****************************************************************************
65 #*****************************************************************************
66 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
66 # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>
67 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
67 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
68 #
68 #
69 # Distributed under the terms of the BSD License. The full license is in
69 # Distributed under the terms of the BSD License. The full license is in
70 # the file COPYING, distributed as part of this software.
70 # the file COPYING, distributed as part of this software.
71 #*****************************************************************************
71 #*****************************************************************************
72
72
73 from IPython import Release
73 from IPython import Release
74 __author__ = '%s <%s>\n%s <%s>' % (Release.authors['Nathan']+
74 __author__ = '%s <%s>\n%s <%s>' % (Release.authors['Nathan']+
75 Release.authors['Fernando'])
75 Release.authors['Fernando'])
76 __license__ = Release.license
76 __license__ = Release.license
77
77
78 # Required modules
78 # Required modules
79 import sys, os, traceback, types, string, time
79 import sys, os, traceback, types, string, time
80 import keyword, tokenize, linecache, inspect, pydoc
80 import keyword, tokenize, linecache, inspect, pydoc
81 from UserDict import UserDict
81 from UserDict import UserDict
82
82
83 # IPython's own modules
83 # IPython's own modules
84 # Modified pdb which doesn't damage IPython's readline handling
84 # Modified pdb which doesn't damage IPython's readline handling
85 from IPython import Debugger
85 from IPython import Debugger
86
86
87 from IPython.Struct import Struct
87 from IPython.Struct import Struct
88 from IPython.ColorANSI import *
88 from IPython.ColorANSI import *
89 from IPython.genutils import Term,uniq_stable,error,info
89 from IPython.genutils import Term,uniq_stable,error,info
90
90
91 #---------------------------------------------------------------------------
91 #---------------------------------------------------------------------------
92 # Code begins
92 # Code begins
93
93
94 def inspect_error():
94 def inspect_error():
95 """Print a message about internal inspect errors.
95 """Print a message about internal inspect errors.
96
96
97 These are unfortunately quite common."""
97 These are unfortunately quite common."""
98
98
99 error('Internal Python error in the inspect module.\n'
99 error('Internal Python error in the inspect module.\n'
100 'Below is the traceback from this internal error.\n')
100 'Below is the traceback from this internal error.\n')
101
101
102 # Make a global variable out of the color scheme table used for coloring
102 # Make a global variable out of the color scheme table used for coloring
103 # exception tracebacks. This allows user code to add new schemes at runtime.
103 # exception tracebacks. This allows user code to add new schemes at runtime.
104 ExceptionColors = ColorSchemeTable()
104 ExceptionColors = ColorSchemeTable()
105
105
106 # Populate it with color schemes
106 # Populate it with color schemes
107 C = TermColors # shorthand and local lookup
107 C = TermColors # shorthand and local lookup
108 ExceptionColors.add_scheme(ColorScheme(
108 ExceptionColors.add_scheme(ColorScheme(
109 'NoColor',
109 'NoColor',
110 # The color to be used for the top line
110 # The color to be used for the top line
111 topline = C.NoColor,
111 topline = C.NoColor,
112
112
113 # The colors to be used in the traceback
113 # The colors to be used in the traceback
114 filename = C.NoColor,
114 filename = C.NoColor,
115 lineno = C.NoColor,
115 lineno = C.NoColor,
116 name = C.NoColor,
116 name = C.NoColor,
117 vName = C.NoColor,
117 vName = C.NoColor,
118 val = C.NoColor,
118 val = C.NoColor,
119 em = C.NoColor,
119 em = C.NoColor,
120
120
121 # Emphasized colors for the last frame of the traceback
121 # Emphasized colors for the last frame of the traceback
122 normalEm = C.NoColor,
122 normalEm = C.NoColor,
123 filenameEm = C.NoColor,
123 filenameEm = C.NoColor,
124 linenoEm = C.NoColor,
124 linenoEm = C.NoColor,
125 nameEm = C.NoColor,
125 nameEm = C.NoColor,
126 valEm = C.NoColor,
126 valEm = C.NoColor,
127
127
128 # Colors for printing the exception
128 # Colors for printing the exception
129 excName = C.NoColor,
129 excName = C.NoColor,
130 line = C.NoColor,
130 line = C.NoColor,
131 caret = C.NoColor,
131 caret = C.NoColor,
132 Normal = C.NoColor
132 Normal = C.NoColor
133 ))
133 ))
134
134
135 # make some schemes as instances so we can copy them for modification easily
135 # make some schemes as instances so we can copy them for modification easily
136 ExceptionColors.add_scheme(ColorScheme(
136 ExceptionColors.add_scheme(ColorScheme(
137 'Linux',
137 'Linux',
138 # The color to be used for the top line
138 # The color to be used for the top line
139 topline = C.LightRed,
139 topline = C.LightRed,
140
140
141 # The colors to be used in the traceback
141 # The colors to be used in the traceback
142 filename = C.Green,
142 filename = C.Green,
143 lineno = C.Green,
143 lineno = C.Green,
144 name = C.Purple,
144 name = C.Purple,
145 vName = C.Cyan,
145 vName = C.Cyan,
146 val = C.Green,
146 val = C.Green,
147 em = C.LightCyan,
147 em = C.LightCyan,
148
148
149 # Emphasized colors for the last frame of the traceback
149 # Emphasized colors for the last frame of the traceback
150 normalEm = C.LightCyan,
150 normalEm = C.LightCyan,
151 filenameEm = C.LightGreen,
151 filenameEm = C.LightGreen,
152 linenoEm = C.LightGreen,
152 linenoEm = C.LightGreen,
153 nameEm = C.LightPurple,
153 nameEm = C.LightPurple,
154 valEm = C.LightBlue,
154 valEm = C.LightBlue,
155
155
156 # Colors for printing the exception
156 # Colors for printing the exception
157 excName = C.LightRed,
157 excName = C.LightRed,
158 line = C.Yellow,
158 line = C.Yellow,
159 caret = C.White,
159 caret = C.White,
160 Normal = C.Normal
160 Normal = C.Normal
161 ))
161 ))
162
162
163 # For light backgrounds, swap dark/light colors
163 # For light backgrounds, swap dark/light colors
164 ExceptionColors.add_scheme(ColorScheme(
164 ExceptionColors.add_scheme(ColorScheme(
165 'LightBG',
165 'LightBG',
166 # The color to be used for the top line
166 # The color to be used for the top line
167 topline = C.Red,
167 topline = C.Red,
168
168
169 # The colors to be used in the traceback
169 # The colors to be used in the traceback
170 filename = C.LightGreen,
170 filename = C.LightGreen,
171 lineno = C.LightGreen,
171 lineno = C.LightGreen,
172 name = C.LightPurple,
172 name = C.LightPurple,
173 vName = C.Cyan,
173 vName = C.Cyan,
174 val = C.LightGreen,
174 val = C.LightGreen,
175 em = C.Cyan,
175 em = C.Cyan,
176
176
177 # Emphasized colors for the last frame of the traceback
177 # Emphasized colors for the last frame of the traceback
178 normalEm = C.Cyan,
178 normalEm = C.Cyan,
179 filenameEm = C.Green,
179 filenameEm = C.Green,
180 linenoEm = C.Green,
180 linenoEm = C.Green,
181 nameEm = C.Purple,
181 nameEm = C.Purple,
182 valEm = C.Blue,
182 valEm = C.Blue,
183
183
184 # Colors for printing the exception
184 # Colors for printing the exception
185 excName = C.Red,
185 excName = C.Red,
186 #line = C.Brown, # brown often is displayed as yellow
186 #line = C.Brown, # brown often is displayed as yellow
187 line = C.Red,
187 line = C.Red,
188 caret = C.Normal,
188 caret = C.Normal,
189 Normal = C.Normal
189 Normal = C.Normal
190 ))
190 ))
191
191
192 class TBTools:
192 class TBTools:
193 """Basic tools used by all traceback printer classes."""
193 """Basic tools used by all traceback printer classes."""
194
194
195 def __init__(self,color_scheme = 'NoColor',call_pdb=0):
195 def __init__(self,color_scheme = 'NoColor',call_pdb=0):
196 # Whether to call the interactive pdb debugger after printing
196 # Whether to call the interactive pdb debugger after printing
197 # tracebacks or not
197 # tracebacks or not
198 self.call_pdb = call_pdb
198 self.call_pdb = call_pdb
199 if call_pdb:
199 if call_pdb:
200 self.pdb = Debugger.Pdb()
200 self.pdb = Debugger.Pdb()
201 else:
201 else:
202 self.pdb = None
202 self.pdb = None
203
203
204 # Create color table
204 # Create color table
205 self.ColorSchemeTable = ExceptionColors
205 self.ColorSchemeTable = ExceptionColors
206
206
207 self.set_colors(color_scheme)
207 self.set_colors(color_scheme)
208 self.old_scheme = color_scheme # save initial value for toggles
208 self.old_scheme = color_scheme # save initial value for toggles
209
209
210 def set_colors(self,*args,**kw):
210 def set_colors(self,*args,**kw):
211 """Shorthand access to the color table scheme selector method."""
211 """Shorthand access to the color table scheme selector method."""
212
212
213 self.ColorSchemeTable.set_active_scheme(*args,**kw)
213 self.ColorSchemeTable.set_active_scheme(*args,**kw)
214 # for convenience, set Colors to the active scheme
214 # for convenience, set Colors to the active scheme
215 self.Colors = self.ColorSchemeTable.active_colors
215 self.Colors = self.ColorSchemeTable.active_colors
216
216
217 def color_toggle(self):
217 def color_toggle(self):
218 """Toggle between the currently active color scheme and NoColor."""
218 """Toggle between the currently active color scheme and NoColor."""
219
219
220 if self.ColorSchemeTable.active_scheme_name == 'NoColor':
220 if self.ColorSchemeTable.active_scheme_name == 'NoColor':
221 self.ColorSchemeTable.set_active_scheme(self.old_scheme)
221 self.ColorSchemeTable.set_active_scheme(self.old_scheme)
222 self.Colors = self.ColorSchemeTable.active_colors
222 self.Colors = self.ColorSchemeTable.active_colors
223 else:
223 else:
224 self.old_scheme = self.ColorSchemeTable.active_scheme_name
224 self.old_scheme = self.ColorSchemeTable.active_scheme_name
225 self.ColorSchemeTable.set_active_scheme('NoColor')
225 self.ColorSchemeTable.set_active_scheme('NoColor')
226 self.Colors = self.ColorSchemeTable.active_colors
226 self.Colors = self.ColorSchemeTable.active_colors
227
227
228 #---------------------------------------------------------------------------
228 #---------------------------------------------------------------------------
229 class ListTB(TBTools):
229 class ListTB(TBTools):
230 """Print traceback information from a traceback list, with optional color.
230 """Print traceback information from a traceback list, with optional color.
231
231
232 Calling: requires 3 arguments:
232 Calling: requires 3 arguments:
233 (etype, evalue, elist)
233 (etype, evalue, elist)
234 as would be obtained by:
234 as would be obtained by:
235 etype, evalue, tb = sys.exc_info()
235 etype, evalue, tb = sys.exc_info()
236 if tb:
236 if tb:
237 elist = traceback.extract_tb(tb)
237 elist = traceback.extract_tb(tb)
238 else:
238 else:
239 elist = None
239 elist = None
240
240
241 It can thus be used by programs which need to process the traceback before
241 It can thus be used by programs which need to process the traceback before
242 printing (such as console replacements based on the code module from the
242 printing (such as console replacements based on the code module from the
243 standard library).
243 standard library).
244
244
245 Because they are meant to be called without a full traceback (only a
245 Because they are meant to be called without a full traceback (only a
246 list), instances of this class can't call the interactive pdb debugger."""
246 list), instances of this class can't call the interactive pdb debugger."""
247
247
248 def __init__(self,color_scheme = 'NoColor'):
248 def __init__(self,color_scheme = 'NoColor'):
249 TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0)
249 TBTools.__init__(self,color_scheme = color_scheme,call_pdb=0)
250
250
251 def __call__(self, etype, value, elist):
251 def __call__(self, etype, value, elist):
252 print >> Term.cerr, self.text(etype,value,elist)
252 print >> Term.cerr, self.text(etype,value,elist)
253
253
254 def text(self,etype, value, elist,context=5):
254 def text(self,etype, value, elist,context=5):
255 """Return a color formatted string with the traceback info."""
255 """Return a color formatted string with the traceback info."""
256
256
257 Colors = self.Colors
257 Colors = self.Colors
258 out_string = ['%s%s%s\n' % (Colors.topline,'-'*60,Colors.Normal)]
258 out_string = ['%s%s%s\n' % (Colors.topline,'-'*60,Colors.Normal)]
259 if elist:
259 if elist:
260 out_string.append('Traceback %s(most recent call last)%s:' % \
260 out_string.append('Traceback %s(most recent call last)%s:' % \
261 (Colors.normalEm, Colors.Normal) + '\n')
261 (Colors.normalEm, Colors.Normal) + '\n')
262 out_string.extend(self._format_list(elist))
262 out_string.extend(self._format_list(elist))
263 lines = self._format_exception_only(etype, value)
263 lines = self._format_exception_only(etype, value)
264 for line in lines[:-1]:
264 for line in lines[:-1]:
265 out_string.append(" "+line)
265 out_string.append(" "+line)
266 out_string.append(lines[-1])
266 out_string.append(lines[-1])
267 return ''.join(out_string)
267 return ''.join(out_string)
268
268
269 def _format_list(self, extracted_list):
269 def _format_list(self, extracted_list):
270 """Format a list of traceback entry tuples for printing.
270 """Format a list of traceback entry tuples for printing.
271
271
272 Given a list of tuples as returned by extract_tb() or
272 Given a list of tuples as returned by extract_tb() or
273 extract_stack(), return a list of strings ready for printing.
273 extract_stack(), return a list of strings ready for printing.
274 Each string in the resulting list corresponds to the item with the
274 Each string in the resulting list corresponds to the item with the
275 same index in the argument list. Each string ends in a newline;
275 same index in the argument list. Each string ends in a newline;
276 the strings may contain internal newlines as well, for those items
276 the strings may contain internal newlines as well, for those items
277 whose source text line is not None.
277 whose source text line is not None.
278
278
279 Lifted almost verbatim from traceback.py
279 Lifted almost verbatim from traceback.py
280 """
280 """
281
281
282 Colors = self.Colors
282 Colors = self.Colors
283 list = []
283 list = []
284 for filename, lineno, name, line in extracted_list[:-1]:
284 for filename, lineno, name, line in extracted_list[:-1]:
285 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
285 item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
286 (Colors.filename, filename, Colors.Normal,
286 (Colors.filename, filename, Colors.Normal,
287 Colors.lineno, lineno, Colors.Normal,
287 Colors.lineno, lineno, Colors.Normal,
288 Colors.name, name, Colors.Normal)
288 Colors.name, name, Colors.Normal)
289 if line:
289 if line:
290 item = item + ' %s\n' % line.strip()
290 item = item + ' %s\n' % line.strip()
291 list.append(item)
291 list.append(item)
292 # Emphasize the last entry
292 # Emphasize the last entry
293 filename, lineno, name, line = extracted_list[-1]
293 filename, lineno, name, line = extracted_list[-1]
294 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
294 item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
295 (Colors.normalEm,
295 (Colors.normalEm,
296 Colors.filenameEm, filename, Colors.normalEm,
296 Colors.filenameEm, filename, Colors.normalEm,
297 Colors.linenoEm, lineno, Colors.normalEm,
297 Colors.linenoEm, lineno, Colors.normalEm,
298 Colors.nameEm, name, Colors.normalEm,
298 Colors.nameEm, name, Colors.normalEm,
299 Colors.Normal)
299 Colors.Normal)
300 if line:
300 if line:
301 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
301 item = item + '%s %s%s\n' % (Colors.line, line.strip(),
302 Colors.Normal)
302 Colors.Normal)
303 list.append(item)
303 list.append(item)
304 return list
304 return list
305
305
306 def _format_exception_only(self, etype, value):
306 def _format_exception_only(self, etype, value):
307 """Format the exception part of a traceback.
307 """Format the exception part of a traceback.
308
308
309 The arguments are the exception type and value such as given by
309 The arguments are the exception type and value such as given by
310 sys.last_type and sys.last_value. The return value is a list of
310 sys.last_type and sys.last_value. The return value is a list of
311 strings, each ending in a newline. Normally, the list contains a
311 strings, each ending in a newline. Normally, the list contains a
312 single string; however, for SyntaxError exceptions, it contains
312 single string; however, for SyntaxError exceptions, it contains
313 several lines that (when printed) display detailed information
313 several lines that (when printed) display detailed information
314 about where the syntax error occurred. The message indicating
314 about where the syntax error occurred. The message indicating
315 which exception occurred is the always last string in the list.
315 which exception occurred is the always last string in the list.
316
316
317 Also lifted nearly verbatim from traceback.py
317 Also lifted nearly verbatim from traceback.py
318 """
318 """
319
319
320 Colors = self.Colors
320 Colors = self.Colors
321 list = []
321 list = []
322 if type(etype) == types.ClassType:
322 if type(etype) == types.ClassType:
323 stype = Colors.excName + etype.__name__ + Colors.Normal
323 stype = Colors.excName + etype.__name__ + Colors.Normal
324 else:
324 else:
325 stype = etype # String exceptions don't get special coloring
325 stype = etype # String exceptions don't get special coloring
326 if value is None:
326 if value is None:
327 list.append( str(stype) + '\n')
327 list.append( str(stype) + '\n')
328 else:
328 else:
329 if etype is SyntaxError:
329 if etype is SyntaxError:
330 try:
330 try:
331 msg, (filename, lineno, offset, line) = value
331 msg, (filename, lineno, offset, line) = value
332 except:
332 except:
333 pass
333 pass
334 else:
334 else:
335 #print 'filename is',filename # dbg
335 #print 'filename is',filename # dbg
336 if not filename: filename = "<string>"
336 if not filename: filename = "<string>"
337 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
337 list.append('%s File %s"%s"%s, line %s%d%s\n' % \
338 (Colors.normalEm,
338 (Colors.normalEm,
339 Colors.filenameEm, filename, Colors.normalEm,
339 Colors.filenameEm, filename, Colors.normalEm,
340 Colors.linenoEm, lineno, Colors.Normal ))
340 Colors.linenoEm, lineno, Colors.Normal ))
341 if line is not None:
341 if line is not None:
342 i = 0
342 i = 0
343 while i < len(line) and line[i].isspace():
343 while i < len(line) and line[i].isspace():
344 i = i+1
344 i = i+1
345 list.append('%s %s%s\n' % (Colors.line,
345 list.append('%s %s%s\n' % (Colors.line,
346 line.strip(),
346 line.strip(),
347 Colors.Normal))
347 Colors.Normal))
348 if offset is not None:
348 if offset is not None:
349 s = ' '
349 s = ' '
350 for c in line[i:offset-1]:
350 for c in line[i:offset-1]:
351 if c.isspace():
351 if c.isspace():
352 s = s + c
352 s = s + c
353 else:
353 else:
354 s = s + ' '
354 s = s + ' '
355 list.append('%s%s^%s\n' % (Colors.caret, s,
355 list.append('%s%s^%s\n' % (Colors.caret, s,
356 Colors.Normal) )
356 Colors.Normal) )
357 value = msg
357 value = msg
358 s = self._some_str(value)
358 s = self._some_str(value)
359 if s:
359 if s:
360 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
360 list.append('%s%s:%s %s\n' % (str(stype), Colors.excName,
361 Colors.Normal, s))
361 Colors.Normal, s))
362 else:
362 else:
363 list.append('%s\n' % str(stype))
363 list.append('%s\n' % str(stype))
364 return list
364 return list
365
365
366 def _some_str(self, value):
366 def _some_str(self, value):
367 # Lifted from traceback.py
367 # Lifted from traceback.py
368 try:
368 try:
369 return str(value)
369 return str(value)
370 except:
370 except:
371 return '<unprintable %s object>' % type(value).__name__
371 return '<unprintable %s object>' % type(value).__name__
372
372
373 #----------------------------------------------------------------------------
373 #----------------------------------------------------------------------------
374 class VerboseTB(TBTools):
374 class VerboseTB(TBTools):
375 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
375 """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead
376 of HTML. Requires inspect and pydoc. Crazy, man.
376 of HTML. Requires inspect and pydoc. Crazy, man.
377
377
378 Modified version which optionally strips the topmost entries from the
378 Modified version which optionally strips the topmost entries from the
379 traceback, to be used with alternate interpreters (because their own code
379 traceback, to be used with alternate interpreters (because their own code
380 would appear in the traceback)."""
380 would appear in the traceback)."""
381
381
382 def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0,
382 def __init__(self,color_scheme = 'Linux',tb_offset=0,long_header=0,
383 call_pdb = 0, include_vars=1):
383 call_pdb = 0, include_vars=1):
384 """Specify traceback offset, headers and color scheme.
384 """Specify traceback offset, headers and color scheme.
385
385
386 Define how many frames to drop from the tracebacks. Calling it with
386 Define how many frames to drop from the tracebacks. Calling it with
387 tb_offset=1 allows use of this handler in interpreters which will have
387 tb_offset=1 allows use of this handler in interpreters which will have
388 their own code at the top of the traceback (VerboseTB will first
388 their own code at the top of the traceback (VerboseTB will first
389 remove that frame before printing the traceback info)."""
389 remove that frame before printing the traceback info)."""
390 TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb)
390 TBTools.__init__(self,color_scheme=color_scheme,call_pdb=call_pdb)
391 self.tb_offset = tb_offset
391 self.tb_offset = tb_offset
392 self.long_header = long_header
392 self.long_header = long_header
393 self.include_vars = include_vars
393 self.include_vars = include_vars
394
394
395 def text(self, etype, evalue, etb, context=5):
395 def text(self, etype, evalue, etb, context=5):
396 """Return a nice text document describing the traceback."""
396 """Return a nice text document describing the traceback."""
397
397
398 # some locals
398 # some locals
399 Colors = self.Colors # just a shorthand + quicker name lookup
399 Colors = self.Colors # just a shorthand + quicker name lookup
400 ColorsNormal = Colors.Normal # used a lot
400 ColorsNormal = Colors.Normal # used a lot
401 indent_size = 8 # we need some space to put line numbers before
401 indent_size = 8 # we need some space to put line numbers before
402 indent = ' '*indent_size
402 indent = ' '*indent_size
403 numbers_width = indent_size - 1 # leave space between numbers & code
403 numbers_width = indent_size - 1 # leave space between numbers & code
404 text_repr = pydoc.text.repr
404 text_repr = pydoc.text.repr
405 exc = '%s%s%s' % (Colors.excName, str(etype), ColorsNormal)
405 exc = '%s%s%s' % (Colors.excName, str(etype), ColorsNormal)
406 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
406 em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal)
407 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
407 undefined = '%sundefined%s' % (Colors.em, ColorsNormal)
408
408
409 # some internal-use functions
409 # some internal-use functions
410 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
410 def eqrepr(value, repr=text_repr): return '=%s' % repr(value)
411 def nullrepr(value, repr=text_repr): return ''
411 def nullrepr(value, repr=text_repr): return ''
412
412
413 # meat of the code begins
413 # meat of the code begins
414 if type(etype) is types.ClassType:
414 if type(etype) is types.ClassType:
415 etype = etype.__name__
415 etype = etype.__name__
416
416
417 if self.long_header:
417 if self.long_header:
418 # Header with the exception type, python version, and date
418 # Header with the exception type, python version, and date
419 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
419 pyver = 'Python ' + string.split(sys.version)[0] + ': ' + sys.executable
420 date = time.ctime(time.time())
420 date = time.ctime(time.time())
421
421
422 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
422 head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal,
423 exc, ' '*(75-len(str(etype))-len(pyver)),
423 exc, ' '*(75-len(str(etype))-len(pyver)),
424 pyver, string.rjust(date, 75) )
424 pyver, string.rjust(date, 75) )
425 head += "\nA problem occured executing Python code. Here is the sequence of function"\
425 head += "\nA problem occured executing Python code. Here is the sequence of function"\
426 "\ncalls leading up to the error, with the most recent (innermost) call last."
426 "\ncalls leading up to the error, with the most recent (innermost) call last."
427 else:
427 else:
428 # Simplified header
428 # Simplified header
429 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
429 head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc,
430 string.rjust('Traceback (most recent call last)',
430 string.rjust('Traceback (most recent call last)',
431 75 - len(str(etype)) ) )
431 75 - len(str(etype)) ) )
432 frames = []
432 frames = []
433 # Flush cache before calling inspect. This helps alleviate some of the
433 # Flush cache before calling inspect. This helps alleviate some of the
434 # problems with python 2.3's inspect.py.
434 # problems with python 2.3's inspect.py.
435 linecache.checkcache()
435 linecache.checkcache()
436 # Drop topmost frames if requested
436 # Drop topmost frames if requested
437 try:
437 try:
438 records = inspect.getinnerframes(etb, context)[self.tb_offset:]
438 records = inspect.getinnerframes(etb, context)[self.tb_offset:]
439 except:
439 except:
440
440
441 # FIXME: I've been getting many crash reports from python 2.3
441 # FIXME: I've been getting many crash reports from python 2.3
442 # users, traceable to inspect.py. If I can find a small test-case
442 # users, traceable to inspect.py. If I can find a small test-case
443 # to reproduce this, I should either write a better workaround or
443 # to reproduce this, I should either write a better workaround or
444 # file a bug report against inspect (if that's the real problem).
444 # file a bug report against inspect (if that's the real problem).
445 # So far, I haven't been able to find an isolated example to
445 # So far, I haven't been able to find an isolated example to
446 # reproduce the problem.
446 # reproduce the problem.
447 inspect_error()
447 inspect_error()
448 traceback.print_exc(file=Term.cerr)
448 traceback.print_exc(file=Term.cerr)
449 info('\nUnfortunately, your original traceback can not be constructed.\n')
449 info('\nUnfortunately, your original traceback can not be constructed.\n')
450 return ''
450 return ''
451
451
452 # build some color string templates outside these nested loops
452 # build some color string templates outside these nested loops
453 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
453 tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal)
454 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
454 tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm,
455 ColorsNormal)
455 ColorsNormal)
456 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
456 tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \
457 (Colors.vName, Colors.valEm, ColorsNormal)
457 (Colors.vName, Colors.valEm, ColorsNormal)
458 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
458 tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal)
459 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
459 tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal,
460 Colors.vName, ColorsNormal)
460 Colors.vName, ColorsNormal)
461 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
461 tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal)
462 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
462 tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal)
463 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
463 tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line,
464 ColorsNormal)
464 ColorsNormal)
465
465
466 # now, loop over all records printing context and info
466 # now, loop over all records printing context and info
467 abspath = os.path.abspath
467 abspath = os.path.abspath
468 for frame, file, lnum, func, lines, index in records:
468 for frame, file, lnum, func, lines, index in records:
469 #print '*** record:',file,lnum,func,lines,index # dbg
469 #print '*** record:',file,lnum,func,lines,index # dbg
470 try:
470 try:
471 file = file and abspath(file) or '?'
471 file = file and abspath(file) or '?'
472 except OSError:
472 except OSError:
473 # if file is '<console>' or something not in the filesystem,
473 # if file is '<console>' or something not in the filesystem,
474 # the abspath call will throw an OSError. Just ignore it and
474 # the abspath call will throw an OSError. Just ignore it and
475 # keep the original file string.
475 # keep the original file string.
476 pass
476 pass
477 link = tpl_link % file
477 link = tpl_link % file
478 try:
478 try:
479 args, varargs, varkw, locals = inspect.getargvalues(frame)
479 args, varargs, varkw, locals = inspect.getargvalues(frame)
480 except:
480 except:
481 # This can happen due to a bug in python2.3. We should be
481 # This can happen due to a bug in python2.3. We should be
482 # able to remove this try/except when 2.4 becomes a
482 # able to remove this try/except when 2.4 becomes a
483 # requirement. Bug details at http://python.org/sf/1005466
483 # requirement. Bug details at http://python.org/sf/1005466
484 inspect_error()
484 inspect_error()
485 traceback.print_exc(file=Term.cerr)
485 traceback.print_exc(file=Term.cerr)
486 info("\nIPython's exception reporting continues...\n")
486 info("\nIPython's exception reporting continues...\n")
487
487
488 if func == '?':
488 if func == '?':
489 call = ''
489 call = ''
490 else:
490 else:
491 # Decide whether to include variable details or not
491 # Decide whether to include variable details or not
492 var_repr = self.include_vars and eqrepr or nullrepr
492 var_repr = self.include_vars and eqrepr or nullrepr
493 try:
493 try:
494 call = tpl_call % (func,inspect.formatargvalues(args,
494 call = tpl_call % (func,inspect.formatargvalues(args,
495 varargs, varkw,
495 varargs, varkw,
496 locals,formatvalue=var_repr))
496 locals,formatvalue=var_repr))
497 except KeyError:
497 except KeyError:
498 # Very odd crash from inspect.formatargvalues(). The
498 # Very odd crash from inspect.formatargvalues(). The
499 # scenario under which it appeared was a call to
499 # scenario under which it appeared was a call to
500 # view(array,scale) in NumTut.view.view(), where scale had
500 # view(array,scale) in NumTut.view.view(), where scale had
501 # been defined as a scalar (it should be a tuple). Somehow
501 # been defined as a scalar (it should be a tuple). Somehow
502 # inspect messes up resolving the argument list of view()
502 # inspect messes up resolving the argument list of view()
503 # and barfs out. At some point I should dig into this one
503 # and barfs out. At some point I should dig into this one
504 # and file a bug report about it.
504 # and file a bug report about it.
505 inspect_error()
505 inspect_error()
506 traceback.print_exc(file=Term.cerr)
506 traceback.print_exc(file=Term.cerr)
507 info("\nIPython's exception reporting continues...\n")
507 info("\nIPython's exception reporting continues...\n")
508 call = tpl_call_fail % func
508 call = tpl_call_fail % func
509
509
510 # Initialize a list of names on the current line, which the
510 # Initialize a list of names on the current line, which the
511 # tokenizer below will populate.
511 # tokenizer below will populate.
512 names = []
512 names = []
513
513
514 def tokeneater(token_type, token, start, end, line):
514 def tokeneater(token_type, token, start, end, line):
515 """Stateful tokeneater which builds dotted names.
515 """Stateful tokeneater which builds dotted names.
516
516
517 The list of names it appends to (from the enclosing scope) can
517 The list of names it appends to (from the enclosing scope) can
518 contain repeated composite names. This is unavoidable, since
518 contain repeated composite names. This is unavoidable, since
519 there is no way to disambguate partial dotted structures until
519 there is no way to disambguate partial dotted structures until
520 the full list is known. The caller is responsible for pruning
520 the full list is known. The caller is responsible for pruning
521 the final list of duplicates before using it."""
521 the final list of duplicates before using it."""
522
522
523 # build composite names
523 # build composite names
524 if token == '.':
524 if token == '.':
525 try:
525 try:
526 names[-1] += '.'
526 names[-1] += '.'
527 # store state so the next token is added for x.y.z names
527 # store state so the next token is added for x.y.z names
528 tokeneater.name_cont = True
528 tokeneater.name_cont = True
529 return
529 return
530 except IndexError:
530 except IndexError:
531 pass
531 pass
532 if token_type == tokenize.NAME and token not in keyword.kwlist:
532 if token_type == tokenize.NAME and token not in keyword.kwlist:
533 if tokeneater.name_cont:
533 if tokeneater.name_cont:
534 # Dotted names
534 # Dotted names
535 names[-1] += token
535 names[-1] += token
536 tokeneater.name_cont = False
536 tokeneater.name_cont = False
537 else:
537 else:
538 # Regular new names. We append everything, the caller
538 # Regular new names. We append everything, the caller
539 # will be responsible for pruning the list later. It's
539 # will be responsible for pruning the list later. It's
540 # very tricky to try to prune as we go, b/c composite
540 # very tricky to try to prune as we go, b/c composite
541 # names can fool us. The pruning at the end is easy
541 # names can fool us. The pruning at the end is easy
542 # to do (or the caller can print a list with repeated
542 # to do (or the caller can print a list with repeated
543 # names if so desired.
543 # names if so desired.
544 names.append(token)
544 names.append(token)
545 elif token_type == tokenize.NEWLINE:
545 elif token_type == tokenize.NEWLINE:
546 raise IndexError
546 raise IndexError
547 # we need to store a bit of state in the tokenizer to build
547 # we need to store a bit of state in the tokenizer to build
548 # dotted names
548 # dotted names
549 tokeneater.name_cont = False
549 tokeneater.name_cont = False
550
550
551 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
551 def linereader(file=file, lnum=[lnum], getline=linecache.getline):
552 line = getline(file, lnum[0])
552 line = getline(file, lnum[0])
553 lnum[0] += 1
553 lnum[0] += 1
554 return line
554 return line
555
555
556 # Build the list of names on this line of code where the exception
556 # Build the list of names on this line of code where the exception
557 # occurred.
557 # occurred.
558 try:
558 try:
559 # This builds the names list in-place by capturing it from the
559 # This builds the names list in-place by capturing it from the
560 # enclosing scope.
560 # enclosing scope.
561 tokenize.tokenize(linereader, tokeneater)
561 tokenize.tokenize(linereader, tokeneater)
562 except IndexError:
562 except IndexError:
563 # signals exit of tokenizer
563 # signals exit of tokenizer
564 pass
564 pass
565 except tokenize.TokenError,msg:
565 except tokenize.TokenError,msg:
566 _m = ("An unexpected error occurred while tokenizing input\n"
566 _m = ("An unexpected error occurred while tokenizing input\n"
567 "The following traceback may be corrupted or invalid\n"
567 "The following traceback may be corrupted or invalid\n"
568 "The error message is: %s\n" % msg)
568 "The error message is: %s\n" % msg)
569 error(_m)
569 error(_m)
570
570
571 # prune names list of duplicates, but keep the right order
571 # prune names list of duplicates, but keep the right order
572 unique_names = uniq_stable(names)
572 unique_names = uniq_stable(names)
573
573
574 # Start loop over vars
574 # Start loop over vars
575 lvals = []
575 lvals = []
576 if self.include_vars:
576 if self.include_vars:
577 for name_full in unique_names:
577 for name_full in unique_names:
578 name_base = name_full.split('.',1)[0]
578 name_base = name_full.split('.',1)[0]
579 if name_base in frame.f_code.co_varnames:
579 if name_base in frame.f_code.co_varnames:
580 if locals.has_key(name_base):
580 if locals.has_key(name_base):
581 try:
581 try:
582 value = repr(eval(name_full,locals))
582 value = repr(eval(name_full,locals))
583 except:
583 except:
584 value = undefined
584 value = undefined
585 else:
585 else:
586 value = undefined
586 value = undefined
587 name = tpl_local_var % name_full
587 name = tpl_local_var % name_full
588 else:
588 else:
589 if frame.f_globals.has_key(name_base):
589 if frame.f_globals.has_key(name_base):
590 try:
590 try:
591 value = repr(eval(name_full,frame.f_globals))
591 value = repr(eval(name_full,frame.f_globals))
592 except:
592 except:
593 value = undefined
593 value = undefined
594 else:
594 else:
595 value = undefined
595 value = undefined
596 name = tpl_global_var % name_full
596 name = tpl_global_var % name_full
597 lvals.append(tpl_name_val % (name,value))
597 lvals.append(tpl_name_val % (name,value))
598 if lvals:
598 if lvals:
599 lvals = '%s%s' % (indent,em_normal.join(lvals))
599 lvals = '%s%s' % (indent,em_normal.join(lvals))
600 else:
600 else:
601 lvals = ''
601 lvals = ''
602
602
603 level = '%s %s\n' % (link,call)
603 level = '%s %s\n' % (link,call)
604 excerpt = []
604 excerpt = []
605 if index is not None:
605 if index is not None:
606 i = lnum - index
606 i = lnum - index
607 for line in lines:
607 for line in lines:
608 if i == lnum:
608 if i == lnum:
609 # This is the line with the error
609 # This is the line with the error
610 pad = numbers_width - len(str(i))
610 pad = numbers_width - len(str(i))
611 if pad >= 3:
611 if pad >= 3:
612 marker = '-'*(pad-3) + '-> '
612 marker = '-'*(pad-3) + '-> '
613 elif pad == 2:
613 elif pad == 2:
614 marker = '> '
614 marker = '> '
615 elif pad == 1:
615 elif pad == 1:
616 marker = '>'
616 marker = '>'
617 else:
617 else:
618 marker = ''
618 marker = ''
619 num = '%s%s' % (marker,i)
619 num = '%s%s' % (marker,i)
620 line = tpl_line_em % (num,line)
620 line = tpl_line_em % (num,line)
621 else:
621 else:
622 num = '%*s' % (numbers_width,i)
622 num = '%*s' % (numbers_width,i)
623 line = tpl_line % (num,line)
623 line = tpl_line % (num,line)
624
624
625 excerpt.append(line)
625 excerpt.append(line)
626 if self.include_vars and i == lnum:
626 if self.include_vars and i == lnum:
627 excerpt.append('%s\n' % lvals)
627 excerpt.append('%s\n' % lvals)
628 i += 1
628 i += 1
629 frames.append('%s%s' % (level,''.join(excerpt)) )
629 frames.append('%s%s' % (level,''.join(excerpt)) )
630
630
631 # Get (safely) a string form of the exception info
631 # Get (safely) a string form of the exception info
632 try:
632 try:
633 etype_str,evalue_str = map(str,(etype,evalue))
633 etype_str,evalue_str = map(str,(etype,evalue))
634 except:
634 except:
635 # User exception is improperly defined.
635 # User exception is improperly defined.
636 etype,evalue = str,sys.exc_info()[:2]
636 etype,evalue = str,sys.exc_info()[:2]
637 etype_str,evalue_str = map(str,(etype,evalue))
637 etype_str,evalue_str = map(str,(etype,evalue))
638 # ... and format it
638 # ... and format it
639 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
639 exception = ['%s%s%s: %s' % (Colors.excName, etype_str,
640 ColorsNormal, evalue_str)]
640 ColorsNormal, evalue_str)]
641 if type(evalue) is types.InstanceType:
641 if type(evalue) is types.InstanceType:
642 for name in dir(evalue):
642 names = [w for w in dir(evalue) if isinstance(w, basestring)]
643 for name in names:
643 value = text_repr(getattr(evalue, name))
644 value = text_repr(getattr(evalue, name))
644 exception.append('\n%s%s = %s' % (indent, name, value))
645 exception.append('\n%s%s = %s' % (indent, name, value))
645 # return all our info assembled as a single string
646 # return all our info assembled as a single string
646 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
647 return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) )
647
648
648 def debugger(self):
649 def debugger(self):
649 """Call up the pdb debugger if desired, always clean up the tb reference.
650 """Call up the pdb debugger if desired, always clean up the tb reference.
650
651
651 If the call_pdb flag is set, the pdb interactive debugger is
652 If the call_pdb flag is set, the pdb interactive debugger is
652 invoked. In all cases, the self.tb reference to the current traceback
653 invoked. In all cases, the self.tb reference to the current traceback
653 is deleted to prevent lingering references which hamper memory
654 is deleted to prevent lingering references which hamper memory
654 management.
655 management.
655
656
656 Note that each call to pdb() does an 'import readline', so if your app
657 Note that each call to pdb() does an 'import readline', so if your app
657 requires a special setup for the readline completers, you'll have to
658 requires a special setup for the readline completers, you'll have to
658 fix that by hand after invoking the exception handler."""
659 fix that by hand after invoking the exception handler."""
659
660
660 if self.call_pdb:
661 if self.call_pdb:
661 if self.pdb is None:
662 if self.pdb is None:
662 self.pdb = Debugger.Pdb()
663 self.pdb = Debugger.Pdb()
663 # the system displayhook may have changed, restore the original for pdb
664 # the system displayhook may have changed, restore the original for pdb
664 dhook = sys.displayhook
665 dhook = sys.displayhook
665 sys.displayhook = sys.__displayhook__
666 sys.displayhook = sys.__displayhook__
666 self.pdb.reset()
667 self.pdb.reset()
667 while self.tb.tb_next is not None:
668 while self.tb.tb_next is not None:
668 self.tb = self.tb.tb_next
669 self.tb = self.tb.tb_next
669 try:
670 try:
670 self.pdb.interaction(self.tb.tb_frame, self.tb)
671 self.pdb.interaction(self.tb.tb_frame, self.tb)
671 except:
672 except:
672 print '*** ERROR ***'
673 print '*** ERROR ***'
673 print 'This version of pdb has a bug and crashed.'
674 print 'This version of pdb has a bug and crashed.'
674 print 'Returning to IPython...'
675 print 'Returning to IPython...'
675 sys.displayhook = dhook
676 sys.displayhook = dhook
676 del self.tb
677 del self.tb
677
678
678 def handler(self, info=None):
679 def handler(self, info=None):
679 (etype, evalue, etb) = info or sys.exc_info()
680 (etype, evalue, etb) = info or sys.exc_info()
680 self.tb = etb
681 self.tb = etb
681 print >> Term.cerr, self.text(etype, evalue, etb)
682 print >> Term.cerr, self.text(etype, evalue, etb)
682
683
683 # Changed so an instance can just be called as VerboseTB_inst() and print
684 # Changed so an instance can just be called as VerboseTB_inst() and print
684 # out the right info on its own.
685 # out the right info on its own.
685 def __call__(self, etype=None, evalue=None, etb=None):
686 def __call__(self, etype=None, evalue=None, etb=None):
686 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
687 """This hook can replace sys.excepthook (for Python 2.1 or higher)."""
687 if etb is not None:
688 if etb is not None:
688 self.handler((etype, evalue, etb))
689 self.handler((etype, evalue, etb))
689 else:
690 else:
690 self.handler()
691 self.handler()
691 self.debugger()
692 self.debugger()
692
693
693 #----------------------------------------------------------------------------
694 #----------------------------------------------------------------------------
694 class FormattedTB(VerboseTB,ListTB):
695 class FormattedTB(VerboseTB,ListTB):
695 """Subclass ListTB but allow calling with a traceback.
696 """Subclass ListTB but allow calling with a traceback.
696
697
697 It can thus be used as a sys.excepthook for Python > 2.1.
698 It can thus be used as a sys.excepthook for Python > 2.1.
698
699
699 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
700 Also adds 'Context' and 'Verbose' modes, not available in ListTB.
700
701
701 Allows a tb_offset to be specified. This is useful for situations where
702 Allows a tb_offset to be specified. This is useful for situations where
702 one needs to remove a number of topmost frames from the traceback (such as
703 one needs to remove a number of topmost frames from the traceback (such as
703 occurs with python programs that themselves execute other python code,
704 occurs with python programs that themselves execute other python code,
704 like Python shells). """
705 like Python shells). """
705
706
706 def __init__(self, mode = 'Plain', color_scheme='Linux',
707 def __init__(self, mode = 'Plain', color_scheme='Linux',
707 tb_offset = 0,long_header=0,call_pdb=0,include_vars=0):
708 tb_offset = 0,long_header=0,call_pdb=0,include_vars=0):
708
709
709 # NEVER change the order of this list. Put new modes at the end:
710 # NEVER change the order of this list. Put new modes at the end:
710 self.valid_modes = ['Plain','Context','Verbose']
711 self.valid_modes = ['Plain','Context','Verbose']
711 self.verbose_modes = self.valid_modes[1:3]
712 self.verbose_modes = self.valid_modes[1:3]
712
713
713 VerboseTB.__init__(self,color_scheme,tb_offset,long_header,
714 VerboseTB.__init__(self,color_scheme,tb_offset,long_header,
714 call_pdb=call_pdb,include_vars=include_vars)
715 call_pdb=call_pdb,include_vars=include_vars)
715 self.set_mode(mode)
716 self.set_mode(mode)
716
717
717 def _extract_tb(self,tb):
718 def _extract_tb(self,tb):
718 if tb:
719 if tb:
719 return traceback.extract_tb(tb)
720 return traceback.extract_tb(tb)
720 else:
721 else:
721 return None
722 return None
722
723
723 def text(self, etype, value, tb,context=5,mode=None):
724 def text(self, etype, value, tb,context=5,mode=None):
724 """Return formatted traceback.
725 """Return formatted traceback.
725
726
726 If the optional mode parameter is given, it overrides the current
727 If the optional mode parameter is given, it overrides the current
727 mode."""
728 mode."""
728
729
729 if mode is None:
730 if mode is None:
730 mode = self.mode
731 mode = self.mode
731 if mode in self.verbose_modes:
732 if mode in self.verbose_modes:
732 # verbose modes need a full traceback
733 # verbose modes need a full traceback
733 return VerboseTB.text(self,etype, value, tb,context=5)
734 return VerboseTB.text(self,etype, value, tb,context=5)
734 else:
735 else:
735 # We must check the source cache because otherwise we can print
736 # We must check the source cache because otherwise we can print
736 # out-of-date source code.
737 # out-of-date source code.
737 linecache.checkcache()
738 linecache.checkcache()
738 # Now we can extract and format the exception
739 # Now we can extract and format the exception
739 elist = self._extract_tb(tb)
740 elist = self._extract_tb(tb)
740 if len(elist) > self.tb_offset:
741 if len(elist) > self.tb_offset:
741 del elist[:self.tb_offset]
742 del elist[:self.tb_offset]
742 return ListTB.text(self,etype,value,elist)
743 return ListTB.text(self,etype,value,elist)
743
744
744 def set_mode(self,mode=None):
745 def set_mode(self,mode=None):
745 """Switch to the desired mode.
746 """Switch to the desired mode.
746
747
747 If mode is not specified, cycles through the available modes."""
748 If mode is not specified, cycles through the available modes."""
748
749
749 if not mode:
750 if not mode:
750 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
751 new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \
751 len(self.valid_modes)
752 len(self.valid_modes)
752 self.mode = self.valid_modes[new_idx]
753 self.mode = self.valid_modes[new_idx]
753 elif mode not in self.valid_modes:
754 elif mode not in self.valid_modes:
754 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
755 raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\
755 'Valid modes: '+str(self.valid_modes)
756 'Valid modes: '+str(self.valid_modes)
756 else:
757 else:
757 self.mode = mode
758 self.mode = mode
758 # include variable details only in 'Verbose' mode
759 # include variable details only in 'Verbose' mode
759 self.include_vars = (self.mode == self.valid_modes[2])
760 self.include_vars = (self.mode == self.valid_modes[2])
760
761
761 # some convenient shorcuts
762 # some convenient shorcuts
762 def plain(self):
763 def plain(self):
763 self.set_mode(self.valid_modes[0])
764 self.set_mode(self.valid_modes[0])
764
765
765 def context(self):
766 def context(self):
766 self.set_mode(self.valid_modes[1])
767 self.set_mode(self.valid_modes[1])
767
768
768 def verbose(self):
769 def verbose(self):
769 self.set_mode(self.valid_modes[2])
770 self.set_mode(self.valid_modes[2])
770
771
771 #----------------------------------------------------------------------------
772 #----------------------------------------------------------------------------
772 class AutoFormattedTB(FormattedTB):
773 class AutoFormattedTB(FormattedTB):
773 """A traceback printer which can be called on the fly.
774 """A traceback printer which can be called on the fly.
774
775
775 It will find out about exceptions by itself.
776 It will find out about exceptions by itself.
776
777
777 A brief example:
778 A brief example:
778
779
779 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
780 AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux')
780 try:
781 try:
781 ...
782 ...
782 except:
783 except:
783 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
784 AutoTB() # or AutoTB(out=logfile) where logfile is an open file object
784 """
785 """
785 def __call__(self,etype=None,evalue=None,etb=None,
786 def __call__(self,etype=None,evalue=None,etb=None,
786 out=None,tb_offset=None):
787 out=None,tb_offset=None):
787 """Print out a formatted exception traceback.
788 """Print out a formatted exception traceback.
788
789
789 Optional arguments:
790 Optional arguments:
790 - out: an open file-like object to direct output to.
791 - out: an open file-like object to direct output to.
791
792
792 - tb_offset: the number of frames to skip over in the stack, on a
793 - tb_offset: the number of frames to skip over in the stack, on a
793 per-call basis (this overrides temporarily the instance's tb_offset
794 per-call basis (this overrides temporarily the instance's tb_offset
794 given at initialization time. """
795 given at initialization time. """
795
796
796 if out is None:
797 if out is None:
797 out = Term.cerr
798 out = Term.cerr
798 if tb_offset is not None:
799 if tb_offset is not None:
799 tb_offset, self.tb_offset = self.tb_offset, tb_offset
800 tb_offset, self.tb_offset = self.tb_offset, tb_offset
800 print >> out, self.text(etype, evalue, etb)
801 print >> out, self.text(etype, evalue, etb)
801 self.tb_offset = tb_offset
802 self.tb_offset = tb_offset
802 else:
803 else:
803 print >> out, self.text()
804 print >> out, self.text()
804 self.debugger()
805 self.debugger()
805
806
806 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
807 def text(self,etype=None,value=None,tb=None,context=5,mode=None):
807 if etype is None:
808 if etype is None:
808 etype,value,tb = sys.exc_info()
809 etype,value,tb = sys.exc_info()
809 self.tb = tb
810 self.tb = tb
810 return FormattedTB.text(self,etype,value,tb,context=5,mode=mode)
811 return FormattedTB.text(self,etype,value,tb,context=5,mode=mode)
811
812
812 #---------------------------------------------------------------------------
813 #---------------------------------------------------------------------------
813 # A simple class to preserve Nathan's original functionality.
814 # A simple class to preserve Nathan's original functionality.
814 class ColorTB(FormattedTB):
815 class ColorTB(FormattedTB):
815 """Shorthand to initialize a FormattedTB in Linux colors mode."""
816 """Shorthand to initialize a FormattedTB in Linux colors mode."""
816 def __init__(self,color_scheme='Linux',call_pdb=0):
817 def __init__(self,color_scheme='Linux',call_pdb=0):
817 FormattedTB.__init__(self,color_scheme=color_scheme,
818 FormattedTB.__init__(self,color_scheme=color_scheme,
818 call_pdb=call_pdb)
819 call_pdb=call_pdb)
819
820
820 #----------------------------------------------------------------------------
821 #----------------------------------------------------------------------------
821 # module testing (minimal)
822 # module testing (minimal)
822 if __name__ == "__main__":
823 if __name__ == "__main__":
823 def spam(c, (d, e)):
824 def spam(c, (d, e)):
824 x = c + d
825 x = c + d
825 y = c * d
826 y = c * d
826 foo(x, y)
827 foo(x, y)
827
828
828 def foo(a, b, bar=1):
829 def foo(a, b, bar=1):
829 eggs(a, b + bar)
830 eggs(a, b + bar)
830
831
831 def eggs(f, g, z=globals()):
832 def eggs(f, g, z=globals()):
832 h = f + g
833 h = f + g
833 i = f - g
834 i = f - g
834 return h / i
835 return h / i
835
836
836 print ''
837 print ''
837 print '*** Before ***'
838 print '*** Before ***'
838 try:
839 try:
839 print spam(1, (2, 3))
840 print spam(1, (2, 3))
840 except:
841 except:
841 traceback.print_exc()
842 traceback.print_exc()
842 print ''
843 print ''
843
844
844 handler = ColorTB()
845 handler = ColorTB()
845 print '*** ColorTB ***'
846 print '*** ColorTB ***'
846 try:
847 try:
847 print spam(1, (2, 3))
848 print spam(1, (2, 3))
848 except:
849 except:
849 apply(handler, sys.exc_info() )
850 apply(handler, sys.exc_info() )
850 print ''
851 print ''
851
852
852 handler = VerboseTB()
853 handler = VerboseTB()
853 print '*** VerboseTB ***'
854 print '*** VerboseTB ***'
854 try:
855 try:
855 print spam(1, (2, 3))
856 print spam(1, (2, 3))
856 except:
857 except:
857 apply(handler, sys.exc_info() )
858 apply(handler, sys.exc_info() )
858 print ''
859 print ''
859
860
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
General Comments 0
You need to be logged in to leave comments. Login now