##// END OF EJS Templates
Minor fixes in genutils, and a BIG fix for threading. I _think_ I got...
fperez -
Show More

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

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