##// END OF EJS Templates
Close issue 41, remove obsolete gtk 1.x code, trap os.getcwd exceptions at...
fperez -
Show More

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

@@ -1,886 +1,881 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 703 2005-08-16 17:34:44Z fperez $"""
7 $Id: Shell.py 802 2005-09-06 03:49:12Z fperez $"""
8
8
9 #*****************************************************************************
9 #*****************************************************************************
10 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
10 # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu>
11 #
11 #
12 # Distributed under the terms of the BSD License. The full license is in
12 # Distributed under the terms of the BSD License. The full license is in
13 # the file COPYING, distributed as part of this software.
13 # the file COPYING, distributed as part of this software.
14 #*****************************************************************************
14 #*****************************************************************************
15
15
16 from IPython import Release
16 from IPython import Release
17 __author__ = '%s <%s>' % Release.authors['Fernando']
17 __author__ = '%s <%s>' % Release.authors['Fernando']
18 __license__ = Release.license
18 __license__ = Release.license
19
19
20 # Code begins
20 # Code begins
21 import __main__
21 import __main__
22 import __builtin__
22 import __builtin__
23 import sys
23 import sys
24 import os
24 import os
25 import code
25 import code
26 import threading
26 import threading
27 import signal
27 import signal
28
28
29 import IPython
29 import IPython
30 from IPython.iplib import InteractiveShell
30 from IPython.iplib import InteractiveShell
31 from IPython.ipmaker import make_IPython
31 from IPython.ipmaker import make_IPython
32 from IPython.genutils import Term,warn,error,flag_calls
32 from IPython.genutils import Term,warn,error,flag_calls
33 from IPython.Struct import Struct
33 from IPython.Struct import Struct
34 from IPython.Magic import Magic
34 from IPython.Magic import Magic
35 from IPython import ultraTB
35 from IPython import ultraTB
36
36
37 # global flag to pass around information about Ctrl-C without exceptions
37 # global flag to pass around information about Ctrl-C without exceptions
38 KBINT = False
38 KBINT = False
39
39
40 # global flag to turn on/off Tk support.
40 # global flag to turn on/off Tk support.
41 USE_TK = False
41 USE_TK = False
42
42
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44 # This class is trivial now, but I want to have it in to publish a clean
44 # This class is trivial now, but I want to have it in to publish a clean
45 # interface. Later when the internals are reorganized, code that uses this
45 # interface. Later when the internals are reorganized, code that uses this
46 # shouldn't have to change.
46 # shouldn't have to change.
47
47
48 class IPShell:
48 class IPShell:
49 """Create an IPython instance."""
49 """Create an IPython instance."""
50
50
51 def __init__(self,argv=None,user_ns=None,debug=1,
51 def __init__(self,argv=None,user_ns=None,debug=1,
52 shell_class=InteractiveShell):
52 shell_class=InteractiveShell):
53 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
53 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
54 shell_class=shell_class)
54 shell_class=shell_class)
55
55
56 def mainloop(self,sys_exit=0,banner=None):
56 def mainloop(self,sys_exit=0,banner=None):
57 self.IP.mainloop(banner)
57 self.IP.mainloop(banner)
58 if sys_exit:
58 if sys_exit:
59 sys.exit()
59 sys.exit()
60
60
61 #-----------------------------------------------------------------------------
61 #-----------------------------------------------------------------------------
62 class IPShellEmbed:
62 class IPShellEmbed:
63 """Allow embedding an IPython shell into a running program.
63 """Allow embedding an IPython shell into a running program.
64
64
65 Instances of this class are callable, with the __call__ method being an
65 Instances of this class are callable, with the __call__ method being an
66 alias to the embed() method of an InteractiveShell instance.
66 alias to the embed() method of an InteractiveShell instance.
67
67
68 Usage (see also the example-embed.py file for a running example):
68 Usage (see also the example-embed.py file for a running example):
69
69
70 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
70 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
71
71
72 - argv: list containing valid command-line options for IPython, as they
72 - argv: list containing valid command-line options for IPython, as they
73 would appear in sys.argv[1:].
73 would appear in sys.argv[1:].
74
74
75 For example, the following command-line options:
75 For example, the following command-line options:
76
76
77 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
77 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
78
78
79 would be passed in the argv list as:
79 would be passed in the argv list as:
80
80
81 ['-prompt_in1','Input <\\#>','-colors','LightBG']
81 ['-prompt_in1','Input <\\#>','-colors','LightBG']
82
82
83 - banner: string which gets printed every time the interpreter starts.
83 - banner: string which gets printed every time the interpreter starts.
84
84
85 - exit_msg: string which gets printed every time the interpreter exits.
85 - exit_msg: string which gets printed every time the interpreter exits.
86
86
87 - rc_override: a dict or Struct of configuration options such as those
87 - rc_override: a dict or Struct of configuration options such as those
88 used by IPython. These options are read from your ~/.ipython/ipythonrc
88 used by IPython. These options are read from your ~/.ipython/ipythonrc
89 file when the Shell object is created. Passing an explicit rc_override
89 file when the Shell object is created. Passing an explicit rc_override
90 dict with any options you want allows you to override those values at
90 dict with any options you want allows you to override those values at
91 creation time without having to modify the file. This way you can create
91 creation time without having to modify the file. This way you can create
92 embeddable instances configured in any way you want without editing any
92 embeddable instances configured in any way you want without editing any
93 global files (thus keeping your interactive IPython configuration
93 global files (thus keeping your interactive IPython configuration
94 unchanged).
94 unchanged).
95
95
96 Then the ipshell instance can be called anywhere inside your code:
96 Then the ipshell instance can be called anywhere inside your code:
97
97
98 ipshell(header='') -> Opens up an IPython shell.
98 ipshell(header='') -> Opens up an IPython shell.
99
99
100 - header: string printed by the IPython shell upon startup. This can let
100 - header: string printed by the IPython shell upon startup. This can let
101 you know where in your code you are when dropping into the shell. Note
101 you know where in your code you are when dropping into the shell. Note
102 that 'banner' gets prepended to all calls, so header is used for
102 that 'banner' gets prepended to all calls, so header is used for
103 location-specific information.
103 location-specific information.
104
104
105 For more details, see the __call__ method below.
105 For more details, see the __call__ method below.
106
106
107 When the IPython shell is exited with Ctrl-D, normal program execution
107 When the IPython shell is exited with Ctrl-D, normal program execution
108 resumes.
108 resumes.
109
109
110 This functionality was inspired by a posting on comp.lang.python by cmkl
110 This functionality was inspired by a posting on comp.lang.python by cmkl
111 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
111 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
112 by the IDL stop/continue commands."""
112 by the IDL stop/continue commands."""
113
113
114 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None):
114 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None):
115 """Note that argv here is a string, NOT a list."""
115 """Note that argv here is a string, NOT a list."""
116 self.set_banner(banner)
116 self.set_banner(banner)
117 self.set_exit_msg(exit_msg)
117 self.set_exit_msg(exit_msg)
118 self.set_dummy_mode(0)
118 self.set_dummy_mode(0)
119
119
120 # sys.displayhook is a global, we need to save the user's original
120 # sys.displayhook is a global, we need to save the user's original
121 # Don't rely on __displayhook__, as the user may have changed that.
121 # Don't rely on __displayhook__, as the user may have changed that.
122 self.sys_displayhook_ori = sys.displayhook
122 self.sys_displayhook_ori = sys.displayhook
123
123
124 # save readline completer status
124 # save readline completer status
125 try:
125 try:
126 #print 'Save completer',sys.ipcompleter # dbg
126 #print 'Save completer',sys.ipcompleter # dbg
127 self.sys_ipcompleter_ori = sys.ipcompleter
127 self.sys_ipcompleter_ori = sys.ipcompleter
128 except:
128 except:
129 pass # not nested with IPython
129 pass # not nested with IPython
130
130
131 # FIXME. Passing user_ns breaks namespace handling.
131 # FIXME. Passing user_ns breaks namespace handling.
132 #self.IP = make_IPython(argv,user_ns=__main__.__dict__)
132 #self.IP = make_IPython(argv,user_ns=__main__.__dict__)
133 self.IP = make_IPython(argv,rc_override=rc_override,embedded=True)
133 self.IP = make_IPython(argv,rc_override=rc_override,embedded=True)
134
134
135 self.IP.name_space_init()
135 self.IP.name_space_init()
136 # mark this as an embedded instance so we know if we get a crash
136 # mark this as an embedded instance so we know if we get a crash
137 # post-mortem
137 # post-mortem
138 self.IP.rc.embedded = 1
138 self.IP.rc.embedded = 1
139 # copy our own displayhook also
139 # copy our own displayhook also
140 self.sys_displayhook_embed = sys.displayhook
140 self.sys_displayhook_embed = sys.displayhook
141 # and leave the system's display hook clean
141 # and leave the system's display hook clean
142 sys.displayhook = self.sys_displayhook_ori
142 sys.displayhook = self.sys_displayhook_ori
143 # don't use the ipython crash handler so that user exceptions aren't
143 # don't use the ipython crash handler so that user exceptions aren't
144 # trapped
144 # trapped
145 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
145 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
146 mode = self.IP.rc.xmode,
146 mode = self.IP.rc.xmode,
147 call_pdb = self.IP.rc.pdb)
147 call_pdb = self.IP.rc.pdb)
148 self.restore_system_completer()
148 self.restore_system_completer()
149
149
150 def restore_system_completer(self):
150 def restore_system_completer(self):
151 """Restores the readline completer which was in place.
151 """Restores the readline completer which was in place.
152
152
153 This allows embedded IPython within IPython not to disrupt the
153 This allows embedded IPython within IPython not to disrupt the
154 parent's completion.
154 parent's completion.
155 """
155 """
156
156
157 try:
157 try:
158 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
158 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
159 sys.ipcompleter = self.sys_ipcompleter_ori
159 sys.ipcompleter = self.sys_ipcompleter_ori
160 except:
160 except:
161 pass
161 pass
162
162
163 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
163 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
164 """Activate the interactive interpreter.
164 """Activate the interactive interpreter.
165
165
166 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
166 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
167 the interpreter shell with the given local and global namespaces, and
167 the interpreter shell with the given local and global namespaces, and
168 optionally print a header string at startup.
168 optionally print a header string at startup.
169
169
170 The shell can be globally activated/deactivated using the
170 The shell can be globally activated/deactivated using the
171 set/get_dummy_mode methods. This allows you to turn off a shell used
171 set/get_dummy_mode methods. This allows you to turn off a shell used
172 for debugging globally.
172 for debugging globally.
173
173
174 However, *each* time you call the shell you can override the current
174 However, *each* time you call the shell you can override the current
175 state of dummy_mode with the optional keyword parameter 'dummy'. For
175 state of dummy_mode with the optional keyword parameter 'dummy'. For
176 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
176 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
177 can still have a specific call work by making it as IPShell(dummy=0).
177 can still have a specific call work by making it as IPShell(dummy=0).
178
178
179 The optional keyword parameter dummy controls whether the call
179 The optional keyword parameter dummy controls whether the call
180 actually does anything. """
180 actually does anything. """
181
181
182 # Allow the dummy parameter to override the global __dummy_mode
182 # Allow the dummy parameter to override the global __dummy_mode
183 if dummy or (dummy != 0 and self.__dummy_mode):
183 if dummy or (dummy != 0 and self.__dummy_mode):
184 return
184 return
185
185
186 # Set global subsystems (display,completions) to our values
186 # Set global subsystems (display,completions) to our values
187 sys.displayhook = self.sys_displayhook_embed
187 sys.displayhook = self.sys_displayhook_embed
188 if self.IP.has_readline:
188 if self.IP.has_readline:
189 self.IP.readline.set_completer(self.IP.Completer.complete)
189 self.IP.readline.set_completer(self.IP.Completer.complete)
190
190
191 if self.banner and header:
191 if self.banner and header:
192 format = '%s\n%s\n'
192 format = '%s\n%s\n'
193 else:
193 else:
194 format = '%s%s\n'
194 format = '%s%s\n'
195 banner = format % (self.banner,header)
195 banner = format % (self.banner,header)
196
196
197 # Call the embedding code with a stack depth of 1 so it can skip over
197 # Call the embedding code with a stack depth of 1 so it can skip over
198 # our call and get the original caller's namespaces.
198 # our call and get the original caller's namespaces.
199 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
199 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
200
200
201 if self.exit_msg:
201 if self.exit_msg:
202 print self.exit_msg
202 print self.exit_msg
203
203
204 # Restore global systems (display, completion)
204 # Restore global systems (display, completion)
205 sys.displayhook = self.sys_displayhook_ori
205 sys.displayhook = self.sys_displayhook_ori
206 self.restore_system_completer()
206 self.restore_system_completer()
207
207
208 def set_dummy_mode(self,dummy):
208 def set_dummy_mode(self,dummy):
209 """Sets the embeddable shell's dummy mode parameter.
209 """Sets the embeddable shell's dummy mode parameter.
210
210
211 set_dummy_mode(dummy): dummy = 0 or 1.
211 set_dummy_mode(dummy): dummy = 0 or 1.
212
212
213 This parameter is persistent and makes calls to the embeddable shell
213 This parameter is persistent and makes calls to the embeddable shell
214 silently return without performing any action. This allows you to
214 silently return without performing any action. This allows you to
215 globally activate or deactivate a shell you're using with a single call.
215 globally activate or deactivate a shell you're using with a single call.
216
216
217 If you need to manually"""
217 If you need to manually"""
218
218
219 if dummy not in [0,1]:
219 if dummy not in [0,1]:
220 raise ValueError,'dummy parameter must be 0 or 1'
220 raise ValueError,'dummy parameter must be 0 or 1'
221 self.__dummy_mode = dummy
221 self.__dummy_mode = dummy
222
222
223 def get_dummy_mode(self):
223 def get_dummy_mode(self):
224 """Return the current value of the dummy mode parameter.
224 """Return the current value of the dummy mode parameter.
225 """
225 """
226 return self.__dummy_mode
226 return self.__dummy_mode
227
227
228 def set_banner(self,banner):
228 def set_banner(self,banner):
229 """Sets the global banner.
229 """Sets the global banner.
230
230
231 This banner gets prepended to every header printed when the shell
231 This banner gets prepended to every header printed when the shell
232 instance is called."""
232 instance is called."""
233
233
234 self.banner = banner
234 self.banner = banner
235
235
236 def set_exit_msg(self,exit_msg):
236 def set_exit_msg(self,exit_msg):
237 """Sets the global exit_msg.
237 """Sets the global exit_msg.
238
238
239 This exit message gets printed upon exiting every time the embedded
239 This exit message gets printed upon exiting every time the embedded
240 shell is called. It is None by default. """
240 shell is called. It is None by default. """
241
241
242 self.exit_msg = exit_msg
242 self.exit_msg = exit_msg
243
243
244 #-----------------------------------------------------------------------------
244 #-----------------------------------------------------------------------------
245 def sigint_handler (signum,stack_frame):
245 def sigint_handler (signum,stack_frame):
246 """Sigint handler for threaded apps.
246 """Sigint handler for threaded apps.
247
247
248 This is a horrible hack to pass information about SIGINT _without_ using
248 This is a horrible hack to pass information about SIGINT _without_ using
249 exceptions, since I haven't been able to properly manage cross-thread
249 exceptions, since I haven't been able to properly manage cross-thread
250 exceptions in GTK/WX. In fact, I don't think it can be done (or at least
250 exceptions in GTK/WX. In fact, I don't think it can be done (or at least
251 that's my understanding from a c.l.py thread where this was discussed)."""
251 that's my understanding from a c.l.py thread where this was discussed)."""
252
252
253 global KBINT
253 global KBINT
254
254
255 print '\nKeyboardInterrupt - Press <Enter> to continue.',
255 print '\nKeyboardInterrupt - Press <Enter> to continue.',
256 Term.cout.flush()
256 Term.cout.flush()
257 # Set global flag so that runsource can know that Ctrl-C was hit
257 # Set global flag so that runsource can know that Ctrl-C was hit
258 KBINT = True
258 KBINT = True
259
259
260 class MTInteractiveShell(InteractiveShell):
260 class MTInteractiveShell(InteractiveShell):
261 """Simple multi-threaded shell."""
261 """Simple multi-threaded shell."""
262
262
263 # Threading strategy taken from:
263 # Threading strategy taken from:
264 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
264 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
265 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
265 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
266 # from the pygtk mailing list, to avoid lockups with system calls.
266 # from the pygtk mailing list, to avoid lockups with system calls.
267
267
268 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
268 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
269 user_ns = None, banner2='',**kw):
269 user_ns = None, banner2='',**kw):
270 """Similar to the normal InteractiveShell, but with threading control"""
270 """Similar to the normal InteractiveShell, but with threading control"""
271
271
272 IPython.iplib.InteractiveShell.__init__(self,name,usage,rc,user_ns,banner2)
272 IPython.iplib.InteractiveShell.__init__(self,name,usage,rc,user_ns,banner2)
273
273
274 # Locking control variable
274 # Locking control variable
275 self.thread_ready = threading.Condition()
275 self.thread_ready = threading.Condition()
276
276
277 # Stuff to do at closing time
277 # Stuff to do at closing time
278 self._kill = False
278 self._kill = False
279 on_kill = kw.get('on_kill')
279 on_kill = kw.get('on_kill')
280 if on_kill is None:
280 if on_kill is None:
281 on_kill = []
281 on_kill = []
282 # Check that all things to kill are callable:
282 # Check that all things to kill are callable:
283 for t in on_kill:
283 for t in on_kill:
284 if not callable(t):
284 if not callable(t):
285 raise TypeError,'on_kill must be a list of callables'
285 raise TypeError,'on_kill must be a list of callables'
286 self.on_kill = on_kill
286 self.on_kill = on_kill
287
287
288 def runsource(self, source, filename="<input>", symbol="single"):
288 def runsource(self, source, filename="<input>", symbol="single"):
289 """Compile and run some source in the interpreter.
289 """Compile and run some source in the interpreter.
290
290
291 Modified version of code.py's runsource(), to handle threading issues.
291 Modified version of code.py's runsource(), to handle threading issues.
292 See the original for full docstring details."""
292 See the original for full docstring details."""
293
293
294 global KBINT
294 global KBINT
295
295
296 # If Ctrl-C was typed, we reset the flag and return right away
296 # If Ctrl-C was typed, we reset the flag and return right away
297 if KBINT:
297 if KBINT:
298 KBINT = False
298 KBINT = False
299 return False
299 return False
300
300
301 try:
301 try:
302 code = self.compile(source, filename, symbol)
302 code = self.compile(source, filename, symbol)
303 except (OverflowError, SyntaxError, ValueError):
303 except (OverflowError, SyntaxError, ValueError):
304 # Case 1
304 # Case 1
305 self.showsyntaxerror(filename)
305 self.showsyntaxerror(filename)
306 return False
306 return False
307
307
308 if code is None:
308 if code is None:
309 # Case 2
309 # Case 2
310 return True
310 return True
311
311
312 # Case 3
312 # Case 3
313 # Store code in self, so the execution thread can handle it
313 # Store code in self, so the execution thread can handle it
314 self.thread_ready.acquire()
314 self.thread_ready.acquire()
315 self.code_to_run = code
315 self.code_to_run = code
316 self.thread_ready.wait() # Wait until processed in timeout interval
316 self.thread_ready.wait() # Wait until processed in timeout interval
317 self.thread_ready.release()
317 self.thread_ready.release()
318
318
319 return False
319 return False
320
320
321 def runcode(self):
321 def runcode(self):
322 """Execute a code object.
322 """Execute a code object.
323
323
324 Multithreaded wrapper around IPython's runcode()."""
324 Multithreaded wrapper around IPython's runcode()."""
325
325
326 # lock thread-protected stuff
326 # lock thread-protected stuff
327 self.thread_ready.acquire()
327 self.thread_ready.acquire()
328
328
329 # Install sigint handler
329 # Install sigint handler
330 try:
330 try:
331 signal.signal(signal.SIGINT, sigint_handler)
331 signal.signal(signal.SIGINT, sigint_handler)
332 except SystemError:
332 except SystemError:
333 # This happens under Windows, which seems to have all sorts
333 # This happens under Windows, which seems to have all sorts
334 # of problems with signal handling. Oh well...
334 # of problems with signal handling. Oh well...
335 pass
335 pass
336
336
337 if self._kill:
337 if self._kill:
338 print >>Term.cout, 'Closing threads...',
338 print >>Term.cout, 'Closing threads...',
339 Term.cout.flush()
339 Term.cout.flush()
340 for tokill in self.on_kill:
340 for tokill in self.on_kill:
341 tokill()
341 tokill()
342 print >>Term.cout, 'Done.'
342 print >>Term.cout, 'Done.'
343
343
344 # Run pending code by calling parent class
344 # Run pending code by calling parent class
345 if self.code_to_run is not None:
345 if self.code_to_run is not None:
346 self.thread_ready.notify()
346 self.thread_ready.notify()
347 InteractiveShell.runcode(self,self.code_to_run)
347 InteractiveShell.runcode(self,self.code_to_run)
348
348
349 # We're done with thread-protected variables
349 # We're done with thread-protected variables
350 self.thread_ready.release()
350 self.thread_ready.release()
351 # This MUST return true for gtk threading to work
351 # This MUST return true for gtk threading to work
352 return True
352 return True
353
353
354 def kill (self):
354 def kill (self):
355 """Kill the thread, returning when it has been shut down."""
355 """Kill the thread, returning when it has been shut down."""
356 self.thread_ready.acquire()
356 self.thread_ready.acquire()
357 self._kill = True
357 self._kill = True
358 self.thread_ready.release()
358 self.thread_ready.release()
359
359
360 class MatplotlibShellBase:
360 class MatplotlibShellBase:
361 """Mixin class to provide the necessary modifications to regular IPython
361 """Mixin class to provide the necessary modifications to regular IPython
362 shell classes for matplotlib support.
362 shell classes for matplotlib support.
363
363
364 Given Python's MRO, this should be used as the FIRST class in the
364 Given Python's MRO, this should be used as the FIRST class in the
365 inheritance hierarchy, so that it overrides the relevant methods."""
365 inheritance hierarchy, so that it overrides the relevant methods."""
366
366
367 def _matplotlib_config(self,name):
367 def _matplotlib_config(self,name):
368 """Return various items needed to setup the user's shell with matplotlib"""
368 """Return various items needed to setup the user's shell with matplotlib"""
369
369
370 # Initialize matplotlib to interactive mode always
370 # Initialize matplotlib to interactive mode always
371 import matplotlib
371 import matplotlib
372 from matplotlib import backends
372 from matplotlib import backends
373 matplotlib.interactive(True)
373 matplotlib.interactive(True)
374
374
375 def use(arg):
375 def use(arg):
376 """IPython wrapper for matplotlib's backend switcher.
376 """IPython wrapper for matplotlib's backend switcher.
377
377
378 In interactive use, we can not allow switching to a different
378 In interactive use, we can not allow switching to a different
379 interactive backend, since thread conflicts will most likely crash
379 interactive backend, since thread conflicts will most likely crash
380 the python interpreter. This routine does a safety check first,
380 the python interpreter. This routine does a safety check first,
381 and refuses to perform a dangerous switch. It still allows
381 and refuses to perform a dangerous switch. It still allows
382 switching to non-interactive backends."""
382 switching to non-interactive backends."""
383
383
384 if arg in backends.interactive_bk and arg != self.mpl_backend:
384 if arg in backends.interactive_bk and arg != self.mpl_backend:
385 m=('invalid matplotlib backend switch.\n'
385 m=('invalid matplotlib backend switch.\n'
386 'This script attempted to switch to the interactive '
386 'This script attempted to switch to the interactive '
387 'backend: `%s`\n'
387 'backend: `%s`\n'
388 'Your current choice of interactive backend is: `%s`\n\n'
388 'Your current choice of interactive backend is: `%s`\n\n'
389 'Switching interactive matplotlib backends at runtime\n'
389 'Switching interactive matplotlib backends at runtime\n'
390 'would crash the python interpreter, '
390 'would crash the python interpreter, '
391 'and IPython has blocked it.\n\n'
391 'and IPython has blocked it.\n\n'
392 'You need to either change your choice of matplotlib backend\n'
392 'You need to either change your choice of matplotlib backend\n'
393 'by editing your .matplotlibrc file, or run this script as a \n'
393 'by editing your .matplotlibrc file, or run this script as a \n'
394 'standalone file from the command line, not using IPython.\n' %
394 'standalone file from the command line, not using IPython.\n' %
395 (arg,self.mpl_backend) )
395 (arg,self.mpl_backend) )
396 raise RuntimeError, m
396 raise RuntimeError, m
397 else:
397 else:
398 self.mpl_use(arg)
398 self.mpl_use(arg)
399 self.mpl_use._called = True
399 self.mpl_use._called = True
400
400
401 self.matplotlib = matplotlib
401 self.matplotlib = matplotlib
402 self.mpl_backend = matplotlib.rcParams['backend']
402 self.mpl_backend = matplotlib.rcParams['backend']
403
403
404 # we also need to block switching of interactive backends by use()
404 # we also need to block switching of interactive backends by use()
405 self.mpl_use = matplotlib.use
405 self.mpl_use = matplotlib.use
406 self.mpl_use._called = False
406 self.mpl_use._called = False
407 # overwrite the original matplotlib.use with our wrapper
407 # overwrite the original matplotlib.use with our wrapper
408 matplotlib.use = use
408 matplotlib.use = use
409
409
410
410
411 # This must be imported last in the matplotlib series, after
411 # This must be imported last in the matplotlib series, after
412 # backend/interactivity choices have been made
412 # backend/interactivity choices have been made
413 try:
413 try:
414 import matplotlib.pylab as pylab
414 import matplotlib.pylab as pylab
415 self.pylab = pylab
415 self.pylab = pylab
416 self.pylab_name = 'pylab'
416 self.pylab_name = 'pylab'
417 except ImportError:
417 except ImportError:
418 import matplotlib.matlab as matlab
418 import matplotlib.matlab as matlab
419 self.pylab = matlab
419 self.pylab = matlab
420 self.pylab_name = 'matlab'
420 self.pylab_name = 'matlab'
421
421
422 self.pylab.show._needmain = False
422 self.pylab.show._needmain = False
423 # We need to detect at runtime whether show() is called by the user.
423 # We need to detect at runtime whether show() is called by the user.
424 # For this, we wrap it into a decorator which adds a 'called' flag.
424 # For this, we wrap it into a decorator which adds a 'called' flag.
425 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
425 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
426
426
427 # Build a user namespace initialized with matplotlib/matlab features.
427 # Build a user namespace initialized with matplotlib/matlab features.
428 user_ns = {'__name__':'__main__',
428 user_ns = {'__name__':'__main__',
429 '__builtins__' : __builtin__ }
429 '__builtins__' : __builtin__ }
430
430
431 # Be careful not to remove the final \n in the code string below, or
431 # Be careful not to remove the final \n in the code string below, or
432 # things will break badly with py22 (I think it's a python bug, 2.3 is
432 # things will break badly with py22 (I think it's a python bug, 2.3 is
433 # OK).
433 # OK).
434 pname = self.pylab_name # Python can't interpolate dotted var names
434 pname = self.pylab_name # Python can't interpolate dotted var names
435 exec ("import matplotlib\n"
435 exec ("import matplotlib\n"
436 "import matplotlib.%(pname)s as %(pname)s\n"
436 "import matplotlib.%(pname)s as %(pname)s\n"
437 "from matplotlib.%(pname)s import *\n" % locals()) in user_ns
437 "from matplotlib.%(pname)s import *\n" % locals()) in user_ns
438
438
439 # Build matplotlib info banner
439 # Build matplotlib info banner
440 b="""
440 b="""
441 Welcome to pylab, a matplotlib-based Python environment.
441 Welcome to pylab, a matplotlib-based Python environment.
442 For more information, type 'help(pylab)'.
442 For more information, type 'help(pylab)'.
443 """
443 """
444 return user_ns,b
444 return user_ns,b
445
445
446 def mplot_exec(self,fname,*where,**kw):
446 def mplot_exec(self,fname,*where,**kw):
447 """Execute a matplotlib script.
447 """Execute a matplotlib script.
448
448
449 This is a call to execfile(), but wrapped in safeties to properly
449 This is a call to execfile(), but wrapped in safeties to properly
450 handle interactive rendering and backend switching."""
450 handle interactive rendering and backend switching."""
451
451
452 #print '*** Matplotlib runner ***' # dbg
452 #print '*** Matplotlib runner ***' # dbg
453 # turn off rendering until end of script
453 # turn off rendering until end of script
454 isInteractive = self.matplotlib.rcParams['interactive']
454 isInteractive = self.matplotlib.rcParams['interactive']
455 self.matplotlib.interactive(False)
455 self.matplotlib.interactive(False)
456 self.safe_execfile(fname,*where,**kw)
456 self.safe_execfile(fname,*where,**kw)
457 self.matplotlib.interactive(isInteractive)
457 self.matplotlib.interactive(isInteractive)
458 # make rendering call now, if the user tried to do it
458 # make rendering call now, if the user tried to do it
459 if self.pylab.draw_if_interactive.called:
459 if self.pylab.draw_if_interactive.called:
460 self.pylab.draw()
460 self.pylab.draw()
461 self.pylab.draw_if_interactive.called = False
461 self.pylab.draw_if_interactive.called = False
462
462
463 # if a backend switch was performed, reverse it now
463 # if a backend switch was performed, reverse it now
464 if self.mpl_use._called:
464 if self.mpl_use._called:
465 self.matplotlib.rcParams['backend'] = self.mpl_backend
465 self.matplotlib.rcParams['backend'] = self.mpl_backend
466
466
467 def magic_run(self,parameter_s=''):
467 def magic_run(self,parameter_s=''):
468 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
468 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
469
469
470 # Fix the docstring so users see the original as well
470 # Fix the docstring so users see the original as well
471 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
471 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
472 "\n *** Modified %run for Matplotlib,"
472 "\n *** Modified %run for Matplotlib,"
473 " with proper interactive handling ***")
473 " with proper interactive handling ***")
474
474
475 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
475 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
476 # and multithreaded. Note that these are meant for internal use, the IPShell*
476 # and multithreaded. Note that these are meant for internal use, the IPShell*
477 # classes below are the ones meant for public consumption.
477 # classes below are the ones meant for public consumption.
478
478
479 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
479 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
480 """Single-threaded shell with matplotlib support."""
480 """Single-threaded shell with matplotlib support."""
481
481
482 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
482 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
483 user_ns = None, **kw):
483 user_ns = None, **kw):
484 user_ns,b2 = self._matplotlib_config(name)
484 user_ns,b2 = self._matplotlib_config(name)
485 InteractiveShell.__init__(self,name,usage,rc,user_ns,banner2=b2,**kw)
485 InteractiveShell.__init__(self,name,usage,rc,user_ns,banner2=b2,**kw)
486
486
487 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
487 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
488 """Multi-threaded shell with matplotlib support."""
488 """Multi-threaded shell with matplotlib support."""
489
489
490 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
490 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
491 user_ns = None, **kw):
491 user_ns = None, **kw):
492 user_ns,b2 = self._matplotlib_config(name)
492 user_ns,b2 = self._matplotlib_config(name)
493 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,banner2=b2,**kw)
493 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,banner2=b2,**kw)
494
494
495 #-----------------------------------------------------------------------------
495 #-----------------------------------------------------------------------------
496 # Utility functions for the different GUI enabled IPShell* classes.
496 # Utility functions for the different GUI enabled IPShell* classes.
497
497
498 def get_tk():
498 def get_tk():
499 """Tries to import Tkinter and returns a withdrawn Tkinter root
499 """Tries to import Tkinter and returns a withdrawn Tkinter root
500 window. If Tkinter is already imported or not available, this
500 window. If Tkinter is already imported or not available, this
501 returns None. This function calls `hijack_tk` underneath.
501 returns None. This function calls `hijack_tk` underneath.
502 """
502 """
503 if not USE_TK or sys.modules.has_key('Tkinter'):
503 if not USE_TK or sys.modules.has_key('Tkinter'):
504 return None
504 return None
505 else:
505 else:
506 try:
506 try:
507 import Tkinter
507 import Tkinter
508 except ImportError:
508 except ImportError:
509 return None
509 return None
510 else:
510 else:
511 hijack_tk()
511 hijack_tk()
512 r = Tkinter.Tk()
512 r = Tkinter.Tk()
513 r.withdraw()
513 r.withdraw()
514 return r
514 return r
515
515
516 def hijack_tk():
516 def hijack_tk():
517 """Modifies Tkinter's mainloop with a dummy so when a module calls
517 """Modifies Tkinter's mainloop with a dummy so when a module calls
518 mainloop, it does not block.
518 mainloop, it does not block.
519
519
520 """
520 """
521 def misc_mainloop(self, n=0):
521 def misc_mainloop(self, n=0):
522 pass
522 pass
523 def tkinter_mainloop(n=0):
523 def tkinter_mainloop(n=0):
524 pass
524 pass
525
525
526 import Tkinter
526 import Tkinter
527 Tkinter.Misc.mainloop = misc_mainloop
527 Tkinter.Misc.mainloop = misc_mainloop
528 Tkinter.mainloop = tkinter_mainloop
528 Tkinter.mainloop = tkinter_mainloop
529
529
530 def update_tk(tk):
530 def update_tk(tk):
531 """Updates the Tkinter event loop. This is typically called from
531 """Updates the Tkinter event loop. This is typically called from
532 the respective WX or GTK mainloops.
532 the respective WX or GTK mainloops.
533 """
533 """
534 if tk:
534 if tk:
535 tk.update()
535 tk.update()
536
536
537 def hijack_wx():
537 def hijack_wx():
538 """Modifies wxPython's MainLoop with a dummy so user code does not
538 """Modifies wxPython's MainLoop with a dummy so user code does not
539 block IPython. The hijacked mainloop function is returned.
539 block IPython. The hijacked mainloop function is returned.
540 """
540 """
541 def dummy_mainloop(*args, **kw):
541 def dummy_mainloop(*args, **kw):
542 pass
542 pass
543 import wxPython
543 import wxPython
544 ver = wxPython.__version__
544 ver = wxPython.__version__
545 orig_mainloop = None
545 orig_mainloop = None
546 if ver[:3] >= '2.5':
546 if ver[:3] >= '2.5':
547 import wx
547 import wx
548 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
548 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
549 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
549 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
550 else: raise AttributeError('Could not find wx core module')
550 else: raise AttributeError('Could not find wx core module')
551 orig_mainloop = core.PyApp_MainLoop
551 orig_mainloop = core.PyApp_MainLoop
552 core.PyApp_MainLoop = dummy_mainloop
552 core.PyApp_MainLoop = dummy_mainloop
553 elif ver[:3] == '2.4':
553 elif ver[:3] == '2.4':
554 orig_mainloop = wxPython.wxc.wxPyApp_MainLoop
554 orig_mainloop = wxPython.wxc.wxPyApp_MainLoop
555 wxPython.wxc.wxPyApp_MainLoop = dummy_mainloop
555 wxPython.wxc.wxPyApp_MainLoop = dummy_mainloop
556 else:
556 else:
557 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
557 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
558 return orig_mainloop
558 return orig_mainloop
559
559
560 def hijack_gtk():
560 def hijack_gtk():
561 """Modifies pyGTK's mainloop with a dummy so user code does not
561 """Modifies pyGTK's mainloop with a dummy so user code does not
562 block IPython. This function returns the original `gtk.mainloop`
562 block IPython. This function returns the original `gtk.mainloop`
563 function that has been hijacked.
563 function that has been hijacked.
564
565 NOTE: Make sure you import this *AFTER* you call
566 pygtk.require(...).
567 """
564 """
568 def dummy_mainloop(*args, **kw):
565 def dummy_mainloop(*args, **kw):
569 pass
566 pass
570 import gtk
567 import gtk
571 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
568 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
572 else: orig_mainloop = gtk.mainloop
569 else: orig_mainloop = gtk.mainloop
573 gtk.mainloop = dummy_mainloop
570 gtk.mainloop = dummy_mainloop
574 gtk.main = dummy_mainloop
571 gtk.main = dummy_mainloop
575 return orig_mainloop
572 return orig_mainloop
576
573
577 #-----------------------------------------------------------------------------
574 #-----------------------------------------------------------------------------
578 # The IPShell* classes below are the ones meant to be run by external code as
575 # The IPShell* classes below are the ones meant to be run by external code as
579 # IPython instances. Note that unless a specific threading strategy is
576 # IPython instances. Note that unless a specific threading strategy is
580 # desired, the factory function start() below should be used instead (it
577 # desired, the factory function start() below should be used instead (it
581 # selects the proper threaded class).
578 # selects the proper threaded class).
582
579
583 class IPShellGTK(threading.Thread):
580 class IPShellGTK(threading.Thread):
584 """Run a gtk mainloop() in a separate thread.
581 """Run a gtk mainloop() in a separate thread.
585
582
586 Python commands can be passed to the thread where they will be executed.
583 Python commands can be passed to the thread where they will be executed.
587 This is implemented by periodically checking for passed code using a
584 This is implemented by periodically checking for passed code using a
588 GTK timeout callback."""
585 GTK timeout callback."""
589
586
590 TIMEOUT = 100 # Millisecond interval between timeouts.
587 TIMEOUT = 100 # Millisecond interval between timeouts.
591
588
592 def __init__(self,argv=None,user_ns=None,debug=1,
589 def __init__(self,argv=None,user_ns=None,debug=1,
593 shell_class=MTInteractiveShell):
590 shell_class=MTInteractiveShell):
594
591
595 import pygtk
596 pygtk.require("2.0")
597 import gtk
592 import gtk
598
593
599 self.gtk = gtk
594 self.gtk = gtk
600 self.gtk_mainloop = hijack_gtk()
595 self.gtk_mainloop = hijack_gtk()
601
596
602 # Allows us to use both Tk and GTK.
597 # Allows us to use both Tk and GTK.
603 self.tk = get_tk()
598 self.tk = get_tk()
604
599
605 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
600 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
606 else: mainquit = self.gtk.mainquit
601 else: mainquit = self.gtk.mainquit
607
602
608 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
603 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
609 shell_class=shell_class,
604 shell_class=shell_class,
610 on_kill=[mainquit])
605 on_kill=[mainquit])
611 threading.Thread.__init__(self)
606 threading.Thread.__init__(self)
612
607
613 def run(self):
608 def run(self):
614 self.IP.mainloop()
609 self.IP.mainloop()
615 self.IP.kill()
610 self.IP.kill()
616
611
617 def mainloop(self):
612 def mainloop(self):
618
613
619 if self.gtk.pygtk_version >= (2,4,0):
614 if self.gtk.pygtk_version >= (2,4,0):
620 import gobject
615 import gobject
621 gobject.timeout_add(self.TIMEOUT, self.on_timer)
616 gobject.timeout_add(self.TIMEOUT, self.on_timer)
622 else:
617 else:
623 self.gtk.timeout_add(self.TIMEOUT, self.on_timer)
618 self.gtk.timeout_add(self.TIMEOUT, self.on_timer)
624
619
625 if sys.platform != 'win32':
620 if sys.platform != 'win32':
626 try:
621 try:
627 if self.gtk.gtk_version[0] >= 2:
622 if self.gtk.gtk_version[0] >= 2:
628 self.gtk.threads_init()
623 self.gtk.threads_init()
629 except AttributeError:
624 except AttributeError:
630 pass
625 pass
631 except RuntimeError:
626 except RuntimeError:
632 error('Your pyGTK likely has not been compiled with '
627 error('Your pyGTK likely has not been compiled with '
633 'threading support.\n'
628 'threading support.\n'
634 'The exception printout is below.\n'
629 'The exception printout is below.\n'
635 'You can either rebuild pyGTK with threads, or '
630 'You can either rebuild pyGTK with threads, or '
636 'try using \n'
631 'try using \n'
637 'matplotlib with a different backend (like Tk or WX).\n'
632 'matplotlib with a different backend (like Tk or WX).\n'
638 'Note that matplotlib will most likely not work in its '
633 'Note that matplotlib will most likely not work in its '
639 'current state!')
634 'current state!')
640 self.IP.InteractiveTB()
635 self.IP.InteractiveTB()
641 self.start()
636 self.start()
642 self.gtk.threads_enter()
637 self.gtk.threads_enter()
643 self.gtk_mainloop()
638 self.gtk_mainloop()
644 self.gtk.threads_leave()
639 self.gtk.threads_leave()
645 self.join()
640 self.join()
646
641
647 def on_timer(self):
642 def on_timer(self):
648 update_tk(self.tk)
643 update_tk(self.tk)
649 return self.IP.runcode()
644 return self.IP.runcode()
650
645
651
646
652 class IPShellWX(threading.Thread):
647 class IPShellWX(threading.Thread):
653 """Run a wx mainloop() in a separate thread.
648 """Run a wx mainloop() in a separate thread.
654
649
655 Python commands can be passed to the thread where they will be executed.
650 Python commands can be passed to the thread where they will be executed.
656 This is implemented by periodically checking for passed code using a
651 This is implemented by periodically checking for passed code using a
657 GTK timeout callback."""
652 GTK timeout callback."""
658
653
659 TIMEOUT = 100 # Millisecond interval between timeouts.
654 TIMEOUT = 100 # Millisecond interval between timeouts.
660
655
661 def __init__(self,argv=None,user_ns=None,debug=1,
656 def __init__(self,argv=None,user_ns=None,debug=1,
662 shell_class=MTInteractiveShell):
657 shell_class=MTInteractiveShell):
663
658
664 import wxPython.wx as wx
659 import wxPython.wx as wx
665
660
666 threading.Thread.__init__(self)
661 threading.Thread.__init__(self)
667 self.wx = wx
662 self.wx = wx
668 self.wx_mainloop = hijack_wx()
663 self.wx_mainloop = hijack_wx()
669
664
670 # Allows us to use both Tk and GTK.
665 # Allows us to use both Tk and GTK.
671 self.tk = get_tk()
666 self.tk = get_tk()
672
667
673 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
668 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
674 shell_class=shell_class,
669 shell_class=shell_class,
675 on_kill=[self.wxexit])
670 on_kill=[self.wxexit])
676 self.app = None
671 self.app = None
677
672
678 def wxexit(self, *args):
673 def wxexit(self, *args):
679 if self.app is not None:
674 if self.app is not None:
680 self.app.agent.timer.Stop()
675 self.app.agent.timer.Stop()
681 self.app.ExitMainLoop()
676 self.app.ExitMainLoop()
682
677
683 def run(self):
678 def run(self):
684 self.IP.mainloop()
679 self.IP.mainloop()
685 self.IP.kill()
680 self.IP.kill()
686
681
687 def mainloop(self):
682 def mainloop(self):
688
683
689 self.start()
684 self.start()
690
685
691 class TimerAgent(self.wx.wxMiniFrame):
686 class TimerAgent(self.wx.wxMiniFrame):
692 wx = self.wx
687 wx = self.wx
693 IP = self.IP
688 IP = self.IP
694 tk = self.tk
689 tk = self.tk
695 def __init__(self, parent, interval):
690 def __init__(self, parent, interval):
696 style = self.wx.wxDEFAULT_FRAME_STYLE | self.wx.wxTINY_CAPTION_HORIZ
691 style = self.wx.wxDEFAULT_FRAME_STYLE | self.wx.wxTINY_CAPTION_HORIZ
697 self.wx.wxMiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
692 self.wx.wxMiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
698 size=(100, 100),style=style)
693 size=(100, 100),style=style)
699 self.Show(False)
694 self.Show(False)
700 self.interval = interval
695 self.interval = interval
701 self.timerId = self.wx.wxNewId()
696 self.timerId = self.wx.wxNewId()
702
697
703 def StartWork(self):
698 def StartWork(self):
704 self.timer = self.wx.wxTimer(self, self.timerId)
699 self.timer = self.wx.wxTimer(self, self.timerId)
705 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
700 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
706 self.timer.Start(self.interval)
701 self.timer.Start(self.interval)
707
702
708 def OnTimer(self, event):
703 def OnTimer(self, event):
709 update_tk(self.tk)
704 update_tk(self.tk)
710 self.IP.runcode()
705 self.IP.runcode()
711
706
712 class App(self.wx.wxApp):
707 class App(self.wx.wxApp):
713 wx = self.wx
708 wx = self.wx
714 TIMEOUT = self.TIMEOUT
709 TIMEOUT = self.TIMEOUT
715 def OnInit(self):
710 def OnInit(self):
716 'Create the main window and insert the custom frame'
711 'Create the main window and insert the custom frame'
717 self.agent = TimerAgent(None, self.TIMEOUT)
712 self.agent = TimerAgent(None, self.TIMEOUT)
718 self.agent.Show(self.wx.false)
713 self.agent.Show(self.wx.false)
719 self.agent.StartWork()
714 self.agent.StartWork()
720 return self.wx.true
715 return self.wx.true
721
716
722 self.app = App(redirect=False)
717 self.app = App(redirect=False)
723 self.wx_mainloop(self.app)
718 self.wx_mainloop(self.app)
724 self.join()
719 self.join()
725
720
726
721
727 class IPShellQt(threading.Thread):
722 class IPShellQt(threading.Thread):
728 """Run a Qt event loop in a separate thread.
723 """Run a Qt event loop in a separate thread.
729
724
730 Python commands can be passed to the thread where they will be executed.
725 Python commands can be passed to the thread where they will be executed.
731 This is implemented by periodically checking for passed code using a
726 This is implemented by periodically checking for passed code using a
732 Qt timer / slot."""
727 Qt timer / slot."""
733
728
734 TIMEOUT = 100 # Millisecond interval between timeouts.
729 TIMEOUT = 100 # Millisecond interval between timeouts.
735
730
736 def __init__(self,argv=None,user_ns=None,debug=0,
731 def __init__(self,argv=None,user_ns=None,debug=0,
737 shell_class=MTInteractiveShell):
732 shell_class=MTInteractiveShell):
738
733
739 import qt
734 import qt
740
735
741 class newQApplication:
736 class newQApplication:
742 def __init__( self ):
737 def __init__( self ):
743 self.QApplication = qt.QApplication
738 self.QApplication = qt.QApplication
744
739
745 def __call__( *args, **kwargs ):
740 def __call__( *args, **kwargs ):
746 return qt.qApp
741 return qt.qApp
747
742
748 def exec_loop( *args, **kwargs ):
743 def exec_loop( *args, **kwargs ):
749 pass
744 pass
750
745
751 def __getattr__( self, name ):
746 def __getattr__( self, name ):
752 return getattr( self.QApplication, name )
747 return getattr( self.QApplication, name )
753
748
754 qt.QApplication = newQApplication()
749 qt.QApplication = newQApplication()
755
750
756 # Allows us to use both Tk and QT.
751 # Allows us to use both Tk and QT.
757 self.tk = get_tk()
752 self.tk = get_tk()
758
753
759 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
754 self.IP = make_IPython(argv,user_ns=user_ns,debug=debug,
760 shell_class=shell_class,
755 shell_class=shell_class,
761 on_kill=[qt.qApp.exit])
756 on_kill=[qt.qApp.exit])
762
757
763 threading.Thread.__init__(self)
758 threading.Thread.__init__(self)
764
759
765 def run(self):
760 def run(self):
766 #sys.excepthook = self.IP.excepthook # dbg
761 #sys.excepthook = self.IP.excepthook # dbg
767 self.IP.mainloop()
762 self.IP.mainloop()
768 self.IP.kill()
763 self.IP.kill()
769
764
770 def mainloop(self):
765 def mainloop(self):
771 import qt, sys
766 import qt, sys
772 if qt.QApplication.startingUp():
767 if qt.QApplication.startingUp():
773 a = qt.QApplication.QApplication( sys.argv )
768 a = qt.QApplication.QApplication( sys.argv )
774 self.timer = qt.QTimer()
769 self.timer = qt.QTimer()
775 qt.QObject.connect( self.timer, qt.SIGNAL( 'timeout()' ), self.on_timer )
770 qt.QObject.connect( self.timer, qt.SIGNAL( 'timeout()' ), self.on_timer )
776
771
777 self.start()
772 self.start()
778 self.timer.start( self.TIMEOUT, True )
773 self.timer.start( self.TIMEOUT, True )
779 while True:
774 while True:
780 if self.IP._kill: break
775 if self.IP._kill: break
781 qt.qApp.exec_loop()
776 qt.qApp.exec_loop()
782 self.join()
777 self.join()
783
778
784 def on_timer(self):
779 def on_timer(self):
785 update_tk(self.tk)
780 update_tk(self.tk)
786 result = self.IP.runcode()
781 result = self.IP.runcode()
787 self.timer.start( self.TIMEOUT, True )
782 self.timer.start( self.TIMEOUT, True )
788 return result
783 return result
789
784
790 # A set of matplotlib public IPython shell classes, for single-threaded
785 # A set of matplotlib public IPython shell classes, for single-threaded
791 # (Tk* and FLTK* backends) and multithreaded (GTK* and WX* backends) use.
786 # (Tk* and FLTK* backends) and multithreaded (GTK* and WX* backends) use.
792 class IPShellMatplotlib(IPShell):
787 class IPShellMatplotlib(IPShell):
793 """Subclass IPShell with MatplotlibShell as the internal shell.
788 """Subclass IPShell with MatplotlibShell as the internal shell.
794
789
795 Single-threaded class, meant for the Tk* and FLTK* backends.
790 Single-threaded class, meant for the Tk* and FLTK* backends.
796
791
797 Having this on a separate class simplifies the external driver code."""
792 Having this on a separate class simplifies the external driver code."""
798
793
799 def __init__(self,argv=None,user_ns=None,debug=1):
794 def __init__(self,argv=None,user_ns=None,debug=1):
800 IPShell.__init__(self,argv,user_ns,debug,shell_class=MatplotlibShell)
795 IPShell.__init__(self,argv,user_ns,debug,shell_class=MatplotlibShell)
801
796
802 class IPShellMatplotlibGTK(IPShellGTK):
797 class IPShellMatplotlibGTK(IPShellGTK):
803 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
798 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
804
799
805 Multi-threaded class, meant for the GTK* backends."""
800 Multi-threaded class, meant for the GTK* backends."""
806
801
807 def __init__(self,argv=None,user_ns=None,debug=1):
802 def __init__(self,argv=None,user_ns=None,debug=1):
808 IPShellGTK.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
803 IPShellGTK.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
809
804
810 class IPShellMatplotlibWX(IPShellWX):
805 class IPShellMatplotlibWX(IPShellWX):
811 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
806 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
812
807
813 Multi-threaded class, meant for the WX* backends."""
808 Multi-threaded class, meant for the WX* backends."""
814
809
815 def __init__(self,argv=None,user_ns=None,debug=1):
810 def __init__(self,argv=None,user_ns=None,debug=1):
816 IPShellWX.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
811 IPShellWX.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
817
812
818 class IPShellMatplotlibQt(IPShellQt):
813 class IPShellMatplotlibQt(IPShellQt):
819 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
814 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
820
815
821 Multi-threaded class, meant for the Qt* backends."""
816 Multi-threaded class, meant for the Qt* backends."""
822
817
823 def __init__(self,argv=None,user_ns=None,debug=1):
818 def __init__(self,argv=None,user_ns=None,debug=1):
824 IPShellQt.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
819 IPShellQt.__init__(self,argv,user_ns,debug,shell_class=MatplotlibMTShell)
825
820
826 #-----------------------------------------------------------------------------
821 #-----------------------------------------------------------------------------
827 # Factory functions to actually start the proper thread-aware shell
822 # Factory functions to actually start the proper thread-aware shell
828
823
829 def _matplotlib_shell_class():
824 def _matplotlib_shell_class():
830 """Factory function to handle shell class selection for matplotlib.
825 """Factory function to handle shell class selection for matplotlib.
831
826
832 The proper shell class to use depends on the matplotlib backend, since
827 The proper shell class to use depends on the matplotlib backend, since
833 each backend requires a different threading strategy."""
828 each backend requires a different threading strategy."""
834
829
835 try:
830 try:
836 import matplotlib
831 import matplotlib
837 except ImportError:
832 except ImportError:
838 error('matplotlib could NOT be imported! Starting normal IPython.')
833 error('matplotlib could NOT be imported! Starting normal IPython.')
839 sh_class = IPShell
834 sh_class = IPShell
840 else:
835 else:
841 backend = matplotlib.rcParams['backend']
836 backend = matplotlib.rcParams['backend']
842 if backend.startswith('GTK'):
837 if backend.startswith('GTK'):
843 sh_class = IPShellMatplotlibGTK
838 sh_class = IPShellMatplotlibGTK
844 elif backend.startswith('WX'):
839 elif backend.startswith('WX'):
845 sh_class = IPShellMatplotlibWX
840 sh_class = IPShellMatplotlibWX
846 elif backend.startswith('Qt'):
841 elif backend.startswith('Qt'):
847 sh_class = IPShellMatplotlibQt
842 sh_class = IPShellMatplotlibQt
848 else:
843 else:
849 sh_class = IPShellMatplotlib
844 sh_class = IPShellMatplotlib
850 #print 'Using %s with the %s backend.' % (sh_class,backend) # dbg
845 #print 'Using %s with the %s backend.' % (sh_class,backend) # dbg
851 return sh_class
846 return sh_class
852
847
853 # This is the one which should be called by external code.
848 # This is the one which should be called by external code.
854 def start():
849 def start():
855 """Return a running shell instance, dealing with threading options.
850 """Return a running shell instance, dealing with threading options.
856
851
857 This is a factory function which will instantiate the proper IPython shell
852 This is a factory function which will instantiate the proper IPython shell
858 based on the user's threading choice. Such a selector is needed because
853 based on the user's threading choice. Such a selector is needed because
859 different GUI toolkits require different thread handling details."""
854 different GUI toolkits require different thread handling details."""
860
855
861 global USE_TK
856 global USE_TK
862 # Crude sys.argv hack to extract the threading options.
857 # Crude sys.argv hack to extract the threading options.
863 if len(sys.argv) > 1:
858 if len(sys.argv) > 1:
864 if len(sys.argv) > 2:
859 if len(sys.argv) > 2:
865 arg2 = sys.argv[2]
860 arg2 = sys.argv[2]
866 if arg2.endswith('-tk'):
861 if arg2.endswith('-tk'):
867 USE_TK = True
862 USE_TK = True
868 arg1 = sys.argv[1]
863 arg1 = sys.argv[1]
869 if arg1.endswith('-gthread'):
864 if arg1.endswith('-gthread'):
870 shell = IPShellGTK
865 shell = IPShellGTK
871 elif arg1.endswith( '-qthread' ):
866 elif arg1.endswith( '-qthread' ):
872 shell = IPShellQt
867 shell = IPShellQt
873 elif arg1.endswith('-wthread'):
868 elif arg1.endswith('-wthread'):
874 shell = IPShellWX
869 shell = IPShellWX
875 elif arg1.endswith('-pylab'):
870 elif arg1.endswith('-pylab'):
876 shell = _matplotlib_shell_class()
871 shell = _matplotlib_shell_class()
877 else:
872 else:
878 shell = IPShell
873 shell = IPShell
879 else:
874 else:
880 shell = IPShell
875 shell = IPShell
881 return shell()
876 return shell()
882
877
883 # Some aliases for backwards compatibility
878 # Some aliases for backwards compatibility
884 IPythonShell = IPShell
879 IPythonShell = IPShell
885 IPythonShellEmbed = IPShellEmbed
880 IPythonShellEmbed = IPShellEmbed
886 #************************ End of file <Shell.py> ***************************
881 #************************ End of file <Shell.py> ***************************
@@ -1,2041 +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 774 2005-09-01 00:27:53Z fperez $
9 $Id: iplib.py 802 2005-09-06 03:49:12Z fperez $
10 """
10 """
11
11
12 #*****************************************************************************
12 #*****************************************************************************
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
14 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
14 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #
18 #
19 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Note: this code originally subclassed code.InteractiveConsole from the
20 # Python standard library. Over time, much of that class has been copied
20 # Python standard library. Over time, much of that class has been copied
21 # verbatim here for modifications which could not be accomplished by
21 # verbatim here for modifications which could not be accomplished by
22 # subclassing. The Python License (sec. 2) allows for this, but it's always
22 # subclassing. The Python License (sec. 2) allows for this, but it's always
23 # nice to acknowledge credit where credit is due.
23 # nice to acknowledge credit where credit is due.
24 #*****************************************************************************
24 #*****************************************************************************
25
25
26 #****************************************************************************
26 #****************************************************************************
27 # Modules and globals
27 # Modules and globals
28
28
29 from __future__ import generators # for 2.2 backwards-compatibility
29 from __future__ import generators # for 2.2 backwards-compatibility
30
30
31 from IPython import Release
31 from IPython import Release
32 __author__ = '%s <%s>\n%s <%s>' % \
32 __author__ = '%s <%s>\n%s <%s>' % \
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
33 ( Release.authors['Janko'] + Release.authors['Fernando'] )
34 __license__ = Release.license
34 __license__ = Release.license
35 __version__ = Release.version
35 __version__ = Release.version
36
36
37 # Python standard modules
37 # Python standard modules
38 import __main__
38 import __main__
39 import __builtin__
39 import __builtin__
40 import exceptions
40 import exceptions
41 import keyword
41 import keyword
42 import new
42 import new
43 import os, sys, shutil
43 import os, sys, shutil
44 import code, glob, types, re
44 import code, glob, types, re
45 import string, StringIO
45 import string, StringIO
46 import inspect, pydoc
46 import inspect, pydoc
47 import bdb, pdb
47 import bdb, pdb
48 import UserList # don't subclass list so this works with Python2.1
48 import UserList # don't subclass list so this works with Python2.1
49 from pprint import pprint, pformat
49 from pprint import pprint, pformat
50 import cPickle as pickle
50 import cPickle as pickle
51 import traceback
51 import traceback
52
52
53 # IPython's own modules
53 # IPython's own modules
54 import IPython
54 import IPython
55 from IPython import OInspect,PyColorize,ultraTB
55 from IPython import OInspect,PyColorize,ultraTB
56 from IPython.ultraTB import ColorScheme,ColorSchemeTable # too long names
56 from IPython.ultraTB import ColorScheme,ColorSchemeTable # too long names
57 from IPython.Logger import Logger
57 from IPython.Logger import Logger
58 from IPython.Magic import Magic,magic2python,shlex_split
58 from IPython.Magic import Magic,magic2python,shlex_split
59 from IPython.usage import cmd_line_usage,interactive_usage
59 from IPython.usage import cmd_line_usage,interactive_usage
60 from IPython.Struct import Struct
60 from IPython.Struct import Struct
61 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
61 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
62 from IPython.FakeModule import FakeModule
62 from IPython.FakeModule import FakeModule
63 from IPython.background_jobs import BackgroundJobManager
63 from IPython.background_jobs import BackgroundJobManager
64 from IPython.genutils import *
64 from IPython.genutils import *
65
65
66 # Global pointer to the running
66 # Global pointer to the running
67
67
68 # store the builtin raw_input globally, and use this always, in case user code
68 # store the builtin raw_input globally, and use this always, in case user code
69 # overwrites it (like wx.py.PyShell does)
69 # overwrites it (like wx.py.PyShell does)
70 raw_input_original = raw_input
70 raw_input_original = raw_input
71
71
72 #****************************************************************************
72 #****************************************************************************
73 # Some utility function definitions
73 # Some utility function definitions
74
74
75 class Bunch: pass
75 class Bunch: pass
76
76
77 def esc_quotes(strng):
77 def esc_quotes(strng):
78 """Return the input string with single and double quotes escaped out"""
78 """Return the input string with single and double quotes escaped out"""
79
79
80 return strng.replace('"','\\"').replace("'","\\'")
80 return strng.replace('"','\\"').replace("'","\\'")
81
81
82 def import_fail_info(mod_name,fns=None):
82 def import_fail_info(mod_name,fns=None):
83 """Inform load failure for a module."""
83 """Inform load failure for a module."""
84
84
85 if fns == None:
85 if fns == None:
86 warn("Loading of %s failed.\n" % (mod_name,))
86 warn("Loading of %s failed.\n" % (mod_name,))
87 else:
87 else:
88 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
88 warn("Loading of %s from %s failed.\n" % (fns,mod_name))
89
89
90 def qw_lol(indata):
90 def qw_lol(indata):
91 """qw_lol('a b') -> [['a','b']],
91 """qw_lol('a b') -> [['a','b']],
92 otherwise it's just a call to qw().
92 otherwise it's just a call to qw().
93
93
94 We need this to make sure the modules_some keys *always* end up as a
94 We need this to make sure the modules_some keys *always* end up as a
95 list of lists."""
95 list of lists."""
96
96
97 if type(indata) in StringTypes:
97 if type(indata) in StringTypes:
98 return [qw(indata)]
98 return [qw(indata)]
99 else:
99 else:
100 return qw(indata)
100 return qw(indata)
101
101
102 def ipmagic(arg_s):
102 def ipmagic(arg_s):
103 """Call a magic function by name.
103 """Call a magic function by name.
104
104
105 Input: a string containing the name of the magic function to call and any
105 Input: a string containing the name of the magic function to call and any
106 additional arguments to be passed to the magic.
106 additional arguments to be passed to the magic.
107
107
108 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
108 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
109 prompt:
109 prompt:
110
110
111 In[1]: %name -opt foo bar
111 In[1]: %name -opt foo bar
112
112
113 To call a magic without arguments, simply use ipmagic('name').
113 To call a magic without arguments, simply use ipmagic('name').
114
114
115 This provides a proper Python function to call IPython's magics in any
115 This provides a proper Python function to call IPython's magics in any
116 valid Python code you can type at the interpreter, including loops and
116 valid Python code you can type at the interpreter, including loops and
117 compound statements. It is added by IPython to the Python builtin
117 compound statements. It is added by IPython to the Python builtin
118 namespace upon initialization."""
118 namespace upon initialization."""
119
119
120 args = arg_s.split(' ',1)
120 args = arg_s.split(' ',1)
121 magic_name = args[0]
121 magic_name = args[0]
122 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
122 if magic_name.startswith(__IPYTHON__.ESC_MAGIC):
123 magic_name = magic_name[1:]
123 magic_name = magic_name[1:]
124 try:
124 try:
125 magic_args = args[1]
125 magic_args = args[1]
126 except IndexError:
126 except IndexError:
127 magic_args = ''
127 magic_args = ''
128 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
128 fn = getattr(__IPYTHON__,'magic_'+magic_name,None)
129 if fn is None:
129 if fn is None:
130 error("Magic function `%s` not found." % magic_name)
130 error("Magic function `%s` not found." % magic_name)
131 else:
131 else:
132 magic_args = __IPYTHON__.var_expand(magic_args)
132 magic_args = __IPYTHON__.var_expand(magic_args)
133 return fn(magic_args)
133 return fn(magic_args)
134
134
135 def ipalias(arg_s):
135 def ipalias(arg_s):
136 """Call an alias by name.
136 """Call an alias by name.
137
137
138 Input: a string containing the name of the alias to call and any
138 Input: a string containing the name of the alias to call and any
139 additional arguments to be passed to the magic.
139 additional arguments to be passed to the magic.
140
140
141 ipalias('name -opt foo bar') is equivalent to typing at the ipython
141 ipalias('name -opt foo bar') is equivalent to typing at the ipython
142 prompt:
142 prompt:
143
143
144 In[1]: name -opt foo bar
144 In[1]: name -opt foo bar
145
145
146 To call an alias without arguments, simply use ipalias('name').
146 To call an alias without arguments, simply use ipalias('name').
147
147
148 This provides a proper Python function to call IPython's aliases in any
148 This provides a proper Python function to call IPython's aliases in any
149 valid Python code you can type at the interpreter, including loops and
149 valid Python code you can type at the interpreter, including loops and
150 compound statements. It is added by IPython to the Python builtin
150 compound statements. It is added by IPython to the Python builtin
151 namespace upon initialization."""
151 namespace upon initialization."""
152
152
153 args = arg_s.split(' ',1)
153 args = arg_s.split(' ',1)
154 alias_name = args[0]
154 alias_name = args[0]
155 try:
155 try:
156 alias_args = args[1]
156 alias_args = args[1]
157 except IndexError:
157 except IndexError:
158 alias_args = ''
158 alias_args = ''
159 if alias_name in __IPYTHON__.alias_table:
159 if alias_name in __IPYTHON__.alias_table:
160 __IPYTHON__.call_alias(alias_name,alias_args)
160 __IPYTHON__.call_alias(alias_name,alias_args)
161 else:
161 else:
162 error("Alias `%s` not found." % alias_name)
162 error("Alias `%s` not found." % alias_name)
163
163
164 #-----------------------------------------------------------------------------
164 #-----------------------------------------------------------------------------
165 # Local use classes
165 # Local use classes
166 try:
166 try:
167 from IPython import FlexCompleter
167 from IPython import FlexCompleter
168
168
169 class MagicCompleter(FlexCompleter.Completer):
169 class MagicCompleter(FlexCompleter.Completer):
170 """Extension of the completer class to work on %-prefixed lines."""
170 """Extension of the completer class to work on %-prefixed lines."""
171
171
172 def __init__(self,shell,namespace=None,omit__names=0,alias_table=None):
172 def __init__(self,shell,namespace=None,omit__names=0,alias_table=None):
173 """MagicCompleter() -> completer
173 """MagicCompleter() -> completer
174
174
175 Return a completer object suitable for use by the readline library
175 Return a completer object suitable for use by the readline library
176 via readline.set_completer().
176 via readline.set_completer().
177
177
178 Inputs:
178 Inputs:
179
179
180 - shell: a pointer to the ipython shell itself. This is needed
180 - shell: a pointer to the ipython shell itself. This is needed
181 because this completer knows about magic functions, and those can
181 because this completer knows about magic functions, and those can
182 only be accessed via the ipython instance.
182 only be accessed via the ipython instance.
183
183
184 - namespace: an optional dict where completions are performed.
184 - namespace: an optional dict where completions are performed.
185
185
186 - The optional omit__names parameter sets the completer to omit the
186 - The optional omit__names parameter sets the completer to omit the
187 'magic' names (__magicname__) for python objects unless the text
187 'magic' names (__magicname__) for python objects unless the text
188 to be completed explicitly starts with one or more underscores.
188 to be completed explicitly starts with one or more underscores.
189
189
190 - If alias_table is supplied, it should be a dictionary of aliases
190 - If alias_table is supplied, it should be a dictionary of aliases
191 to complete. """
191 to complete. """
192
192
193 FlexCompleter.Completer.__init__(self,namespace)
193 FlexCompleter.Completer.__init__(self,namespace)
194 self.magic_prefix = shell.name+'.magic_'
194 self.magic_prefix = shell.name+'.magic_'
195 self.magic_escape = shell.ESC_MAGIC
195 self.magic_escape = shell.ESC_MAGIC
196 self.readline = FlexCompleter.readline
196 self.readline = FlexCompleter.readline
197 delims = self.readline.get_completer_delims()
197 delims = self.readline.get_completer_delims()
198 delims = delims.replace(self.magic_escape,'')
198 delims = delims.replace(self.magic_escape,'')
199 self.readline.set_completer_delims(delims)
199 self.readline.set_completer_delims(delims)
200 self.get_line_buffer = self.readline.get_line_buffer
200 self.get_line_buffer = self.readline.get_line_buffer
201 self.omit__names = omit__names
201 self.omit__names = omit__names
202 self.merge_completions = shell.rc.readline_merge_completions
202 self.merge_completions = shell.rc.readline_merge_completions
203
203
204 if alias_table is None:
204 if alias_table is None:
205 alias_table = {}
205 alias_table = {}
206 self.alias_table = alias_table
206 self.alias_table = alias_table
207 # Regexp to split filenames with spaces in them
207 # Regexp to split filenames with spaces in them
208 self.space_name_re = re.compile(r'([^\\] )')
208 self.space_name_re = re.compile(r'([^\\] )')
209 # Hold a local ref. to glob.glob for speed
209 # Hold a local ref. to glob.glob for speed
210 self.glob = glob.glob
210 self.glob = glob.glob
211 # Special handling of backslashes needed in win32 platforms
211 # Special handling of backslashes needed in win32 platforms
212 if sys.platform == "win32":
212 if sys.platform == "win32":
213 self.clean_glob = self._clean_glob_win32
213 self.clean_glob = self._clean_glob_win32
214 else:
214 else:
215 self.clean_glob = self._clean_glob
215 self.clean_glob = self._clean_glob
216 self.matchers = [self.python_matches,
216 self.matchers = [self.python_matches,
217 self.file_matches,
217 self.file_matches,
218 self.alias_matches,
218 self.alias_matches,
219 self.python_func_kw_matches]
219 self.python_func_kw_matches]
220
220
221 # Code contributed by Alex Schmolck, for ipython/emacs integration
221 # Code contributed by Alex Schmolck, for ipython/emacs integration
222 def all_completions(self, text):
222 def all_completions(self, text):
223 """Return all possible completions for the benefit of emacs."""
223 """Return all possible completions for the benefit of emacs."""
224
224
225 completions = []
225 completions = []
226 try:
226 try:
227 for i in xrange(sys.maxint):
227 for i in xrange(sys.maxint):
228 res = self.complete(text, i)
228 res = self.complete(text, i)
229
229
230 if not res: break
230 if not res: break
231
231
232 completions.append(res)
232 completions.append(res)
233 #XXX workaround for ``notDefined.<tab>``
233 #XXX workaround for ``notDefined.<tab>``
234 except NameError:
234 except NameError:
235 pass
235 pass
236 return completions
236 return completions
237 # /end Alex Schmolck code.
237 # /end Alex Schmolck code.
238
238
239 def _clean_glob(self,text):
239 def _clean_glob(self,text):
240 return self.glob("%s*" % text)
240 return self.glob("%s*" % text)
241
241
242 def _clean_glob_win32(self,text):
242 def _clean_glob_win32(self,text):
243 return [f.replace("\\","/")
243 return [f.replace("\\","/")
244 for f in self.glob("%s*" % text)]
244 for f in self.glob("%s*" % text)]
245
245
246 def file_matches(self, text):
246 def file_matches(self, text):
247 """Match filneames, expanding ~USER type strings.
247 """Match filneames, expanding ~USER type strings.
248
248
249 Most of the seemingly convoluted logic in this completer is an
249 Most of the seemingly convoluted logic in this completer is an
250 attempt to handle filenames with spaces in them. And yet it's not
250 attempt to handle filenames with spaces in them. And yet it's not
251 quite perfect, because Python's readline doesn't expose all of the
251 quite perfect, because Python's readline doesn't expose all of the
252 GNU readline details needed for this to be done correctly.
252 GNU readline details needed for this to be done correctly.
253
253
254 For a filename with a space in it, the printed completions will be
254 For a filename with a space in it, the printed completions will be
255 only the parts after what's already been typed (instead of the
255 only the parts after what's already been typed (instead of the
256 full completions, as is normally done). I don't think with the
256 full completions, as is normally done). I don't think with the
257 current (as of Python 2.3) Python readline it's possible to do
257 current (as of Python 2.3) Python readline it's possible to do
258 better."""
258 better."""
259
259
260 #print 'Completer->file_matches: <%s>' % text # dbg
260 #print 'Completer->file_matches: <%s>' % text # dbg
261
261
262 # chars that require escaping with backslash - i.e. chars
262 # chars that require escaping with backslash - i.e. chars
263 # that readline treats incorrectly as delimiters, but we
263 # that readline treats incorrectly as delimiters, but we
264 # don't want to treat as delimiters in filename matching
264 # don't want to treat as delimiters in filename matching
265 # when escaped with backslash
265 # when escaped with backslash
266
266
267 protectables = ' ()[]{}'
267 protectables = ' ()[]{}'
268
268
269 def protect_filename(s):
269 def protect_filename(s):
270 return "".join([(ch in protectables and '\\' + ch or ch)
270 return "".join([(ch in protectables and '\\' + ch or ch)
271 for ch in s])
271 for ch in s])
272
272
273 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
273 lbuf = self.get_line_buffer()[:self.readline.get_endidx()]
274 open_quotes = 0 # track strings with open quotes
274 open_quotes = 0 # track strings with open quotes
275 try:
275 try:
276 lsplit = shlex_split(lbuf)[-1]
276 lsplit = shlex_split(lbuf)[-1]
277 except ValueError:
277 except ValueError:
278 # typically an unmatched ", or backslash without escaped char.
278 # typically an unmatched ", or backslash without escaped char.
279 if lbuf.count('"')==1:
279 if lbuf.count('"')==1:
280 open_quotes = 1
280 open_quotes = 1
281 lsplit = lbuf.split('"')[-1]
281 lsplit = lbuf.split('"')[-1]
282 elif lbuf.count("'")==1:
282 elif lbuf.count("'")==1:
283 open_quotes = 1
283 open_quotes = 1
284 lsplit = lbuf.split("'")[-1]
284 lsplit = lbuf.split("'")[-1]
285 else:
285 else:
286 return None
286 return None
287 except IndexError:
287 except IndexError:
288 # tab pressed on empty line
288 # tab pressed on empty line
289 lsplit = ""
289 lsplit = ""
290
290
291 if lsplit != protect_filename(lsplit):
291 if lsplit != protect_filename(lsplit):
292 # if protectables are found, do matching on the whole escaped
292 # if protectables are found, do matching on the whole escaped
293 # name
293 # name
294 has_protectables = 1
294 has_protectables = 1
295 text0,text = text,lsplit
295 text0,text = text,lsplit
296 else:
296 else:
297 has_protectables = 0
297 has_protectables = 0
298 text = os.path.expanduser(text)
298 text = os.path.expanduser(text)
299
299
300 if text == "":
300 if text == "":
301 return [protect_filename(f) for f in self.glob("*")]
301 return [protect_filename(f) for f in self.glob("*")]
302
302
303 m0 = self.clean_glob(text.replace('\\',''))
303 m0 = self.clean_glob(text.replace('\\',''))
304 if has_protectables:
304 if has_protectables:
305 # If we had protectables, we need to revert our changes to the
305 # If we had protectables, we need to revert our changes to the
306 # beginning of filename so that we don't double-write the part
306 # beginning of filename so that we don't double-write the part
307 # of the filename we have so far
307 # of the filename we have so far
308 len_lsplit = len(lsplit)
308 len_lsplit = len(lsplit)
309 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
309 matches = [text0 + protect_filename(f[len_lsplit:]) for f in m0]
310 else:
310 else:
311 if open_quotes:
311 if open_quotes:
312 # if we have a string with an open quote, we don't need to
312 # if we have a string with an open quote, we don't need to
313 # protect the names at all (and we _shouldn't_, as it
313 # protect the names at all (and we _shouldn't_, as it
314 # would cause bugs when the filesystem call is made).
314 # would cause bugs when the filesystem call is made).
315 matches = m0
315 matches = m0
316 else:
316 else:
317 matches = [protect_filename(f) for f in m0]
317 matches = [protect_filename(f) for f in m0]
318 if len(matches) == 1 and os.path.isdir(matches[0]):
318 if len(matches) == 1 and os.path.isdir(matches[0]):
319 # Takes care of links to directories also. Use '/'
319 # Takes care of links to directories also. Use '/'
320 # explicitly, even under Windows, so that name completions
320 # explicitly, even under Windows, so that name completions
321 # don't end up escaped.
321 # don't end up escaped.
322 matches[0] += '/'
322 matches[0] += '/'
323 return matches
323 return matches
324
324
325 def alias_matches(self, text):
325 def alias_matches(self, text):
326 """Match internal system aliases"""
326 """Match internal system aliases"""
327 #print 'Completer->alias_matches:',text # dbg
327 #print 'Completer->alias_matches:',text # dbg
328 text = os.path.expanduser(text)
328 text = os.path.expanduser(text)
329 aliases = self.alias_table.keys()
329 aliases = self.alias_table.keys()
330 if text == "":
330 if text == "":
331 return aliases
331 return aliases
332 else:
332 else:
333 return [alias for alias in aliases if alias.startswith(text)]
333 return [alias for alias in aliases if alias.startswith(text)]
334
334
335 def python_matches(self,text):
335 def python_matches(self,text):
336 """Match attributes or global python names"""
336 """Match attributes or global python names"""
337 #print 'Completer->python_matches' # dbg
337 #print 'Completer->python_matches' # dbg
338 if "." in text:
338 if "." in text:
339 try:
339 try:
340 matches = self.attr_matches(text)
340 matches = self.attr_matches(text)
341 if text.endswith('.') and self.omit__names:
341 if text.endswith('.') and self.omit__names:
342 if self.omit__names == 1:
342 if self.omit__names == 1:
343 # true if txt is _not_ a __ name, false otherwise:
343 # true if txt is _not_ a __ name, false otherwise:
344 no__name = (lambda txt:
344 no__name = (lambda txt:
345 re.match(r'.*\.__.*?__',txt) is None)
345 re.match(r'.*\.__.*?__',txt) is None)
346 else:
346 else:
347 # true if txt is _not_ a _ name, false otherwise:
347 # true if txt is _not_ a _ name, false otherwise:
348 no__name = (lambda txt:
348 no__name = (lambda txt:
349 re.match(r'.*\._.*?',txt) is None)
349 re.match(r'.*\._.*?',txt) is None)
350 matches = filter(no__name, matches)
350 matches = filter(no__name, matches)
351 except NameError:
351 except NameError:
352 # catches <undefined attributes>.<tab>
352 # catches <undefined attributes>.<tab>
353 matches = []
353 matches = []
354 else:
354 else:
355 matches = self.global_matches(text)
355 matches = self.global_matches(text)
356 # this is so completion finds magics when automagic is on:
356 # this is so completion finds magics when automagic is on:
357 if matches == [] and not text.startswith(os.sep):
357 if matches == [] and not text.startswith(os.sep):
358 matches = self.attr_matches(self.magic_prefix+text)
358 matches = self.attr_matches(self.magic_prefix+text)
359 return matches
359 return matches
360
360
361 def _default_arguments(self, obj):
361 def _default_arguments(self, obj):
362 """Return the list of default arguments of obj if it is callable,
362 """Return the list of default arguments of obj if it is callable,
363 or empty list otherwise."""
363 or empty list otherwise."""
364
364
365 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
365 if not (inspect.isfunction(obj) or inspect.ismethod(obj)):
366 # for classes, check for __init__,__new__
366 # for classes, check for __init__,__new__
367 if inspect.isclass(obj):
367 if inspect.isclass(obj):
368 obj = (getattr(obj,'__init__',None) or
368 obj = (getattr(obj,'__init__',None) or
369 getattr(obj,'__new__',None))
369 getattr(obj,'__new__',None))
370 # for all others, check if they are __call__able
370 # for all others, check if they are __call__able
371 elif hasattr(obj, '__call__'):
371 elif hasattr(obj, '__call__'):
372 obj = obj.__call__
372 obj = obj.__call__
373 # XXX: is there a way to handle the builtins ?
373 # XXX: is there a way to handle the builtins ?
374 try:
374 try:
375 args,_,_1,defaults = inspect.getargspec(obj)
375 args,_,_1,defaults = inspect.getargspec(obj)
376 if defaults:
376 if defaults:
377 return args[-len(defaults):]
377 return args[-len(defaults):]
378 except TypeError: pass
378 except TypeError: pass
379 return []
379 return []
380
380
381 def python_func_kw_matches(self,text):
381 def python_func_kw_matches(self,text):
382 """Match named parameters (kwargs) of the last open function"""
382 """Match named parameters (kwargs) of the last open function"""
383
383
384 if "." in text: # a parameter cannot be dotted
384 if "." in text: # a parameter cannot be dotted
385 return []
385 return []
386 try: regexp = self.__funcParamsRegex
386 try: regexp = self.__funcParamsRegex
387 except AttributeError:
387 except AttributeError:
388 regexp = self.__funcParamsRegex = re.compile(r'''
388 regexp = self.__funcParamsRegex = re.compile(r'''
389 '.*?' | # single quoted strings or
389 '.*?' | # single quoted strings or
390 ".*?" | # double quoted strings or
390 ".*?" | # double quoted strings or
391 \w+ | # identifier
391 \w+ | # identifier
392 \S # other characters
392 \S # other characters
393 ''', re.VERBOSE | re.DOTALL)
393 ''', re.VERBOSE | re.DOTALL)
394 # 1. find the nearest identifier that comes before an unclosed
394 # 1. find the nearest identifier that comes before an unclosed
395 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
395 # parenthesis e.g. for "foo (1+bar(x), pa", the candidate is "foo"
396 tokens = regexp.findall(self.get_line_buffer())
396 tokens = regexp.findall(self.get_line_buffer())
397 tokens.reverse()
397 tokens.reverse()
398 iterTokens = iter(tokens); openPar = 0
398 iterTokens = iter(tokens); openPar = 0
399 for token in iterTokens:
399 for token in iterTokens:
400 if token == ')':
400 if token == ')':
401 openPar -= 1
401 openPar -= 1
402 elif token == '(':
402 elif token == '(':
403 openPar += 1
403 openPar += 1
404 if openPar > 0:
404 if openPar > 0:
405 # found the last unclosed parenthesis
405 # found the last unclosed parenthesis
406 break
406 break
407 else:
407 else:
408 return []
408 return []
409 # 2. Concatenate any dotted names (e.g. "foo.bar" for "foo.bar(x, pa" )
409 # 2. Concatenate any dotted names (e.g. "foo.bar" for "foo.bar(x, pa" )
410 ids = []
410 ids = []
411 isId = re.compile(r'\w+$').match
411 isId = re.compile(r'\w+$').match
412 while True:
412 while True:
413 try:
413 try:
414 ids.append(iterTokens.next())
414 ids.append(iterTokens.next())
415 if not isId(ids[-1]):
415 if not isId(ids[-1]):
416 ids.pop(); break
416 ids.pop(); break
417 if not iterTokens.next() == '.':
417 if not iterTokens.next() == '.':
418 break
418 break
419 except StopIteration:
419 except StopIteration:
420 break
420 break
421 # lookup the candidate callable matches either using global_matches
421 # lookup the candidate callable matches either using global_matches
422 # or attr_matches for dotted names
422 # or attr_matches for dotted names
423 if len(ids) == 1:
423 if len(ids) == 1:
424 callableMatches = self.global_matches(ids[0])
424 callableMatches = self.global_matches(ids[0])
425 else:
425 else:
426 callableMatches = self.attr_matches('.'.join(ids[::-1]))
426 callableMatches = self.attr_matches('.'.join(ids[::-1]))
427 argMatches = []
427 argMatches = []
428 for callableMatch in callableMatches:
428 for callableMatch in callableMatches:
429 try: namedArgs = self._default_arguments(eval(callableMatch,
429 try: namedArgs = self._default_arguments(eval(callableMatch,
430 self.namespace))
430 self.namespace))
431 except: continue
431 except: continue
432 for namedArg in namedArgs:
432 for namedArg in namedArgs:
433 if namedArg.startswith(text):
433 if namedArg.startswith(text):
434 argMatches.append("%s=" %namedArg)
434 argMatches.append("%s=" %namedArg)
435 return argMatches
435 return argMatches
436
436
437 def complete(self, text, state):
437 def complete(self, text, state):
438 """Return the next possible completion for 'text'.
438 """Return the next possible completion for 'text'.
439
439
440 This is called successively with state == 0, 1, 2, ... until it
440 This is called successively with state == 0, 1, 2, ... until it
441 returns None. The completion should begin with 'text'. """
441 returns None. The completion should begin with 'text'. """
442
442
443 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
443 #print '\n*** COMPLETE: <%s> (%s)' % (text,state) # dbg
444 magic_escape = self.magic_escape
444 magic_escape = self.magic_escape
445 magic_prefix = self.magic_prefix
445 magic_prefix = self.magic_prefix
446
446
447 try:
447 try:
448 if text.startswith(magic_escape):
448 if text.startswith(magic_escape):
449 text = text.replace(magic_escape,magic_prefix)
449 text = text.replace(magic_escape,magic_prefix)
450 elif text.startswith('~'):
450 elif text.startswith('~'):
451 text = os.path.expanduser(text)
451 text = os.path.expanduser(text)
452 if state == 0:
452 if state == 0:
453 # Extend the list of completions with the results of each
453 # Extend the list of completions with the results of each
454 # matcher, so we return results to the user from all
454 # matcher, so we return results to the user from all
455 # namespaces.
455 # namespaces.
456 if self.merge_completions:
456 if self.merge_completions:
457 self.matches = []
457 self.matches = []
458 for matcher in self.matchers:
458 for matcher in self.matchers:
459 self.matches.extend(matcher(text))
459 self.matches.extend(matcher(text))
460 else:
460 else:
461 for matcher in self.matchers:
461 for matcher in self.matchers:
462 self.matches = matcher(text)
462 self.matches = matcher(text)
463 if self.matches:
463 if self.matches:
464 break
464 break
465
465
466 try:
466 try:
467 return self.matches[state].replace(magic_prefix,magic_escape)
467 return self.matches[state].replace(magic_prefix,magic_escape)
468 except IndexError:
468 except IndexError:
469 return None
469 return None
470 except:
470 except:
471 # If completion fails, don't annoy the user.
471 # If completion fails, don't annoy the user.
472 pass
472 pass
473
473
474 except ImportError:
474 except ImportError:
475 pass # no readline support
475 pass # no readline support
476
476
477 except KeyError:
477 except KeyError:
478 pass # Windows doesn't set TERM, it doesn't matter
478 pass # Windows doesn't set TERM, it doesn't matter
479
479
480
480
481 class InputList(UserList.UserList):
481 class InputList(UserList.UserList):
482 """Class to store user input.
482 """Class to store user input.
483
483
484 It's basically a list, but slices return a string instead of a list, thus
484 It's basically a list, but slices return a string instead of a list, thus
485 allowing things like (assuming 'In' is an instance):
485 allowing things like (assuming 'In' is an instance):
486
486
487 exec In[4:7]
487 exec In[4:7]
488
488
489 or
489 or
490
490
491 exec In[5:9] + In[14] + In[21:25]"""
491 exec In[5:9] + In[14] + In[21:25]"""
492
492
493 def __getslice__(self,i,j):
493 def __getslice__(self,i,j):
494 return ''.join(UserList.UserList.__getslice__(self,i,j))
494 return ''.join(UserList.UserList.__getslice__(self,i,j))
495
495
496 #****************************************************************************
496 #****************************************************************************
497 # Local use exceptions
497 # Local use exceptions
498 class SpaceInInput(exceptions.Exception):
498 class SpaceInInput(exceptions.Exception):
499 pass
499 pass
500
500
501 #****************************************************************************
501 #****************************************************************************
502 # Main IPython class
502 # Main IPython class
503
503
504 class InteractiveShell(code.InteractiveConsole, Logger, Magic):
504 class InteractiveShell(code.InteractiveConsole, Logger, Magic):
505 """An enhanced console for Python."""
505 """An enhanced console for Python."""
506
506
507 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
507 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
508 user_ns = None,banner2='',
508 user_ns = None,banner2='',
509 custom_exceptions=((),None)):
509 custom_exceptions=((),None)):
510
510
511 # Put a reference to self in builtins so that any form of embedded or
511 # Put a reference to self in builtins so that any form of embedded or
512 # imported code can test for being inside IPython.
512 # imported code can test for being inside IPython.
513 __builtin__.__IPYTHON__ = self
513 __builtin__.__IPYTHON__ = self
514
514
515 # And load into builtins ipmagic/ipalias as well
515 # And load into builtins ipmagic/ipalias as well
516 __builtin__.ipmagic = ipmagic
516 __builtin__.ipmagic = ipmagic
517 __builtin__.ipalias = ipalias
517 __builtin__.ipalias = ipalias
518
518
519 # Add to __builtin__ other parts of IPython's public API
519 # Add to __builtin__ other parts of IPython's public API
520 __builtin__.ip_set_hook = self.set_hook
520 __builtin__.ip_set_hook = self.set_hook
521
521
522 # Keep in the builtins a flag for when IPython is active. We set it
522 # Keep in the builtins a flag for when IPython is active. We set it
523 # with setdefault so that multiple nested IPythons don't clobber one
523 # with setdefault so that multiple nested IPythons don't clobber one
524 # another. Each will increase its value by one upon being activated,
524 # another. Each will increase its value by one upon being activated,
525 # which also gives us a way to determine the nesting level.
525 # which also gives us a way to determine the nesting level.
526 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
526 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
527
527
528 # Inform the user of ipython's fast exit magics.
528 # Inform the user of ipython's fast exit magics.
529 _exit = ' Use %Exit or %Quit to exit without confirmation.'
529 _exit = ' Use %Exit or %Quit to exit without confirmation.'
530 __builtin__.exit += _exit
530 __builtin__.exit += _exit
531 __builtin__.quit += _exit
531 __builtin__.quit += _exit
532
532
533 # Create the namespace where the user will operate:
533 # Create the namespace where the user will operate:
534
534
535 # FIXME. For some strange reason, __builtins__ is showing up at user
535 # FIXME. For some strange reason, __builtins__ is showing up at user
536 # level as a dict instead of a module. This is a manual fix, but I
536 # level as a dict instead of a module. This is a manual fix, but I
537 # should really track down where the problem is coming from. Alex
537 # should really track down where the problem is coming from. Alex
538 # Schmolck reported this problem first.
538 # Schmolck reported this problem first.
539
539
540 # A useful post by Alex Martelli on this topic:
540 # A useful post by Alex Martelli on this topic:
541 # Re: inconsistent value from __builtins__
541 # Re: inconsistent value from __builtins__
542 # Von: Alex Martelli <aleaxit@yahoo.com>
542 # Von: Alex Martelli <aleaxit@yahoo.com>
543 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
543 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
544 # Gruppen: comp.lang.python
544 # Gruppen: comp.lang.python
545 # Referenzen: 1
545 # Referenzen: 1
546
546
547 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
547 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
548 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
548 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
549 # > <type 'dict'>
549 # > <type 'dict'>
550 # > >>> print type(__builtins__)
550 # > >>> print type(__builtins__)
551 # > <type 'module'>
551 # > <type 'module'>
552 # > Is this difference in return value intentional?
552 # > Is this difference in return value intentional?
553
553
554 # Well, it's documented that '__builtins__' can be either a dictionary
554 # Well, it's documented that '__builtins__' can be either a dictionary
555 # or a module, and it's been that way for a long time. Whether it's
555 # or a module, and it's been that way for a long time. Whether it's
556 # intentional (or sensible), I don't know. In any case, the idea is that
556 # intentional (or sensible), I don't know. In any case, the idea is that
557 # if you need to access the built-in namespace directly, you should start
557 # if you need to access the built-in namespace directly, you should start
558 # with "import __builtin__" (note, no 's') which will definitely give you
558 # with "import __builtin__" (note, no 's') which will definitely give you
559 # a module. Yeah, it's somewhat confusing:-(.
559 # a module. Yeah, it's somewhat confusing:-(.
560
560
561 if user_ns is None:
561 if user_ns is None:
562 # Set __name__ to __main__ to better match the behavior of the
562 # Set __name__ to __main__ to better match the behavior of the
563 # normal interpreter.
563 # normal interpreter.
564 self.user_ns = {'__name__' :'__main__',
564 self.user_ns = {'__name__' :'__main__',
565 '__builtins__' : __builtin__,
565 '__builtins__' : __builtin__,
566 }
566 }
567 else:
567 else:
568 self.user_ns = user_ns
568 self.user_ns = user_ns
569
569
570 # The user namespace MUST have a pointer to the shell itself.
570 # The user namespace MUST have a pointer to the shell itself.
571 self.user_ns[name] = self
571 self.user_ns[name] = self
572
572
573 # We need to insert into sys.modules something that looks like a
573 # We need to insert into sys.modules something that looks like a
574 # module but which accesses the IPython namespace, for shelve and
574 # module but which accesses the IPython namespace, for shelve and
575 # pickle to work interactively. Normally they rely on getting
575 # pickle to work interactively. Normally they rely on getting
576 # everything out of __main__, but for embedding purposes each IPython
576 # everything out of __main__, but for embedding purposes each IPython
577 # instance has its own private namespace, so we can't go shoving
577 # instance has its own private namespace, so we can't go shoving
578 # everything into __main__.
578 # everything into __main__.
579
579
580 try:
580 try:
581 main_name = self.user_ns['__name__']
581 main_name = self.user_ns['__name__']
582 except KeyError:
582 except KeyError:
583 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
583 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
584 else:
584 else:
585 #print "pickle hack in place" # dbg
585 #print "pickle hack in place" # dbg
586 sys.modules[main_name] = FakeModule(self.user_ns)
586 sys.modules[main_name] = FakeModule(self.user_ns)
587
587
588 # List of input with multi-line handling.
588 # List of input with multi-line handling.
589 # Fill its zero entry, user counter starts at 1
589 # Fill its zero entry, user counter starts at 1
590 self.input_hist = InputList(['\n'])
590 self.input_hist = InputList(['\n'])
591
591
592 # list of visited directories
592 # list of visited directories
593 self.dir_hist = [os.getcwd()]
593 try:
594 self.dir_hist = [os.getcwd()]
595 except IOError, e:
596 self.dir_hist = []
594
597
595 # dict of output history
598 # dict of output history
596 self.output_hist = {}
599 self.output_hist = {}
597
600
598 # 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
599 # 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
600 # number of positional arguments of the alias.
603 # number of positional arguments of the alias.
601 self.alias_table = {}
604 self.alias_table = {}
602
605
603 # dict of things NOT to alias (keywords and builtins)
606 # dict of things NOT to alias (keywords, builtins and some special magics)
604 self.no_alias = {}
607 no_alias = {}
605 for key in keyword.kwlist:
608 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
606 self.no_alias[key] = 1
609 for key in keyword.kwlist + no_alias_magics:
607 self.no_alias.update(__builtin__.__dict__)
610 no_alias[key] = 1
611 no_alias.update(__builtin__.__dict__)
612 self.no_alias = no_alias
613
608
614
609 # make global variables for user access to these
615 # make global variables for user access to these
610 self.user_ns['_ih'] = self.input_hist
616 self.user_ns['_ih'] = self.input_hist
611 self.user_ns['_oh'] = self.output_hist
617 self.user_ns['_oh'] = self.output_hist
612 self.user_ns['_dh'] = self.dir_hist
618 self.user_ns['_dh'] = self.dir_hist
613
619
614 # user aliases to input and output histories
620 # user aliases to input and output histories
615 self.user_ns['In'] = self.input_hist
621 self.user_ns['In'] = self.input_hist
616 self.user_ns['Out'] = self.output_hist
622 self.user_ns['Out'] = self.output_hist
617
623
618 # Store the actual shell's name
624 # Store the actual shell's name
619 self.name = name
625 self.name = name
620
626
621 # Object variable to store code object waiting execution. This is
627 # Object variable to store code object waiting execution. This is
622 # 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
623 # 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
624 # item which gets cleared once run.
630 # item which gets cleared once run.
625 self.code_to_run = None
631 self.code_to_run = None
626
632
627 # Job manager (for jobs run as background threads)
633 # Job manager (for jobs run as background threads)
628 self.jobs = BackgroundJobManager()
634 self.jobs = BackgroundJobManager()
629 # Put the job manager into builtins so it's always there.
635 # Put the job manager into builtins so it's always there.
630 __builtin__.jobs = self.jobs
636 __builtin__.jobs = self.jobs
631
637
632 # escapes for automatic behavior on the command line
638 # escapes for automatic behavior on the command line
633 self.ESC_SHELL = '!'
639 self.ESC_SHELL = '!'
634 self.ESC_HELP = '?'
640 self.ESC_HELP = '?'
635 self.ESC_MAGIC = '%'
641 self.ESC_MAGIC = '%'
636 self.ESC_QUOTE = ','
642 self.ESC_QUOTE = ','
637 self.ESC_QUOTE2 = ';'
643 self.ESC_QUOTE2 = ';'
638 self.ESC_PAREN = '/'
644 self.ESC_PAREN = '/'
639
645
640 # And their associated handlers
646 # And their associated handlers
641 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
647 self.esc_handlers = {self.ESC_PAREN:self.handle_auto,
642 self.ESC_QUOTE:self.handle_auto,
648 self.ESC_QUOTE:self.handle_auto,
643 self.ESC_QUOTE2:self.handle_auto,
649 self.ESC_QUOTE2:self.handle_auto,
644 self.ESC_MAGIC:self.handle_magic,
650 self.ESC_MAGIC:self.handle_magic,
645 self.ESC_HELP:self.handle_help,
651 self.ESC_HELP:self.handle_help,
646 self.ESC_SHELL:self.handle_shell_escape,
652 self.ESC_SHELL:self.handle_shell_escape,
647 }
653 }
648
654
649 # class initializations
655 # class initializations
650 code.InteractiveConsole.__init__(self,locals = self.user_ns)
656 code.InteractiveConsole.__init__(self,locals = self.user_ns)
651 Logger.__init__(self,log_ns = self.user_ns)
657 Logger.__init__(self,log_ns = self.user_ns)
652 Magic.__init__(self,self)
658 Magic.__init__(self,self)
653
659
654 # 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
655 # magic code via this pointer instead of the current mixin salad.
661 # magic code via this pointer instead of the current mixin salad.
656 Magic.set_shell(self,self)
662 Magic.set_shell(self,self)
657
663
658 # hooks holds pointers used for user-side customizations
664 # hooks holds pointers used for user-side customizations
659 self.hooks = Struct()
665 self.hooks = Struct()
660
666
661 # Set all default hooks, defined in the IPython.hooks module.
667 # Set all default hooks, defined in the IPython.hooks module.
662 hooks = IPython.hooks
668 hooks = IPython.hooks
663 for hook_name in hooks.__all__:
669 for hook_name in hooks.__all__:
664 self.set_hook(hook_name,getattr(hooks,hook_name))
670 self.set_hook(hook_name,getattr(hooks,hook_name))
665
671
666 # Flag to mark unconditional exit
672 # Flag to mark unconditional exit
667 self.exit_now = False
673 self.exit_now = False
668
674
669 self.usage_min = """\
675 self.usage_min = """\
670 An enhanced console for Python.
676 An enhanced console for Python.
671 Some of its features are:
677 Some of its features are:
672 - Readline support if the readline library is present.
678 - Readline support if the readline library is present.
673 - Tab completion in the local namespace.
679 - Tab completion in the local namespace.
674 - Logging of input, see command-line options.
680 - Logging of input, see command-line options.
675 - System shell escape via ! , eg !ls.
681 - System shell escape via ! , eg !ls.
676 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
682 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
677 - Keeps track of locally defined variables via %who, %whos.
683 - Keeps track of locally defined variables via %who, %whos.
678 - 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).
679 """
685 """
680 if usage: self.usage = usage
686 if usage: self.usage = usage
681 else: self.usage = self.usage_min
687 else: self.usage = self.usage_min
682
688
683 # Storage
689 # Storage
684 self.rc = rc # This will hold all configuration information
690 self.rc = rc # This will hold all configuration information
685 self.inputcache = []
691 self.inputcache = []
686 self._boundcache = []
692 self._boundcache = []
687 self.pager = 'less'
693 self.pager = 'less'
688 # temporary files used for various purposes. Deleted at exit.
694 # temporary files used for various purposes. Deleted at exit.
689 self.tempfiles = []
695 self.tempfiles = []
690
696
691 # Keep track of readline usage (later set by init_readline)
697 # Keep track of readline usage (later set by init_readline)
692 self.has_readline = 0
698 self.has_readline = 0
693
699
694 # for pushd/popd management
700 # for pushd/popd management
695 try:
701 try:
696 self.home_dir = get_home_dir()
702 self.home_dir = get_home_dir()
697 except HomeDirError,msg:
703 except HomeDirError,msg:
698 fatal(msg)
704 fatal(msg)
699
705
700 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
706 self.dir_stack = [os.getcwd().replace(self.home_dir,'~')]
701
707
702 # Functions to call the underlying shell.
708 # Functions to call the underlying shell.
703
709
704 # utility to expand user variables via Itpl
710 # utility to expand user variables via Itpl
705 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
711 self.var_expand = lambda cmd: str(ItplNS(cmd.replace('#','\#'),
706 self.user_ns))
712 self.user_ns))
707 # 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,
708 # and it allows interpolation of variables in the user's namespace.
714 # and it allows interpolation of variables in the user's namespace.
709 self.system = lambda cmd: shell(self.var_expand(cmd),
715 self.system = lambda cmd: shell(self.var_expand(cmd),
710 header='IPython system call: ',
716 header='IPython system call: ',
711 verbose=self.rc.system_verbose)
717 verbose=self.rc.system_verbose)
712 # These are for getoutput and getoutputerror:
718 # These are for getoutput and getoutputerror:
713 self.getoutput = lambda cmd: \
719 self.getoutput = lambda cmd: \
714 getoutput(self.var_expand(cmd),
720 getoutput(self.var_expand(cmd),
715 header='IPython system call: ',
721 header='IPython system call: ',
716 verbose=self.rc.system_verbose)
722 verbose=self.rc.system_verbose)
717 self.getoutputerror = lambda cmd: \
723 self.getoutputerror = lambda cmd: \
718 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
724 getoutputerror(str(ItplNS(cmd.replace('#','\#'),
719 self.user_ns)),
725 self.user_ns)),
720 header='IPython system call: ',
726 header='IPython system call: ',
721 verbose=self.rc.system_verbose)
727 verbose=self.rc.system_verbose)
722
728
723 # RegExp for splitting line contents into pre-char//first
729 # RegExp for splitting line contents into pre-char//first
724 # word-method//rest. For clarity, each group in on one line.
730 # word-method//rest. For clarity, each group in on one line.
725
731
726 # 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
727 # are hardwired in.
733 # are hardwired in.
728
734
729 # 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
730 # 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
731 # evals() somewhere and end up causing side effects.
737 # evals() somewhere and end up causing side effects.
732
738
733 self.line_split = re.compile(r'^([\s*,;/])'
739 self.line_split = re.compile(r'^([\s*,;/])'
734 r'([\?\w\.]+\w*\s*)'
740 r'([\?\w\.]+\w*\s*)'
735 r'(\(?.*$)')
741 r'(\(?.*$)')
736
742
737 # 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
738 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
744 #self.line_split = re.compile(r'(^[\s*!\?%,/]?)'
739 # r'(\s*[\?\w\.]+\w*\s*)'
745 # r'(\s*[\?\w\.]+\w*\s*)'
740 # r'(\(?.*$)')
746 # r'(\(?.*$)')
741
747
742 # RegExp to identify potential function names
748 # RegExp to identify potential function names
743 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_.]*) *$')
744 # RegExp to exclude strings with this start from autocalling
750 # RegExp to exclude strings with this start from autocalling
745 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
751 self.re_exclude_auto = re.compile('^[!=()<>,\*/\+-]|^is ')
746 # 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
747 # (experimental). For this to work, the line_split regexp would need
753 # (experimental). For this to work, the line_split regexp would need
748 # 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
749 # 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_.
750 #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_.\[\]]*) ?$')
751
757
752 # 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)
753 self.starting_dir = os.getcwd()
759 self.starting_dir = os.getcwd()
754
760
755 # Attributes for Logger mixin class, make defaults here
761 # Attributes for Logger mixin class, make defaults here
756 self._dolog = 0
762 self._dolog = 0
757 self.LOG = ''
763 self.LOG = ''
758 self.LOGDEF = '.InteractiveShell.log'
764 self.LOGDEF = '.InteractiveShell.log'
759 self.LOGMODE = 'over'
765 self.LOGMODE = 'over'
760 self.LOGHEAD = Itpl(
766 self.LOGHEAD = Itpl(
761 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
767 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
762 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
768 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
763 #log# opts = $self.rc.opts
769 #log# opts = $self.rc.opts
764 #log# args = $self.rc.args
770 #log# args = $self.rc.args
765 #log# It is safe to make manual edits below here.
771 #log# It is safe to make manual edits below here.
766 #log#-----------------------------------------------------------------------
772 #log#-----------------------------------------------------------------------
767 """)
773 """)
768 # Various switches which can be set
774 # Various switches which can be set
769 self.CACHELENGTH = 5000 # this is cheap, it's just text
775 self.CACHELENGTH = 5000 # this is cheap, it's just text
770 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
776 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
771 self.banner2 = banner2
777 self.banner2 = banner2
772
778
773 # TraceBack handlers:
779 # TraceBack handlers:
774 # Need two, one for syntax errors and one for other exceptions.
780 # Need two, one for syntax errors and one for other exceptions.
775 self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor')
781 self.SyntaxTB = ultraTB.ListTB(color_scheme='NoColor')
776 # 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
777 # 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
778 # code. Valid modes: ['Plain','Context','Verbose']
784 # code. Valid modes: ['Plain','Context','Verbose']
779 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
785 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
780 color_scheme='NoColor',
786 color_scheme='NoColor',
781 tb_offset = 1)
787 tb_offset = 1)
782 # and add any custom exception handlers the user may have specified
788 # and add any custom exception handlers the user may have specified
783 self.set_custom_exc(*custom_exceptions)
789 self.set_custom_exc(*custom_exceptions)
784
790
785 # Object inspector
791 # Object inspector
786 ins_colors = OInspect.InspectColors
792 ins_colors = OInspect.InspectColors
787 code_colors = PyColorize.ANSICodeColors
793 code_colors = PyColorize.ANSICodeColors
788 self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor')
794 self.inspector = OInspect.Inspector(ins_colors,code_colors,'NoColor')
789 self.autoindent = 0
795 self.autoindent = 0
790
796
791 # Make some aliases automatically
797 # Make some aliases automatically
792 # Prepare list of shell aliases to auto-define
798 # Prepare list of shell aliases to auto-define
793 if os.name == 'posix':
799 if os.name == 'posix':
794 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
800 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
795 'mv mv -i','rm rm -i','cp cp -i',
801 'mv mv -i','rm rm -i','cp cp -i',
796 'cat cat','less less','clear clear',
802 'cat cat','less less','clear clear',
797 # a better ls
803 # a better ls
798 'ls ls -F',
804 'ls ls -F',
799 # long ls
805 # long ls
800 'll ls -lF',
806 'll ls -lF',
801 # color ls
807 # color ls
802 'lc ls -F -o --color',
808 'lc ls -F -o --color',
803 # ls normal files only
809 # ls normal files only
804 'lf ls -F -o --color %l | grep ^-',
810 'lf ls -F -o --color %l | grep ^-',
805 # ls symbolic links
811 # ls symbolic links
806 'lk ls -F -o --color %l | grep ^l',
812 'lk ls -F -o --color %l | grep ^l',
807 # directories or links to directories,
813 # directories or links to directories,
808 'ldir ls -F -o --color %l | grep /$',
814 'ldir ls -F -o --color %l | grep /$',
809 # things which are executable
815 # things which are executable
810 'lx ls -F -o --color %l | grep ^-..x',
816 'lx ls -F -o --color %l | grep ^-..x',
811 )
817 )
812 elif os.name in ['nt','dos']:
818 elif os.name in ['nt','dos']:
813 auto_alias = ('dir dir /on', 'ls dir /on',
819 auto_alias = ('dir dir /on', 'ls dir /on',
814 'ddir dir /ad /on', 'ldir dir /ad /on',
820 'ddir dir /ad /on', 'ldir dir /ad /on',
815 'mkdir mkdir','rmdir rmdir','echo echo',
821 'mkdir mkdir','rmdir rmdir','echo echo',
816 'ren ren','cls cls','copy copy')
822 'ren ren','cls cls','copy copy')
817 else:
823 else:
818 auto_alias = ()
824 auto_alias = ()
819 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)
820 # Call the actual (public) initializer
826 # Call the actual (public) initializer
821 self.init_auto_alias()
827 self.init_auto_alias()
822 # end __init__
828 # end __init__
823
829
824 def set_hook(self,name,hook):
830 def set_hook(self,name,hook):
825 """set_hook(name,hook) -> sets an internal IPython hook.
831 """set_hook(name,hook) -> sets an internal IPython hook.
826
832
827 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
828 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
829 call at runtime your own routines."""
835 call at runtime your own routines."""
830
836
831 # 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
832 # 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
833 # of args it's supposed to.
839 # of args it's supposed to.
834 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
840 setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
835
841
836 def set_custom_exc(self,exc_tuple,handler):
842 def set_custom_exc(self,exc_tuple,handler):
837 """set_custom_exc(exc_tuple,handler)
843 """set_custom_exc(exc_tuple,handler)
838
844
839 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
840 exceptions in exc_tuple occur in the mainloop (specifically, in the
846 exceptions in exc_tuple occur in the mainloop (specifically, in the
841 runcode() method.
847 runcode() method.
842
848
843 Inputs:
849 Inputs:
844
850
845 - exc_tuple: a *tuple* of valid exceptions to call the defined
851 - exc_tuple: a *tuple* of valid exceptions to call the defined
846 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
847 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
848 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:
849
855
850 exc_tuple == (MyCustomException,)
856 exc_tuple == (MyCustomException,)
851
857
852 - handler: this must be defined as a function with the following
858 - handler: this must be defined as a function with the following
853 basic interface: def my_handler(self,etype,value,tb).
859 basic interface: def my_handler(self,etype,value,tb).
854
860
855 This will be made into an instance method (via new.instancemethod)
861 This will be made into an instance method (via new.instancemethod)
856 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
857 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
858 internal basic one is used, which just prints basic info.
864 internal basic one is used, which just prints basic info.
859
865
860 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
861 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
862 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."""
863
869
864 assert type(exc_tuple)==type(()) , \
870 assert type(exc_tuple)==type(()) , \
865 "The custom exceptions must be given AS A TUPLE."
871 "The custom exceptions must be given AS A TUPLE."
866
872
867 def dummy_handler(self,etype,value,tb):
873 def dummy_handler(self,etype,value,tb):
868 print '*** Simple custom exception handler ***'
874 print '*** Simple custom exception handler ***'
869 print 'Exception type :',etype
875 print 'Exception type :',etype
870 print 'Exception value:',value
876 print 'Exception value:',value
871 print 'Traceback :',tb
877 print 'Traceback :',tb
872 print 'Source code :','\n'.join(self.buffer)
878 print 'Source code :','\n'.join(self.buffer)
873
879
874 if handler is None: handler = dummy_handler
880 if handler is None: handler = dummy_handler
875
881
876 self.CustomTB = new.instancemethod(handler,self,self.__class__)
882 self.CustomTB = new.instancemethod(handler,self,self.__class__)
877 self.custom_exceptions = exc_tuple
883 self.custom_exceptions = exc_tuple
878
884
879 def set_custom_completer(self,completer,pos=0):
885 def set_custom_completer(self,completer,pos=0):
880 """set_custom_completer(completer,pos=0)
886 """set_custom_completer(completer,pos=0)
881
887
882 Adds a new custom completer function.
888 Adds a new custom completer function.
883
889
884 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
885 list where you want the completer to be inserted."""
891 list where you want the completer to be inserted."""
886
892
887 newcomp = new.instancemethod(completer,self.Completer,
893 newcomp = new.instancemethod(completer,self.Completer,
888 self.Completer.__class__)
894 self.Completer.__class__)
889 self.Completer.matchers.insert(pos,newcomp)
895 self.Completer.matchers.insert(pos,newcomp)
890
896
891 def complete(self,text):
897 def complete(self,text):
892 """Return a sorted list of all possible completions on text.
898 """Return a sorted list of all possible completions on text.
893
899
894 Inputs:
900 Inputs:
895
901
896 - text: a string of text to be completed on.
902 - text: a string of text to be completed on.
897
903
898 This is a wrapper around the completion mechanism, similar to what
904 This is a wrapper around the completion mechanism, similar to what
899 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
900 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
901 environments (such as GUIs) for text completion.
907 environments (such as GUIs) for text completion.
902
908
903 Simple usage example:
909 Simple usage example:
904
910
905 In [1]: x = 'hello'
911 In [1]: x = 'hello'
906
912
907 In [2]: __IP.complete('x.l')
913 In [2]: __IP.complete('x.l')
908 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
914 Out[2]: ['x.ljust', 'x.lower', 'x.lstrip']"""
909
915
910 complete = self.Completer.complete
916 complete = self.Completer.complete
911 state = 0
917 state = 0
912 # 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
913 # completers can return duplicates.
919 # completers can return duplicates.
914 comps = {}
920 comps = {}
915 while True:
921 while True:
916 newcomp = complete(text,state)
922 newcomp = complete(text,state)
917 if newcomp is None:
923 if newcomp is None:
918 break
924 break
919 comps[newcomp] = 1
925 comps[newcomp] = 1
920 state += 1
926 state += 1
921 outcomps = comps.keys()
927 outcomps = comps.keys()
922 outcomps.sort()
928 outcomps.sort()
923 return outcomps
929 return outcomps
924
930
925 def post_config_initialization(self):
931 def post_config_initialization(self):
926 """Post configuration init method
932 """Post configuration init method
927
933
928 This is called after the configuration files have been processed to
934 This is called after the configuration files have been processed to
929 'finalize' the initialization."""
935 'finalize' the initialization."""
930
936
931 # dynamic data that survives through sessions
937 # dynamic data that survives through sessions
932 # XXX make the filename a config option?
938 # XXX make the filename a config option?
933 persist_base = 'persist'
939 persist_base = 'persist'
934 if self.rc.profile:
940 if self.rc.profile:
935 persist_base += '_%s' % self.rc.profile
941 persist_base += '_%s' % self.rc.profile
936 self.persist_fname = os.path.join(self.rc.ipythondir,persist_base)
942 self.persist_fname = os.path.join(self.rc.ipythondir,persist_base)
937
943
938 try:
944 try:
939 self.persist = pickle.load(file(self.persist_fname))
945 self.persist = pickle.load(file(self.persist_fname))
940 except:
946 except:
941 self.persist = {}
947 self.persist = {}
942
948
943 def init_auto_alias(self):
949 def init_auto_alias(self):
944 """Define some aliases automatically.
950 """Define some aliases automatically.
945
951
946 These are ALL parameter-less aliases"""
952 These are ALL parameter-less aliases"""
947 for alias,cmd in self.auto_alias:
953 for alias,cmd in self.auto_alias:
948 self.alias_table[alias] = (0,cmd)
954 self.alias_table[alias] = (0,cmd)
949
955
950 def alias_table_validate(self,verbose=0):
956 def alias_table_validate(self,verbose=0):
951 """Update information about the alias table.
957 """Update information about the alias table.
952
958
953 In particular, make sure no Python keywords/builtins are in it."""
959 In particular, make sure no Python keywords/builtins are in it."""
954
960
955 no_alias = self.no_alias
961 no_alias = self.no_alias
956 for k in self.alias_table.keys():
962 for k in self.alias_table:
957 if k in no_alias:
963 if k in no_alias:
958 del self.alias_table[k]
964 del self.alias_table[k]
959 if verbose:
965 if verbose:
960 print ("Deleting alias <%s>, it's a Python "
966 print ("Deleting alias <%s>, it's a Python "
961 "keyword or builtin." % k)
967 "keyword or builtin." % k)
962
968
963 def set_autoindent(self,value=None):
969 def set_autoindent(self,value=None):
964 """Set the autoindent flag, checking for readline support.
970 """Set the autoindent flag, checking for readline support.
965
971
966 If called with no arguments, it acts as a toggle."""
972 If called with no arguments, it acts as a toggle."""
967
973
968 if not self.has_readline:
974 if not self.has_readline:
969 if os.name == 'posix':
975 if os.name == 'posix':
970 warn("The auto-indent feature requires the readline library")
976 warn("The auto-indent feature requires the readline library")
971 self.autoindent = 0
977 self.autoindent = 0
972 return
978 return
973 if value is None:
979 if value is None:
974 self.autoindent = not self.autoindent
980 self.autoindent = not self.autoindent
975 else:
981 else:
976 self.autoindent = value
982 self.autoindent = value
977
983
978 def rc_set_toggle(self,rc_field,value=None):
984 def rc_set_toggle(self,rc_field,value=None):
979 """Set or toggle a field in IPython's rc config. structure.
985 """Set or toggle a field in IPython's rc config. structure.
980
986
981 If called with no arguments, it acts as a toggle.
987 If called with no arguments, it acts as a toggle.
982
988
983 If called with a non-existent field, the resulting AttributeError
989 If called with a non-existent field, the resulting AttributeError
984 exception will propagate out."""
990 exception will propagate out."""
985
991
986 rc_val = getattr(self.rc,rc_field)
992 rc_val = getattr(self.rc,rc_field)
987 if value is None:
993 if value is None:
988 value = not rc_val
994 value = not rc_val
989 setattr(self.rc,rc_field,value)
995 setattr(self.rc,rc_field,value)
990
996
991 def user_setup(self,ipythondir,rc_suffix,mode='install'):
997 def user_setup(self,ipythondir,rc_suffix,mode='install'):
992 """Install the user configuration directory.
998 """Install the user configuration directory.
993
999
994 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
995 .ipython/ directory with the mode parameter. Valid modes are 'install'
1001 .ipython/ directory with the mode parameter. Valid modes are 'install'
996 and 'upgrade'."""
1002 and 'upgrade'."""
997
1003
998 def wait():
1004 def wait():
999 try:
1005 try:
1000 raw_input("Please press <RETURN> to start IPython.")
1006 raw_input("Please press <RETURN> to start IPython.")
1001 except EOFError:
1007 except EOFError:
1002 print >> Term.cout
1008 print >> Term.cout
1003 print '*'*70
1009 print '*'*70
1004
1010
1005 cwd = os.getcwd() # remember where we started
1011 cwd = os.getcwd() # remember where we started
1006 glb = glob.glob
1012 glb = glob.glob
1007 print '*'*70
1013 print '*'*70
1008 if mode == 'install':
1014 if mode == 'install':
1009 print \
1015 print \
1010 """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
1011 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"""
1012 else:
1018 else:
1013 print 'I am going to upgrade your configuration in:'
1019 print 'I am going to upgrade your configuration in:'
1014
1020
1015 print ipythondir
1021 print ipythondir
1016
1022
1017 rcdirend = os.path.join('IPython','UserConfig')
1023 rcdirend = os.path.join('IPython','UserConfig')
1018 cfg = lambda d: os.path.join(d,rcdirend)
1024 cfg = lambda d: os.path.join(d,rcdirend)
1019 try:
1025 try:
1020 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1026 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1021 except IOError:
1027 except IOError:
1022 warning = """
1028 warning = """
1023 Installation error. IPython's directory was not found.
1029 Installation error. IPython's directory was not found.
1024
1030
1025 Check the following:
1031 Check the following:
1026
1032
1027 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
1028 PYTHONPATH environment variable (that is, it should be in a directory
1034 PYTHONPATH environment variable (that is, it should be in a directory
1029 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.
1030
1036
1031 IPython will proceed with builtin defaults.
1037 IPython will proceed with builtin defaults.
1032 """
1038 """
1033 warn(warning)
1039 warn(warning)
1034 wait()
1040 wait()
1035 return
1041 return
1036
1042
1037 if mode == 'install':
1043 if mode == 'install':
1038 try:
1044 try:
1039 shutil.copytree(rcdir,ipythondir)
1045 shutil.copytree(rcdir,ipythondir)
1040 os.chdir(ipythondir)
1046 os.chdir(ipythondir)
1041 rc_files = glb("ipythonrc*")
1047 rc_files = glb("ipythonrc*")
1042 for rc_file in rc_files:
1048 for rc_file in rc_files:
1043 os.rename(rc_file,rc_file+rc_suffix)
1049 os.rename(rc_file,rc_file+rc_suffix)
1044 except:
1050 except:
1045 warning = """
1051 warning = """
1046
1052
1047 There was a problem with the installation:
1053 There was a problem with the installation:
1048 %s
1054 %s
1049 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.
1050 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1056 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1051 warn(warning)
1057 warn(warning)
1052 wait()
1058 wait()
1053 return
1059 return
1054
1060
1055 elif mode == 'upgrade':
1061 elif mode == 'upgrade':
1056 try:
1062 try:
1057 os.chdir(ipythondir)
1063 os.chdir(ipythondir)
1058 except:
1064 except:
1059 print """
1065 print """
1060 Can not upgrade: changing to directory %s failed. Details:
1066 Can not upgrade: changing to directory %s failed. Details:
1061 %s
1067 %s
1062 """ % (ipythondir,sys.exc_info()[1])
1068 """ % (ipythondir,sys.exc_info()[1])
1063 wait()
1069 wait()
1064 return
1070 return
1065 else:
1071 else:
1066 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1072 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1067 for new_full_path in sources:
1073 for new_full_path in sources:
1068 new_filename = os.path.basename(new_full_path)
1074 new_filename = os.path.basename(new_full_path)
1069 if new_filename.startswith('ipythonrc'):
1075 if new_filename.startswith('ipythonrc'):
1070 new_filename = new_filename + rc_suffix
1076 new_filename = new_filename + rc_suffix
1071 # The config directory should only contain files, skip any
1077 # The config directory should only contain files, skip any
1072 # directories which may be there (like CVS)
1078 # directories which may be there (like CVS)
1073 if os.path.isdir(new_full_path):
1079 if os.path.isdir(new_full_path):
1074 continue
1080 continue
1075 if os.path.exists(new_filename):
1081 if os.path.exists(new_filename):
1076 old_file = new_filename+'.old'
1082 old_file = new_filename+'.old'
1077 if os.path.exists(old_file):
1083 if os.path.exists(old_file):
1078 os.remove(old_file)
1084 os.remove(old_file)
1079 os.rename(new_filename,old_file)
1085 os.rename(new_filename,old_file)
1080 shutil.copy(new_full_path,new_filename)
1086 shutil.copy(new_full_path,new_filename)
1081 else:
1087 else:
1082 raise ValueError,'unrecognized mode for install:',`mode`
1088 raise ValueError,'unrecognized mode for install:',`mode`
1083
1089
1084 # 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
1085 # directory.
1091 # directory.
1086 try:
1092 try:
1087 os.chdir(ipythondir)
1093 os.chdir(ipythondir)
1088 except:
1094 except:
1089 print """
1095 print """
1090 Problem: changing to directory %s failed.
1096 Problem: changing to directory %s failed.
1091 Details:
1097 Details:
1092 %s
1098 %s
1093
1099
1094 Some configuration files may have incorrect line endings. This should not
1100 Some configuration files may have incorrect line endings. This should not
1095 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1101 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1096 wait()
1102 wait()
1097 else:
1103 else:
1098 for fname in glb('ipythonrc*'):
1104 for fname in glb('ipythonrc*'):
1099 try:
1105 try:
1100 native_line_ends(fname,backup=0)
1106 native_line_ends(fname,backup=0)
1101 except IOError:
1107 except IOError:
1102 pass
1108 pass
1103
1109
1104 if mode == 'install':
1110 if mode == 'install':
1105 print """
1111 print """
1106 Successful installation!
1112 Successful installation!
1107
1113
1108 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1114 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1109 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
1110 distribution) to make sure that your system environment is properly configured
1116 distribution) to make sure that your system environment is properly configured
1111 to take advantage of IPython's features."""
1117 to take advantage of IPython's features."""
1112 else:
1118 else:
1113 print """
1119 print """
1114 Successful upgrade!
1120 Successful upgrade!
1115
1121
1116 All files in your directory:
1122 All files in your directory:
1117 %(ipythondir)s
1123 %(ipythondir)s
1118 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
1119 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
1120 want to merge them back into the new files.""" % locals()
1126 want to merge them back into the new files.""" % locals()
1121 wait()
1127 wait()
1122 os.chdir(cwd)
1128 os.chdir(cwd)
1123 # end user_setup()
1129 # end user_setup()
1124
1130
1125 def atexit_operations(self):
1131 def atexit_operations(self):
1126 """This will be executed at the time of exit.
1132 """This will be executed at the time of exit.
1127
1133
1128 Saving of persistent data should be performed here. """
1134 Saving of persistent data should be performed here. """
1129
1135
1130 # input history
1136 # input history
1131 self.savehist()
1137 self.savehist()
1132
1138
1133 # Cleanup all tempfiles left around
1139 # Cleanup all tempfiles left around
1134 for tfile in self.tempfiles:
1140 for tfile in self.tempfiles:
1135 try:
1141 try:
1136 os.unlink(tfile)
1142 os.unlink(tfile)
1137 except OSError:
1143 except OSError:
1138 pass
1144 pass
1139
1145
1140 # save the "persistent data" catch-all dictionary
1146 # save the "persistent data" catch-all dictionary
1141 try:
1147 try:
1142 pickle.dump(self.persist, open(self.persist_fname,"w"))
1148 pickle.dump(self.persist, open(self.persist_fname,"w"))
1143 except:
1149 except:
1144 print "*** ERROR *** persistent data saving failed."
1150 print "*** ERROR *** persistent data saving failed."
1145
1151
1146 def savehist(self):
1152 def savehist(self):
1147 """Save input history to a file (via readline library)."""
1153 """Save input history to a file (via readline library)."""
1148 try:
1154 try:
1149 self.readline.write_history_file(self.histfile)
1155 self.readline.write_history_file(self.histfile)
1150 except:
1156 except:
1151 print 'Unable to save IPython command history to file: ' + \
1157 print 'Unable to save IPython command history to file: ' + \
1152 `self.histfile`
1158 `self.histfile`
1153
1159
1154 def pre_readline(self):
1160 def pre_readline(self):
1155 """readline hook to be used at the start of each line.
1161 """readline hook to be used at the start of each line.
1156
1162
1157 Currently it handles auto-indent only."""
1163 Currently it handles auto-indent only."""
1158
1164
1159 self.readline.insert_text(' '* self.readline_indent)
1165 self.readline.insert_text(' '* self.readline_indent)
1160
1166
1161 def init_readline(self):
1167 def init_readline(self):
1162 """Command history completion/saving/reloading."""
1168 """Command history completion/saving/reloading."""
1163 try:
1169 try:
1164 import readline
1170 import readline
1165 self.Completer = MagicCompleter(self,
1171 self.Completer = MagicCompleter(self,
1166 self.user_ns,
1172 self.user_ns,
1167 self.rc.readline_omit__names,
1173 self.rc.readline_omit__names,
1168 self.alias_table)
1174 self.alias_table)
1169 except ImportError,NameError:
1175 except ImportError,NameError:
1170 # If FlexCompleter failed to import, MagicCompleter won't be
1176 # If FlexCompleter failed to import, MagicCompleter won't be
1171 # defined. This can happen because of a problem with readline
1177 # defined. This can happen because of a problem with readline
1172 self.has_readline = 0
1178 self.has_readline = 0
1173 # no point in bugging windows users with this every time:
1179 # no point in bugging windows users with this every time:
1174 if os.name == 'posix':
1180 if os.name == 'posix':
1175 warn('Readline services not available on this platform.')
1181 warn('Readline services not available on this platform.')
1176 else:
1182 else:
1177 import atexit
1183 import atexit
1178
1184
1179 # Platform-specific configuration
1185 # Platform-specific configuration
1180 if os.name == 'nt':
1186 if os.name == 'nt':
1181 # readline under Windows modifies the default exit behavior
1187 # readline under Windows modifies the default exit behavior
1182 # from being Ctrl-Z/Return to the Unix Ctrl-D one.
1188 # from being Ctrl-Z/Return to the Unix Ctrl-D one.
1183 __builtin__.exit = __builtin__.quit = \
1189 __builtin__.exit = __builtin__.quit = \
1184 ('Use Ctrl-D (i.e. EOF) to exit. '
1190 ('Use Ctrl-D (i.e. EOF) to exit. '
1185 'Use %Exit or %Quit to exit without confirmation.')
1191 'Use %Exit or %Quit to exit without confirmation.')
1186 self.readline_startup_hook = readline.set_pre_input_hook
1192 self.readline_startup_hook = readline.set_pre_input_hook
1187 else:
1193 else:
1188 self.readline_startup_hook = readline.set_startup_hook
1194 self.readline_startup_hook = readline.set_startup_hook
1189
1195
1190 # Load user's initrc file (readline config)
1196 # Load user's initrc file (readline config)
1191 inputrc_name = os.environ.get('INPUTRC')
1197 inputrc_name = os.environ.get('INPUTRC')
1192 if inputrc_name is None:
1198 if inputrc_name is None:
1193 home_dir = get_home_dir()
1199 home_dir = get_home_dir()
1194 if home_dir is not None:
1200 if home_dir is not None:
1195 inputrc_name = os.path.join(home_dir,'.inputrc')
1201 inputrc_name = os.path.join(home_dir,'.inputrc')
1196 if os.path.isfile(inputrc_name):
1202 if os.path.isfile(inputrc_name):
1197 try:
1203 try:
1198 readline.read_init_file(inputrc_name)
1204 readline.read_init_file(inputrc_name)
1199 except:
1205 except:
1200 warn('Problems reading readline initialization file <%s>'
1206 warn('Problems reading readline initialization file <%s>'
1201 % inputrc_name)
1207 % inputrc_name)
1202
1208
1203 self.has_readline = 1
1209 self.has_readline = 1
1204 self.readline = readline
1210 self.readline = readline
1205 self.readline_indent = 0 # for auto-indenting via readline
1211 self.readline_indent = 0 # for auto-indenting via readline
1206 # save this in sys so embedded copies can restore it properly
1212 # save this in sys so embedded copies can restore it properly
1207 sys.ipcompleter = self.Completer.complete
1213 sys.ipcompleter = self.Completer.complete
1208 readline.set_completer(self.Completer.complete)
1214 readline.set_completer(self.Completer.complete)
1209
1215
1210 # Configure readline according to user's prefs
1216 # Configure readline according to user's prefs
1211 for rlcommand in self.rc.readline_parse_and_bind:
1217 for rlcommand in self.rc.readline_parse_and_bind:
1212 readline.parse_and_bind(rlcommand)
1218 readline.parse_and_bind(rlcommand)
1213
1219
1214 # remove some chars from the delimiters list
1220 # remove some chars from the delimiters list
1215 delims = readline.get_completer_delims()
1221 delims = readline.get_completer_delims()
1216 delims = delims.translate(string._idmap,
1222 delims = delims.translate(string._idmap,
1217 self.rc.readline_remove_delims)
1223 self.rc.readline_remove_delims)
1218 readline.set_completer_delims(delims)
1224 readline.set_completer_delims(delims)
1219 # otherwise we end up with a monster history after a while:
1225 # otherwise we end up with a monster history after a while:
1220 readline.set_history_length(1000)
1226 readline.set_history_length(1000)
1221 try:
1227 try:
1222 #print '*** Reading readline history' # dbg
1228 #print '*** Reading readline history' # dbg
1223 readline.read_history_file(self.histfile)
1229 readline.read_history_file(self.histfile)
1224 except IOError:
1230 except IOError:
1225 pass # It doesn't exist yet.
1231 pass # It doesn't exist yet.
1226
1232
1227 atexit.register(self.atexit_operations)
1233 atexit.register(self.atexit_operations)
1228 del atexit
1234 del atexit
1229
1235
1230 # Configure auto-indent for all platforms
1236 # Configure auto-indent for all platforms
1231 self.set_autoindent(self.rc.autoindent)
1237 self.set_autoindent(self.rc.autoindent)
1232
1238
1233 def showsyntaxerror(self, filename=None):
1239 def showsyntaxerror(self, filename=None):
1234 """Display the syntax error that just occurred.
1240 """Display the syntax error that just occurred.
1235
1241
1236 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.
1237
1243
1238 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
1239 of what was there before (because Python's parser always uses
1245 of what was there before (because Python's parser always uses
1240 "<string>" when reading from a string).
1246 "<string>" when reading from a string).
1241 """
1247 """
1242 type, value, sys.last_traceback = sys.exc_info()
1248 type, value, sys.last_traceback = sys.exc_info()
1243 sys.last_type = type
1249 sys.last_type = type
1244 sys.last_value = value
1250 sys.last_value = value
1245 if filename and type is SyntaxError:
1251 if filename and type is SyntaxError:
1246 # Work hard to stuff the correct filename in the exception
1252 # Work hard to stuff the correct filename in the exception
1247 try:
1253 try:
1248 msg, (dummy_filename, lineno, offset, line) = value
1254 msg, (dummy_filename, lineno, offset, line) = value
1249 except:
1255 except:
1250 # Not the format we expect; leave it alone
1256 # Not the format we expect; leave it alone
1251 pass
1257 pass
1252 else:
1258 else:
1253 # Stuff in the right filename
1259 # Stuff in the right filename
1254 try:
1260 try:
1255 # Assume SyntaxError is a class exception
1261 # Assume SyntaxError is a class exception
1256 value = SyntaxError(msg, (filename, lineno, offset, line))
1262 value = SyntaxError(msg, (filename, lineno, offset, line))
1257 except:
1263 except:
1258 # If that failed, assume SyntaxError is a string
1264 # If that failed, assume SyntaxError is a string
1259 value = msg, (filename, lineno, offset, line)
1265 value = msg, (filename, lineno, offset, line)
1260 self.SyntaxTB(type,value,[])
1266 self.SyntaxTB(type,value,[])
1261
1267
1262 def debugger(self):
1268 def debugger(self):
1263 """Call the pdb debugger."""
1269 """Call the pdb debugger."""
1264
1270
1265 if not self.rc.pdb:
1271 if not self.rc.pdb:
1266 return
1272 return
1267 pdb.pm()
1273 pdb.pm()
1268
1274
1269 def showtraceback(self,exc_tuple = None):
1275 def showtraceback(self,exc_tuple = None):
1270 """Display the exception that just occurred."""
1276 """Display the exception that just occurred."""
1271
1277
1272 # 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,
1273 # there may be SyntaxError cases whith imported code.
1279 # there may be SyntaxError cases whith imported code.
1274 if exc_tuple is None:
1280 if exc_tuple is None:
1275 type, value, tb = sys.exc_info()
1281 type, value, tb = sys.exc_info()
1276 else:
1282 else:
1277 type, value, tb = exc_tuple
1283 type, value, tb = exc_tuple
1278 if type is SyntaxError:
1284 if type is SyntaxError:
1279 self.showsyntaxerror()
1285 self.showsyntaxerror()
1280 else:
1286 else:
1281 sys.last_type = type
1287 sys.last_type = type
1282 sys.last_value = value
1288 sys.last_value = value
1283 sys.last_traceback = tb
1289 sys.last_traceback = tb
1284 self.InteractiveTB()
1290 self.InteractiveTB()
1285 if self.InteractiveTB.call_pdb and self.has_readline:
1291 if self.InteractiveTB.call_pdb and self.has_readline:
1286 # pdb mucks up readline, fix it back
1292 # pdb mucks up readline, fix it back
1287 self.readline.set_completer(self.Completer.complete)
1293 self.readline.set_completer(self.Completer.complete)
1288
1294
1289 def update_cache(self, line):
1295 def update_cache(self, line):
1290 """puts line into cache"""
1296 """puts line into cache"""
1291 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1297 self.inputcache.insert(0, line) # This copies the cache every time ... :-(
1292 if len(self.inputcache) >= self.CACHELENGTH:
1298 if len(self.inputcache) >= self.CACHELENGTH:
1293 self.inputcache.pop() # This not :-)
1299 self.inputcache.pop() # This not :-)
1294
1300
1295 def name_space_init(self):
1301 def name_space_init(self):
1296 """Create local namespace."""
1302 """Create local namespace."""
1297 # We want this to be a method to facilitate embedded initialization.
1303 # We want this to be a method to facilitate embedded initialization.
1298 code.InteractiveConsole.__init__(self,self.user_ns)
1304 code.InteractiveConsole.__init__(self,self.user_ns)
1299
1305
1300 def mainloop(self,banner=None):
1306 def mainloop(self,banner=None):
1301 """Creates the local namespace and starts the mainloop.
1307 """Creates the local namespace and starts the mainloop.
1302
1308
1303 If an optional banner argument is given, it will override the
1309 If an optional banner argument is given, it will override the
1304 internally created default banner."""
1310 internally created default banner."""
1305
1311
1306 self.name_space_init()
1312 self.name_space_init()
1307 if self.rc.c: # Emulate Python's -c option
1313 if self.rc.c: # Emulate Python's -c option
1308 self.exec_init_cmd()
1314 self.exec_init_cmd()
1309 if banner is None:
1315 if banner is None:
1310 if self.rc.banner:
1316 if self.rc.banner:
1311 banner = self.BANNER+self.banner2
1317 banner = self.BANNER+self.banner2
1312 else:
1318 else:
1313 banner = ''
1319 banner = ''
1314 self.interact(banner)
1320 self.interact(banner)
1315
1321
1316 def exec_init_cmd(self):
1322 def exec_init_cmd(self):
1317 """Execute a command given at the command line.
1323 """Execute a command given at the command line.
1318
1324
1319 This emulates Python's -c option."""
1325 This emulates Python's -c option."""
1320
1326
1321 sys.argv = ['-c']
1327 sys.argv = ['-c']
1322 self.push(self.rc.c)
1328 self.push(self.rc.c)
1323
1329
1324 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):
1325 """Embeds IPython into a running python program.
1331 """Embeds IPython into a running python program.
1326
1332
1327 Input:
1333 Input:
1328
1334
1329 - header: An optional header message can be specified.
1335 - header: An optional header message can be specified.
1330
1336
1331 - local_ns, global_ns: working namespaces. If given as None, the
1337 - local_ns, global_ns: working namespaces. If given as None, the
1332 IPython-initialized one is updated with __main__.__dict__, so that
1338 IPython-initialized one is updated with __main__.__dict__, so that
1333 program variables become visible but user-specific configuration
1339 program variables become visible but user-specific configuration
1334 remains possible.
1340 remains possible.
1335
1341
1336 - 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
1337 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
1338 allows an intermediate caller to make sure that this function gets
1344 allows an intermediate caller to make sure that this function gets
1339 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)
1340 it will get its locals and globals from the immediate caller.
1346 it will get its locals and globals from the immediate caller.
1341
1347
1342 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
1343 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
1344 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
1345 there is no fundamental reason why it can't work perfectly."""
1351 there is no fundamental reason why it can't work perfectly."""
1346
1352
1347 # 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
1348 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1354 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1349 # FIXME. Test this a bit more carefully (the if.. is new)
1355 # FIXME. Test this a bit more carefully (the if.. is new)
1350 if local_ns is None and global_ns is None:
1356 if local_ns is None and global_ns is None:
1351 self.user_ns.update(__main__.__dict__)
1357 self.user_ns.update(__main__.__dict__)
1352
1358
1353 # Get locals and globals from caller
1359 # Get locals and globals from caller
1354 if local_ns is None or global_ns is None:
1360 if local_ns is None or global_ns is None:
1355 call_frame = sys._getframe(stack_depth).f_back
1361 call_frame = sys._getframe(stack_depth).f_back
1356
1362
1357 if local_ns is None:
1363 if local_ns is None:
1358 local_ns = call_frame.f_locals
1364 local_ns = call_frame.f_locals
1359 if global_ns is None:
1365 if global_ns is None:
1360 global_ns = call_frame.f_globals
1366 global_ns = call_frame.f_globals
1361
1367
1362 # Update namespaces and fire up interpreter
1368 # Update namespaces and fire up interpreter
1363 self.user_ns.update(local_ns)
1369 self.user_ns.update(local_ns)
1364 self.interact(header)
1370 self.interact(header)
1365
1371
1366 # Remove locals from namespace
1372 # Remove locals from namespace
1367 for k in local_ns:
1373 for k in local_ns:
1368 del self.user_ns[k]
1374 del self.user_ns[k]
1369
1375
1370 def interact(self, banner=None):
1376 def interact(self, banner=None):
1371 """Closely emulate the interactive Python console.
1377 """Closely emulate the interactive Python console.
1372
1378
1373 The optional banner argument specify the banner to print
1379 The optional banner argument specify the banner to print
1374 before the first interaction; by default it prints a banner
1380 before the first interaction; by default it prints a banner
1375 similar to the one printed by the real Python interpreter,
1381 similar to the one printed by the real Python interpreter,
1376 followed by the current class name in parentheses (so as not
1382 followed by the current class name in parentheses (so as not
1377 to confuse this with the real interpreter -- since it's so
1383 to confuse this with the real interpreter -- since it's so
1378 close!).
1384 close!).
1379
1385
1380 """
1386 """
1381 cprt = 'Type "copyright", "credits" or "license" for more information.'
1387 cprt = 'Type "copyright", "credits" or "license" for more information.'
1382 if banner is None:
1388 if banner is None:
1383 self.write("Python %s on %s\n%s\n(%s)\n" %
1389 self.write("Python %s on %s\n%s\n(%s)\n" %
1384 (sys.version, sys.platform, cprt,
1390 (sys.version, sys.platform, cprt,
1385 self.__class__.__name__))
1391 self.__class__.__name__))
1386 else:
1392 else:
1387 self.write(banner)
1393 self.write(banner)
1388
1394
1389 more = 0
1395 more = 0
1390
1396
1391 # Mark activity in the builtins
1397 # Mark activity in the builtins
1392 __builtin__.__dict__['__IPYTHON__active'] += 1
1398 __builtin__.__dict__['__IPYTHON__active'] += 1
1393
1399
1394 # exit_now is set by a call to %Exit or %Quit
1400 # exit_now is set by a call to %Exit or %Quit
1395 while not self.exit_now:
1401 while not self.exit_now:
1396 try:
1402 try:
1397 if more:
1403 if more:
1398 prompt = self.outputcache.prompt2
1404 prompt = self.outputcache.prompt2
1399 if self.autoindent:
1405 if self.autoindent:
1400 self.readline_startup_hook(self.pre_readline)
1406 self.readline_startup_hook(self.pre_readline)
1401 else:
1407 else:
1402 prompt = self.outputcache.prompt1
1408 prompt = self.outputcache.prompt1
1403 try:
1409 try:
1404 line = self.raw_input(prompt)
1410 line = self.raw_input(prompt)
1405 if self.autoindent:
1411 if self.autoindent:
1406 self.readline_startup_hook(None)
1412 self.readline_startup_hook(None)
1407 except EOFError:
1413 except EOFError:
1408 if self.autoindent:
1414 if self.autoindent:
1409 self.readline_startup_hook(None)
1415 self.readline_startup_hook(None)
1410 self.write("\n")
1416 self.write("\n")
1411 if self.rc.confirm_exit:
1417 if self.rc.confirm_exit:
1412 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'):
1413 break
1419 break
1414 else:
1420 else:
1415 break
1421 break
1416 else:
1422 else:
1417 more = self.push(line)
1423 more = self.push(line)
1418 # Auto-indent management
1424 # Auto-indent management
1419 if self.autoindent:
1425 if self.autoindent:
1420 if line:
1426 if line:
1421 ini_spaces = re.match('^(\s+)',line)
1427 ini_spaces = re.match('^(\s+)',line)
1422 if ini_spaces:
1428 if ini_spaces:
1423 nspaces = ini_spaces.end()
1429 nspaces = ini_spaces.end()
1424 else:
1430 else:
1425 nspaces = 0
1431 nspaces = 0
1426 self.readline_indent = nspaces
1432 self.readline_indent = nspaces
1427
1433
1428 if line[-1] == ':':
1434 if line[-1] == ':':
1429 self.readline_indent += 4
1435 self.readline_indent += 4
1430 elif re.match(r'^\s+raise|^\s+return',line):
1436 elif re.match(r'^\s+raise|^\s+return',line):
1431 self.readline_indent -= 4
1437 self.readline_indent -= 4
1432 else:
1438 else:
1433 self.readline_indent = 0
1439 self.readline_indent = 0
1434
1440
1435 except KeyboardInterrupt:
1441 except KeyboardInterrupt:
1436 self.write("\nKeyboardInterrupt\n")
1442 self.write("\nKeyboardInterrupt\n")
1437 self.resetbuffer()
1443 self.resetbuffer()
1438 more = 0
1444 more = 0
1439 # keep cache in sync with the prompt counter:
1445 # keep cache in sync with the prompt counter:
1440 self.outputcache.prompt_count -= 1
1446 self.outputcache.prompt_count -= 1
1441
1447
1442 if self.autoindent:
1448 if self.autoindent:
1443 self.readline_indent = 0
1449 self.readline_indent = 0
1444
1450
1445 except bdb.BdbQuit:
1451 except bdb.BdbQuit:
1446 warn("The Python debugger has exited with a BdbQuit exception.\n"
1452 warn("The Python debugger has exited with a BdbQuit exception.\n"
1447 "Because of how pdb handles the stack, it is impossible\n"
1453 "Because of how pdb handles the stack, it is impossible\n"
1448 "for IPython to properly format this particular exception.\n"
1454 "for IPython to properly format this particular exception.\n"
1449 "IPython will resume normal operation.")
1455 "IPython will resume normal operation.")
1450
1456
1451 # We are off again...
1457 # We are off again...
1452 __builtin__.__dict__['__IPYTHON__active'] -= 1
1458 __builtin__.__dict__['__IPYTHON__active'] -= 1
1453
1459
1454 def excepthook(self, type, value, tb):
1460 def excepthook(self, type, value, tb):
1455 """One more defense for GUI apps that call sys.excepthook.
1461 """One more defense for GUI apps that call sys.excepthook.
1456
1462
1457 GUI frameworks like wxPython trap exceptions and call
1463 GUI frameworks like wxPython trap exceptions and call
1458 sys.excepthook themselves. I guess this is a feature that
1464 sys.excepthook themselves. I guess this is a feature that
1459 enables them to keep running after exceptions that would
1465 enables them to keep running after exceptions that would
1460 otherwise kill their mainloop. This is a bother for IPython
1466 otherwise kill their mainloop. This is a bother for IPython
1461 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:
1462 except: statement.
1468 except: statement.
1463
1469
1464 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1470 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1465 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
1466 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
1467 CrashHandler and replace it with this excepthook instead, which prints a
1473 CrashHandler and replace it with this excepthook instead, which prints a
1468 regular traceback using our InteractiveTB. In this fashion, apps which
1474 regular traceback using our InteractiveTB. In this fashion, apps which
1469 call sys.excepthook will generate a regular-looking exception from
1475 call sys.excepthook will generate a regular-looking exception from
1470 IPython, and the CrashHandler will only be triggered by real IPython
1476 IPython, and the CrashHandler will only be triggered by real IPython
1471 crashes.
1477 crashes.
1472
1478
1473 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
1474 to be true IPython errors.
1480 to be true IPython errors.
1475 """
1481 """
1476
1482
1477 self.InteractiveTB(type, value, tb, tb_offset=0)
1483 self.InteractiveTB(type, value, tb, tb_offset=0)
1478 if self.InteractiveTB.call_pdb and self.has_readline:
1484 if self.InteractiveTB.call_pdb and self.has_readline:
1479 self.readline.set_completer(self.Completer.complete)
1485 self.readline.set_completer(self.Completer.complete)
1480
1486
1481 def call_alias(self,alias,rest=''):
1487 def call_alias(self,alias,rest=''):
1482 """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.
1483
1489
1484 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
1485 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
1486 responsible for invoking it only with a valid alias."""
1492 responsible for invoking it only with a valid alias."""
1487
1493
1488 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1494 #print 'ALIAS: <%s>+<%s>' % (alias,rest) # dbg
1489 nargs,cmd = self.alias_table[alias]
1495 nargs,cmd = self.alias_table[alias]
1490 # Expand the %l special to be the user's input line
1496 # Expand the %l special to be the user's input line
1491 if cmd.find('%l') >= 0:
1497 if cmd.find('%l') >= 0:
1492 cmd = cmd.replace('%l',rest)
1498 cmd = cmd.replace('%l',rest)
1493 rest = ''
1499 rest = ''
1494 if nargs==0:
1500 if nargs==0:
1495 # Simple, argument-less aliases
1501 # Simple, argument-less aliases
1496 cmd = '%s %s' % (cmd,rest)
1502 cmd = '%s %s' % (cmd,rest)
1497 else:
1503 else:
1498 # Handle aliases with positional arguments
1504 # Handle aliases with positional arguments
1499 args = rest.split(None,nargs)
1505 args = rest.split(None,nargs)
1500 if len(args)< nargs:
1506 if len(args)< nargs:
1501 error('Alias <%s> requires %s arguments, %s given.' %
1507 error('Alias <%s> requires %s arguments, %s given.' %
1502 (alias,nargs,len(args)))
1508 (alias,nargs,len(args)))
1503 return
1509 return
1504 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1510 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1505 # Now call the macro, evaluating in the user's namespace
1511 # Now call the macro, evaluating in the user's namespace
1506 try:
1512 try:
1507 self.system(cmd)
1513 self.system(cmd)
1508 except:
1514 except:
1509 self.showtraceback()
1515 self.showtraceback()
1510
1516
1511 def runlines(self,lines):
1517 def runlines(self,lines):
1512 """Run a string of one or more lines of source.
1518 """Run a string of one or more lines of source.
1513
1519
1514 This method is capable of running a string containing multiple source
1520 This method is capable of running a string containing multiple source
1515 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
1516 exposes IPython's processing machinery, the given strings can contain
1522 exposes IPython's processing machinery, the given strings can contain
1517 magic calls (%magic), special shell access (!cmd), etc."""
1523 magic calls (%magic), special shell access (!cmd), etc."""
1518
1524
1519 # 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
1520 # interactive IPython session (via a magic, for example).
1526 # interactive IPython session (via a magic, for example).
1521 self.resetbuffer()
1527 self.resetbuffer()
1522 lines = lines.split('\n')
1528 lines = lines.split('\n')
1523 more = 0
1529 more = 0
1524 for line in lines:
1530 for line in lines:
1525 # 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
1526 # 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
1527 # true)
1533 # true)
1528 if line or more:
1534 if line or more:
1529 more = self.push((self.prefilter(line,more)))
1535 more = self.push((self.prefilter(line,more)))
1530 # IPython's runsource returns None if there was an error
1536 # IPython's runsource returns None if there was an error
1531 # compiling the code. This allows us to stop processing right
1537 # compiling the code. This allows us to stop processing right
1532 # 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.
1533 if more is None:
1539 if more is None:
1534 break
1540 break
1535 # 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
1536 # actually does get executed
1542 # actually does get executed
1537 if more:
1543 if more:
1538 self.push('\n')
1544 self.push('\n')
1539
1545
1540 def runsource(self, source, filename="<input>", symbol="single"):
1546 def runsource(self, source, filename="<input>", symbol="single"):
1541 """Compile and run some source in the interpreter.
1547 """Compile and run some source in the interpreter.
1542
1548
1543 Arguments are as for compile_command().
1549 Arguments are as for compile_command().
1544
1550
1545 One several things can happen:
1551 One several things can happen:
1546
1552
1547 1) The input is incorrect; compile_command() raised an
1553 1) The input is incorrect; compile_command() raised an
1548 exception (SyntaxError or OverflowError). A syntax traceback
1554 exception (SyntaxError or OverflowError). A syntax traceback
1549 will be printed by calling the showsyntaxerror() method.
1555 will be printed by calling the showsyntaxerror() method.
1550
1556
1551 2) The input is incomplete, and more input is required;
1557 2) The input is incomplete, and more input is required;
1552 compile_command() returned None. Nothing happens.
1558 compile_command() returned None. Nothing happens.
1553
1559
1554 3) The input is complete; compile_command() returned a code
1560 3) The input is complete; compile_command() returned a code
1555 object. The code is executed by calling self.runcode() (which
1561 object. The code is executed by calling self.runcode() (which
1556 also handles run-time exceptions, except for SystemExit).
1562 also handles run-time exceptions, except for SystemExit).
1557
1563
1558 The return value is:
1564 The return value is:
1559
1565
1560 - True in case 2
1566 - True in case 2
1561
1567
1562 - False in the other cases, unless an exception is raised, where
1568 - False in the other cases, unless an exception is raised, where
1563 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
1564 know whether to continue feeding input or not.
1570 know whether to continue feeding input or not.
1565
1571
1566 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
1567 sys.ps2 to prompt the next line."""
1573 sys.ps2 to prompt the next line."""
1568
1574
1569 try:
1575 try:
1570 code = self.compile(source, filename, symbol)
1576 code = self.compile(source, filename, symbol)
1571 except (OverflowError, SyntaxError, ValueError):
1577 except (OverflowError, SyntaxError, ValueError):
1572 # Case 1
1578 # Case 1
1573 self.showsyntaxerror(filename)
1579 self.showsyntaxerror(filename)
1574 return None
1580 return None
1575
1581
1576 if code is None:
1582 if code is None:
1577 # Case 2
1583 # Case 2
1578 return True
1584 return True
1579
1585
1580 # Case 3
1586 # Case 3
1581 # We store the code object so that threaded shells and
1587 # We store the code object so that threaded shells and
1582 # custom exception handlers can access all this info if needed.
1588 # custom exception handlers can access all this info if needed.
1583 # The source corresponding to this can be obtained from the
1589 # The source corresponding to this can be obtained from the
1584 # buffer attribute as '\n'.join(self.buffer).
1590 # buffer attribute as '\n'.join(self.buffer).
1585 self.code_to_run = code
1591 self.code_to_run = code
1586 # now actually execute the code object
1592 # now actually execute the code object
1587 if self.runcode(code) == 0:
1593 if self.runcode(code) == 0:
1588 return False
1594 return False
1589 else:
1595 else:
1590 return None
1596 return None
1591
1597
1592 def runcode(self,code_obj):
1598 def runcode(self,code_obj):
1593 """Execute a code object.
1599 """Execute a code object.
1594
1600
1595 When an exception occurs, self.showtraceback() is called to display a
1601 When an exception occurs, self.showtraceback() is called to display a
1596 traceback.
1602 traceback.
1597
1603
1598 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
1599 successfully:
1605 successfully:
1600
1606
1601 - 0: successful execution.
1607 - 0: successful execution.
1602 - 1: an error occurred.
1608 - 1: an error occurred.
1603 """
1609 """
1604
1610
1605 # 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
1606 # directly, so that the IPython crash handler doesn't get triggered
1612 # directly, so that the IPython crash handler doesn't get triggered
1607 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1613 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
1608 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
1609 try:
1615 try:
1610 try:
1616 try:
1611 exec code_obj in self.locals
1617 exec code_obj in self.locals
1612 finally:
1618 finally:
1613 # Reset our crash handler in place
1619 # Reset our crash handler in place
1614 sys.excepthook = old_excepthook
1620 sys.excepthook = old_excepthook
1615 except SystemExit:
1621 except SystemExit:
1616 self.resetbuffer()
1622 self.resetbuffer()
1617 self.showtraceback()
1623 self.showtraceback()
1618 warn( __builtin__.exit,level=1)
1624 warn( __builtin__.exit,level=1)
1619 except self.custom_exceptions:
1625 except self.custom_exceptions:
1620 etype,value,tb = sys.exc_info()
1626 etype,value,tb = sys.exc_info()
1621 self.CustomTB(etype,value,tb)
1627 self.CustomTB(etype,value,tb)
1622 except:
1628 except:
1623 self.showtraceback()
1629 self.showtraceback()
1624 else:
1630 else:
1625 outflag = 0
1631 outflag = 0
1626 if code.softspace(sys.stdout, 0):
1632 if code.softspace(sys.stdout, 0):
1627 print
1633 print
1628 # Flush out code object which has been run (and source)
1634 # Flush out code object which has been run (and source)
1629 self.code_to_run = None
1635 self.code_to_run = None
1630 return outflag
1636 return outflag
1631
1637
1632 def raw_input(self, prompt=""):
1638 def raw_input(self, prompt=""):
1633 """Write a prompt and read a line.
1639 """Write a prompt and read a line.
1634
1640
1635 The returned line does not include the trailing newline.
1641 The returned line does not include the trailing newline.
1636 When the user enters the EOF key sequence, EOFError is raised.
1642 When the user enters the EOF key sequence, EOFError is raised.
1637
1643
1638 The base implementation uses the built-in function
1644 The base implementation uses the built-in function
1639 raw_input(); a subclass may replace this with a different
1645 raw_input(); a subclass may replace this with a different
1640 implementation.
1646 implementation.
1641 """
1647 """
1642 return self.prefilter(raw_input_original(prompt),
1648 return self.prefilter(raw_input_original(prompt),
1643 prompt==self.outputcache.prompt2)
1649 prompt==self.outputcache.prompt2)
1644
1650
1645 def split_user_input(self,line):
1651 def split_user_input(self,line):
1646 """Split user input into pre-char, function part and rest."""
1652 """Split user input into pre-char, function part and rest."""
1647
1653
1648 lsplit = self.line_split.match(line)
1654 lsplit = self.line_split.match(line)
1649 if lsplit is None: # no regexp match returns None
1655 if lsplit is None: # no regexp match returns None
1650 try:
1656 try:
1651 iFun,theRest = line.split(None,1)
1657 iFun,theRest = line.split(None,1)
1652 except ValueError:
1658 except ValueError:
1653 iFun,theRest = line,''
1659 iFun,theRest = line,''
1654 pre = re.match('^(\s*)(.*)',line).groups()[0]
1660 pre = re.match('^(\s*)(.*)',line).groups()[0]
1655 else:
1661 else:
1656 pre,iFun,theRest = lsplit.groups()
1662 pre,iFun,theRest = lsplit.groups()
1657
1663
1658 #print 'line:<%s>' % line # dbg
1664 #print 'line:<%s>' % line # dbg
1659 #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
1660 return pre,iFun.strip(),theRest
1666 return pre,iFun.strip(),theRest
1661
1667
1662 def _prefilter(self, line, continue_prompt):
1668 def _prefilter(self, line, continue_prompt):
1663 """Calls different preprocessors, depending on the form of line."""
1669 """Calls different preprocessors, depending on the form of line."""
1664
1670
1665 # All handlers *must* return a value, even if it's blank ('').
1671 # All handlers *must* return a value, even if it's blank ('').
1666
1672
1667 # Lines are NOT logged here. Handlers should process the line as
1673 # Lines are NOT logged here. Handlers should process the line as
1668 # 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
1669 # stays synced).
1675 # stays synced).
1670
1676
1671 # 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
1672 # 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
1673 # 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
1674 # 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.
1675
1681
1676 # This function is the main responsible for maintaining IPython's
1682 # This function is the main responsible for maintaining IPython's
1677 # behavior respectful of Python's semantics. So be _very_ careful if
1683 # behavior respectful of Python's semantics. So be _very_ careful if
1678 # making changes to anything here.
1684 # making changes to anything here.
1679
1685
1680 #.....................................................................
1686 #.....................................................................
1681 # Code begins
1687 # Code begins
1682
1688
1683 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1689 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
1684
1690
1685 # 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
1686 # record it
1692 # record it
1687 self._last_input_line = line
1693 self._last_input_line = line
1688
1694
1689 #print '***line: <%s>' % line # dbg
1695 #print '***line: <%s>' % line # dbg
1690
1696
1691 # the input history needs to track even empty lines
1697 # the input history needs to track even empty lines
1692 if not line.strip():
1698 if not line.strip():
1693 if not continue_prompt:
1699 if not continue_prompt:
1694 self.outputcache.prompt_count -= 1
1700 self.outputcache.prompt_count -= 1
1695 return self.handle_normal('',continue_prompt)
1701 return self.handle_normal('',continue_prompt)
1696
1702
1697 # print '***cont',continue_prompt # dbg
1703 # print '***cont',continue_prompt # dbg
1698 # special handlers are only allowed for single line statements
1704 # special handlers are only allowed for single line statements
1699 if continue_prompt and not self.rc.multi_line_specials:
1705 if continue_prompt and not self.rc.multi_line_specials:
1700 return self.handle_normal(line,continue_prompt)
1706 return self.handle_normal(line,continue_prompt)
1701
1707
1702 # For the rest, we need the structure of the input
1708 # For the rest, we need the structure of the input
1703 pre,iFun,theRest = self.split_user_input(line)
1709 pre,iFun,theRest = self.split_user_input(line)
1704 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1710 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1705
1711
1706 # First check for explicit escapes in the last/first character
1712 # First check for explicit escapes in the last/first character
1707 handler = None
1713 handler = None
1708 if line[-1] == self.ESC_HELP:
1714 if line[-1] == self.ESC_HELP:
1709 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
1710 if handler is None:
1716 if handler is None:
1711 # 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
1712 # leading whitespace in multiline input
1718 # leading whitespace in multiline input
1713 handler = self.esc_handlers.get(iFun[0:1])
1719 handler = self.esc_handlers.get(iFun[0:1])
1714 if handler is not None:
1720 if handler is not None:
1715 return handler(line,continue_prompt,pre,iFun,theRest)
1721 return handler(line,continue_prompt,pre,iFun,theRest)
1716 # Emacs ipython-mode tags certain input lines
1722 # Emacs ipython-mode tags certain input lines
1717 if line.endswith('# PYTHON-MODE'):
1723 if line.endswith('# PYTHON-MODE'):
1718 return self.handle_emacs(line,continue_prompt)
1724 return self.handle_emacs(line,continue_prompt)
1719
1725
1720 # Next, check if we can automatically execute this thing
1726 # Next, check if we can automatically execute this thing
1721
1727
1722 # Allow ! in multi-line statements if multi_line_specials is on:
1728 # Allow ! in multi-line statements if multi_line_specials is on:
1723 if continue_prompt and self.rc.multi_line_specials and \
1729 if continue_prompt and self.rc.multi_line_specials and \
1724 iFun.startswith(self.ESC_SHELL):
1730 iFun.startswith(self.ESC_SHELL):
1725 return self.handle_shell_escape(line,continue_prompt,
1731 return self.handle_shell_escape(line,continue_prompt,
1726 pre=pre,iFun=iFun,
1732 pre=pre,iFun=iFun,
1727 theRest=theRest)
1733 theRest=theRest)
1728
1734
1729 # 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
1730 oinfo = None
1736 oinfo = None
1731 if hasattr(self,'magic_'+iFun):
1737 if hasattr(self,'magic_'+iFun):
1732 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1738 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1733 if oinfo['ismagic']:
1739 if oinfo['ismagic']:
1734 # Be careful not to call magics when a variable assignment is
1740 # Be careful not to call magics when a variable assignment is
1735 # being made (ls='hi', for example)
1741 # being made (ls='hi', for example)
1736 if self.rc.automagic and \
1742 if self.rc.automagic and \
1737 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1743 (len(theRest)==0 or theRest[0] not in '!=()<>,') and \
1738 (self.rc.multi_line_specials or not continue_prompt):
1744 (self.rc.multi_line_specials or not continue_prompt):
1739 return self.handle_magic(line,continue_prompt,
1745 return self.handle_magic(line,continue_prompt,
1740 pre,iFun,theRest)
1746 pre,iFun,theRest)
1741 else:
1747 else:
1742 return self.handle_normal(line,continue_prompt)
1748 return self.handle_normal(line,continue_prompt)
1743
1749
1744 # 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
1745 # function call, we should not call _ofind but simply execute it.
1751 # function call, we should not call _ofind but simply execute it.
1746 # This avoids spurious geattr() accesses on objects upon assignment.
1752 # This avoids spurious geattr() accesses on objects upon assignment.
1747 #
1753 #
1748 # 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
1749 # python variables (the magic/alias systems always take second seat to
1755 # python variables (the magic/alias systems always take second seat to
1750 # true python code).
1756 # true python code).
1751 if theRest and theRest[0] in '!=()':
1757 if theRest and theRest[0] in '!=()':
1752 return self.handle_normal(line,continue_prompt)
1758 return self.handle_normal(line,continue_prompt)
1753
1759
1754 if oinfo is None:
1760 if oinfo is None:
1755 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1761 oinfo = self._ofind(iFun) # FIXME - _ofind is part of Magic
1756
1762
1757 if not oinfo['found']:
1763 if not oinfo['found']:
1758 return self.handle_normal(line,continue_prompt)
1764 return self.handle_normal(line,continue_prompt)
1759 else:
1765 else:
1760 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1766 #print 'iFun <%s> rest <%s>' % (iFun,theRest) # dbg
1761 if oinfo['isalias']:
1767 if oinfo['isalias']:
1762 return self.handle_alias(line,continue_prompt,
1768 return self.handle_alias(line,continue_prompt,
1763 pre,iFun,theRest)
1769 pre,iFun,theRest)
1764
1770
1765 if self.rc.autocall and \
1771 if self.rc.autocall and \
1766 not self.re_exclude_auto.match(theRest) and \
1772 not self.re_exclude_auto.match(theRest) and \
1767 self.re_fun_name.match(iFun) and \
1773 self.re_fun_name.match(iFun) and \
1768 callable(oinfo['obj']) :
1774 callable(oinfo['obj']) :
1769 #print 'going auto' # dbg
1775 #print 'going auto' # dbg
1770 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1776 return self.handle_auto(line,continue_prompt,pre,iFun,theRest)
1771 else:
1777 else:
1772 #print 'was callable?', callable(oinfo['obj']) # dbg
1778 #print 'was callable?', callable(oinfo['obj']) # dbg
1773 return self.handle_normal(line,continue_prompt)
1779 return self.handle_normal(line,continue_prompt)
1774
1780
1775 # 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.
1776 return self.handle_normal(line,continue_prompt)
1782 return self.handle_normal(line,continue_prompt)
1777
1783
1778 def _prefilter_dumb(self, line, continue_prompt):
1784 def _prefilter_dumb(self, line, continue_prompt):
1779 """simple prefilter function, for debugging"""
1785 """simple prefilter function, for debugging"""
1780 return self.handle_normal(line,continue_prompt)
1786 return self.handle_normal(line,continue_prompt)
1781
1787
1782 # Set the default prefilter() function (this can be user-overridden)
1788 # Set the default prefilter() function (this can be user-overridden)
1783 prefilter = _prefilter
1789 prefilter = _prefilter
1784
1790
1785 def handle_normal(self,line,continue_prompt=None,
1791 def handle_normal(self,line,continue_prompt=None,
1786 pre=None,iFun=None,theRest=None):
1792 pre=None,iFun=None,theRest=None):
1787 """Handle normal input lines. Use as a template for handlers."""
1793 """Handle normal input lines. Use as a template for handlers."""
1788
1794
1789 self.log(line,continue_prompt)
1795 self.log(line,continue_prompt)
1790 self.update_cache(line)
1796 self.update_cache(line)
1791 return line
1797 return line
1792
1798
1793 def handle_alias(self,line,continue_prompt=None,
1799 def handle_alias(self,line,continue_prompt=None,
1794 pre=None,iFun=None,theRest=None):
1800 pre=None,iFun=None,theRest=None):
1795 """Handle alias input lines. """
1801 """Handle alias input lines. """
1796
1802
1797 theRest = esc_quotes(theRest)
1803 theRest = esc_quotes(theRest)
1798 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)
1799 self.log(line_out,continue_prompt)
1805 self.log(line_out,continue_prompt)
1800 self.update_cache(line_out)
1806 self.update_cache(line_out)
1801 return line_out
1807 return line_out
1802
1808
1803 def handle_shell_escape(self, line, continue_prompt=None,
1809 def handle_shell_escape(self, line, continue_prompt=None,
1804 pre=None,iFun=None,theRest=None):
1810 pre=None,iFun=None,theRest=None):
1805 """Execute the line in a shell, empty return value"""
1811 """Execute the line in a shell, empty return value"""
1806
1812
1807 #print 'line in :', `line` # dbg
1813 #print 'line in :', `line` # dbg
1808 # Example of a special handler. Others follow a similar pattern.
1814 # Example of a special handler. Others follow a similar pattern.
1809 if continue_prompt: # multi-line statements
1815 if continue_prompt: # multi-line statements
1810 if iFun.startswith('!!'):
1816 if iFun.startswith('!!'):
1811 print 'SyntaxError: !! is not allowed in multiline statements'
1817 print 'SyntaxError: !! is not allowed in multiline statements'
1812 return pre
1818 return pre
1813 else:
1819 else:
1814 cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
1820 cmd = ("%s %s" % (iFun[1:],theRest)).replace('"','\\"')
1815 line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1821 line_out = '%s%s.system("%s")' % (pre,self.name,cmd)
1816 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1822 #line_out = ('%s%s.system(' % (pre,self.name)) + repr(cmd) + ')'
1817 else: # single-line input
1823 else: # single-line input
1818 if line.startswith('!!'):
1824 if line.startswith('!!'):
1819 # rewrite iFun/theRest to properly hold the call to %sx and
1825 # rewrite iFun/theRest to properly hold the call to %sx and
1820 # the actual command to be executed, so handle_magic can work
1826 # the actual command to be executed, so handle_magic can work
1821 # correctly
1827 # correctly
1822 theRest = '%s %s' % (iFun[2:],theRest)
1828 theRest = '%s %s' % (iFun[2:],theRest)
1823 iFun = 'sx'
1829 iFun = 'sx'
1824 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1830 return self.handle_magic('%ssx %s' % (self.ESC_MAGIC,line[2:]),
1825 continue_prompt,pre,iFun,theRest)
1831 continue_prompt,pre,iFun,theRest)
1826 else:
1832 else:
1827 cmd = esc_quotes(line[1:])
1833 cmd = esc_quotes(line[1:])
1828 line_out = '%s.system("%s")' % (self.name,cmd)
1834 line_out = '%s.system("%s")' % (self.name,cmd)
1829 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1835 #line_out = ('%s.system(' % self.name) + repr(cmd)+ ')'
1830 # update cache/log and return
1836 # update cache/log and return
1831 self.log(line_out,continue_prompt)
1837 self.log(line_out,continue_prompt)
1832 self.update_cache(line_out) # readline cache gets normal line
1838 self.update_cache(line_out) # readline cache gets normal line
1833 #print 'line out r:', `line_out` # dbg
1839 #print 'line out r:', `line_out` # dbg
1834 #print 'line out s:', line_out # dbg
1840 #print 'line out s:', line_out # dbg
1835 return line_out
1841 return line_out
1836
1842
1837 def handle_magic(self, line, continue_prompt=None,
1843 def handle_magic(self, line, continue_prompt=None,
1838 pre=None,iFun=None,theRest=None):
1844 pre=None,iFun=None,theRest=None):
1839 """Execute magic functions.
1845 """Execute magic functions.
1840
1846
1841 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."""
1842
1848
1843 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1849 cmd = '%sipmagic("%s")' % (pre,esc_quotes('%s %s' % (iFun,theRest)))
1844 self.log(cmd,continue_prompt)
1850 self.log(cmd,continue_prompt)
1845 self.update_cache(line)
1851 self.update_cache(line)
1846 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1852 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
1847 return cmd
1853 return cmd
1848
1854
1849 def handle_auto(self, line, continue_prompt=None,
1855 def handle_auto(self, line, continue_prompt=None,
1850 pre=None,iFun=None,theRest=None):
1856 pre=None,iFun=None,theRest=None):
1851 """Hande lines which can be auto-executed, quoting if requested."""
1857 """Hande lines which can be auto-executed, quoting if requested."""
1852
1858
1853 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1859 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
1854
1860
1855 # This should only be active for single-line input!
1861 # This should only be active for single-line input!
1856 if continue_prompt:
1862 if continue_prompt:
1857 return line
1863 return line
1858
1864
1859 if pre == self.ESC_QUOTE:
1865 if pre == self.ESC_QUOTE:
1860 # Auto-quote splitting on whitespace
1866 # Auto-quote splitting on whitespace
1861 newcmd = '%s("%s")\n' % (iFun,'", "'.join(theRest.split()) )
1867 newcmd = '%s("%s")\n' % (iFun,'", "'.join(theRest.split()) )
1862 elif pre == self.ESC_QUOTE2:
1868 elif pre == self.ESC_QUOTE2:
1863 # Auto-quote whole string
1869 # Auto-quote whole string
1864 newcmd = '%s("%s")\n' % (iFun,theRest)
1870 newcmd = '%s("%s")\n' % (iFun,theRest)
1865 else:
1871 else:
1866 # Auto-paren
1872 # Auto-paren
1867 if theRest[0:1] in ('=','['):
1873 if theRest[0:1] in ('=','['):
1868 # Don't autocall in these cases. They can be either
1874 # Don't autocall in these cases. They can be either
1869 # rebindings of an existing callable's name, or item access
1875 # rebindings of an existing callable's name, or item access
1870 # for an object which is BOTH callable and implements
1876 # for an object which is BOTH callable and implements
1871 # __getitem__.
1877 # __getitem__.
1872 return '%s %s\n' % (iFun,theRest)
1878 return '%s %s\n' % (iFun,theRest)
1873 if theRest.endswith(';'):
1879 if theRest.endswith(';'):
1874 newcmd = '%s(%s);\n' % (iFun.rstrip(),theRest[:-1])
1880 newcmd = '%s(%s);\n' % (iFun.rstrip(),theRest[:-1])
1875 else:
1881 else:
1876 newcmd = '%s(%s)\n' % (iFun.rstrip(),theRest)
1882 newcmd = '%s(%s)\n' % (iFun.rstrip(),theRest)
1877
1883
1878 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd,
1884 print >>Term.cout, self.outputcache.prompt1.auto_rewrite() + newcmd,
1879 # 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
1880 # final newline)
1886 # final newline)
1881 self.log(newcmd.strip(),continue_prompt)
1887 self.log(newcmd.strip(),continue_prompt)
1882 return newcmd
1888 return newcmd
1883
1889
1884 def handle_help(self, line, continue_prompt=None,
1890 def handle_help(self, line, continue_prompt=None,
1885 pre=None,iFun=None,theRest=None):
1891 pre=None,iFun=None,theRest=None):
1886 """Try to get some help for the object.
1892 """Try to get some help for the object.
1887
1893
1888 obj? or ?obj -> basic information.
1894 obj? or ?obj -> basic information.
1889 obj?? or ??obj -> more details.
1895 obj?? or ??obj -> more details.
1890 """
1896 """
1891
1897
1892 # 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
1893 # otherwise valid python, such as "x=1 # what?"
1899 # otherwise valid python, such as "x=1 # what?"
1894 try:
1900 try:
1895 code.compile_command(line)
1901 code.compile_command(line)
1896 except SyntaxError:
1902 except SyntaxError:
1897 # 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
1898 if line[0]==self.ESC_HELP:
1904 if line[0]==self.ESC_HELP:
1899 line = line[1:]
1905 line = line[1:]
1900 elif line[-1]==self.ESC_HELP:
1906 elif line[-1]==self.ESC_HELP:
1901 line = line[:-1]
1907 line = line[:-1]
1902 self.log('#?'+line)
1908 self.log('#?'+line)
1903 self.update_cache(line)
1909 self.update_cache(line)
1904 if line:
1910 if line:
1905 self.magic_pinfo(line)
1911 self.magic_pinfo(line)
1906 else:
1912 else:
1907 page(self.usage,screen_lines=self.rc.screen_length)
1913 page(self.usage,screen_lines=self.rc.screen_length)
1908 return '' # Empty string is needed here!
1914 return '' # Empty string is needed here!
1909 except:
1915 except:
1910 # Pass any other exceptions through to the normal handler
1916 # Pass any other exceptions through to the normal handler
1911 return self.handle_normal(line,continue_prompt)
1917 return self.handle_normal(line,continue_prompt)
1912 else:
1918 else:
1913 # If the code compiles ok, we should handle it normally
1919 # If the code compiles ok, we should handle it normally
1914 return self.handle_normal(line,continue_prompt)
1920 return self.handle_normal(line,continue_prompt)
1915
1921
1916 def handle_emacs(self,line,continue_prompt=None,
1922 def handle_emacs(self,line,continue_prompt=None,
1917 pre=None,iFun=None,theRest=None):
1923 pre=None,iFun=None,theRest=None):
1918 """Handle input lines marked by python-mode."""
1924 """Handle input lines marked by python-mode."""
1919
1925
1920 # Currently, nothing is done. Later more functionality can be added
1926 # Currently, nothing is done. Later more functionality can be added
1921 # here if needed.
1927 # here if needed.
1922
1928
1923 # The input cache shouldn't be updated
1929 # The input cache shouldn't be updated
1924
1930
1925 return line
1931 return line
1926
1932
1927 def write(self,data):
1933 def write(self,data):
1928 """Write a string to the default output"""
1934 """Write a string to the default output"""
1929 Term.cout.write(data)
1935 Term.cout.write(data)
1930
1936
1931 def write_err(self,data):
1937 def write_err(self,data):
1932 """Write a string to the default error output"""
1938 """Write a string to the default error output"""
1933 Term.cerr.write(data)
1939 Term.cerr.write(data)
1934
1940
1935 def safe_execfile(self,fname,*where,**kw):
1941 def safe_execfile(self,fname,*where,**kw):
1936 fname = os.path.expanduser(fname)
1942 fname = os.path.expanduser(fname)
1937
1943
1938 # find things also in current directory
1944 # find things also in current directory
1939 dname = os.path.dirname(fname)
1945 dname = os.path.dirname(fname)
1940 if not sys.path.count(dname):
1946 if not sys.path.count(dname):
1941 sys.path.append(dname)
1947 sys.path.append(dname)
1942
1948
1943 try:
1949 try:
1944 xfile = open(fname)
1950 xfile = open(fname)
1945 except:
1951 except:
1946 print >> Term.cerr, \
1952 print >> Term.cerr, \
1947 'Could not open file <%s> for safe execution.' % fname
1953 'Could not open file <%s> for safe execution.' % fname
1948 return None
1954 return None
1949
1955
1950 kw.setdefault('islog',0)
1956 kw.setdefault('islog',0)
1951 kw.setdefault('quiet',1)
1957 kw.setdefault('quiet',1)
1952 kw.setdefault('exit_ignore',0)
1958 kw.setdefault('exit_ignore',0)
1953 first = xfile.readline()
1959 first = xfile.readline()
1954 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
1960 _LOGHEAD = str(self.LOGHEAD).split('\n',1)[0].strip()
1955 xfile.close()
1961 xfile.close()
1956 # line by line execution
1962 # line by line execution
1957 if first.startswith(_LOGHEAD) or kw['islog']:
1963 if first.startswith(_LOGHEAD) or kw['islog']:
1958 print 'Loading log file <%s> one line at a time...' % fname
1964 print 'Loading log file <%s> one line at a time...' % fname
1959 if kw['quiet']:
1965 if kw['quiet']:
1960 stdout_save = sys.stdout
1966 stdout_save = sys.stdout
1961 sys.stdout = StringIO.StringIO()
1967 sys.stdout = StringIO.StringIO()
1962 try:
1968 try:
1963 globs,locs = where[0:2]
1969 globs,locs = where[0:2]
1964 except:
1970 except:
1965 try:
1971 try:
1966 globs = locs = where[0]
1972 globs = locs = where[0]
1967 except:
1973 except:
1968 globs = locs = globals()
1974 globs = locs = globals()
1969 badblocks = []
1975 badblocks = []
1970
1976
1971 # we also need to identify indented blocks of code when replaying
1977 # we also need to identify indented blocks of code when replaying
1972 # logs and put them together before passing them to an exec
1978 # logs and put them together before passing them to an exec
1973 # 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
1974 # 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
1975 # first, and manually walk through the lines list moving the
1981 # first, and manually walk through the lines list moving the
1976 # counter ourselves.
1982 # counter ourselves.
1977 indent_re = re.compile('\s+\S')
1983 indent_re = re.compile('\s+\S')
1978 xfile = open(fname)
1984 xfile = open(fname)
1979 filelines = xfile.readlines()
1985 filelines = xfile.readlines()
1980 xfile.close()
1986 xfile.close()
1981 nlines = len(filelines)
1987 nlines = len(filelines)
1982 lnum = 0
1988 lnum = 0
1983 while lnum < nlines:
1989 while lnum < nlines:
1984 line = filelines[lnum]
1990 line = filelines[lnum]
1985 lnum += 1
1991 lnum += 1
1986 # don't re-insert logger status info into cache
1992 # don't re-insert logger status info into cache
1987 if line.startswith('#log#'):
1993 if line.startswith('#log#'):
1988 continue
1994 continue
1989 elif line.startswith('#%s'% self.ESC_MAGIC):
1995 elif line.startswith('#%s'% self.ESC_MAGIC):
1990 self.update_cache(line[1:])
1996 self.update_cache(line[1:])
1991 line = magic2python(line)
1997 line = magic2python(line)
1992 elif line.startswith('#!'):
1998 elif line.startswith('#!'):
1993 self.update_cache(line[1:])
1999 self.update_cache(line[1:])
1994 else:
2000 else:
1995 # build a block of code (maybe a single line) for execution
2001 # build a block of code (maybe a single line) for execution
1996 block = line
2002 block = line
1997 try:
2003 try:
1998 next = filelines[lnum] # lnum has already incremented
2004 next = filelines[lnum] # lnum has already incremented
1999 except:
2005 except:
2000 next = None
2006 next = None
2001 while next and indent_re.match(next):
2007 while next and indent_re.match(next):
2002 block += next
2008 block += next
2003 lnum += 1
2009 lnum += 1
2004 try:
2010 try:
2005 next = filelines[lnum]
2011 next = filelines[lnum]
2006 except:
2012 except:
2007 next = None
2013 next = None
2008 # now execute the block of one or more lines
2014 # now execute the block of one or more lines
2009 try:
2015 try:
2010 exec block in globs,locs
2016 exec block in globs,locs
2011 self.update_cache(block.rstrip())
2017 self.update_cache(block.rstrip())
2012 except SystemExit:
2018 except SystemExit:
2013 pass
2019 pass
2014 except:
2020 except:
2015 badblocks.append(block.rstrip())
2021 badblocks.append(block.rstrip())
2016 if kw['quiet']: # restore stdout
2022 if kw['quiet']: # restore stdout
2017 sys.stdout.close()
2023 sys.stdout.close()
2018 sys.stdout = stdout_save
2024 sys.stdout = stdout_save
2019 print 'Finished replaying log file <%s>' % fname
2025 print 'Finished replaying log file <%s>' % fname
2020 if badblocks:
2026 if badblocks:
2021 print >> sys.stderr, \
2027 print >> sys.stderr, \
2022 '\nThe following lines/blocks in file <%s> reported errors:' \
2028 '\nThe following lines/blocks in file <%s> reported errors:' \
2023 % fname
2029 % fname
2024 for badline in badblocks:
2030 for badline in badblocks:
2025 print >> sys.stderr, badline
2031 print >> sys.stderr, badline
2026 else: # regular file execution
2032 else: # regular file execution
2027 try:
2033 try:
2028 execfile(fname,*where)
2034 execfile(fname,*where)
2029 except SyntaxError:
2035 except SyntaxError:
2030 etype, evalue = sys.exc_info()[0:2]
2036 etype, evalue = sys.exc_info()[0:2]
2031 self.SyntaxTB(etype,evalue,[])
2037 self.SyntaxTB(etype,evalue,[])
2032 warn('Failure executing file: <%s>' % fname)
2038 warn('Failure executing file: <%s>' % fname)
2033 except SystemExit,status:
2039 except SystemExit,status:
2034 if not kw['exit_ignore']:
2040 if not kw['exit_ignore']:
2035 self.InteractiveTB()
2041 self.InteractiveTB()
2036 warn('Failure executing file: <%s>' % fname)
2042 warn('Failure executing file: <%s>' % fname)
2037 except:
2043 except:
2038 self.InteractiveTB()
2044 self.InteractiveTB()
2039 warn('Failure executing file: <%s>' % fname)
2045 warn('Failure executing file: <%s>' % fname)
2040
2046
2041 #************************* end of file <iplib.py> *****************************
2047 #************************* end of file <iplib.py> *****************************
@@ -1,725 +1,725 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 IPython -- An enhanced Interactive Python
3 IPython -- An enhanced Interactive Python
4
4
5 Requires Python 2.1 or better.
5 Requires Python 2.1 or better.
6
6
7 This file contains the main make_IPython() starter function.
7 This file contains the main make_IPython() starter function.
8
8
9 $Id: ipmaker.py 638 2005-07-18 03:01:41Z fperez $"""
9 $Id: ipmaker.py 802 2005-09-06 03:49:12Z fperez $"""
10
10
11 #*****************************************************************************
11 #*****************************************************************************
12 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
12 # Copyright (C) 2001-2004 Fernando Perez. <fperez@colorado.edu>
13 #
13 #
14 # Distributed under the terms of the BSD License. The full license is in
14 # Distributed under the terms of the BSD License. The full license is in
15 # the file COPYING, distributed as part of this software.
15 # the file COPYING, distributed as part of this software.
16 #*****************************************************************************
16 #*****************************************************************************
17
17
18 from IPython import Release
18 from IPython import Release
19 __author__ = '%s <%s>' % Release.authors['Fernando']
19 __author__ = '%s <%s>' % Release.authors['Fernando']
20 __license__ = Release.license
20 __license__ = Release.license
21 __version__ = Release.version
21 __version__ = Release.version
22
22
23 credits._Printer__data = """
23 credits._Printer__data = """
24 Python: %s
24 Python: %s
25
25
26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
26 IPython: Fernando Perez, Janko Hauser, Nathan Gray, and many users.
27 See http://ipython.scipy.org for more information.""" \
27 See http://ipython.scipy.org for more information.""" \
28 % credits._Printer__data
28 % credits._Printer__data
29
29
30 copyright._Printer__data += """
30 copyright._Printer__data += """
31
31
32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
32 Copyright (c) 2001-2004 Fernando Perez, Janko Hauser, Nathan Gray.
33 All Rights Reserved."""
33 All Rights Reserved."""
34
34
35 #****************************************************************************
35 #****************************************************************************
36 # Required modules
36 # Required modules
37
37
38 # From the standard library
38 # From the standard library
39 import __main__, __builtin__
39 import __main__, __builtin__
40 import os,sys,types,re
40 import os,sys,types,re
41 from pprint import pprint,pformat
41 from pprint import pprint,pformat
42
42
43 # Our own
43 # Our own
44 from IPython import DPyGetOpt
44 from IPython import DPyGetOpt
45 from IPython.Struct import Struct
45 from IPython.Struct import Struct
46 from IPython.OutputTrap import OutputTrap
46 from IPython.OutputTrap import OutputTrap
47 from IPython.ConfigLoader import ConfigLoader
47 from IPython.ConfigLoader import ConfigLoader
48 from IPython.iplib import InteractiveShell,qw_lol,import_fail_info
48 from IPython.iplib import InteractiveShell,qw_lol,import_fail_info
49 from IPython.usage import cmd_line_usage,interactive_usage
49 from IPython.usage import cmd_line_usage,interactive_usage
50 from IPython.Prompts import CachedOutput
50 from IPython.Prompts import CachedOutput
51 from IPython.genutils import *
51 from IPython.genutils import *
52
52
53 #-----------------------------------------------------------------------------
53 #-----------------------------------------------------------------------------
54 def make_IPython(argv=None,user_ns=None,debug=1,rc_override=None,
54 def make_IPython(argv=None,user_ns=None,debug=1,rc_override=None,
55 shell_class=InteractiveShell,embedded=False,**kw):
55 shell_class=InteractiveShell,embedded=False,**kw):
56 """This is a dump of IPython into a single function.
56 """This is a dump of IPython into a single function.
57
57
58 Later it will have to be broken up in a sensible manner.
58 Later it will have to be broken up in a sensible manner.
59
59
60 Arguments:
60 Arguments:
61
61
62 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
62 - argv: a list similar to sys.argv[1:]. It should NOT contain the desired
63 script name, b/c DPyGetOpt strips the first argument only for the real
63 script name, b/c DPyGetOpt strips the first argument only for the real
64 sys.argv.
64 sys.argv.
65
65
66 - user_ns: a dict to be used as the user's namespace."""
66 - user_ns: a dict to be used as the user's namespace."""
67
67
68 #----------------------------------------------------------------------
68 #----------------------------------------------------------------------
69 # Defaults and initialization
69 # Defaults and initialization
70
70
71 # For developer debugging, deactivates crash handler and uses pdb.
71 # For developer debugging, deactivates crash handler and uses pdb.
72 DEVDEBUG = False
72 DEVDEBUG = False
73
73
74 if argv is None:
74 if argv is None:
75 argv = sys.argv
75 argv = sys.argv
76
76
77 # __IP is the main global that lives throughout and represents the whole
77 # __IP is the main global that lives throughout and represents the whole
78 # application. If the user redefines it, all bets are off as to what
78 # application. If the user redefines it, all bets are off as to what
79 # happens.
79 # happens.
80
80
81 # __IP is the name of he global which the caller will have accessible as
81 # __IP is the name of he global which the caller will have accessible as
82 # __IP.name. We set its name via the first parameter passed to
82 # __IP.name. We set its name via the first parameter passed to
83 # InteractiveShell:
83 # InteractiveShell:
84
84
85 IP = shell_class('__IP',user_ns=user_ns,**kw)
85 IP = shell_class('__IP',user_ns=user_ns,**kw)
86
86
87 # Put 'help' in the user namespace
87 # Put 'help' in the user namespace
88 from site import _Helper
88 from site import _Helper
89 IP.user_ns['help'] = _Helper()
89 IP.user_ns['help'] = _Helper()
90
90
91 if DEVDEBUG:
91 if DEVDEBUG:
92 # For developer debugging only (global flag)
92 # For developer debugging only (global flag)
93 from IPython import ultraTB
93 from IPython import ultraTB
94 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
94 sys.excepthook = ultraTB.VerboseTB(call_pdb=1)
95 else:
95 else:
96 # IPython itself shouldn't crash. This will produce a detailed
96 # IPython itself shouldn't crash. This will produce a detailed
97 # post-mortem if it does
97 # post-mortem if it does
98 from IPython import CrashHandler
98 from IPython import CrashHandler
99 sys.excepthook = CrashHandler.CrashHandler(IP)
99 sys.excepthook = CrashHandler.CrashHandler(IP)
100
100
101 IP.BANNER_PARTS = ['Python %s\n'
101 IP.BANNER_PARTS = ['Python %s\n'
102 'Type "copyright", "credits" or "license" '
102 'Type "copyright", "credits" or "license" '
103 'for more information.\n'
103 'for more information.\n'
104 % (sys.version.split('\n')[0],),
104 % (sys.version.split('\n')[0],),
105 "IPython %s -- An enhanced Interactive Python."
105 "IPython %s -- An enhanced Interactive Python."
106 % (__version__,),
106 % (__version__,),
107 """? -> Introduction to IPython's features.
107 """? -> Introduction to IPython's features.
108 %magic -> Information about IPython's 'magic' % functions.
108 %magic -> Information about IPython's 'magic' % functions.
109 help -> Python's own help system.
109 help -> Python's own help system.
110 object? -> Details about 'object'. ?object also works, ?? prints more.
110 object? -> Details about 'object'. ?object also works, ?? prints more.
111 """ ]
111 """ ]
112
112
113 IP.usage = interactive_usage
113 IP.usage = interactive_usage
114
114
115 # Platform-dependent suffix and directory names
115 # Platform-dependent suffix and directory names
116 if os.name == 'posix':
116 if os.name == 'posix':
117 rc_suffix = ''
117 rc_suffix = ''
118 ipdir_def = '.ipython'
118 ipdir_def = '.ipython'
119 else:
119 else:
120 rc_suffix = '.ini'
120 rc_suffix = '.ini'
121 ipdir_def = '_ipython'
121 ipdir_def = '_ipython'
122
122
123 # default directory for configuration
123 # default directory for configuration
124 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
124 ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR',
125 os.path.join(IP.home_dir,ipdir_def)))
125 os.path.join(IP.home_dir,ipdir_def)))
126
126
127 # we need the directory where IPython itself is installed
127 # we need the directory where IPython itself is installed
128 import IPython
128 import IPython
129 IPython_dir = os.path.dirname(IPython.__file__)
129 IPython_dir = os.path.dirname(IPython.__file__)
130 del IPython
130 del IPython
131
131
132 #-------------------------------------------------------------------------
132 #-------------------------------------------------------------------------
133 # Command line handling
133 # Command line handling
134
134
135 # Valid command line options (uses DPyGetOpt syntax, like Perl's
135 # Valid command line options (uses DPyGetOpt syntax, like Perl's
136 # GetOpt::Long)
136 # GetOpt::Long)
137
137
138 # Any key not listed here gets deleted even if in the file (like session
138 # Any key not listed here gets deleted even if in the file (like session
139 # or profile). That's deliberate, to maintain the rc namespace clean.
139 # or profile). That's deliberate, to maintain the rc namespace clean.
140
140
141 # Each set of options appears twice: under _conv only the names are
141 # Each set of options appears twice: under _conv only the names are
142 # listed, indicating which type they must be converted to when reading the
142 # listed, indicating which type they must be converted to when reading the
143 # ipythonrc file. And under DPyGetOpt they are listed with the regular
143 # ipythonrc file. And under DPyGetOpt they are listed with the regular
144 # DPyGetOpt syntax (=s,=i,:f,etc).
144 # DPyGetOpt syntax (=s,=i,:f,etc).
145
145
146 # Make sure there's a space before each end of line (they get auto-joined!)
146 # Make sure there's a space before each end of line (they get auto-joined!)
147 cmdline_opts = ('autocall! autoindent! automagic! banner! cache_size|cs=i '
147 cmdline_opts = ('autocall! autoindent! automagic! banner! cache_size|cs=i '
148 'c=s classic|cl color_info! colors=s confirm_exit! '
148 'c=s classic|cl color_info! colors=s confirm_exit! '
149 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
149 'debug! deep_reload! editor=s log|l messages! nosep pdb! '
150 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
150 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s '
151 'quick screen_length|sl=i prompts_pad_left=i '
151 'quick screen_length|sl=i prompts_pad_left=i '
152 'logfile|lf=s logplay|lp=s profile|p=s '
152 'logfile|lf=s logplay|lp=s profile|p=s '
153 'readline! readline_merge_completions! '
153 'readline! readline_merge_completions! '
154 'readline_omit__names! '
154 'readline_omit__names! '
155 'rcfile=s separate_in|si=s separate_out|so=s '
155 'rcfile=s separate_in|si=s separate_out|so=s '
156 'separate_out2|so2=s xmode=s '
156 'separate_out2|so2=s xmode=s '
157 'magic_docstrings system_verbose! '
157 'magic_docstrings system_verbose! '
158 'multi_line_specials!')
158 'multi_line_specials!')
159
159
160 # Options that can *only* appear at the cmd line (not in rcfiles).
160 # Options that can *only* appear at the cmd line (not in rcfiles).
161
161
162 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
162 # The "ignore" option is a kludge so that Emacs buffers don't crash, since
163 # the 'C-c !' command in emacs automatically appends a -i option at the end.
163 # the 'C-c !' command in emacs automatically appends a -i option at the end.
164 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
164 cmdline_only = ('help ignore|i ipythondir=s Version upgrade '
165 'gthread! qthread! wthread! pylab! tk!')
165 'gthread! qthread! wthread! pylab! tk!')
166
166
167 # Build the actual name list to be used by DPyGetOpt
167 # Build the actual name list to be used by DPyGetOpt
168 opts_names = qw(cmdline_opts) + qw(cmdline_only)
168 opts_names = qw(cmdline_opts) + qw(cmdline_only)
169
169
170 # Set sensible command line defaults.
170 # Set sensible command line defaults.
171 # This should have everything from cmdline_opts and cmdline_only
171 # This should have everything from cmdline_opts and cmdline_only
172 opts_def = Struct(autocall = 1,
172 opts_def = Struct(autocall = 1,
173 autoindent=0,
173 autoindent=0,
174 automagic = 1,
174 automagic = 1,
175 banner = 1,
175 banner = 1,
176 cache_size = 1000,
176 cache_size = 1000,
177 c = '',
177 c = '',
178 classic = 0,
178 classic = 0,
179 colors = 'NoColor',
179 colors = 'NoColor',
180 color_info = 0,
180 color_info = 0,
181 confirm_exit = 1,
181 confirm_exit = 1,
182 debug = 0,
182 debug = 0,
183 deep_reload = 0,
183 deep_reload = 0,
184 editor = '0',
184 editor = '0',
185 help = 0,
185 help = 0,
186 ignore = 0,
186 ignore = 0,
187 ipythondir = ipythondir,
187 ipythondir = ipythondir,
188 log = 0,
188 log = 0,
189 logfile = '',
189 logfile = '',
190 logplay = '',
190 logplay = '',
191 multi_line_specials = 1,
191 multi_line_specials = 1,
192 messages = 1,
192 messages = 1,
193 nosep = 0,
193 nosep = 0,
194 pdb = 0,
194 pdb = 0,
195 pprint = 0,
195 pprint = 0,
196 profile = '',
196 profile = '',
197 prompt_in1 = 'In [\\#]:',
197 prompt_in1 = 'In [\\#]: ',
198 prompt_in2 = ' .\\D.:',
198 prompt_in2 = ' .\\D.: ',
199 prompt_out = 'Out[\\#]:',
199 prompt_out = 'Out[\\#]: ',
200 prompts_pad_left = 1,
200 prompts_pad_left = 1,
201 quick = 0,
201 quick = 0,
202 readline = 1,
202 readline = 1,
203 readline_merge_completions = 1,
203 readline_merge_completions = 1,
204 readline_omit__names = 0,
204 readline_omit__names = 0,
205 rcfile = 'ipythonrc' + rc_suffix,
205 rcfile = 'ipythonrc' + rc_suffix,
206 screen_length = 0,
206 screen_length = 0,
207 separate_in = '\n',
207 separate_in = '\n',
208 separate_out = '\n',
208 separate_out = '\n',
209 separate_out2 = '',
209 separate_out2 = '',
210 system_verbose = 0,
210 system_verbose = 0,
211 gthread = 0,
211 gthread = 0,
212 qthread = 0,
212 qthread = 0,
213 wthread = 0,
213 wthread = 0,
214 pylab = 0,
214 pylab = 0,
215 tk = 0,
215 tk = 0,
216 upgrade = 0,
216 upgrade = 0,
217 Version = 0,
217 Version = 0,
218 xmode = 'Verbose',
218 xmode = 'Verbose',
219 magic_docstrings = 0, # undocumented, for doc generation
219 magic_docstrings = 0, # undocumented, for doc generation
220 )
220 )
221
221
222 # Things that will *only* appear in rcfiles (not at the command line).
222 # Things that will *only* appear in rcfiles (not at the command line).
223 # Make sure there's a space before each end of line (they get auto-joined!)
223 # Make sure there's a space before each end of line (they get auto-joined!)
224 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
224 rcfile_opts = { qwflat: 'include import_mod import_all execfile ',
225 qw_lol: 'import_some ',
225 qw_lol: 'import_some ',
226 # for things with embedded whitespace:
226 # for things with embedded whitespace:
227 list_strings:'execute alias readline_parse_and_bind ',
227 list_strings:'execute alias readline_parse_and_bind ',
228 # Regular strings need no conversion:
228 # Regular strings need no conversion:
229 None:'readline_remove_delims ',
229 None:'readline_remove_delims ',
230 }
230 }
231 # Default values for these
231 # Default values for these
232 rc_def = Struct(include = [],
232 rc_def = Struct(include = [],
233 import_mod = [],
233 import_mod = [],
234 import_all = [],
234 import_all = [],
235 import_some = [[]],
235 import_some = [[]],
236 execute = [],
236 execute = [],
237 execfile = [],
237 execfile = [],
238 alias = [],
238 alias = [],
239 readline_parse_and_bind = [],
239 readline_parse_and_bind = [],
240 readline_remove_delims = '',
240 readline_remove_delims = '',
241 )
241 )
242
242
243 # Build the type conversion dictionary from the above tables:
243 # Build the type conversion dictionary from the above tables:
244 typeconv = rcfile_opts.copy()
244 typeconv = rcfile_opts.copy()
245 typeconv.update(optstr2types(cmdline_opts))
245 typeconv.update(optstr2types(cmdline_opts))
246
246
247 # FIXME: the None key appears in both, put that back together by hand. Ugly!
247 # FIXME: the None key appears in both, put that back together by hand. Ugly!
248 typeconv[None] += ' ' + rcfile_opts[None]
248 typeconv[None] += ' ' + rcfile_opts[None]
249
249
250 # Remove quotes at ends of all strings (used to protect spaces)
250 # Remove quotes at ends of all strings (used to protect spaces)
251 typeconv[unquote_ends] = typeconv[None]
251 typeconv[unquote_ends] = typeconv[None]
252 del typeconv[None]
252 del typeconv[None]
253
253
254 # Build the list we'll use to make all config decisions with defaults:
254 # Build the list we'll use to make all config decisions with defaults:
255 opts_all = opts_def.copy()
255 opts_all = opts_def.copy()
256 opts_all.update(rc_def)
256 opts_all.update(rc_def)
257
257
258 # Build conflict resolver for recursive loading of config files:
258 # Build conflict resolver for recursive loading of config files:
259 # - preserve means the outermost file maintains the value, it is not
259 # - preserve means the outermost file maintains the value, it is not
260 # overwritten if an included file has the same key.
260 # overwritten if an included file has the same key.
261 # - add_flip applies + to the two values, so it better make sense to add
261 # - add_flip applies + to the two values, so it better make sense to add
262 # those types of keys. But it flips them first so that things loaded
262 # those types of keys. But it flips them first so that things loaded
263 # deeper in the inclusion chain have lower precedence.
263 # deeper in the inclusion chain have lower precedence.
264 conflict = {'preserve': ' '.join([ typeconv[int],
264 conflict = {'preserve': ' '.join([ typeconv[int],
265 typeconv[unquote_ends] ]),
265 typeconv[unquote_ends] ]),
266 'add_flip': ' '.join([ typeconv[qwflat],
266 'add_flip': ' '.join([ typeconv[qwflat],
267 typeconv[qw_lol],
267 typeconv[qw_lol],
268 typeconv[list_strings] ])
268 typeconv[list_strings] ])
269 }
269 }
270
270
271 # Now actually process the command line
271 # Now actually process the command line
272 getopt = DPyGetOpt.DPyGetOpt()
272 getopt = DPyGetOpt.DPyGetOpt()
273 getopt.setIgnoreCase(0)
273 getopt.setIgnoreCase(0)
274
274
275 getopt.parseConfiguration(opts_names)
275 getopt.parseConfiguration(opts_names)
276
276
277 try:
277 try:
278 getopt.processArguments(argv)
278 getopt.processArguments(argv)
279 except:
279 except:
280 print cmd_line_usage
280 print cmd_line_usage
281 warn('\nError in Arguments: ' + `sys.exc_value`)
281 warn('\nError in Arguments: ' + `sys.exc_value`)
282 sys.exit()
282 sys.exit()
283
283
284 # convert the options dict to a struct for much lighter syntax later
284 # convert the options dict to a struct for much lighter syntax later
285 opts = Struct(getopt.optionValues)
285 opts = Struct(getopt.optionValues)
286 args = getopt.freeValues
286 args = getopt.freeValues
287
287
288 # this is the struct (which has default values at this point) with which
288 # this is the struct (which has default values at this point) with which
289 # we make all decisions:
289 # we make all decisions:
290 opts_all.update(opts)
290 opts_all.update(opts)
291
291
292 # Options that force an immediate exit
292 # Options that force an immediate exit
293 if opts_all.help:
293 if opts_all.help:
294 page(cmd_line_usage)
294 page(cmd_line_usage)
295 sys.exit()
295 sys.exit()
296
296
297 if opts_all.Version:
297 if opts_all.Version:
298 print __version__
298 print __version__
299 sys.exit()
299 sys.exit()
300
300
301 if opts_all.magic_docstrings:
301 if opts_all.magic_docstrings:
302 IP.magic_magic('-latex')
302 IP.magic_magic('-latex')
303 sys.exit()
303 sys.exit()
304
304
305 # Create user config directory if it doesn't exist. This must be done
305 # Create user config directory if it doesn't exist. This must be done
306 # *after* getting the cmd line options.
306 # *after* getting the cmd line options.
307 if not os.path.isdir(opts_all.ipythondir):
307 if not os.path.isdir(opts_all.ipythondir):
308 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
308 IP.user_setup(opts_all.ipythondir,rc_suffix,'install')
309
309
310 # upgrade user config files while preserving a copy of the originals
310 # upgrade user config files while preserving a copy of the originals
311 if opts_all.upgrade:
311 if opts_all.upgrade:
312 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
312 IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade')
313
313
314 # check mutually exclusive options in the *original* command line
314 # check mutually exclusive options in the *original* command line
315 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
315 mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'),
316 qw('classic profile'),qw('classic rcfile')])
316 qw('classic profile'),qw('classic rcfile')])
317
317
318 # default logfilename used when -log is called.
318 # default logfilename used when -log is called.
319 IP.LOGDEF = 'ipython.log'
319 IP.LOGDEF = 'ipython.log'
320
320
321 #---------------------------------------------------------------------------
321 #---------------------------------------------------------------------------
322 # Log replay
322 # Log replay
323
323
324 # if -logplay, we need to 'become' the other session. That basically means
324 # if -logplay, we need to 'become' the other session. That basically means
325 # replacing the current command line environment with that of the old
325 # replacing the current command line environment with that of the old
326 # session and moving on.
326 # session and moving on.
327
327
328 # this is needed so that later we know we're in session reload mode, as
328 # this is needed so that later we know we're in session reload mode, as
329 # opts_all will get overwritten:
329 # opts_all will get overwritten:
330 load_logplay = 0
330 load_logplay = 0
331
331
332 if opts_all.logplay:
332 if opts_all.logplay:
333 load_logplay = opts_all.logplay
333 load_logplay = opts_all.logplay
334 opts_debug_save = opts_all.debug
334 opts_debug_save = opts_all.debug
335 try:
335 try:
336 logplay = open(opts_all.logplay)
336 logplay = open(opts_all.logplay)
337 except IOError:
337 except IOError:
338 if opts_all.debug: IP.InteractiveTB()
338 if opts_all.debug: IP.InteractiveTB()
339 warn('Could not open logplay file '+`opts_all.logplay`)
339 warn('Could not open logplay file '+`opts_all.logplay`)
340 # restore state as if nothing had happened and move on, but make
340 # restore state as if nothing had happened and move on, but make
341 # sure that later we don't try to actually load the session file
341 # sure that later we don't try to actually load the session file
342 logplay = None
342 logplay = None
343 load_logplay = 0
343 load_logplay = 0
344 del opts_all.logplay
344 del opts_all.logplay
345 else:
345 else:
346 try:
346 try:
347 logplay.readline()
347 logplay.readline()
348 logplay.readline();
348 logplay.readline();
349 # this reloads that session's command line
349 # this reloads that session's command line
350 cmd = logplay.readline()[6:]
350 cmd = logplay.readline()[6:]
351 exec cmd
351 exec cmd
352 # restore the true debug flag given so that the process of
352 # restore the true debug flag given so that the process of
353 # session loading itself can be monitored.
353 # session loading itself can be monitored.
354 opts.debug = opts_debug_save
354 opts.debug = opts_debug_save
355 # save the logplay flag so later we don't overwrite the log
355 # save the logplay flag so later we don't overwrite the log
356 opts.logplay = load_logplay
356 opts.logplay = load_logplay
357 # now we must update our own structure with defaults
357 # now we must update our own structure with defaults
358 opts_all.update(opts)
358 opts_all.update(opts)
359 # now load args
359 # now load args
360 cmd = logplay.readline()[6:]
360 cmd = logplay.readline()[6:]
361 exec cmd
361 exec cmd
362 logplay.close()
362 logplay.close()
363 except:
363 except:
364 logplay.close()
364 logplay.close()
365 if opts_all.debug: IP.InteractiveTB()
365 if opts_all.debug: IP.InteractiveTB()
366 warn("Logplay file lacking full configuration information.\n"
366 warn("Logplay file lacking full configuration information.\n"
367 "I'll try to read it, but some things may not work.")
367 "I'll try to read it, but some things may not work.")
368
368
369 #-------------------------------------------------------------------------
369 #-------------------------------------------------------------------------
370 # set up output traps: catch all output from files, being run, modules
370 # set up output traps: catch all output from files, being run, modules
371 # loaded, etc. Then give it to the user in a clean form at the end.
371 # loaded, etc. Then give it to the user in a clean form at the end.
372
372
373 msg_out = 'Output messages. '
373 msg_out = 'Output messages. '
374 msg_err = 'Error messages. '
374 msg_err = 'Error messages. '
375 msg_sep = '\n'
375 msg_sep = '\n'
376 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
376 msg = Struct(config = OutputTrap('Configuration Loader',msg_out,
377 msg_err,msg_sep,debug,
377 msg_err,msg_sep,debug,
378 quiet_out=1),
378 quiet_out=1),
379 user_exec = OutputTrap('User File Execution',msg_out,
379 user_exec = OutputTrap('User File Execution',msg_out,
380 msg_err,msg_sep,debug),
380 msg_err,msg_sep,debug),
381 logplay = OutputTrap('Log Loader',msg_out,
381 logplay = OutputTrap('Log Loader',msg_out,
382 msg_err,msg_sep,debug),
382 msg_err,msg_sep,debug),
383 summary = ''
383 summary = ''
384 )
384 )
385
385
386 #-------------------------------------------------------------------------
386 #-------------------------------------------------------------------------
387 # Process user ipythonrc-type configuration files
387 # Process user ipythonrc-type configuration files
388
388
389 # turn on output trapping and log to msg.config
389 # turn on output trapping and log to msg.config
390 # remember that with debug on, trapping is actually disabled
390 # remember that with debug on, trapping is actually disabled
391 msg.config.trap_all()
391 msg.config.trap_all()
392
392
393 # look for rcfile in current or default directory
393 # look for rcfile in current or default directory
394 try:
394 try:
395 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
395 opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir)
396 except IOError:
396 except IOError:
397 if opts_all.debug: IP.InteractiveTB()
397 if opts_all.debug: IP.InteractiveTB()
398 warn('Configuration file %s not found. Ignoring request.'
398 warn('Configuration file %s not found. Ignoring request.'
399 % (opts_all.rcfile) )
399 % (opts_all.rcfile) )
400
400
401 # 'profiles' are a shorthand notation for config filenames
401 # 'profiles' are a shorthand notation for config filenames
402 if opts_all.profile:
402 if opts_all.profile:
403 try:
403 try:
404 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
404 opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile
405 + rc_suffix,
405 + rc_suffix,
406 opts_all.ipythondir)
406 opts_all.ipythondir)
407 except IOError:
407 except IOError:
408 if opts_all.debug: IP.InteractiveTB()
408 if opts_all.debug: IP.InteractiveTB()
409 opts.profile = '' # remove profile from options if invalid
409 opts.profile = '' # remove profile from options if invalid
410 warn('Profile configuration file %s not found. Ignoring request.'
410 warn('Profile configuration file %s not found. Ignoring request.'
411 % (opts_all.profile) )
411 % (opts_all.profile) )
412
412
413 # load the config file
413 # load the config file
414 rcfiledata = None
414 rcfiledata = None
415 if opts_all.quick:
415 if opts_all.quick:
416 print 'Launching IPython in quick mode. No config file read.'
416 print 'Launching IPython in quick mode. No config file read.'
417 elif opts_all.classic:
417 elif opts_all.classic:
418 print 'Launching IPython in classic mode. No config file read.'
418 print 'Launching IPython in classic mode. No config file read.'
419 elif opts_all.rcfile:
419 elif opts_all.rcfile:
420 try:
420 try:
421 cfg_loader = ConfigLoader(conflict)
421 cfg_loader = ConfigLoader(conflict)
422 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
422 rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv,
423 'include',opts_all.ipythondir,
423 'include',opts_all.ipythondir,
424 purge = 1,
424 purge = 1,
425 unique = conflict['preserve'])
425 unique = conflict['preserve'])
426 except:
426 except:
427 IP.InteractiveTB()
427 IP.InteractiveTB()
428 warn('Problems loading configuration file '+
428 warn('Problems loading configuration file '+
429 `opts_all.rcfile`+
429 `opts_all.rcfile`+
430 '\nStarting with default -bare bones- configuration.')
430 '\nStarting with default -bare bones- configuration.')
431 else:
431 else:
432 warn('No valid configuration file found in either currrent directory\n'+
432 warn('No valid configuration file found in either currrent directory\n'+
433 'or in the IPython config. directory: '+`opts_all.ipythondir`+
433 'or in the IPython config. directory: '+`opts_all.ipythondir`+
434 '\nProceeding with internal defaults.')
434 '\nProceeding with internal defaults.')
435
435
436 #------------------------------------------------------------------------
436 #------------------------------------------------------------------------
437 # Set exception handlers in mode requested by user.
437 # Set exception handlers in mode requested by user.
438 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
438 otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode
439 IP.magic_xmode(opts_all.xmode)
439 IP.magic_xmode(opts_all.xmode)
440 otrap.release_out()
440 otrap.release_out()
441
441
442 #------------------------------------------------------------------------
442 #------------------------------------------------------------------------
443 # Execute user config
443 # Execute user config
444
444
445 # first, create a valid config structure with the right precedence order:
445 # first, create a valid config structure with the right precedence order:
446 # defaults < rcfile < command line
446 # defaults < rcfile < command line
447 IP.rc = rc_def.copy()
447 IP.rc = rc_def.copy()
448 IP.rc.update(opts_def)
448 IP.rc.update(opts_def)
449 if rcfiledata:
449 if rcfiledata:
450 # now we can update
450 # now we can update
451 IP.rc.update(rcfiledata)
451 IP.rc.update(rcfiledata)
452 IP.rc.update(opts)
452 IP.rc.update(opts)
453 IP.rc.update(rc_override)
453 IP.rc.update(rc_override)
454
454
455 # Store the original cmd line for reference:
455 # Store the original cmd line for reference:
456 IP.rc.opts = opts
456 IP.rc.opts = opts
457 IP.rc.args = args
457 IP.rc.args = args
458
458
459 # create a *runtime* Struct like rc for holding parameters which may be
459 # create a *runtime* Struct like rc for holding parameters which may be
460 # created and/or modified by runtime user extensions.
460 # created and/or modified by runtime user extensions.
461 IP.runtime_rc = Struct()
461 IP.runtime_rc = Struct()
462
462
463 # from this point on, all config should be handled through IP.rc,
463 # from this point on, all config should be handled through IP.rc,
464 # opts* shouldn't be used anymore.
464 # opts* shouldn't be used anymore.
465
465
466 # add personal .ipython dir to sys.path so that users can put things in
466 # add personal .ipython dir to sys.path so that users can put things in
467 # there for customization
467 # there for customization
468 sys.path.append(IP.rc.ipythondir)
468 sys.path.append(IP.rc.ipythondir)
469 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
469 sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran
470
470
471 # update IP.rc with some special things that need manual
471 # update IP.rc with some special things that need manual
472 # tweaks. Basically options which affect other options. I guess this
472 # tweaks. Basically options which affect other options. I guess this
473 # should just be written so that options are fully orthogonal and we
473 # should just be written so that options are fully orthogonal and we
474 # wouldn't worry about this stuff!
474 # wouldn't worry about this stuff!
475
475
476 if IP.rc.classic:
476 if IP.rc.classic:
477 IP.rc.quick = 1
477 IP.rc.quick = 1
478 IP.rc.cache_size = 0
478 IP.rc.cache_size = 0
479 IP.rc.pprint = 0
479 IP.rc.pprint = 0
480 IP.rc.prompt_in1 = '>>> '
480 IP.rc.prompt_in1 = '>>> '
481 IP.rc.prompt_in2 = '... '
481 IP.rc.prompt_in2 = '... '
482 IP.rc.prompt_out = ''
482 IP.rc.prompt_out = ''
483 IP.rc.separate_in = IP.rc.separate_out = IP.rc.separate_out2 = '0'
483 IP.rc.separate_in = IP.rc.separate_out = IP.rc.separate_out2 = '0'
484 IP.rc.colors = 'NoColor'
484 IP.rc.colors = 'NoColor'
485 IP.rc.xmode = 'Plain'
485 IP.rc.xmode = 'Plain'
486
486
487 # configure readline
487 # configure readline
488 # Define the history file for saving commands in between sessions
488 # Define the history file for saving commands in between sessions
489 if IP.rc.profile:
489 if IP.rc.profile:
490 histfname = 'history-%s' % IP.rc.profile
490 histfname = 'history-%s' % IP.rc.profile
491 else:
491 else:
492 histfname = 'history'
492 histfname = 'history'
493 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
493 IP.histfile = os.path.join(opts_all.ipythondir,histfname)
494 # Load readline proper
494 # Load readline proper
495 if IP.rc.readline:
495 if IP.rc.readline:
496 IP.init_readline()
496 IP.init_readline()
497
497
498 # update exception handlers with rc file status
498 # update exception handlers with rc file status
499 otrap.trap_out() # I don't want these messages ever.
499 otrap.trap_out() # I don't want these messages ever.
500 IP.magic_xmode(IP.rc.xmode)
500 IP.magic_xmode(IP.rc.xmode)
501 otrap.release_out()
501 otrap.release_out()
502
502
503 # activate logging if requested and not reloading a log
503 # activate logging if requested and not reloading a log
504 if IP.rc.logplay:
504 if IP.rc.logplay:
505 IP.magic_logstart(IP.rc.logplay + ' append')
505 IP.magic_logstart(IP.rc.logplay + ' append')
506 elif IP.rc.logfile:
506 elif IP.rc.logfile:
507 IP.magic_logstart(IP.rc.logfile)
507 IP.magic_logstart(IP.rc.logfile)
508 elif IP.rc.log:
508 elif IP.rc.log:
509 IP.magic_logstart()
509 IP.magic_logstart()
510
510
511 # find user editor so that it we don't have to look it up constantly
511 # find user editor so that it we don't have to look it up constantly
512 if IP.rc.editor.strip()=='0':
512 if IP.rc.editor.strip()=='0':
513 try:
513 try:
514 ed = os.environ['EDITOR']
514 ed = os.environ['EDITOR']
515 except KeyError:
515 except KeyError:
516 if os.name == 'posix':
516 if os.name == 'posix':
517 ed = 'vi' # the only one guaranteed to be there!
517 ed = 'vi' # the only one guaranteed to be there!
518 else:
518 else:
519 ed = 'notepad' # same in Windows!
519 ed = 'notepad' # same in Windows!
520 IP.rc.editor = ed
520 IP.rc.editor = ed
521
521
522 # Recursive reload
522 # Recursive reload
523 try:
523 try:
524 from IPython import deep_reload
524 from IPython import deep_reload
525 if IP.rc.deep_reload:
525 if IP.rc.deep_reload:
526 __builtin__.reload = deep_reload.reload
526 __builtin__.reload = deep_reload.reload
527 else:
527 else:
528 __builtin__.dreload = deep_reload.reload
528 __builtin__.dreload = deep_reload.reload
529 del deep_reload
529 del deep_reload
530 except ImportError:
530 except ImportError:
531 pass
531 pass
532
532
533 # Save the current state of our namespace so that the interactive shell
533 # Save the current state of our namespace so that the interactive shell
534 # can later know which variables have been created by us from config files
534 # can later know which variables have been created by us from config files
535 # and loading. This way, loading a file (in any way) is treated just like
535 # and loading. This way, loading a file (in any way) is treated just like
536 # defining things on the command line, and %who works as expected.
536 # defining things on the command line, and %who works as expected.
537
537
538 # DON'T do anything that affects the namespace beyond this point!
538 # DON'T do anything that affects the namespace beyond this point!
539 IP.internal_ns = __main__.__dict__.copy()
539 IP.internal_ns = __main__.__dict__.copy()
540
540
541 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
541 #IP.internal_ns.update(locals()) # so our stuff doesn't show up in %who
542
542
543 # Now run through the different sections of the users's config
543 # Now run through the different sections of the users's config
544 if IP.rc.debug:
544 if IP.rc.debug:
545 print 'Trying to execute the following configuration structure:'
545 print 'Trying to execute the following configuration structure:'
546 print '(Things listed first are deeper in the inclusion tree and get'
546 print '(Things listed first are deeper in the inclusion tree and get'
547 print 'loaded first).\n'
547 print 'loaded first).\n'
548 pprint(IP.rc.__dict__)
548 pprint(IP.rc.__dict__)
549
549
550 for mod in IP.rc.import_mod:
550 for mod in IP.rc.import_mod:
551 try:
551 try:
552 exec 'import '+mod in IP.user_ns
552 exec 'import '+mod in IP.user_ns
553 except :
553 except :
554 IP.InteractiveTB()
554 IP.InteractiveTB()
555 import_fail_info(mod)
555 import_fail_info(mod)
556
556
557 for mod_fn in IP.rc.import_some:
557 for mod_fn in IP.rc.import_some:
558 if mod_fn == []: break
558 if mod_fn == []: break
559 mod,fn = mod_fn[0],','.join(mod_fn[1:])
559 mod,fn = mod_fn[0],','.join(mod_fn[1:])
560 try:
560 try:
561 exec 'from '+mod+' import '+fn in IP.user_ns
561 exec 'from '+mod+' import '+fn in IP.user_ns
562 except :
562 except :
563 IP.InteractiveTB()
563 IP.InteractiveTB()
564 import_fail_info(mod,fn)
564 import_fail_info(mod,fn)
565
565
566 for mod in IP.rc.import_all:
566 for mod in IP.rc.import_all:
567 try:
567 try:
568 exec 'from '+mod+' import *' in IP.user_ns
568 exec 'from '+mod+' import *' in IP.user_ns
569 except :
569 except :
570 IP.InteractiveTB()
570 IP.InteractiveTB()
571 import_fail_info(mod)
571 import_fail_info(mod)
572
572
573 for code in IP.rc.execute:
573 for code in IP.rc.execute:
574 try:
574 try:
575 exec code in IP.user_ns
575 exec code in IP.user_ns
576 except:
576 except:
577 IP.InteractiveTB()
577 IP.InteractiveTB()
578 warn('Failure executing code: ' + `code`)
578 warn('Failure executing code: ' + `code`)
579
579
580 # Execute the files the user wants in ipythonrc
580 # Execute the files the user wants in ipythonrc
581 for file in IP.rc.execfile:
581 for file in IP.rc.execfile:
582 try:
582 try:
583 file = filefind(file,sys.path+[IPython_dir])
583 file = filefind(file,sys.path+[IPython_dir])
584 except IOError:
584 except IOError:
585 warn(itpl('File $file not found. Skipping it.'))
585 warn(itpl('File $file not found. Skipping it.'))
586 else:
586 else:
587 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
587 IP.safe_execfile(os.path.expanduser(file),IP.user_ns)
588
588
589 # Load user aliases
589 # Load user aliases
590 for alias in IP.rc.alias:
590 for alias in IP.rc.alias:
591 IP.magic_alias(alias)
591 IP.magic_alias(alias)
592
592
593 # release stdout and stderr and save config log into a global summary
593 # release stdout and stderr and save config log into a global summary
594 msg.config.release_all()
594 msg.config.release_all()
595 if IP.rc.messages:
595 if IP.rc.messages:
596 msg.summary += msg.config.summary_all()
596 msg.summary += msg.config.summary_all()
597
597
598 #------------------------------------------------------------------------
598 #------------------------------------------------------------------------
599 # Setup interactive session
599 # Setup interactive session
600
600
601 # Now we should be fully configured. We can then execute files or load
601 # Now we should be fully configured. We can then execute files or load
602 # things only needed for interactive use. Then we'll open the shell.
602 # things only needed for interactive use. Then we'll open the shell.
603
603
604 # Take a snapshot of the user namespace before opening the shell. That way
604 # Take a snapshot of the user namespace before opening the shell. That way
605 # we'll be able to identify which things were interactively defined and
605 # we'll be able to identify which things were interactively defined and
606 # which were defined through config files.
606 # which were defined through config files.
607 IP.user_config_ns = IP.user_ns.copy()
607 IP.user_config_ns = IP.user_ns.copy()
608
608
609 # Force reading a file as if it were a session log. Slower but safer.
609 # Force reading a file as if it were a session log. Slower but safer.
610 if load_logplay:
610 if load_logplay:
611 print 'Replaying log...'
611 print 'Replaying log...'
612 try:
612 try:
613 if IP.rc.debug:
613 if IP.rc.debug:
614 logplay_quiet = 0
614 logplay_quiet = 0
615 else:
615 else:
616 logplay_quiet = 1
616 logplay_quiet = 1
617
617
618 msg.logplay.trap_all()
618 msg.logplay.trap_all()
619 IP.safe_execfile(load_logplay,IP.user_ns,
619 IP.safe_execfile(load_logplay,IP.user_ns,
620 islog = 1, quiet = logplay_quiet)
620 islog = 1, quiet = logplay_quiet)
621 msg.logplay.release_all()
621 msg.logplay.release_all()
622 if IP.rc.messages:
622 if IP.rc.messages:
623 msg.summary += msg.logplay.summary_all()
623 msg.summary += msg.logplay.summary_all()
624 except:
624 except:
625 warn('Problems replaying logfile %s.' % load_logplay)
625 warn('Problems replaying logfile %s.' % load_logplay)
626 IP.InteractiveTB()
626 IP.InteractiveTB()
627
627
628 # Load remaining files in command line
628 # Load remaining files in command line
629 msg.user_exec.trap_all()
629 msg.user_exec.trap_all()
630
630
631 # Do NOT execute files named in the command line as scripts to be loaded
631 # Do NOT execute files named in the command line as scripts to be loaded
632 # by embedded instances. Doing so has the potential for an infinite
632 # by embedded instances. Doing so has the potential for an infinite
633 # recursion if there are exceptions thrown in the process.
633 # recursion if there are exceptions thrown in the process.
634
634
635 # XXX FIXME: the execution of user files should be moved out to after
635 # XXX FIXME: the execution of user files should be moved out to after
636 # ipython is fully initialized, just as if they were run via %run at the
636 # ipython is fully initialized, just as if they were run via %run at the
637 # ipython prompt. This would also give them the benefit of ipython's
637 # ipython prompt. This would also give them the benefit of ipython's
638 # nice tracebacks.
638 # nice tracebacks.
639
639
640 if not embedded and IP.rc.args:
640 if not embedded and IP.rc.args:
641 name_save = IP.user_ns['__name__']
641 name_save = IP.user_ns['__name__']
642 IP.user_ns['__name__'] = '__main__'
642 IP.user_ns['__name__'] = '__main__'
643 try:
643 try:
644 # Set our own excepthook in case the user code tries to call it
644 # Set our own excepthook in case the user code tries to call it
645 # directly. This prevents triggering the IPython crash handler.
645 # directly. This prevents triggering the IPython crash handler.
646 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
646 old_excepthook,sys.excepthook = sys.excepthook, IP.excepthook
647 for run in args:
647 for run in args:
648 IP.safe_execfile(run,IP.user_ns)
648 IP.safe_execfile(run,IP.user_ns)
649 finally:
649 finally:
650 # Reset our crash handler in place
650 # Reset our crash handler in place
651 sys.excepthook = old_excepthook
651 sys.excepthook = old_excepthook
652
652
653 IP.user_ns['__name__'] = name_save
653 IP.user_ns['__name__'] = name_save
654
654
655 msg.user_exec.release_all()
655 msg.user_exec.release_all()
656 if IP.rc.messages:
656 if IP.rc.messages:
657 msg.summary += msg.user_exec.summary_all()
657 msg.summary += msg.user_exec.summary_all()
658
658
659 # since we can't specify a null string on the cmd line, 0 is the equivalent:
659 # since we can't specify a null string on the cmd line, 0 is the equivalent:
660 if IP.rc.nosep:
660 if IP.rc.nosep:
661 IP.rc.separate_in = IP.rc.separate_out = IP.rc.separate_out2 = '0'
661 IP.rc.separate_in = IP.rc.separate_out = IP.rc.separate_out2 = '0'
662 if IP.rc.separate_in == '0': IP.rc.separate_in = ''
662 if IP.rc.separate_in == '0': IP.rc.separate_in = ''
663 if IP.rc.separate_out == '0': IP.rc.separate_out = ''
663 if IP.rc.separate_out == '0': IP.rc.separate_out = ''
664 if IP.rc.separate_out2 == '0': IP.rc.separate_out2 = ''
664 if IP.rc.separate_out2 == '0': IP.rc.separate_out2 = ''
665 IP.rc.separate_in = IP.rc.separate_in.replace('\\n','\n')
665 IP.rc.separate_in = IP.rc.separate_in.replace('\\n','\n')
666 IP.rc.separate_out = IP.rc.separate_out.replace('\\n','\n')
666 IP.rc.separate_out = IP.rc.separate_out.replace('\\n','\n')
667 IP.rc.separate_out2 = IP.rc.separate_out2.replace('\\n','\n')
667 IP.rc.separate_out2 = IP.rc.separate_out2.replace('\\n','\n')
668
668
669 # Determine how many lines at the bottom of the screen are needed for
669 # Determine how many lines at the bottom of the screen are needed for
670 # showing prompts, so we can know wheter long strings are to be printed or
670 # showing prompts, so we can know wheter long strings are to be printed or
671 # paged:
671 # paged:
672 num_lines_bot = IP.rc.separate_in.count('\n')+1
672 num_lines_bot = IP.rc.separate_in.count('\n')+1
673 IP.rc.screen_length = IP.rc.screen_length - num_lines_bot
673 IP.rc.screen_length = IP.rc.screen_length - num_lines_bot
674 # Initialize cache, set in/out prompts and printing system
674 # Initialize cache, set in/out prompts and printing system
675 IP.outputcache = CachedOutput(IP.rc.cache_size,
675 IP.outputcache = CachedOutput(IP.rc.cache_size,
676 IP.rc.pprint,
676 IP.rc.pprint,
677 input_sep = IP.rc.separate_in,
677 input_sep = IP.rc.separate_in,
678 output_sep = IP.rc.separate_out,
678 output_sep = IP.rc.separate_out,
679 output_sep2 = IP.rc.separate_out2,
679 output_sep2 = IP.rc.separate_out2,
680 ps1 = IP.rc.prompt_in1,
680 ps1 = IP.rc.prompt_in1,
681 ps2 = IP.rc.prompt_in2,
681 ps2 = IP.rc.prompt_in2,
682 ps_out = IP.rc.prompt_out,
682 ps_out = IP.rc.prompt_out,
683 user_ns = IP.user_ns,
683 user_ns = IP.user_ns,
684 input_hist = IP.input_hist,
684 input_hist = IP.input_hist,
685 pad_left = IP.rc.prompts_pad_left)
685 pad_left = IP.rc.prompts_pad_left)
686
686
687 # Set user colors (don't do it in the constructor above so that it doesn't
687 # Set user colors (don't do it in the constructor above so that it doesn't
688 # crash if colors option is invalid)
688 # crash if colors option is invalid)
689 IP.magic_colors(IP.rc.colors)
689 IP.magic_colors(IP.rc.colors)
690
690
691 # user may have over-ridden the default print hook:
691 # user may have over-ridden the default print hook:
692 try:
692 try:
693 IP.outputcache.__class__.display = IP.hooks.display
693 IP.outputcache.__class__.display = IP.hooks.display
694 except AttributeError:
694 except AttributeError:
695 pass
695 pass
696
696
697 # Set calling of pdb on exceptions
697 # Set calling of pdb on exceptions
698 IP.InteractiveTB.call_pdb = IP.rc.pdb
698 IP.InteractiveTB.call_pdb = IP.rc.pdb
699
699
700 # I don't like assigning globally to sys, because it means when embedding
700 # I don't like assigning globally to sys, because it means when embedding
701 # instances, each embedded instance overrides the previous choice. But
701 # instances, each embedded instance overrides the previous choice. But
702 # sys.displayhook seems to be called internally by exec, so I don't see a
702 # sys.displayhook seems to be called internally by exec, so I don't see a
703 # way around it.
703 # way around it.
704 sys.displayhook = IP.outputcache
704 sys.displayhook = IP.outputcache
705
705
706 # we need to know globally if we're caching i/o or not
706 # we need to know globally if we're caching i/o or not
707 IP.do_full_cache = IP.outputcache.do_full_cache
707 IP.do_full_cache = IP.outputcache.do_full_cache
708
708
709 # configure startup banner
709 # configure startup banner
710 if IP.rc.c: # regular python doesn't print the banner with -c
710 if IP.rc.c: # regular python doesn't print the banner with -c
711 IP.rc.banner = 0
711 IP.rc.banner = 0
712 if IP.rc.banner:
712 if IP.rc.banner:
713 IP.BANNER = '\n'.join(IP.BANNER_PARTS)
713 IP.BANNER = '\n'.join(IP.BANNER_PARTS)
714 else:
714 else:
715 IP.BANNER = ''
715 IP.BANNER = ''
716
716
717 if IP.rc.profile: IP.BANNER += '\nIPython profile: '+IP.rc.profile+'\n'
717 if IP.rc.profile: IP.BANNER += '\nIPython profile: '+IP.rc.profile+'\n'
718
718
719 # add message log (possibly empty)
719 # add message log (possibly empty)
720 IP.BANNER += msg.summary
720 IP.BANNER += msg.summary
721
721
722 IP.post_config_initialization()
722 IP.post_config_initialization()
723
723
724 return IP
724 return IP
725 #************************ end of file <ipmaker.py> **************************
725 #************************ end of file <ipmaker.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