##// END OF EJS Templates
Merge with upstream.
gvaroquaux -
r1474:a0ad5ffc merge
parent child Browse files
Show More
@@ -1,1235 +1,1236 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 3024 2008-02-07 15:34:42Z darren.dale $"""
7 $Id: Shell.py 3024 2008-02-07 15:34:42Z darren.dale $"""
8
8
9 #*****************************************************************************
9 #*****************************************************************************
10 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
10 # Copyright (C) 2001-2006 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 # Stdlib imports
21 # Stdlib imports
22 import __builtin__
22 import __builtin__
23 import __main__
23 import __main__
24 import Queue
24 import Queue
25 import inspect
25 import inspect
26 import os
26 import os
27 import sys
27 import sys
28 import thread
28 import thread
29 import threading
29 import threading
30 import time
30 import time
31
31
32 from signal import signal, SIGINT
32 from signal import signal, SIGINT
33
33
34 try:
34 try:
35 import ctypes
35 import ctypes
36 HAS_CTYPES = True
36 HAS_CTYPES = True
37 except ImportError:
37 except ImportError:
38 HAS_CTYPES = False
38 HAS_CTYPES = False
39
39
40 # IPython imports
40 # IPython imports
41 import IPython
41 import IPython
42 from IPython import ultraTB, ipapi
42 from IPython import ultraTB, ipapi
43 from IPython.genutils import Term,warn,error,flag_calls, ask_yes_no
43 from IPython.genutils import Term,warn,error,flag_calls, ask_yes_no
44 from IPython.iplib import InteractiveShell
44 from IPython.iplib import InteractiveShell
45 from IPython.ipmaker import make_IPython
45 from IPython.ipmaker import make_IPython
46 from IPython.Magic import Magic
46 from IPython.Magic import Magic
47 from IPython.ipstruct import Struct
47 from IPython.ipstruct import Struct
48
48
49 # Globals
49 # Globals
50 # global flag to pass around information about Ctrl-C without exceptions
50 # global flag to pass around information about Ctrl-C without exceptions
51 KBINT = False
51 KBINT = False
52
52
53 # global flag to turn on/off Tk support.
53 # global flag to turn on/off Tk support.
54 USE_TK = False
54 USE_TK = False
55
55
56 # ID for the main thread, used for cross-thread exceptions
56 # ID for the main thread, used for cross-thread exceptions
57 MAIN_THREAD_ID = thread.get_ident()
57 MAIN_THREAD_ID = thread.get_ident()
58
58
59 # Tag when runcode() is active, for exception handling
59 # Tag when runcode() is active, for exception handling
60 CODE_RUN = None
60 CODE_RUN = None
61
61
62 # Default timeout for waiting for multithreaded shells (in seconds)
62 # Default timeout for waiting for multithreaded shells (in seconds)
63 GUI_TIMEOUT = 10
63 GUI_TIMEOUT = 10
64
64
65 #-----------------------------------------------------------------------------
65 #-----------------------------------------------------------------------------
66 # This class is trivial now, but I want to have it in to publish a clean
66 # This class is trivial now, but I want to have it in to publish a clean
67 # interface. Later when the internals are reorganized, code that uses this
67 # interface. Later when the internals are reorganized, code that uses this
68 # shouldn't have to change.
68 # shouldn't have to change.
69
69
70 class IPShell:
70 class IPShell:
71 """Create an IPython instance."""
71 """Create an IPython instance."""
72
72
73 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
73 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
74 debug=1,shell_class=InteractiveShell):
74 debug=1,shell_class=InteractiveShell):
75 self.IP = make_IPython(argv,user_ns=user_ns,
75 self.IP = make_IPython(argv,user_ns=user_ns,
76 user_global_ns=user_global_ns,
76 user_global_ns=user_global_ns,
77 debug=debug,shell_class=shell_class)
77 debug=debug,shell_class=shell_class)
78
78
79 def mainloop(self,sys_exit=0,banner=None):
79 def mainloop(self,sys_exit=0,banner=None):
80 self.IP.mainloop(banner)
80 self.IP.mainloop(banner)
81 if sys_exit:
81 if sys_exit:
82 sys.exit()
82 sys.exit()
83
83
84 #-----------------------------------------------------------------------------
84 #-----------------------------------------------------------------------------
85 def kill_embedded(self,parameter_s=''):
85 def kill_embedded(self,parameter_s=''):
86 """%kill_embedded : deactivate for good the current embedded IPython.
86 """%kill_embedded : deactivate for good the current embedded IPython.
87
87
88 This function (after asking for confirmation) sets an internal flag so that
88 This function (after asking for confirmation) sets an internal flag so that
89 an embedded IPython will never activate again. This is useful to
89 an embedded IPython will never activate again. This is useful to
90 permanently disable a shell that is being called inside a loop: once you've
90 permanently disable a shell that is being called inside a loop: once you've
91 figured out what you needed from it, you may then kill it and the program
91 figured out what you needed from it, you may then kill it and the program
92 will then continue to run without the interactive shell interfering again.
92 will then continue to run without the interactive shell interfering again.
93 """
93 """
94
94
95 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
95 kill = ask_yes_no("Are you sure you want to kill this embedded instance "
96 "(y/n)? [y/N] ",'n')
96 "(y/n)? [y/N] ",'n')
97 if kill:
97 if kill:
98 self.shell.embedded_active = False
98 self.shell.embedded_active = False
99 print "This embedded IPython will not reactivate anymore once you exit."
99 print "This embedded IPython will not reactivate anymore once you exit."
100
100
101 class IPShellEmbed:
101 class IPShellEmbed:
102 """Allow embedding an IPython shell into a running program.
102 """Allow embedding an IPython shell into a running program.
103
103
104 Instances of this class are callable, with the __call__ method being an
104 Instances of this class are callable, with the __call__ method being an
105 alias to the embed() method of an InteractiveShell instance.
105 alias to the embed() method of an InteractiveShell instance.
106
106
107 Usage (see also the example-embed.py file for a running example):
107 Usage (see also the example-embed.py file for a running example):
108
108
109 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
109 ipshell = IPShellEmbed([argv,banner,exit_msg,rc_override])
110
110
111 - argv: list containing valid command-line options for IPython, as they
111 - argv: list containing valid command-line options for IPython, as they
112 would appear in sys.argv[1:].
112 would appear in sys.argv[1:].
113
113
114 For example, the following command-line options:
114 For example, the following command-line options:
115
115
116 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
116 $ ipython -prompt_in1 'Input <\\#>' -colors LightBG
117
117
118 would be passed in the argv list as:
118 would be passed in the argv list as:
119
119
120 ['-prompt_in1','Input <\\#>','-colors','LightBG']
120 ['-prompt_in1','Input <\\#>','-colors','LightBG']
121
121
122 - banner: string which gets printed every time the interpreter starts.
122 - banner: string which gets printed every time the interpreter starts.
123
123
124 - exit_msg: string which gets printed every time the interpreter exits.
124 - exit_msg: string which gets printed every time the interpreter exits.
125
125
126 - rc_override: a dict or Struct of configuration options such as those
126 - rc_override: a dict or Struct of configuration options such as those
127 used by IPython. These options are read from your ~/.ipython/ipythonrc
127 used by IPython. These options are read from your ~/.ipython/ipythonrc
128 file when the Shell object is created. Passing an explicit rc_override
128 file when the Shell object is created. Passing an explicit rc_override
129 dict with any options you want allows you to override those values at
129 dict with any options you want allows you to override those values at
130 creation time without having to modify the file. This way you can create
130 creation time without having to modify the file. This way you can create
131 embeddable instances configured in any way you want without editing any
131 embeddable instances configured in any way you want without editing any
132 global files (thus keeping your interactive IPython configuration
132 global files (thus keeping your interactive IPython configuration
133 unchanged).
133 unchanged).
134
134
135 Then the ipshell instance can be called anywhere inside your code:
135 Then the ipshell instance can be called anywhere inside your code:
136
136
137 ipshell(header='') -> Opens up an IPython shell.
137 ipshell(header='') -> Opens up an IPython shell.
138
138
139 - header: string printed by the IPython shell upon startup. This can let
139 - header: string printed by the IPython shell upon startup. This can let
140 you know where in your code you are when dropping into the shell. Note
140 you know where in your code you are when dropping into the shell. Note
141 that 'banner' gets prepended to all calls, so header is used for
141 that 'banner' gets prepended to all calls, so header is used for
142 location-specific information.
142 location-specific information.
143
143
144 For more details, see the __call__ method below.
144 For more details, see the __call__ method below.
145
145
146 When the IPython shell is exited with Ctrl-D, normal program execution
146 When the IPython shell is exited with Ctrl-D, normal program execution
147 resumes.
147 resumes.
148
148
149 This functionality was inspired by a posting on comp.lang.python by cmkl
149 This functionality was inspired by a posting on comp.lang.python by cmkl
150 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
150 <cmkleffner@gmx.de> on Dec. 06/01 concerning similar uses of pyrepl, and
151 by the IDL stop/continue commands."""
151 by the IDL stop/continue commands."""
152
152
153 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None,
153 def __init__(self,argv=None,banner='',exit_msg=None,rc_override=None,
154 user_ns=None):
154 user_ns=None):
155 """Note that argv here is a string, NOT a list."""
155 """Note that argv here is a string, NOT a list."""
156 self.set_banner(banner)
156 self.set_banner(banner)
157 self.set_exit_msg(exit_msg)
157 self.set_exit_msg(exit_msg)
158 self.set_dummy_mode(0)
158 self.set_dummy_mode(0)
159
159
160 # sys.displayhook is a global, we need to save the user's original
160 # sys.displayhook is a global, we need to save the user's original
161 # Don't rely on __displayhook__, as the user may have changed that.
161 # Don't rely on __displayhook__, as the user may have changed that.
162 self.sys_displayhook_ori = sys.displayhook
162 self.sys_displayhook_ori = sys.displayhook
163
163
164 # save readline completer status
164 # save readline completer status
165 try:
165 try:
166 #print 'Save completer',sys.ipcompleter # dbg
166 #print 'Save completer',sys.ipcompleter # dbg
167 self.sys_ipcompleter_ori = sys.ipcompleter
167 self.sys_ipcompleter_ori = sys.ipcompleter
168 except:
168 except:
169 pass # not nested with IPython
169 pass # not nested with IPython
170
170
171 self.IP = make_IPython(argv,rc_override=rc_override,
171 self.IP = make_IPython(argv,rc_override=rc_override,
172 embedded=True,
172 embedded=True,
173 user_ns=user_ns)
173 user_ns=user_ns)
174
174
175 ip = ipapi.IPApi(self.IP)
175 ip = ipapi.IPApi(self.IP)
176 ip.expose_magic("kill_embedded",kill_embedded)
176 ip.expose_magic("kill_embedded",kill_embedded)
177
177
178 # copy our own displayhook also
178 # copy our own displayhook also
179 self.sys_displayhook_embed = sys.displayhook
179 self.sys_displayhook_embed = sys.displayhook
180 # and leave the system's display hook clean
180 # and leave the system's display hook clean
181 sys.displayhook = self.sys_displayhook_ori
181 sys.displayhook = self.sys_displayhook_ori
182 # don't use the ipython crash handler so that user exceptions aren't
182 # don't use the ipython crash handler so that user exceptions aren't
183 # trapped
183 # trapped
184 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
184 sys.excepthook = ultraTB.FormattedTB(color_scheme = self.IP.rc.colors,
185 mode = self.IP.rc.xmode,
185 mode = self.IP.rc.xmode,
186 call_pdb = self.IP.rc.pdb)
186 call_pdb = self.IP.rc.pdb)
187 self.restore_system_completer()
187 self.restore_system_completer()
188
188
189 def restore_system_completer(self):
189 def restore_system_completer(self):
190 """Restores the readline completer which was in place.
190 """Restores the readline completer which was in place.
191
191
192 This allows embedded IPython within IPython not to disrupt the
192 This allows embedded IPython within IPython not to disrupt the
193 parent's completion.
193 parent's completion.
194 """
194 """
195
195
196 try:
196 try:
197 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
197 self.IP.readline.set_completer(self.sys_ipcompleter_ori)
198 sys.ipcompleter = self.sys_ipcompleter_ori
198 sys.ipcompleter = self.sys_ipcompleter_ori
199 except:
199 except:
200 pass
200 pass
201
201
202 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
202 def __call__(self,header='',local_ns=None,global_ns=None,dummy=None):
203 """Activate the interactive interpreter.
203 """Activate the interactive interpreter.
204
204
205 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
205 __call__(self,header='',local_ns=None,global_ns,dummy=None) -> Start
206 the interpreter shell with the given local and global namespaces, and
206 the interpreter shell with the given local and global namespaces, and
207 optionally print a header string at startup.
207 optionally print a header string at startup.
208
208
209 The shell can be globally activated/deactivated using the
209 The shell can be globally activated/deactivated using the
210 set/get_dummy_mode methods. This allows you to turn off a shell used
210 set/get_dummy_mode methods. This allows you to turn off a shell used
211 for debugging globally.
211 for debugging globally.
212
212
213 However, *each* time you call the shell you can override the current
213 However, *each* time you call the shell you can override the current
214 state of dummy_mode with the optional keyword parameter 'dummy'. For
214 state of dummy_mode with the optional keyword parameter 'dummy'. For
215 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
215 example, if you set dummy mode on with IPShell.set_dummy_mode(1), you
216 can still have a specific call work by making it as IPShell(dummy=0).
216 can still have a specific call work by making it as IPShell(dummy=0).
217
217
218 The optional keyword parameter dummy controls whether the call
218 The optional keyword parameter dummy controls whether the call
219 actually does anything. """
219 actually does anything. """
220
220
221 # If the user has turned it off, go away
221 # If the user has turned it off, go away
222 if not self.IP.embedded_active:
222 if not self.IP.embedded_active:
223 return
223 return
224
224
225 # Normal exits from interactive mode set this flag, so the shell can't
225 # Normal exits from interactive mode set this flag, so the shell can't
226 # re-enter (it checks this variable at the start of interactive mode).
226 # re-enter (it checks this variable at the start of interactive mode).
227 self.IP.exit_now = False
227 self.IP.exit_now = False
228
228
229 # Allow the dummy parameter to override the global __dummy_mode
229 # Allow the dummy parameter to override the global __dummy_mode
230 if dummy or (dummy != 0 and self.__dummy_mode):
230 if dummy or (dummy != 0 and self.__dummy_mode):
231 return
231 return
232
232
233 # Set global subsystems (display,completions) to our values
233 # Set global subsystems (display,completions) to our values
234 sys.displayhook = self.sys_displayhook_embed
234 sys.displayhook = self.sys_displayhook_embed
235 if self.IP.has_readline:
235 if self.IP.has_readline:
236 self.IP.set_completer()
236 self.IP.set_completer()
237
237
238 if self.banner and header:
238 if self.banner and header:
239 format = '%s\n%s\n'
239 format = '%s\n%s\n'
240 else:
240 else:
241 format = '%s%s\n'
241 format = '%s%s\n'
242 banner = format % (self.banner,header)
242 banner = format % (self.banner,header)
243
243
244 # Call the embedding code with a stack depth of 1 so it can skip over
244 # Call the embedding code with a stack depth of 1 so it can skip over
245 # our call and get the original caller's namespaces.
245 # our call and get the original caller's namespaces.
246 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
246 self.IP.embed_mainloop(banner,local_ns,global_ns,stack_depth=1)
247
247
248 if self.exit_msg:
248 if self.exit_msg:
249 print self.exit_msg
249 print self.exit_msg
250
250
251 # Restore global systems (display, completion)
251 # Restore global systems (display, completion)
252 sys.displayhook = self.sys_displayhook_ori
252 sys.displayhook = self.sys_displayhook_ori
253 self.restore_system_completer()
253 self.restore_system_completer()
254
254
255 def set_dummy_mode(self,dummy):
255 def set_dummy_mode(self,dummy):
256 """Sets the embeddable shell's dummy mode parameter.
256 """Sets the embeddable shell's dummy mode parameter.
257
257
258 set_dummy_mode(dummy): dummy = 0 or 1.
258 set_dummy_mode(dummy): dummy = 0 or 1.
259
259
260 This parameter is persistent and makes calls to the embeddable shell
260 This parameter is persistent and makes calls to the embeddable shell
261 silently return without performing any action. This allows you to
261 silently return without performing any action. This allows you to
262 globally activate or deactivate a shell you're using with a single call.
262 globally activate or deactivate a shell you're using with a single call.
263
263
264 If you need to manually"""
264 If you need to manually"""
265
265
266 if dummy not in [0,1,False,True]:
266 if dummy not in [0,1,False,True]:
267 raise ValueError,'dummy parameter must be boolean'
267 raise ValueError,'dummy parameter must be boolean'
268 self.__dummy_mode = dummy
268 self.__dummy_mode = dummy
269
269
270 def get_dummy_mode(self):
270 def get_dummy_mode(self):
271 """Return the current value of the dummy mode parameter.
271 """Return the current value of the dummy mode parameter.
272 """
272 """
273 return self.__dummy_mode
273 return self.__dummy_mode
274
274
275 def set_banner(self,banner):
275 def set_banner(self,banner):
276 """Sets the global banner.
276 """Sets the global banner.
277
277
278 This banner gets prepended to every header printed when the shell
278 This banner gets prepended to every header printed when the shell
279 instance is called."""
279 instance is called."""
280
280
281 self.banner = banner
281 self.banner = banner
282
282
283 def set_exit_msg(self,exit_msg):
283 def set_exit_msg(self,exit_msg):
284 """Sets the global exit_msg.
284 """Sets the global exit_msg.
285
285
286 This exit message gets printed upon exiting every time the embedded
286 This exit message gets printed upon exiting every time the embedded
287 shell is called. It is None by default. """
287 shell is called. It is None by default. """
288
288
289 self.exit_msg = exit_msg
289 self.exit_msg = exit_msg
290
290
291 #-----------------------------------------------------------------------------
291 #-----------------------------------------------------------------------------
292 if HAS_CTYPES:
292 if HAS_CTYPES:
293 # Add async exception support. Trick taken from:
293 # Add async exception support. Trick taken from:
294 # http://sebulba.wikispaces.com/recipe+thread2
294 # http://sebulba.wikispaces.com/recipe+thread2
295 def _async_raise(tid, exctype):
295 def _async_raise(tid, exctype):
296 """raises the exception, performs cleanup if needed"""
296 """raises the exception, performs cleanup if needed"""
297 if not inspect.isclass(exctype):
297 if not inspect.isclass(exctype):
298 raise TypeError("Only types can be raised (not instances)")
298 raise TypeError("Only types can be raised (not instances)")
299 res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,
299 res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid,
300 ctypes.py_object(exctype))
300 ctypes.py_object(exctype))
301 if res == 0:
301 if res == 0:
302 raise ValueError("invalid thread id")
302 raise ValueError("invalid thread id")
303 elif res != 1:
303 elif res != 1:
304 # """if it returns a number greater than one, you're in trouble,
304 # """if it returns a number greater than one, you're in trouble,
305 # and you should call it again with exc=NULL to revert the effect"""
305 # and you should call it again with exc=NULL to revert the effect"""
306 ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
306 ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0)
307 raise SystemError("PyThreadState_SetAsyncExc failed")
307 raise SystemError("PyThreadState_SetAsyncExc failed")
308
308
309 def sigint_handler (signum,stack_frame):
309 def sigint_handler (signum,stack_frame):
310 """Sigint handler for threaded apps.
310 """Sigint handler for threaded apps.
311
311
312 This is a horrible hack to pass information about SIGINT _without_
312 This is a horrible hack to pass information about SIGINT _without_
313 using exceptions, since I haven't been able to properly manage
313 using exceptions, since I haven't been able to properly manage
314 cross-thread exceptions in GTK/WX. In fact, I don't think it can be
314 cross-thread exceptions in GTK/WX. In fact, I don't think it can be
315 done (or at least that's my understanding from a c.l.py thread where
315 done (or at least that's my understanding from a c.l.py thread where
316 this was discussed)."""
316 this was discussed)."""
317
317
318 global KBINT
318 global KBINT
319
319
320 if CODE_RUN:
320 if CODE_RUN:
321 _async_raise(MAIN_THREAD_ID,KeyboardInterrupt)
321 _async_raise(MAIN_THREAD_ID,KeyboardInterrupt)
322 else:
322 else:
323 KBINT = True
323 KBINT = True
324 print '\nKeyboardInterrupt - Press <Enter> to continue.',
324 print '\nKeyboardInterrupt - Press <Enter> to continue.',
325 Term.cout.flush()
325 Term.cout.flush()
326
326
327 else:
327 else:
328 def sigint_handler (signum,stack_frame):
328 def sigint_handler (signum,stack_frame):
329 """Sigint handler for threaded apps.
329 """Sigint handler for threaded apps.
330
330
331 This is a horrible hack to pass information about SIGINT _without_
331 This is a horrible hack to pass information about SIGINT _without_
332 using exceptions, since I haven't been able to properly manage
332 using exceptions, since I haven't been able to properly manage
333 cross-thread exceptions in GTK/WX. In fact, I don't think it can be
333 cross-thread exceptions in GTK/WX. In fact, I don't think it can be
334 done (or at least that's my understanding from a c.l.py thread where
334 done (or at least that's my understanding from a c.l.py thread where
335 this was discussed)."""
335 this was discussed)."""
336
336
337 global KBINT
337 global KBINT
338
338
339 print '\nKeyboardInterrupt - Press <Enter> to continue.',
339 print '\nKeyboardInterrupt - Press <Enter> to continue.',
340 Term.cout.flush()
340 Term.cout.flush()
341 # Set global flag so that runsource can know that Ctrl-C was hit
341 # Set global flag so that runsource can know that Ctrl-C was hit
342 KBINT = True
342 KBINT = True
343
343
344
344
345 class MTInteractiveShell(InteractiveShell):
345 class MTInteractiveShell(InteractiveShell):
346 """Simple multi-threaded shell."""
346 """Simple multi-threaded shell."""
347
347
348 # Threading strategy taken from:
348 # Threading strategy taken from:
349 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
349 # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65109, by Brian
350 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
350 # McErlean and John Finlay. Modified with corrections by Antoon Pardon,
351 # from the pygtk mailing list, to avoid lockups with system calls.
351 # from the pygtk mailing list, to avoid lockups with system calls.
352
352
353 # class attribute to indicate whether the class supports threads or not.
353 # class attribute to indicate whether the class supports threads or not.
354 # Subclasses with thread support should override this as needed.
354 # Subclasses with thread support should override this as needed.
355 isthreaded = True
355 isthreaded = True
356
356
357 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
357 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
358 user_ns=None,user_global_ns=None,banner2='',
358 user_ns=None,user_global_ns=None,banner2='',
359 gui_timeout=GUI_TIMEOUT,**kw):
359 gui_timeout=GUI_TIMEOUT,**kw):
360 """Similar to the normal InteractiveShell, but with threading control"""
360 """Similar to the normal InteractiveShell, but with threading control"""
361
361
362 InteractiveShell.__init__(self,name,usage,rc,user_ns,
362 InteractiveShell.__init__(self,name,usage,rc,user_ns,
363 user_global_ns,banner2)
363 user_global_ns,banner2)
364
364
365 # Timeout we wait for GUI thread
365 # Timeout we wait for GUI thread
366 self.gui_timeout = gui_timeout
366 self.gui_timeout = gui_timeout
367
367
368 # A queue to hold the code to be executed.
368 # A queue to hold the code to be executed.
369 self.code_queue = Queue.Queue()
369 self.code_queue = Queue.Queue()
370
370
371 # Stuff to do at closing time
371 # Stuff to do at closing time
372 self._kill = None
372 self._kill = None
373 on_kill = kw.get('on_kill', [])
373 on_kill = kw.get('on_kill', [])
374 # Check that all things to kill are callable:
374 # Check that all things to kill are callable:
375 for t in on_kill:
375 for t in on_kill:
376 if not callable(t):
376 if not callable(t):
377 raise TypeError,'on_kill must be a list of callables'
377 raise TypeError,'on_kill must be a list of callables'
378 self.on_kill = on_kill
378 self.on_kill = on_kill
379 # thread identity of the "worker thread" (that may execute code directly)
379 # thread identity of the "worker thread" (that may execute code directly)
380 self.worker_ident = None
380 self.worker_ident = None
381
381
382 def runsource(self, source, filename="<input>", symbol="single"):
382 def runsource(self, source, filename="<input>", symbol="single"):
383 """Compile and run some source in the interpreter.
383 """Compile and run some source in the interpreter.
384
384
385 Modified version of code.py's runsource(), to handle threading issues.
385 Modified version of code.py's runsource(), to handle threading issues.
386 See the original for full docstring details."""
386 See the original for full docstring details."""
387
387
388 global KBINT
388 global KBINT
389
389
390 # If Ctrl-C was typed, we reset the flag and return right away
390 # If Ctrl-C was typed, we reset the flag and return right away
391 if KBINT:
391 if KBINT:
392 KBINT = False
392 KBINT = False
393 return False
393 return False
394
394
395 if self._kill:
395 if self._kill:
396 # can't queue new code if we are being killed
396 # can't queue new code if we are being killed
397 return True
397 return True
398
398
399 try:
399 try:
400 code = self.compile(source, filename, symbol)
400 code = self.compile(source, filename, symbol)
401 except (OverflowError, SyntaxError, ValueError):
401 except (OverflowError, SyntaxError, ValueError):
402 # Case 1
402 # Case 1
403 self.showsyntaxerror(filename)
403 self.showsyntaxerror(filename)
404 return False
404 return False
405
405
406 if code is None:
406 if code is None:
407 # Case 2
407 # Case 2
408 return True
408 return True
409
409
410 # shortcut - if we are in worker thread, or the worker thread is not
410 # shortcut - if we are in worker thread, or the worker thread is not
411 # running, execute directly (to allow recursion and prevent deadlock if
411 # running, execute directly (to allow recursion and prevent deadlock if
412 # code is run early in IPython construction)
412 # code is run early in IPython construction)
413
413
414 if (self.worker_ident is None
414 if (self.worker_ident is None
415 or self.worker_ident == thread.get_ident() ):
415 or self.worker_ident == thread.get_ident() ):
416 InteractiveShell.runcode(self,code)
416 InteractiveShell.runcode(self,code)
417 return
417 return
418
418
419 # Case 3
419 # Case 3
420 # Store code in queue, so the execution thread can handle it.
420 # Store code in queue, so the execution thread can handle it.
421
421
422 completed_ev, received_ev = threading.Event(), threading.Event()
422 completed_ev, received_ev = threading.Event(), threading.Event()
423
423
424 self.code_queue.put((code,completed_ev, received_ev))
424 self.code_queue.put((code,completed_ev, received_ev))
425 # first make sure the message was received, with timeout
425 # first make sure the message was received, with timeout
426 received_ev.wait(self.gui_timeout)
426 received_ev.wait(self.gui_timeout)
427 if not received_ev.isSet():
427 if not received_ev.isSet():
428 # the mainloop is dead, start executing code directly
428 # the mainloop is dead, start executing code directly
429 print "Warning: Timeout for mainloop thread exceeded"
429 print "Warning: Timeout for mainloop thread exceeded"
430 print "switching to nonthreaded mode (until mainloop wakes up again)"
430 print "switching to nonthreaded mode (until mainloop wakes up again)"
431 self.worker_ident = None
431 self.worker_ident = None
432 else:
432 else:
433 completed_ev.wait()
433 completed_ev.wait()
434 return False
434 return False
435
435
436 def runcode(self):
436 def runcode(self):
437 """Execute a code object.
437 """Execute a code object.
438
438
439 Multithreaded wrapper around IPython's runcode()."""
439 Multithreaded wrapper around IPython's runcode()."""
440
440
441 global CODE_RUN
441 global CODE_RUN
442
442
443 # we are in worker thread, stash out the id for runsource()
443 # we are in worker thread, stash out the id for runsource()
444 self.worker_ident = thread.get_ident()
444 self.worker_ident = thread.get_ident()
445
445
446 if self._kill:
446 if self._kill:
447 print >>Term.cout, 'Closing threads...',
447 print >>Term.cout, 'Closing threads...',
448 Term.cout.flush()
448 Term.cout.flush()
449 for tokill in self.on_kill:
449 for tokill in self.on_kill:
450 tokill()
450 tokill()
451 print >>Term.cout, 'Done.'
451 print >>Term.cout, 'Done.'
452 # allow kill() to return
452 # allow kill() to return
453 self._kill.set()
453 self._kill.set()
454 return True
454 return True
455
455
456 # Install sigint handler. We do it every time to ensure that if user
456 # Install sigint handler. We do it every time to ensure that if user
457 # code modifies it, we restore our own handling.
457 # code modifies it, we restore our own handling.
458 try:
458 try:
459 signal(SIGINT,sigint_handler)
459 signal(SIGINT,sigint_handler)
460 except SystemError:
460 except SystemError:
461 # This happens under Windows, which seems to have all sorts
461 # This happens under Windows, which seems to have all sorts
462 # of problems with signal handling. Oh well...
462 # of problems with signal handling. Oh well...
463 pass
463 pass
464
464
465 # Flush queue of pending code by calling the run methood of the parent
465 # Flush queue of pending code by calling the run methood of the parent
466 # class with all items which may be in the queue.
466 # class with all items which may be in the queue.
467 code_to_run = None
467 code_to_run = None
468 while 1:
468 while 1:
469 try:
469 try:
470 code_to_run, completed_ev, received_ev = self.code_queue.get_nowait()
470 code_to_run, completed_ev, received_ev = self.code_queue.get_nowait()
471 except Queue.Empty:
471 except Queue.Empty:
472 break
472 break
473 received_ev.set()
473 received_ev.set()
474
474
475 # Exceptions need to be raised differently depending on which
475 # Exceptions need to be raised differently depending on which
476 # thread is active. This convoluted try/except is only there to
476 # thread is active. This convoluted try/except is only there to
477 # protect against asynchronous exceptions, to ensure that a KBINT
477 # protect against asynchronous exceptions, to ensure that a KBINT
478 # at the wrong time doesn't deadlock everything. The global
478 # at the wrong time doesn't deadlock everything. The global
479 # CODE_TO_RUN is set to true/false as close as possible to the
479 # CODE_TO_RUN is set to true/false as close as possible to the
480 # runcode() call, so that the KBINT handler is correctly informed.
480 # runcode() call, so that the KBINT handler is correctly informed.
481 try:
481 try:
482 try:
482 try:
483 CODE_RUN = True
483 CODE_RUN = True
484 InteractiveShell.runcode(self,code_to_run)
484 InteractiveShell.runcode(self,code_to_run)
485 except KeyboardInterrupt:
485 except KeyboardInterrupt:
486 print "Keyboard interrupted in mainloop"
486 print "Keyboard interrupted in mainloop"
487 while not self.code_queue.empty():
487 while not self.code_queue.empty():
488 code, ev1,ev2 = self.code_queue.get_nowait()
488 code, ev1,ev2 = self.code_queue.get_nowait()
489 ev1.set()
489 ev1.set()
490 ev2.set()
490 ev2.set()
491 break
491 break
492 finally:
492 finally:
493 CODE_RUN = False
493 CODE_RUN = False
494 # allow runsource() return from wait
494 # allow runsource() return from wait
495 completed_ev.set()
495 completed_ev.set()
496
496
497
497
498 # This MUST return true for gtk threading to work
498 # This MUST return true for gtk threading to work
499 return True
499 return True
500
500
501 def kill(self):
501 def kill(self):
502 """Kill the thread, returning when it has been shut down."""
502 """Kill the thread, returning when it has been shut down."""
503 self._kill = threading.Event()
503 self._kill = threading.Event()
504 self._kill.wait()
504 self._kill.wait()
505
505
506 class MatplotlibShellBase:
506 class MatplotlibShellBase:
507 """Mixin class to provide the necessary modifications to regular IPython
507 """Mixin class to provide the necessary modifications to regular IPython
508 shell classes for matplotlib support.
508 shell classes for matplotlib support.
509
509
510 Given Python's MRO, this should be used as the FIRST class in the
510 Given Python's MRO, this should be used as the FIRST class in the
511 inheritance hierarchy, so that it overrides the relevant methods."""
511 inheritance hierarchy, so that it overrides the relevant methods."""
512
512
513 def _matplotlib_config(self,name,user_ns):
513 def _matplotlib_config(self,name,user_ns,user_global_ns=None):
514 """Return items needed to setup the user's shell with matplotlib"""
514 """Return items needed to setup the user's shell with matplotlib"""
515
515
516 # Initialize matplotlib to interactive mode always
516 # Initialize matplotlib to interactive mode always
517 import matplotlib
517 import matplotlib
518 from matplotlib import backends
518 from matplotlib import backends
519 matplotlib.interactive(True)
519 matplotlib.interactive(True)
520
520
521 def use(arg):
521 def use(arg):
522 """IPython wrapper for matplotlib's backend switcher.
522 """IPython wrapper for matplotlib's backend switcher.
523
523
524 In interactive use, we can not allow switching to a different
524 In interactive use, we can not allow switching to a different
525 interactive backend, since thread conflicts will most likely crash
525 interactive backend, since thread conflicts will most likely crash
526 the python interpreter. This routine does a safety check first,
526 the python interpreter. This routine does a safety check first,
527 and refuses to perform a dangerous switch. It still allows
527 and refuses to perform a dangerous switch. It still allows
528 switching to non-interactive backends."""
528 switching to non-interactive backends."""
529
529
530 if arg in backends.interactive_bk and arg != self.mpl_backend:
530 if arg in backends.interactive_bk and arg != self.mpl_backend:
531 m=('invalid matplotlib backend switch.\n'
531 m=('invalid matplotlib backend switch.\n'
532 'This script attempted to switch to the interactive '
532 'This script attempted to switch to the interactive '
533 'backend: `%s`\n'
533 'backend: `%s`\n'
534 'Your current choice of interactive backend is: `%s`\n\n'
534 'Your current choice of interactive backend is: `%s`\n\n'
535 'Switching interactive matplotlib backends at runtime\n'
535 'Switching interactive matplotlib backends at runtime\n'
536 'would crash the python interpreter, '
536 'would crash the python interpreter, '
537 'and IPython has blocked it.\n\n'
537 'and IPython has blocked it.\n\n'
538 'You need to either change your choice of matplotlib backend\n'
538 'You need to either change your choice of matplotlib backend\n'
539 'by editing your .matplotlibrc file, or run this script as a \n'
539 'by editing your .matplotlibrc file, or run this script as a \n'
540 'standalone file from the command line, not using IPython.\n' %
540 'standalone file from the command line, not using IPython.\n' %
541 (arg,self.mpl_backend) )
541 (arg,self.mpl_backend) )
542 raise RuntimeError, m
542 raise RuntimeError, m
543 else:
543 else:
544 self.mpl_use(arg)
544 self.mpl_use(arg)
545 self.mpl_use._called = True
545 self.mpl_use._called = True
546
546
547 self.matplotlib = matplotlib
547 self.matplotlib = matplotlib
548 self.mpl_backend = matplotlib.rcParams['backend']
548 self.mpl_backend = matplotlib.rcParams['backend']
549
549
550 # we also need to block switching of interactive backends by use()
550 # we also need to block switching of interactive backends by use()
551 self.mpl_use = matplotlib.use
551 self.mpl_use = matplotlib.use
552 self.mpl_use._called = False
552 self.mpl_use._called = False
553 # overwrite the original matplotlib.use with our wrapper
553 # overwrite the original matplotlib.use with our wrapper
554 matplotlib.use = use
554 matplotlib.use = use
555
555
556 # This must be imported last in the matplotlib series, after
556 # This must be imported last in the matplotlib series, after
557 # backend/interactivity choices have been made
557 # backend/interactivity choices have been made
558 import matplotlib.pylab as pylab
558 import matplotlib.pylab as pylab
559 self.pylab = pylab
559 self.pylab = pylab
560
560
561 self.pylab.show._needmain = False
561 self.pylab.show._needmain = False
562 # We need to detect at runtime whether show() is called by the user.
562 # We need to detect at runtime whether show() is called by the user.
563 # For this, we wrap it into a decorator which adds a 'called' flag.
563 # For this, we wrap it into a decorator which adds a 'called' flag.
564 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
564 self.pylab.draw_if_interactive = flag_calls(self.pylab.draw_if_interactive)
565
565
566 # Build a user namespace initialized with matplotlib/matlab features.
566 # Build a user namespace initialized with matplotlib/matlab features.
567 user_ns = IPython.ipapi.make_user_ns(user_ns)
567 user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
568 user_global_ns)
568
569
569 # Import numpy as np/pyplot as plt are conventions we're trying to
570 # Import numpy as np/pyplot as plt are conventions we're trying to
570 # somewhat standardize on. Making them available to users by default
571 # somewhat standardize on. Making them available to users by default
571 # will greatly help this.
572 # will greatly help this.
572 exec ("import numpy\n"
573 exec ("import numpy\n"
573 "import numpy as np\n"
574 "import numpy as np\n"
574 "import matplotlib\n"
575 "import matplotlib\n"
575 "import matplotlib.pylab as pylab\n"
576 "import matplotlib.pylab as pylab\n"
576 "try:\n"
577 "try:\n"
577 " import matplotlib.pyplot as plt\n"
578 " import matplotlib.pyplot as plt\n"
578 "except ImportError:\n"
579 "except ImportError:\n"
579 " pass\n"
580 " pass\n"
580 ) in user_ns
581 ) in user_ns
581
582
582 # Build matplotlib info banner
583 # Build matplotlib info banner
583 b="""
584 b="""
584 Welcome to pylab, a matplotlib-based Python environment.
585 Welcome to pylab, a matplotlib-based Python environment.
585 For more information, type 'help(pylab)'.
586 For more information, type 'help(pylab)'.
586 """
587 """
587 return user_ns,b
588 return user_ns,user_global_ns,b
588
589
589 def mplot_exec(self,fname,*where,**kw):
590 def mplot_exec(self,fname,*where,**kw):
590 """Execute a matplotlib script.
591 """Execute a matplotlib script.
591
592
592 This is a call to execfile(), but wrapped in safeties to properly
593 This is a call to execfile(), but wrapped in safeties to properly
593 handle interactive rendering and backend switching."""
594 handle interactive rendering and backend switching."""
594
595
595 #print '*** Matplotlib runner ***' # dbg
596 #print '*** Matplotlib runner ***' # dbg
596 # turn off rendering until end of script
597 # turn off rendering until end of script
597 isInteractive = self.matplotlib.rcParams['interactive']
598 isInteractive = self.matplotlib.rcParams['interactive']
598 self.matplotlib.interactive(False)
599 self.matplotlib.interactive(False)
599 self.safe_execfile(fname,*where,**kw)
600 self.safe_execfile(fname,*where,**kw)
600 self.matplotlib.interactive(isInteractive)
601 self.matplotlib.interactive(isInteractive)
601 # make rendering call now, if the user tried to do it
602 # make rendering call now, if the user tried to do it
602 if self.pylab.draw_if_interactive.called:
603 if self.pylab.draw_if_interactive.called:
603 self.pylab.draw()
604 self.pylab.draw()
604 self.pylab.draw_if_interactive.called = False
605 self.pylab.draw_if_interactive.called = False
605
606
606 # if a backend switch was performed, reverse it now
607 # if a backend switch was performed, reverse it now
607 if self.mpl_use._called:
608 if self.mpl_use._called:
608 self.matplotlib.rcParams['backend'] = self.mpl_backend
609 self.matplotlib.rcParams['backend'] = self.mpl_backend
609
610
610 def magic_run(self,parameter_s=''):
611 def magic_run(self,parameter_s=''):
611 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
612 Magic.magic_run(self,parameter_s,runner=self.mplot_exec)
612
613
613 # Fix the docstring so users see the original as well
614 # Fix the docstring so users see the original as well
614 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
615 magic_run.__doc__ = "%s\n%s" % (Magic.magic_run.__doc__,
615 "\n *** Modified %run for Matplotlib,"
616 "\n *** Modified %run for Matplotlib,"
616 " with proper interactive handling ***")
617 " with proper interactive handling ***")
617
618
618 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
619 # Now we provide 2 versions of a matplotlib-aware IPython base shells, single
619 # and multithreaded. Note that these are meant for internal use, the IPShell*
620 # and multithreaded. Note that these are meant for internal use, the IPShell*
620 # classes below are the ones meant for public consumption.
621 # classes below are the ones meant for public consumption.
621
622
622 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
623 class MatplotlibShell(MatplotlibShellBase,InteractiveShell):
623 """Single-threaded shell with matplotlib support."""
624 """Single-threaded shell with matplotlib support."""
624
625
625 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
626 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
626 user_ns=None,user_global_ns=None,**kw):
627 user_ns=None,user_global_ns=None,**kw):
627 user_ns,b2 = self._matplotlib_config(name,user_ns)
628 user_ns,user_global_ns,b2 = self._matplotlib_config(name,user_ns,user_global_ns)
628 InteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
629 InteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
629 banner2=b2,**kw)
630 banner2=b2,**kw)
630
631
631 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
632 class MatplotlibMTShell(MatplotlibShellBase,MTInteractiveShell):
632 """Multi-threaded shell with matplotlib support."""
633 """Multi-threaded shell with matplotlib support."""
633
634
634 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
635 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
635 user_ns=None,user_global_ns=None, **kw):
636 user_ns=None,user_global_ns=None, **kw):
636 user_ns,b2 = self._matplotlib_config(name,user_ns)
637 user_ns,b2 = self._matplotlib_config(name,user_ns)
637 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
638 MTInteractiveShell.__init__(self,name,usage,rc,user_ns,user_global_ns,
638 banner2=b2,**kw)
639 banner2=b2,**kw)
639
640
640 #-----------------------------------------------------------------------------
641 #-----------------------------------------------------------------------------
641 # Utility functions for the different GUI enabled IPShell* classes.
642 # Utility functions for the different GUI enabled IPShell* classes.
642
643
643 def get_tk():
644 def get_tk():
644 """Tries to import Tkinter and returns a withdrawn Tkinter root
645 """Tries to import Tkinter and returns a withdrawn Tkinter root
645 window. If Tkinter is already imported or not available, this
646 window. If Tkinter is already imported or not available, this
646 returns None. This function calls `hijack_tk` underneath.
647 returns None. This function calls `hijack_tk` underneath.
647 """
648 """
648 if not USE_TK or sys.modules.has_key('Tkinter'):
649 if not USE_TK or sys.modules.has_key('Tkinter'):
649 return None
650 return None
650 else:
651 else:
651 try:
652 try:
652 import Tkinter
653 import Tkinter
653 except ImportError:
654 except ImportError:
654 return None
655 return None
655 else:
656 else:
656 hijack_tk()
657 hijack_tk()
657 r = Tkinter.Tk()
658 r = Tkinter.Tk()
658 r.withdraw()
659 r.withdraw()
659 return r
660 return r
660
661
661 def hijack_tk():
662 def hijack_tk():
662 """Modifies Tkinter's mainloop with a dummy so when a module calls
663 """Modifies Tkinter's mainloop with a dummy so when a module calls
663 mainloop, it does not block.
664 mainloop, it does not block.
664
665
665 """
666 """
666 def misc_mainloop(self, n=0):
667 def misc_mainloop(self, n=0):
667 pass
668 pass
668 def tkinter_mainloop(n=0):
669 def tkinter_mainloop(n=0):
669 pass
670 pass
670
671
671 import Tkinter
672 import Tkinter
672 Tkinter.Misc.mainloop = misc_mainloop
673 Tkinter.Misc.mainloop = misc_mainloop
673 Tkinter.mainloop = tkinter_mainloop
674 Tkinter.mainloop = tkinter_mainloop
674
675
675 def update_tk(tk):
676 def update_tk(tk):
676 """Updates the Tkinter event loop. This is typically called from
677 """Updates the Tkinter event loop. This is typically called from
677 the respective WX or GTK mainloops.
678 the respective WX or GTK mainloops.
678 """
679 """
679 if tk:
680 if tk:
680 tk.update()
681 tk.update()
681
682
682 def hijack_wx():
683 def hijack_wx():
683 """Modifies wxPython's MainLoop with a dummy so user code does not
684 """Modifies wxPython's MainLoop with a dummy so user code does not
684 block IPython. The hijacked mainloop function is returned.
685 block IPython. The hijacked mainloop function is returned.
685 """
686 """
686 def dummy_mainloop(*args, **kw):
687 def dummy_mainloop(*args, **kw):
687 pass
688 pass
688
689
689 try:
690 try:
690 import wx
691 import wx
691 except ImportError:
692 except ImportError:
692 # For very old versions of WX
693 # For very old versions of WX
693 import wxPython as wx
694 import wxPython as wx
694
695
695 ver = wx.__version__
696 ver = wx.__version__
696 orig_mainloop = None
697 orig_mainloop = None
697 if ver[:3] >= '2.5':
698 if ver[:3] >= '2.5':
698 import wx
699 import wx
699 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
700 if hasattr(wx, '_core_'): core = getattr(wx, '_core_')
700 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
701 elif hasattr(wx, '_core'): core = getattr(wx, '_core')
701 else: raise AttributeError('Could not find wx core module')
702 else: raise AttributeError('Could not find wx core module')
702 orig_mainloop = core.PyApp_MainLoop
703 orig_mainloop = core.PyApp_MainLoop
703 core.PyApp_MainLoop = dummy_mainloop
704 core.PyApp_MainLoop = dummy_mainloop
704 elif ver[:3] == '2.4':
705 elif ver[:3] == '2.4':
705 orig_mainloop = wx.wxc.wxPyApp_MainLoop
706 orig_mainloop = wx.wxc.wxPyApp_MainLoop
706 wx.wxc.wxPyApp_MainLoop = dummy_mainloop
707 wx.wxc.wxPyApp_MainLoop = dummy_mainloop
707 else:
708 else:
708 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
709 warn("Unable to find either wxPython version 2.4 or >= 2.5.")
709 return orig_mainloop
710 return orig_mainloop
710
711
711 def hijack_gtk():
712 def hijack_gtk():
712 """Modifies pyGTK's mainloop with a dummy so user code does not
713 """Modifies pyGTK's mainloop with a dummy so user code does not
713 block IPython. This function returns the original `gtk.mainloop`
714 block IPython. This function returns the original `gtk.mainloop`
714 function that has been hijacked.
715 function that has been hijacked.
715 """
716 """
716 def dummy_mainloop(*args, **kw):
717 def dummy_mainloop(*args, **kw):
717 pass
718 pass
718 import gtk
719 import gtk
719 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
720 if gtk.pygtk_version >= (2,4,0): orig_mainloop = gtk.main
720 else: orig_mainloop = gtk.mainloop
721 else: orig_mainloop = gtk.mainloop
721 gtk.mainloop = dummy_mainloop
722 gtk.mainloop = dummy_mainloop
722 gtk.main = dummy_mainloop
723 gtk.main = dummy_mainloop
723 return orig_mainloop
724 return orig_mainloop
724
725
725 def hijack_qt():
726 def hijack_qt():
726 """Modifies PyQt's mainloop with a dummy so user code does not
727 """Modifies PyQt's mainloop with a dummy so user code does not
727 block IPython. This function returns the original
728 block IPython. This function returns the original
728 `qt.qApp.exec_loop` function that has been hijacked.
729 `qt.qApp.exec_loop` function that has been hijacked.
729 """
730 """
730 def dummy_mainloop(*args, **kw):
731 def dummy_mainloop(*args, **kw):
731 pass
732 pass
732 import qt
733 import qt
733 orig_mainloop = qt.qApp.exec_loop
734 orig_mainloop = qt.qApp.exec_loop
734 qt.qApp.exec_loop = dummy_mainloop
735 qt.qApp.exec_loop = dummy_mainloop
735 qt.QApplication.exec_loop = dummy_mainloop
736 qt.QApplication.exec_loop = dummy_mainloop
736 return orig_mainloop
737 return orig_mainloop
737
738
738 def hijack_qt4():
739 def hijack_qt4():
739 """Modifies PyQt4's mainloop with a dummy so user code does not
740 """Modifies PyQt4's mainloop with a dummy so user code does not
740 block IPython. This function returns the original
741 block IPython. This function returns the original
741 `QtGui.qApp.exec_` function that has been hijacked.
742 `QtGui.qApp.exec_` function that has been hijacked.
742 """
743 """
743 def dummy_mainloop(*args, **kw):
744 def dummy_mainloop(*args, **kw):
744 pass
745 pass
745 from PyQt4 import QtGui, QtCore
746 from PyQt4 import QtGui, QtCore
746 orig_mainloop = QtGui.qApp.exec_
747 orig_mainloop = QtGui.qApp.exec_
747 QtGui.qApp.exec_ = dummy_mainloop
748 QtGui.qApp.exec_ = dummy_mainloop
748 QtGui.QApplication.exec_ = dummy_mainloop
749 QtGui.QApplication.exec_ = dummy_mainloop
749 QtCore.QCoreApplication.exec_ = dummy_mainloop
750 QtCore.QCoreApplication.exec_ = dummy_mainloop
750 return orig_mainloop
751 return orig_mainloop
751
752
752 #-----------------------------------------------------------------------------
753 #-----------------------------------------------------------------------------
753 # The IPShell* classes below are the ones meant to be run by external code as
754 # The IPShell* classes below are the ones meant to be run by external code as
754 # IPython instances. Note that unless a specific threading strategy is
755 # IPython instances. Note that unless a specific threading strategy is
755 # desired, the factory function start() below should be used instead (it
756 # desired, the factory function start() below should be used instead (it
756 # selects the proper threaded class).
757 # selects the proper threaded class).
757
758
758 class IPThread(threading.Thread):
759 class IPThread(threading.Thread):
759 def run(self):
760 def run(self):
760 self.IP.mainloop(self._banner)
761 self.IP.mainloop(self._banner)
761 self.IP.kill()
762 self.IP.kill()
762
763
763 class IPShellGTK(IPThread):
764 class IPShellGTK(IPThread):
764 """Run a gtk mainloop() in a separate thread.
765 """Run a gtk mainloop() in a separate thread.
765
766
766 Python commands can be passed to the thread where they will be executed.
767 Python commands can be passed to the thread where they will be executed.
767 This is implemented by periodically checking for passed code using a
768 This is implemented by periodically checking for passed code using a
768 GTK timeout callback."""
769 GTK timeout callback."""
769
770
770 TIMEOUT = 100 # Millisecond interval between timeouts.
771 TIMEOUT = 100 # Millisecond interval between timeouts.
771
772
772 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
773 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
773 debug=1,shell_class=MTInteractiveShell):
774 debug=1,shell_class=MTInteractiveShell):
774
775
775 import gtk
776 import gtk
776
777
777 self.gtk = gtk
778 self.gtk = gtk
778 self.gtk_mainloop = hijack_gtk()
779 self.gtk_mainloop = hijack_gtk()
779
780
780 # Allows us to use both Tk and GTK.
781 # Allows us to use both Tk and GTK.
781 self.tk = get_tk()
782 self.tk = get_tk()
782
783
783 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
784 if gtk.pygtk_version >= (2,4,0): mainquit = self.gtk.main_quit
784 else: mainquit = self.gtk.mainquit
785 else: mainquit = self.gtk.mainquit
785
786
786 self.IP = make_IPython(argv,user_ns=user_ns,
787 self.IP = make_IPython(argv,user_ns=user_ns,
787 user_global_ns=user_global_ns,
788 user_global_ns=user_global_ns,
788 debug=debug,
789 debug=debug,
789 shell_class=shell_class,
790 shell_class=shell_class,
790 on_kill=[mainquit])
791 on_kill=[mainquit])
791
792
792 # HACK: slot for banner in self; it will be passed to the mainloop
793 # HACK: slot for banner in self; it will be passed to the mainloop
793 # method only and .run() needs it. The actual value will be set by
794 # method only and .run() needs it. The actual value will be set by
794 # .mainloop().
795 # .mainloop().
795 self._banner = None
796 self._banner = None
796
797
797 threading.Thread.__init__(self)
798 threading.Thread.__init__(self)
798
799
799 def mainloop(self,sys_exit=0,banner=None):
800 def mainloop(self,sys_exit=0,banner=None):
800
801
801 self._banner = banner
802 self._banner = banner
802
803
803 if self.gtk.pygtk_version >= (2,4,0):
804 if self.gtk.pygtk_version >= (2,4,0):
804 import gobject
805 import gobject
805 gobject.idle_add(self.on_timer)
806 gobject.idle_add(self.on_timer)
806 else:
807 else:
807 self.gtk.idle_add(self.on_timer)
808 self.gtk.idle_add(self.on_timer)
808
809
809 if sys.platform != 'win32':
810 if sys.platform != 'win32':
810 try:
811 try:
811 if self.gtk.gtk_version[0] >= 2:
812 if self.gtk.gtk_version[0] >= 2:
812 self.gtk.gdk.threads_init()
813 self.gtk.gdk.threads_init()
813 except AttributeError:
814 except AttributeError:
814 pass
815 pass
815 except RuntimeError:
816 except RuntimeError:
816 error('Your pyGTK likely has not been compiled with '
817 error('Your pyGTK likely has not been compiled with '
817 'threading support.\n'
818 'threading support.\n'
818 'The exception printout is below.\n'
819 'The exception printout is below.\n'
819 'You can either rebuild pyGTK with threads, or '
820 'You can either rebuild pyGTK with threads, or '
820 'try using \n'
821 'try using \n'
821 'matplotlib with a different backend (like Tk or WX).\n'
822 'matplotlib with a different backend (like Tk or WX).\n'
822 'Note that matplotlib will most likely not work in its '
823 'Note that matplotlib will most likely not work in its '
823 'current state!')
824 'current state!')
824 self.IP.InteractiveTB()
825 self.IP.InteractiveTB()
825
826
826 self.start()
827 self.start()
827 self.gtk.gdk.threads_enter()
828 self.gtk.gdk.threads_enter()
828 self.gtk_mainloop()
829 self.gtk_mainloop()
829 self.gtk.gdk.threads_leave()
830 self.gtk.gdk.threads_leave()
830 self.join()
831 self.join()
831
832
832 def on_timer(self):
833 def on_timer(self):
833 """Called when GTK is idle.
834 """Called when GTK is idle.
834
835
835 Must return True always, otherwise GTK stops calling it"""
836 Must return True always, otherwise GTK stops calling it"""
836
837
837 update_tk(self.tk)
838 update_tk(self.tk)
838 self.IP.runcode()
839 self.IP.runcode()
839 time.sleep(0.01)
840 time.sleep(0.01)
840 return True
841 return True
841
842
842
843
843 class IPShellWX(IPThread):
844 class IPShellWX(IPThread):
844 """Run a wx mainloop() in a separate thread.
845 """Run a wx mainloop() in a separate thread.
845
846
846 Python commands can be passed to the thread where they will be executed.
847 Python commands can be passed to the thread where they will be executed.
847 This is implemented by periodically checking for passed code using a
848 This is implemented by periodically checking for passed code using a
848 GTK timeout callback."""
849 GTK timeout callback."""
849
850
850 TIMEOUT = 100 # Millisecond interval between timeouts.
851 TIMEOUT = 100 # Millisecond interval between timeouts.
851
852
852 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
853 def __init__(self,argv=None,user_ns=None,user_global_ns=None,
853 debug=1,shell_class=MTInteractiveShell):
854 debug=1,shell_class=MTInteractiveShell):
854
855
855 self.IP = make_IPython(argv,user_ns=user_ns,
856 self.IP = make_IPython(argv,user_ns=user_ns,
856 user_global_ns=user_global_ns,
857 user_global_ns=user_global_ns,
857 debug=debug,
858 debug=debug,
858 shell_class=shell_class,
859 shell_class=shell_class,
859 on_kill=[self.wxexit])
860 on_kill=[self.wxexit])
860
861
861 wantedwxversion=self.IP.rc.wxversion
862 wantedwxversion=self.IP.rc.wxversion
862 if wantedwxversion!="0":
863 if wantedwxversion!="0":
863 try:
864 try:
864 import wxversion
865 import wxversion
865 except ImportError:
866 except ImportError:
866 error('The wxversion module is needed for WX version selection')
867 error('The wxversion module is needed for WX version selection')
867 else:
868 else:
868 try:
869 try:
869 wxversion.select(wantedwxversion)
870 wxversion.select(wantedwxversion)
870 except:
871 except:
871 self.IP.InteractiveTB()
872 self.IP.InteractiveTB()
872 error('Requested wxPython version %s could not be loaded' %
873 error('Requested wxPython version %s could not be loaded' %
873 wantedwxversion)
874 wantedwxversion)
874
875
875 import wx
876 import wx
876
877
877 threading.Thread.__init__(self)
878 threading.Thread.__init__(self)
878 self.wx = wx
879 self.wx = wx
879 self.wx_mainloop = hijack_wx()
880 self.wx_mainloop = hijack_wx()
880
881
881 # Allows us to use both Tk and GTK.
882 # Allows us to use both Tk and GTK.
882 self.tk = get_tk()
883 self.tk = get_tk()
883
884
884 # HACK: slot for banner in self; it will be passed to the mainloop
885 # HACK: slot for banner in self; it will be passed to the mainloop
885 # method only and .run() needs it. The actual value will be set by
886 # method only and .run() needs it. The actual value will be set by
886 # .mainloop().
887 # .mainloop().
887 self._banner = None
888 self._banner = None
888
889
889 self.app = None
890 self.app = None
890
891
891 def wxexit(self, *args):
892 def wxexit(self, *args):
892 if self.app is not None:
893 if self.app is not None:
893 self.app.agent.timer.Stop()
894 self.app.agent.timer.Stop()
894 self.app.ExitMainLoop()
895 self.app.ExitMainLoop()
895
896
896 def mainloop(self,sys_exit=0,banner=None):
897 def mainloop(self,sys_exit=0,banner=None):
897
898
898 self._banner = banner
899 self._banner = banner
899
900
900 self.start()
901 self.start()
901
902
902 class TimerAgent(self.wx.MiniFrame):
903 class TimerAgent(self.wx.MiniFrame):
903 wx = self.wx
904 wx = self.wx
904 IP = self.IP
905 IP = self.IP
905 tk = self.tk
906 tk = self.tk
906 def __init__(self, parent, interval):
907 def __init__(self, parent, interval):
907 style = self.wx.DEFAULT_FRAME_STYLE | self.wx.TINY_CAPTION_HORIZ
908 style = self.wx.DEFAULT_FRAME_STYLE | self.wx.TINY_CAPTION_HORIZ
908 self.wx.MiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
909 self.wx.MiniFrame.__init__(self, parent, -1, ' ', pos=(200, 200),
909 size=(100, 100),style=style)
910 size=(100, 100),style=style)
910 self.Show(False)
911 self.Show(False)
911 self.interval = interval
912 self.interval = interval
912 self.timerId = self.wx.NewId()
913 self.timerId = self.wx.NewId()
913
914
914 def StartWork(self):
915 def StartWork(self):
915 self.timer = self.wx.Timer(self, self.timerId)
916 self.timer = self.wx.Timer(self, self.timerId)
916 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
917 self.wx.EVT_TIMER(self, self.timerId, self.OnTimer)
917 self.timer.Start(self.interval)
918 self.timer.Start(self.interval)
918
919
919 def OnTimer(self, event):
920 def OnTimer(self, event):
920 update_tk(self.tk)
921 update_tk(self.tk)
921 self.IP.runcode()
922 self.IP.runcode()
922
923
923 class App(self.wx.App):
924 class App(self.wx.App):
924 wx = self.wx
925 wx = self.wx
925 TIMEOUT = self.TIMEOUT
926 TIMEOUT = self.TIMEOUT
926 def OnInit(self):
927 def OnInit(self):
927 'Create the main window and insert the custom frame'
928 'Create the main window and insert the custom frame'
928 self.agent = TimerAgent(None, self.TIMEOUT)
929 self.agent = TimerAgent(None, self.TIMEOUT)
929 self.agent.Show(False)
930 self.agent.Show(False)
930 self.agent.StartWork()
931 self.agent.StartWork()
931 return True
932 return True
932
933
933 self.app = App(redirect=False)
934 self.app = App(redirect=False)
934 self.wx_mainloop(self.app)
935 self.wx_mainloop(self.app)
935 self.join()
936 self.join()
936
937
937
938
938 class IPShellQt(IPThread):
939 class IPShellQt(IPThread):
939 """Run a Qt event loop in a separate thread.
940 """Run a Qt event loop in a separate thread.
940
941
941 Python commands can be passed to the thread where they will be executed.
942 Python commands can be passed to the thread where they will be executed.
942 This is implemented by periodically checking for passed code using a
943 This is implemented by periodically checking for passed code using a
943 Qt timer / slot."""
944 Qt timer / slot."""
944
945
945 TIMEOUT = 100 # Millisecond interval between timeouts.
946 TIMEOUT = 100 # Millisecond interval between timeouts.
946
947
947 def __init__(self, argv=None, user_ns=None, user_global_ns=None,
948 def __init__(self, argv=None, user_ns=None, user_global_ns=None,
948 debug=0, shell_class=MTInteractiveShell):
949 debug=0, shell_class=MTInteractiveShell):
949
950
950 import qt
951 import qt
951
952
952 self.exec_loop = hijack_qt()
953 self.exec_loop = hijack_qt()
953
954
954 # Allows us to use both Tk and QT.
955 # Allows us to use both Tk and QT.
955 self.tk = get_tk()
956 self.tk = get_tk()
956
957
957 self.IP = make_IPython(argv,
958 self.IP = make_IPython(argv,
958 user_ns=user_ns,
959 user_ns=user_ns,
959 user_global_ns=user_global_ns,
960 user_global_ns=user_global_ns,
960 debug=debug,
961 debug=debug,
961 shell_class=shell_class,
962 shell_class=shell_class,
962 on_kill=[qt.qApp.exit])
963 on_kill=[qt.qApp.exit])
963
964
964 # HACK: slot for banner in self; it will be passed to the mainloop
965 # HACK: slot for banner in self; it will be passed to the mainloop
965 # method only and .run() needs it. The actual value will be set by
966 # method only and .run() needs it. The actual value will be set by
966 # .mainloop().
967 # .mainloop().
967 self._banner = None
968 self._banner = None
968
969
969 threading.Thread.__init__(self)
970 threading.Thread.__init__(self)
970
971
971 def mainloop(self, sys_exit=0, banner=None):
972 def mainloop(self, sys_exit=0, banner=None):
972
973
973 import qt
974 import qt
974
975
975 self._banner = banner
976 self._banner = banner
976
977
977 if qt.QApplication.startingUp():
978 if qt.QApplication.startingUp():
978 a = qt.QApplication(sys.argv)
979 a = qt.QApplication(sys.argv)
979
980
980 self.timer = qt.QTimer()
981 self.timer = qt.QTimer()
981 qt.QObject.connect(self.timer,
982 qt.QObject.connect(self.timer,
982 qt.SIGNAL('timeout()'),
983 qt.SIGNAL('timeout()'),
983 self.on_timer)
984 self.on_timer)
984
985
985 self.start()
986 self.start()
986 self.timer.start(self.TIMEOUT, True)
987 self.timer.start(self.TIMEOUT, True)
987 while True:
988 while True:
988 if self.IP._kill: break
989 if self.IP._kill: break
989 self.exec_loop()
990 self.exec_loop()
990 self.join()
991 self.join()
991
992
992 def on_timer(self):
993 def on_timer(self):
993 update_tk(self.tk)
994 update_tk(self.tk)
994 result = self.IP.runcode()
995 result = self.IP.runcode()
995 self.timer.start(self.TIMEOUT, True)
996 self.timer.start(self.TIMEOUT, True)
996 return result
997 return result
997
998
998
999
999 class IPShellQt4(IPThread):
1000 class IPShellQt4(IPThread):
1000 """Run a Qt event loop in a separate thread.
1001 """Run a Qt event loop in a separate thread.
1001
1002
1002 Python commands can be passed to the thread where they will be executed.
1003 Python commands can be passed to the thread where they will be executed.
1003 This is implemented by periodically checking for passed code using a
1004 This is implemented by periodically checking for passed code using a
1004 Qt timer / slot."""
1005 Qt timer / slot."""
1005
1006
1006 TIMEOUT = 100 # Millisecond interval between timeouts.
1007 TIMEOUT = 100 # Millisecond interval between timeouts.
1007
1008
1008 def __init__(self, argv=None, user_ns=None, user_global_ns=None,
1009 def __init__(self, argv=None, user_ns=None, user_global_ns=None,
1009 debug=0, shell_class=MTInteractiveShell):
1010 debug=0, shell_class=MTInteractiveShell):
1010
1011
1011 from PyQt4 import QtCore, QtGui
1012 from PyQt4 import QtCore, QtGui
1012
1013
1013 try:
1014 try:
1014 # present in PyQt4-4.2.1 or later
1015 # present in PyQt4-4.2.1 or later
1015 QtCore.pyqtRemoveInputHook()
1016 QtCore.pyqtRemoveInputHook()
1016 except AttributeError:
1017 except AttributeError:
1017 pass
1018 pass
1018
1019
1019 if QtCore.PYQT_VERSION_STR == '4.3':
1020 if QtCore.PYQT_VERSION_STR == '4.3':
1020 warn('''PyQt4 version 4.3 detected.
1021 warn('''PyQt4 version 4.3 detected.
1021 If you experience repeated threading warnings, please update PyQt4.
1022 If you experience repeated threading warnings, please update PyQt4.
1022 ''')
1023 ''')
1023
1024
1024 self.exec_ = hijack_qt4()
1025 self.exec_ = hijack_qt4()
1025
1026
1026 # Allows us to use both Tk and QT.
1027 # Allows us to use both Tk and QT.
1027 self.tk = get_tk()
1028 self.tk = get_tk()
1028
1029
1029 self.IP = make_IPython(argv,
1030 self.IP = make_IPython(argv,
1030 user_ns=user_ns,
1031 user_ns=user_ns,
1031 user_global_ns=user_global_ns,
1032 user_global_ns=user_global_ns,
1032 debug=debug,
1033 debug=debug,
1033 shell_class=shell_class,
1034 shell_class=shell_class,
1034 on_kill=[QtGui.qApp.exit])
1035 on_kill=[QtGui.qApp.exit])
1035
1036
1036 # HACK: slot for banner in self; it will be passed to the mainloop
1037 # HACK: slot for banner in self; it will be passed to the mainloop
1037 # method only and .run() needs it. The actual value will be set by
1038 # method only and .run() needs it. The actual value will be set by
1038 # .mainloop().
1039 # .mainloop().
1039 self._banner = None
1040 self._banner = None
1040
1041
1041 threading.Thread.__init__(self)
1042 threading.Thread.__init__(self)
1042
1043
1043 def mainloop(self, sys_exit=0, banner=None):
1044 def mainloop(self, sys_exit=0, banner=None):
1044
1045
1045 from PyQt4 import QtCore, QtGui
1046 from PyQt4 import QtCore, QtGui
1046
1047
1047 self._banner = banner
1048 self._banner = banner
1048
1049
1049 if QtGui.QApplication.startingUp():
1050 if QtGui.QApplication.startingUp():
1050 a = QtGui.QApplication(sys.argv)
1051 a = QtGui.QApplication(sys.argv)
1051
1052
1052 self.timer = QtCore.QTimer()
1053 self.timer = QtCore.QTimer()
1053 QtCore.QObject.connect(self.timer,
1054 QtCore.QObject.connect(self.timer,
1054 QtCore.SIGNAL('timeout()'),
1055 QtCore.SIGNAL('timeout()'),
1055 self.on_timer)
1056 self.on_timer)
1056
1057
1057 self.start()
1058 self.start()
1058 self.timer.start(self.TIMEOUT)
1059 self.timer.start(self.TIMEOUT)
1059 while True:
1060 while True:
1060 if self.IP._kill: break
1061 if self.IP._kill: break
1061 self.exec_()
1062 self.exec_()
1062 self.join()
1063 self.join()
1063
1064
1064 def on_timer(self):
1065 def on_timer(self):
1065 update_tk(self.tk)
1066 update_tk(self.tk)
1066 result = self.IP.runcode()
1067 result = self.IP.runcode()
1067 self.timer.start(self.TIMEOUT)
1068 self.timer.start(self.TIMEOUT)
1068 return result
1069 return result
1069
1070
1070
1071
1071 # A set of matplotlib public IPython shell classes, for single-threaded (Tk*
1072 # A set of matplotlib public IPython shell classes, for single-threaded (Tk*
1072 # and FLTK*) and multithreaded (GTK*, WX* and Qt*) backends to use.
1073 # and FLTK*) and multithreaded (GTK*, WX* and Qt*) backends to use.
1073 def _load_pylab(user_ns):
1074 def _load_pylab(user_ns):
1074 """Allow users to disable pulling all of pylab into the top-level
1075 """Allow users to disable pulling all of pylab into the top-level
1075 namespace.
1076 namespace.
1076
1077
1077 This little utility must be called AFTER the actual ipython instance is
1078 This little utility must be called AFTER the actual ipython instance is
1078 running, since only then will the options file have been fully parsed."""
1079 running, since only then will the options file have been fully parsed."""
1079
1080
1080 ip = IPython.ipapi.get()
1081 ip = IPython.ipapi.get()
1081 if ip.options.pylab_import_all:
1082 if ip.options.pylab_import_all:
1082 ip.ex("from matplotlib.pylab import *")
1083 ip.ex("from matplotlib.pylab import *")
1083 ip.IP.user_config_ns.update(ip.user_ns)
1084 ip.IP.user_config_ns.update(ip.user_ns)
1084
1085
1085
1086
1086 class IPShellMatplotlib(IPShell):
1087 class IPShellMatplotlib(IPShell):
1087 """Subclass IPShell with MatplotlibShell as the internal shell.
1088 """Subclass IPShell with MatplotlibShell as the internal shell.
1088
1089
1089 Single-threaded class, meant for the Tk* and FLTK* backends.
1090 Single-threaded class, meant for the Tk* and FLTK* backends.
1090
1091
1091 Having this on a separate class simplifies the external driver code."""
1092 Having this on a separate class simplifies the external driver code."""
1092
1093
1093 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1094 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1094 IPShell.__init__(self,argv,user_ns,user_global_ns,debug,
1095 IPShell.__init__(self,argv,user_ns,user_global_ns,debug,
1095 shell_class=MatplotlibShell)
1096 shell_class=MatplotlibShell)
1096 _load_pylab(self.IP.user_ns)
1097 _load_pylab(self.IP.user_ns)
1097
1098
1098 class IPShellMatplotlibGTK(IPShellGTK):
1099 class IPShellMatplotlibGTK(IPShellGTK):
1099 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
1100 """Subclass IPShellGTK with MatplotlibMTShell as the internal shell.
1100
1101
1101 Multi-threaded class, meant for the GTK* backends."""
1102 Multi-threaded class, meant for the GTK* backends."""
1102
1103
1103 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1104 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1104 IPShellGTK.__init__(self,argv,user_ns,user_global_ns,debug,
1105 IPShellGTK.__init__(self,argv,user_ns,user_global_ns,debug,
1105 shell_class=MatplotlibMTShell)
1106 shell_class=MatplotlibMTShell)
1106 _load_pylab(self.IP.user_ns)
1107 _load_pylab(self.IP.user_ns)
1107
1108
1108 class IPShellMatplotlibWX(IPShellWX):
1109 class IPShellMatplotlibWX(IPShellWX):
1109 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
1110 """Subclass IPShellWX with MatplotlibMTShell as the internal shell.
1110
1111
1111 Multi-threaded class, meant for the WX* backends."""
1112 Multi-threaded class, meant for the WX* backends."""
1112
1113
1113 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1114 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1114 IPShellWX.__init__(self,argv,user_ns,user_global_ns,debug,
1115 IPShellWX.__init__(self,argv,user_ns,user_global_ns,debug,
1115 shell_class=MatplotlibMTShell)
1116 shell_class=MatplotlibMTShell)
1116 _load_pylab(self.IP.user_ns)
1117 _load_pylab(self.IP.user_ns)
1117
1118
1118 class IPShellMatplotlibQt(IPShellQt):
1119 class IPShellMatplotlibQt(IPShellQt):
1119 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
1120 """Subclass IPShellQt with MatplotlibMTShell as the internal shell.
1120
1121
1121 Multi-threaded class, meant for the Qt* backends."""
1122 Multi-threaded class, meant for the Qt* backends."""
1122
1123
1123 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1124 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1124 IPShellQt.__init__(self,argv,user_ns,user_global_ns,debug,
1125 IPShellQt.__init__(self,argv,user_ns,user_global_ns,debug,
1125 shell_class=MatplotlibMTShell)
1126 shell_class=MatplotlibMTShell)
1126 _load_pylab(self.IP.user_ns)
1127 _load_pylab(self.IP.user_ns)
1127
1128
1128 class IPShellMatplotlibQt4(IPShellQt4):
1129 class IPShellMatplotlibQt4(IPShellQt4):
1129 """Subclass IPShellQt4 with MatplotlibMTShell as the internal shell.
1130 """Subclass IPShellQt4 with MatplotlibMTShell as the internal shell.
1130
1131
1131 Multi-threaded class, meant for the Qt4* backends."""
1132 Multi-threaded class, meant for the Qt4* backends."""
1132
1133
1133 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1134 def __init__(self,argv=None,user_ns=None,user_global_ns=None,debug=1):
1134 IPShellQt4.__init__(self,argv,user_ns,user_global_ns,debug,
1135 IPShellQt4.__init__(self,argv,user_ns,user_global_ns,debug,
1135 shell_class=MatplotlibMTShell)
1136 shell_class=MatplotlibMTShell)
1136 _load_pylab(self.IP.user_ns)
1137 _load_pylab(self.IP.user_ns)
1137
1138
1138 #-----------------------------------------------------------------------------
1139 #-----------------------------------------------------------------------------
1139 # Factory functions to actually start the proper thread-aware shell
1140 # Factory functions to actually start the proper thread-aware shell
1140
1141
1141 def _select_shell(argv):
1142 def _select_shell(argv):
1142 """Select a shell from the given argv vector.
1143 """Select a shell from the given argv vector.
1143
1144
1144 This function implements the threading selection policy, allowing runtime
1145 This function implements the threading selection policy, allowing runtime
1145 control of the threading mode, both for general users and for matplotlib.
1146 control of the threading mode, both for general users and for matplotlib.
1146
1147
1147 Return:
1148 Return:
1148 Shell class to be instantiated for runtime operation.
1149 Shell class to be instantiated for runtime operation.
1149 """
1150 """
1150
1151
1151 global USE_TK
1152 global USE_TK
1152
1153
1153 mpl_shell = {'gthread' : IPShellMatplotlibGTK,
1154 mpl_shell = {'gthread' : IPShellMatplotlibGTK,
1154 'wthread' : IPShellMatplotlibWX,
1155 'wthread' : IPShellMatplotlibWX,
1155 'qthread' : IPShellMatplotlibQt,
1156 'qthread' : IPShellMatplotlibQt,
1156 'q4thread' : IPShellMatplotlibQt4,
1157 'q4thread' : IPShellMatplotlibQt4,
1157 'tkthread' : IPShellMatplotlib, # Tk is built-in
1158 'tkthread' : IPShellMatplotlib, # Tk is built-in
1158 }
1159 }
1159
1160
1160 th_shell = {'gthread' : IPShellGTK,
1161 th_shell = {'gthread' : IPShellGTK,
1161 'wthread' : IPShellWX,
1162 'wthread' : IPShellWX,
1162 'qthread' : IPShellQt,
1163 'qthread' : IPShellQt,
1163 'q4thread' : IPShellQt4,
1164 'q4thread' : IPShellQt4,
1164 'tkthread' : IPShell, # Tk is built-in
1165 'tkthread' : IPShell, # Tk is built-in
1165 }
1166 }
1166
1167
1167 backends = {'gthread' : 'GTKAgg',
1168 backends = {'gthread' : 'GTKAgg',
1168 'wthread' : 'WXAgg',
1169 'wthread' : 'WXAgg',
1169 'qthread' : 'QtAgg',
1170 'qthread' : 'QtAgg',
1170 'q4thread' :'Qt4Agg',
1171 'q4thread' :'Qt4Agg',
1171 'tkthread' :'TkAgg',
1172 'tkthread' :'TkAgg',
1172 }
1173 }
1173
1174
1174 all_opts = set(['tk','pylab','gthread','qthread','q4thread','wthread',
1175 all_opts = set(['tk','pylab','gthread','qthread','q4thread','wthread',
1175 'tkthread'])
1176 'tkthread'])
1176 user_opts = set([s.replace('-','') for s in argv[:3]])
1177 user_opts = set([s.replace('-','') for s in argv[:3]])
1177 special_opts = user_opts & all_opts
1178 special_opts = user_opts & all_opts
1178
1179
1179 if 'tk' in special_opts:
1180 if 'tk' in special_opts:
1180 USE_TK = True
1181 USE_TK = True
1181 special_opts.remove('tk')
1182 special_opts.remove('tk')
1182
1183
1183 if 'pylab' in special_opts:
1184 if 'pylab' in special_opts:
1184
1185
1185 try:
1186 try:
1186 import matplotlib
1187 import matplotlib
1187 except ImportError:
1188 except ImportError:
1188 error('matplotlib could NOT be imported! Starting normal IPython.')
1189 error('matplotlib could NOT be imported! Starting normal IPython.')
1189 return IPShell
1190 return IPShell
1190
1191
1191 special_opts.remove('pylab')
1192 special_opts.remove('pylab')
1192 # If there's any option left, it means the user wants to force the
1193 # If there's any option left, it means the user wants to force the
1193 # threading backend, else it's auto-selected from the rc file
1194 # threading backend, else it's auto-selected from the rc file
1194 if special_opts:
1195 if special_opts:
1195 th_mode = special_opts.pop()
1196 th_mode = special_opts.pop()
1196 matplotlib.rcParams['backend'] = backends[th_mode]
1197 matplotlib.rcParams['backend'] = backends[th_mode]
1197 else:
1198 else:
1198 backend = matplotlib.rcParams['backend']
1199 backend = matplotlib.rcParams['backend']
1199 if backend.startswith('GTK'):
1200 if backend.startswith('GTK'):
1200 th_mode = 'gthread'
1201 th_mode = 'gthread'
1201 elif backend.startswith('WX'):
1202 elif backend.startswith('WX'):
1202 th_mode = 'wthread'
1203 th_mode = 'wthread'
1203 elif backend.startswith('Qt4'):
1204 elif backend.startswith('Qt4'):
1204 th_mode = 'q4thread'
1205 th_mode = 'q4thread'
1205 elif backend.startswith('Qt'):
1206 elif backend.startswith('Qt'):
1206 th_mode = 'qthread'
1207 th_mode = 'qthread'
1207 else:
1208 else:
1208 # Any other backend, use plain Tk
1209 # Any other backend, use plain Tk
1209 th_mode = 'tkthread'
1210 th_mode = 'tkthread'
1210
1211
1211 return mpl_shell[th_mode]
1212 return mpl_shell[th_mode]
1212 else:
1213 else:
1213 # No pylab requested, just plain threads
1214 # No pylab requested, just plain threads
1214 try:
1215 try:
1215 th_mode = special_opts.pop()
1216 th_mode = special_opts.pop()
1216 except KeyError:
1217 except KeyError:
1217 th_mode = 'tkthread'
1218 th_mode = 'tkthread'
1218 return th_shell[th_mode]
1219 return th_shell[th_mode]
1219
1220
1220
1221
1221 # This is the one which should be called by external code.
1222 # This is the one which should be called by external code.
1222 def start(user_ns = None):
1223 def start(user_ns = None):
1223 """Return a running shell instance, dealing with threading options.
1224 """Return a running shell instance, dealing with threading options.
1224
1225
1225 This is a factory function which will instantiate the proper IPython shell
1226 This is a factory function which will instantiate the proper IPython shell
1226 based on the user's threading choice. Such a selector is needed because
1227 based on the user's threading choice. Such a selector is needed because
1227 different GUI toolkits require different thread handling details."""
1228 different GUI toolkits require different thread handling details."""
1228
1229
1229 shell = _select_shell(sys.argv)
1230 shell = _select_shell(sys.argv)
1230 return shell(user_ns = user_ns)
1231 return shell(user_ns = user_ns)
1231
1232
1232 # Some aliases for backwards compatibility
1233 # Some aliases for backwards compatibility
1233 IPythonShell = IPShell
1234 IPythonShell = IPShell
1234 IPythonShellEmbed = IPShellEmbed
1235 IPythonShellEmbed = IPShellEmbed
1235 #************************ End of file <Shell.py> ***************************
1236 #************************ End of file <Shell.py> ***************************
@@ -1,609 +1,647 b''
1 """IPython customization API
1 """IPython customization API
2
2
3 Your one-stop module for configuring & extending ipython
3 Your one-stop module for configuring & extending ipython
4
4
5 The API will probably break when ipython 1.0 is released, but so
5 The API will probably break when ipython 1.0 is released, but so
6 will the other configuration method (rc files).
6 will the other configuration method (rc files).
7
7
8 All names prefixed by underscores are for internal use, not part
8 All names prefixed by underscores are for internal use, not part
9 of the public api.
9 of the public api.
10
10
11 Below is an example that you can just put to a module and import from ipython.
11 Below is an example that you can just put to a module and import from ipython.
12
12
13 A good practice is to install the config script below as e.g.
13 A good practice is to install the config script below as e.g.
14
14
15 ~/.ipython/my_private_conf.py
15 ~/.ipython/my_private_conf.py
16
16
17 And do
17 And do
18
18
19 import_mod my_private_conf
19 import_mod my_private_conf
20
20
21 in ~/.ipython/ipythonrc
21 in ~/.ipython/ipythonrc
22
22
23 That way the module is imported at startup and you can have all your
23 That way the module is imported at startup and you can have all your
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
24 personal configuration (as opposed to boilerplate ipythonrc-PROFILENAME
25 stuff) in there.
25 stuff) in there.
26
26
27 -----------------------------------------------
27 -----------------------------------------------
28 import IPython.ipapi
28 import IPython.ipapi
29 ip = IPython.ipapi.get()
29 ip = IPython.ipapi.get()
30
30
31 def ankka_f(self, arg):
31 def ankka_f(self, arg):
32 print 'Ankka',self,'says uppercase:',arg.upper()
32 print 'Ankka',self,'says uppercase:',arg.upper()
33
33
34 ip.expose_magic('ankka',ankka_f)
34 ip.expose_magic('ankka',ankka_f)
35
35
36 ip.magic('alias sayhi echo "Testing, hi ok"')
36 ip.magic('alias sayhi echo "Testing, hi ok"')
37 ip.magic('alias helloworld echo "Hello world"')
37 ip.magic('alias helloworld echo "Hello world"')
38 ip.system('pwd')
38 ip.system('pwd')
39
39
40 ip.ex('import re')
40 ip.ex('import re')
41 ip.ex('''
41 ip.ex('''
42 def funcci(a,b):
42 def funcci(a,b):
43 print a+b
43 print a+b
44 print funcci(3,4)
44 print funcci(3,4)
45 ''')
45 ''')
46 ip.ex('funcci(348,9)')
46 ip.ex('funcci(348,9)')
47
47
48 def jed_editor(self,filename, linenum=None):
48 def jed_editor(self,filename, linenum=None):
49 print 'Calling my own editor, jed ... via hook!'
49 print 'Calling my own editor, jed ... via hook!'
50 import os
50 import os
51 if linenum is None: linenum = 0
51 if linenum is None: linenum = 0
52 os.system('jed +%d %s' % (linenum, filename))
52 os.system('jed +%d %s' % (linenum, filename))
53 print 'exiting jed'
53 print 'exiting jed'
54
54
55 ip.set_hook('editor',jed_editor)
55 ip.set_hook('editor',jed_editor)
56
56
57 o = ip.options
57 o = ip.options
58 o.autocall = 2 # FULL autocall mode
58 o.autocall = 2 # FULL autocall mode
59
59
60 print 'done!'
60 print 'done!'
61 """
61 """
62
62
63 #-----------------------------------------------------------------------------
63 #-----------------------------------------------------------------------------
64 # Modules and globals
64 # Modules and globals
65
65
66 # stdlib imports
66 # stdlib imports
67 import __builtin__
67 import __builtin__
68 import sys
68 import sys
69
69
70 # contains the most recently instantiated IPApi
70 # contains the most recently instantiated IPApi
71 _RECENT_IP = None
71 _RECENT_IP = None
72
72
73 #-----------------------------------------------------------------------------
73 #-----------------------------------------------------------------------------
74 # Code begins
74 # Code begins
75
75
76 class TryNext(Exception):
76 class TryNext(Exception):
77 """Try next hook exception.
77 """Try next hook exception.
78
78
79 Raise this in your hook function to indicate that the next hook handler
79 Raise this in your hook function to indicate that the next hook handler
80 should be used to handle the operation. If you pass arguments to the
80 should be used to handle the operation. If you pass arguments to the
81 constructor those arguments will be used by the next hook instead of the
81 constructor those arguments will be used by the next hook instead of the
82 original ones.
82 original ones.
83 """
83 """
84
84
85 def __init__(self, *args, **kwargs):
85 def __init__(self, *args, **kwargs):
86 self.args = args
86 self.args = args
87 self.kwargs = kwargs
87 self.kwargs = kwargs
88
88
89
89
90 class UsageError(Exception):
90 class UsageError(Exception):
91 """ Error in magic function arguments, etc.
91 """ Error in magic function arguments, etc.
92
92
93 Something that probably won't warrant a full traceback, but should
93 Something that probably won't warrant a full traceback, but should
94 nevertheless interrupt a macro / batch file.
94 nevertheless interrupt a macro / batch file.
95 """
95 """
96
96
97
97
98 class IPyAutocall:
98 class IPyAutocall:
99 """ Instances of this class are always autocalled
99 """ Instances of this class are always autocalled
100
100
101 This happens regardless of 'autocall' variable state. Use this to
101 This happens regardless of 'autocall' variable state. Use this to
102 develop macro-like mechanisms.
102 develop macro-like mechanisms.
103 """
103 """
104
104
105 def set_ip(self,ip):
105 def set_ip(self,ip):
106 """ Will be used to set _ip point to current ipython instance b/f call
106 """ Will be used to set _ip point to current ipython instance b/f call
107
107
108 Override this method if you don't want this to happen.
108 Override this method if you don't want this to happen.
109
109
110 """
110 """
111 self._ip = ip
111 self._ip = ip
112
112
113
113
114 class IPythonNotRunning:
114 class IPythonNotRunning:
115 """Dummy do-nothing class.
115 """Dummy do-nothing class.
116
116
117 Instances of this class return a dummy attribute on all accesses, which
117 Instances of this class return a dummy attribute on all accesses, which
118 can be called and warns. This makes it easier to write scripts which use
118 can be called and warns. This makes it easier to write scripts which use
119 the ipapi.get() object for informational purposes to operate both with and
119 the ipapi.get() object for informational purposes to operate both with and
120 without ipython. Obviously code which uses the ipython object for
120 without ipython. Obviously code which uses the ipython object for
121 computations will not work, but this allows a wider range of code to
121 computations will not work, but this allows a wider range of code to
122 transparently work whether ipython is being used or not."""
122 transparently work whether ipython is being used or not."""
123
123
124 def __init__(self,warn=True):
124 def __init__(self,warn=True):
125 if warn:
125 if warn:
126 self.dummy = self._dummy_warn
126 self.dummy = self._dummy_warn
127 else:
127 else:
128 self.dummy = self._dummy_silent
128 self.dummy = self._dummy_silent
129
129
130 def __str__(self):
130 def __str__(self):
131 return "<IPythonNotRunning>"
131 return "<IPythonNotRunning>"
132
132
133 __repr__ = __str__
133 __repr__ = __str__
134
134
135 def __getattr__(self,name):
135 def __getattr__(self,name):
136 return self.dummy
136 return self.dummy
137
137
138 def _dummy_warn(self,*args,**kw):
138 def _dummy_warn(self,*args,**kw):
139 """Dummy function, which doesn't do anything but warn."""
139 """Dummy function, which doesn't do anything but warn."""
140
140
141 print ("IPython is not running, this is a dummy no-op function")
141 print ("IPython is not running, this is a dummy no-op function")
142
142
143 def _dummy_silent(self,*args,**kw):
143 def _dummy_silent(self,*args,**kw):
144 """Dummy function, which doesn't do anything and emits no warnings."""
144 """Dummy function, which doesn't do anything and emits no warnings."""
145 pass
145 pass
146
146
147
147
148 def get(allow_dummy=False,dummy_warn=True):
148 def get(allow_dummy=False,dummy_warn=True):
149 """Get an IPApi object.
149 """Get an IPApi object.
150
150
151 If allow_dummy is true, returns an instance of IPythonNotRunning
151 If allow_dummy is true, returns an instance of IPythonNotRunning
152 instead of None if not running under IPython.
152 instead of None if not running under IPython.
153
153
154 If dummy_warn is false, the dummy instance will be completely silent.
154 If dummy_warn is false, the dummy instance will be completely silent.
155
155
156 Running this should be the first thing you do when writing extensions that
156 Running this should be the first thing you do when writing extensions that
157 can be imported as normal modules. You can then direct all the
157 can be imported as normal modules. You can then direct all the
158 configuration operations against the returned object.
158 configuration operations against the returned object.
159 """
159 """
160 global _RECENT_IP
160 global _RECENT_IP
161 if allow_dummy and not _RECENT_IP:
161 if allow_dummy and not _RECENT_IP:
162 _RECENT_IP = IPythonNotRunning(dummy_warn)
162 _RECENT_IP = IPythonNotRunning(dummy_warn)
163 return _RECENT_IP
163 return _RECENT_IP
164
164
165
165
166 class IPApi(object):
166 class IPApi(object):
167 """ The actual API class for configuring IPython
167 """ The actual API class for configuring IPython
168
168
169 You should do all of the IPython configuration by getting an IPApi object
169 You should do all of the IPython configuration by getting an IPApi object
170 with IPython.ipapi.get() and using the attributes and methods of the
170 with IPython.ipapi.get() and using the attributes and methods of the
171 returned object."""
171 returned object."""
172
172
173 def __init__(self,ip):
173 def __init__(self,ip):
174
174
175 global _RECENT_IP
175 global _RECENT_IP
176
176
177 # All attributes exposed here are considered to be the public API of
177 # All attributes exposed here are considered to be the public API of
178 # IPython. As needs dictate, some of these may be wrapped as
178 # IPython. As needs dictate, some of these may be wrapped as
179 # properties.
179 # properties.
180
180
181 self.magic = ip.ipmagic
181 self.magic = ip.ipmagic
182
182
183 self.system = ip.system
183 self.system = ip.system
184
184
185 self.set_hook = ip.set_hook
185 self.set_hook = ip.set_hook
186
186
187 self.set_custom_exc = ip.set_custom_exc
187 self.set_custom_exc = ip.set_custom_exc
188
188
189 self.user_ns = ip.user_ns
189 self.user_ns = ip.user_ns
190 self.user_ns['_ip'] = self
190 self.user_ns['_ip'] = self
191
191
192 self.set_crash_handler = ip.set_crash_handler
192 self.set_crash_handler = ip.set_crash_handler
193
193
194 # Session-specific data store, which can be used to store
194 # Session-specific data store, which can be used to store
195 # data that should persist through the ipython session.
195 # data that should persist through the ipython session.
196 self.meta = ip.meta
196 self.meta = ip.meta
197
197
198 # The ipython instance provided
198 # The ipython instance provided
199 self.IP = ip
199 self.IP = ip
200
200
201 self.extensions = {}
201 self.extensions = {}
202
202
203 self.dbg = DebugTools(self)
203 self.dbg = DebugTools(self)
204
204
205 _RECENT_IP = self
205 _RECENT_IP = self
206
206
207 # Use a property for some things which are added to the instance very
207 # Use a property for some things which are added to the instance very
208 # late. I don't have time right now to disentangle the initialization
208 # late. I don't have time right now to disentangle the initialization
209 # order issues, so a property lets us delay item extraction while
209 # order issues, so a property lets us delay item extraction while
210 # providing a normal attribute API.
210 # providing a normal attribute API.
211 def get_db(self):
211 def get_db(self):
212 """A handle to persistent dict-like database (a PickleShareDB object)"""
212 """A handle to persistent dict-like database (a PickleShareDB object)"""
213 return self.IP.db
213 return self.IP.db
214
214
215 db = property(get_db,None,None,get_db.__doc__)
215 db = property(get_db,None,None,get_db.__doc__)
216
216
217 def get_options(self):
217 def get_options(self):
218 """All configurable variables."""
218 """All configurable variables."""
219
219
220 # catch typos by disabling new attribute creation. If new attr creation
220 # catch typos by disabling new attribute creation. If new attr creation
221 # is in fact wanted (e.g. when exposing new options), do
221 # is in fact wanted (e.g. when exposing new options), do
222 # allow_new_attr(True) for the received rc struct.
222 # allow_new_attr(True) for the received rc struct.
223
223
224 self.IP.rc.allow_new_attr(False)
224 self.IP.rc.allow_new_attr(False)
225 return self.IP.rc
225 return self.IP.rc
226
226
227 options = property(get_options,None,None,get_options.__doc__)
227 options = property(get_options,None,None,get_options.__doc__)
228
228
229 def expose_magic(self,magicname, func):
229 def expose_magic(self,magicname, func):
230 """Expose own function as magic function for ipython
230 """Expose own function as magic function for ipython
231
231
232 def foo_impl(self,parameter_s=''):
232 def foo_impl(self,parameter_s=''):
233 'My very own magic!. (Use docstrings, IPython reads them).'
233 'My very own magic!. (Use docstrings, IPython reads them).'
234 print 'Magic function. Passed parameter is between < >:'
234 print 'Magic function. Passed parameter is between < >:'
235 print '<%s>' % parameter_s
235 print '<%s>' % parameter_s
236 print 'The self object is:',self
236 print 'The self object is:',self
237
237
238 ipapi.expose_magic('foo',foo_impl)
238 ipapi.expose_magic('foo',foo_impl)
239 """
239 """
240
240
241 import new
241 import new
242 im = new.instancemethod(func,self.IP, self.IP.__class__)
242 im = new.instancemethod(func,self.IP, self.IP.__class__)
243 old = getattr(self.IP, "magic_" + magicname, None)
243 old = getattr(self.IP, "magic_" + magicname, None)
244 if old:
244 if old:
245 self.dbg.debug_stack("Magic redefinition '%s', old %s" %
245 self.dbg.debug_stack("Magic redefinition '%s', old %s" %
246 (magicname,old) )
246 (magicname,old) )
247
247
248 setattr(self.IP, "magic_" + magicname, im)
248 setattr(self.IP, "magic_" + magicname, im)
249
249
250 def ex(self,cmd):
250 def ex(self,cmd):
251 """ Execute a normal python statement in user namespace """
251 """ Execute a normal python statement in user namespace """
252 exec cmd in self.user_ns
252 exec cmd in self.user_ns
253
253
254 def ev(self,expr):
254 def ev(self,expr):
255 """ Evaluate python expression expr in user namespace
255 """ Evaluate python expression expr in user namespace
256
256
257 Returns the result of evaluation"""
257 Returns the result of evaluation"""
258 return eval(expr,self.user_ns)
258 return eval(expr,self.user_ns)
259
259
260 def runlines(self,lines):
260 def runlines(self,lines):
261 """ Run the specified lines in interpreter, honoring ipython directives.
261 """ Run the specified lines in interpreter, honoring ipython directives.
262
262
263 This allows %magic and !shell escape notations.
263 This allows %magic and !shell escape notations.
264
264
265 Takes either all lines in one string or list of lines.
265 Takes either all lines in one string or list of lines.
266 """
266 """
267
267
268 def cleanup_ipy_script(script):
268 def cleanup_ipy_script(script):
269 """ Make a script safe for _ip.runlines()
269 """ Make a script safe for _ip.runlines()
270
270
271 - Removes empty lines Suffixes all indented blocks that end with
271 - Removes empty lines Suffixes all indented blocks that end with
272 - unindented lines with empty lines
272 - unindented lines with empty lines
273 """
273 """
274
274
275 res = []
275 res = []
276 lines = script.splitlines()
276 lines = script.splitlines()
277
277
278 level = 0
278 level = 0
279 for l in lines:
279 for l in lines:
280 lstripped = l.lstrip()
280 lstripped = l.lstrip()
281 stripped = l.strip()
281 stripped = l.strip()
282 if not stripped:
282 if not stripped:
283 continue
283 continue
284 newlevel = len(l) - len(lstripped)
284 newlevel = len(l) - len(lstripped)
285 def is_secondary_block_start(s):
285 def is_secondary_block_start(s):
286 if not s.endswith(':'):
286 if not s.endswith(':'):
287 return False
287 return False
288 if (s.startswith('elif') or
288 if (s.startswith('elif') or
289 s.startswith('else') or
289 s.startswith('else') or
290 s.startswith('except') or
290 s.startswith('except') or
291 s.startswith('finally')):
291 s.startswith('finally')):
292 return True
292 return True
293
293
294 if level > 0 and newlevel == 0 and \
294 if level > 0 and newlevel == 0 and \
295 not is_secondary_block_start(stripped):
295 not is_secondary_block_start(stripped):
296 # add empty line
296 # add empty line
297 res.append('')
297 res.append('')
298
298
299 res.append(l)
299 res.append(l)
300 level = newlevel
300 level = newlevel
301 return '\n'.join(res) + '\n'
301 return '\n'.join(res) + '\n'
302
302
303 if isinstance(lines,basestring):
303 if isinstance(lines,basestring):
304 script = lines
304 script = lines
305 else:
305 else:
306 script = '\n'.join(lines)
306 script = '\n'.join(lines)
307 clean=cleanup_ipy_script(script)
307 clean=cleanup_ipy_script(script)
308 # print "_ip.runlines() script:\n",clean # dbg
308 # print "_ip.runlines() script:\n",clean # dbg
309 self.IP.runlines(clean)
309 self.IP.runlines(clean)
310
310
311 def to_user_ns(self,vars, interactive = True):
311 def to_user_ns(self,vars, interactive = True):
312 """Inject a group of variables into the IPython user namespace.
312 """Inject a group of variables into the IPython user namespace.
313
313
314 Inputs:
314 Inputs:
315
315
316 - vars: string with variable names separated by whitespace, or a
316 - vars: string with variable names separated by whitespace, or a
317 dict with name/value pairs.
317 dict with name/value pairs.
318
318
319 - interactive: if True (default), the var will be listed with
319 - interactive: if True (default), the var will be listed with
320 %whos et. al.
320 %whos et. al.
321
321
322 This utility routine is meant to ease interactive debugging work,
322 This utility routine is meant to ease interactive debugging work,
323 where you want to easily propagate some internal variable in your code
323 where you want to easily propagate some internal variable in your code
324 up to the interactive namespace for further exploration.
324 up to the interactive namespace for further exploration.
325
325
326 When you run code via %run, globals in your script become visible at
326 When you run code via %run, globals in your script become visible at
327 the interactive prompt, but this doesn't happen for locals inside your
327 the interactive prompt, but this doesn't happen for locals inside your
328 own functions and methods. Yet when debugging, it is common to want
328 own functions and methods. Yet when debugging, it is common to want
329 to explore some internal variables further at the interactive propmt.
329 to explore some internal variables further at the interactive propmt.
330
330
331 Examples:
331 Examples:
332
332
333 To use this, you first must obtain a handle on the ipython object as
333 To use this, you first must obtain a handle on the ipython object as
334 indicated above, via:
334 indicated above, via:
335
335
336 import IPython.ipapi
336 import IPython.ipapi
337 ip = IPython.ipapi.get()
337 ip = IPython.ipapi.get()
338
338
339 Once this is done, inside a routine foo() where you want to expose
339 Once this is done, inside a routine foo() where you want to expose
340 variables x and y, you do the following:
340 variables x and y, you do the following:
341
341
342 def foo():
342 def foo():
343 ...
343 ...
344 x = your_computation()
344 x = your_computation()
345 y = something_else()
345 y = something_else()
346
346
347 # This pushes x and y to the interactive prompt immediately, even
347 # This pushes x and y to the interactive prompt immediately, even
348 # if this routine crashes on the next line after:
348 # if this routine crashes on the next line after:
349 ip.to_user_ns('x y')
349 ip.to_user_ns('x y')
350 ...
350 ...
351
351
352 # To expose *ALL* the local variables from the function, use:
352 # To expose *ALL* the local variables from the function, use:
353 ip.to_user_ns(locals())
353 ip.to_user_ns(locals())
354
354
355 ...
355 ...
356 # return
356 # return
357
357
358
358
359 If you need to rename variables, the dict input makes it easy. For
359 If you need to rename variables, the dict input makes it easy. For
360 example, this call exposes variables 'foo' as 'x' and 'bar' as 'y'
360 example, this call exposes variables 'foo' as 'x' and 'bar' as 'y'
361 in IPython user namespace:
361 in IPython user namespace:
362
362
363 ip.to_user_ns(dict(x=foo,y=bar))
363 ip.to_user_ns(dict(x=foo,y=bar))
364 """
364 """
365
365
366 # print 'vars given:',vars # dbg
366 # print 'vars given:',vars # dbg
367
367
368 # We need a dict of name/value pairs to do namespace updates.
368 # We need a dict of name/value pairs to do namespace updates.
369 if isinstance(vars,dict):
369 if isinstance(vars,dict):
370 # If a dict was given, no need to change anything.
370 # If a dict was given, no need to change anything.
371 vdict = vars
371 vdict = vars
372 elif isinstance(vars,basestring):
372 elif isinstance(vars,basestring):
373 # If a string with names was given, get the caller's frame to
373 # If a string with names was given, get the caller's frame to
374 # evaluate the given names in
374 # evaluate the given names in
375 cf = sys._getframe(1)
375 cf = sys._getframe(1)
376 vdict = {}
376 vdict = {}
377 for name in vars.split():
377 for name in vars.split():
378 try:
378 try:
379 vdict[name] = eval(name,cf.f_globals,cf.f_locals)
379 vdict[name] = eval(name,cf.f_globals,cf.f_locals)
380 except:
380 except:
381 print ('could not get var. %s from %s' %
381 print ('could not get var. %s from %s' %
382 (name,cf.f_code.co_name))
382 (name,cf.f_code.co_name))
383 else:
383 else:
384 raise ValueError('vars must be a string or a dict')
384 raise ValueError('vars must be a string or a dict')
385
385
386 # Propagate variables to user namespace
386 # Propagate variables to user namespace
387 self.user_ns.update(vdict)
387 self.user_ns.update(vdict)
388
388
389 # And configure interactive visibility
389 # And configure interactive visibility
390 config_ns = self.IP.user_config_ns
390 config_ns = self.IP.user_config_ns
391 if interactive:
391 if interactive:
392 for name,val in vdict.iteritems():
392 for name,val in vdict.iteritems():
393 config_ns.pop(name,None)
393 config_ns.pop(name,None)
394 else:
394 else:
395 for name,val in vdict.iteritems():
395 for name,val in vdict.iteritems():
396 config_ns[name] = val
396 config_ns[name] = val
397
397
398 def expand_alias(self,line):
398 def expand_alias(self,line):
399 """ Expand an alias in the command line
399 """ Expand an alias in the command line
400
400
401 Returns the provided command line, possibly with the first word
401 Returns the provided command line, possibly with the first word
402 (command) translated according to alias expansion rules.
402 (command) translated according to alias expansion rules.
403
403
404 [ipython]|16> _ip.expand_aliases("np myfile.txt")
404 [ipython]|16> _ip.expand_aliases("np myfile.txt")
405 <16> 'q:/opt/np/notepad++.exe myfile.txt'
405 <16> 'q:/opt/np/notepad++.exe myfile.txt'
406 """
406 """
407
407
408 pre,fn,rest = self.IP.split_user_input(line)
408 pre,fn,rest = self.IP.split_user_input(line)
409 res = pre + self.IP.expand_aliases(fn,rest)
409 res = pre + self.IP.expand_aliases(fn,rest)
410 return res
410 return res
411
411
412 def itpl(self, s, depth = 1):
412 def itpl(self, s, depth = 1):
413 """ Expand Itpl format string s.
413 """ Expand Itpl format string s.
414
414
415 Only callable from command line (i.e. prefilter results);
415 Only callable from command line (i.e. prefilter results);
416 If you use in your scripts, you need to use a bigger depth!
416 If you use in your scripts, you need to use a bigger depth!
417 """
417 """
418 return self.IP.var_expand(s, depth)
418 return self.IP.var_expand(s, depth)
419
419
420 def defalias(self, name, cmd):
420 def defalias(self, name, cmd):
421 """ Define a new alias
421 """ Define a new alias
422
422
423 _ip.defalias('bb','bldmake bldfiles')
423 _ip.defalias('bb','bldmake bldfiles')
424
424
425 Creates a new alias named 'bb' in ipython user namespace
425 Creates a new alias named 'bb' in ipython user namespace
426 """
426 """
427
427
428 self.dbg.check_hotname(name)
428 self.dbg.check_hotname(name)
429
429
430 if name in self.IP.alias_table:
430 if name in self.IP.alias_table:
431 self.dbg.debug_stack("Alias redefinition: '%s' => '%s' (old '%s')"
431 self.dbg.debug_stack("Alias redefinition: '%s' => '%s' (old '%s')"
432 % (name, cmd, self.IP.alias_table[name]))
432 % (name, cmd, self.IP.alias_table[name]))
433
433
434 if callable(cmd):
434 if callable(cmd):
435 self.IP.alias_table[name] = cmd
435 self.IP.alias_table[name] = cmd
436 import IPython.shadowns
436 import IPython.shadowns
437 setattr(IPython.shadowns, name,cmd)
437 setattr(IPython.shadowns, name,cmd)
438 return
438 return
439
439
440 if isinstance(cmd,basestring):
440 if isinstance(cmd,basestring):
441 nargs = cmd.count('%s')
441 nargs = cmd.count('%s')
442 if nargs>0 and cmd.find('%l')>=0:
442 if nargs>0 and cmd.find('%l')>=0:
443 raise Exception('The %s and %l specifiers are mutually '
443 raise Exception('The %s and %l specifiers are mutually '
444 'exclusive in alias definitions.')
444 'exclusive in alias definitions.')
445
445
446 self.IP.alias_table[name] = (nargs,cmd)
446 self.IP.alias_table[name] = (nargs,cmd)
447 return
447 return
448
448
449 # just put it in - it's probably (0,'foo')
449 # just put it in - it's probably (0,'foo')
450 self.IP.alias_table[name] = cmd
450 self.IP.alias_table[name] = cmd
451
451
452 def defmacro(self, *args):
452 def defmacro(self, *args):
453 """ Define a new macro
453 """ Define a new macro
454
454
455 2 forms of calling:
455 2 forms of calling:
456
456
457 mac = _ip.defmacro('print "hello"\nprint "world"')
457 mac = _ip.defmacro('print "hello"\nprint "world"')
458
458
459 (doesn't put the created macro on user namespace)
459 (doesn't put the created macro on user namespace)
460
460
461 _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb')
461 _ip.defmacro('build', 'bldmake bldfiles\nabld build winscw udeb')
462
462
463 (creates a macro named 'build' in user namespace)
463 (creates a macro named 'build' in user namespace)
464 """
464 """
465
465
466 import IPython.macro
466 import IPython.macro
467
467
468 if len(args) == 1:
468 if len(args) == 1:
469 return IPython.macro.Macro(args[0])
469 return IPython.macro.Macro(args[0])
470 elif len(args) == 2:
470 elif len(args) == 2:
471 self.user_ns[args[0]] = IPython.macro.Macro(args[1])
471 self.user_ns[args[0]] = IPython.macro.Macro(args[1])
472 else:
472 else:
473 return Exception("_ip.defmacro must be called with 1 or 2 arguments")
473 return Exception("_ip.defmacro must be called with 1 or 2 arguments")
474
474
475 def set_next_input(self, s):
475 def set_next_input(self, s):
476 """ Sets the 'default' input string for the next command line.
476 """ Sets the 'default' input string for the next command line.
477
477
478 Requires readline.
478 Requires readline.
479
479
480 Example:
480 Example:
481
481
482 [D:\ipython]|1> _ip.set_next_input("Hello Word")
482 [D:\ipython]|1> _ip.set_next_input("Hello Word")
483 [D:\ipython]|2> Hello Word_ # cursor is here
483 [D:\ipython]|2> Hello Word_ # cursor is here
484 """
484 """
485
485
486 self.IP.rl_next_input = s
486 self.IP.rl_next_input = s
487
487
488 def load(self, mod):
488 def load(self, mod):
489 """ Load an extension.
489 """ Load an extension.
490
490
491 Some modules should (or must) be 'load()':ed, rather than just imported.
491 Some modules should (or must) be 'load()':ed, rather than just imported.
492
492
493 Loading will do:
493 Loading will do:
494
494
495 - run init_ipython(ip)
495 - run init_ipython(ip)
496 - run ipython_firstrun(ip)
496 - run ipython_firstrun(ip)
497 """
497 """
498
498
499 if mod in self.extensions:
499 if mod in self.extensions:
500 # just to make sure we don't init it twice
500 # just to make sure we don't init it twice
501 # note that if you 'load' a module that has already been
501 # note that if you 'load' a module that has already been
502 # imported, init_ipython gets run anyway
502 # imported, init_ipython gets run anyway
503
503
504 return self.extensions[mod]
504 return self.extensions[mod]
505 __import__(mod)
505 __import__(mod)
506 m = sys.modules[mod]
506 m = sys.modules[mod]
507 if hasattr(m,'init_ipython'):
507 if hasattr(m,'init_ipython'):
508 m.init_ipython(self)
508 m.init_ipython(self)
509
509
510 if hasattr(m,'ipython_firstrun'):
510 if hasattr(m,'ipython_firstrun'):
511 already_loaded = self.db.get('firstrun_done', set())
511 already_loaded = self.db.get('firstrun_done', set())
512 if mod not in already_loaded:
512 if mod not in already_loaded:
513 m.ipython_firstrun(self)
513 m.ipython_firstrun(self)
514 already_loaded.add(mod)
514 already_loaded.add(mod)
515 self.db['firstrun_done'] = already_loaded
515 self.db['firstrun_done'] = already_loaded
516
516
517 self.extensions[mod] = m
517 self.extensions[mod] = m
518 return m
518 return m
519
519
520
520
521 class DebugTools:
521 class DebugTools:
522 """ Used for debugging mishaps in api usage
522 """ Used for debugging mishaps in api usage
523
523
524 So far, tracing redefinitions is supported.
524 So far, tracing redefinitions is supported.
525 """
525 """
526
526
527 def __init__(self, ip):
527 def __init__(self, ip):
528 self.ip = ip
528 self.ip = ip
529 self.debugmode = False
529 self.debugmode = False
530 self.hotnames = set()
530 self.hotnames = set()
531
531
532 def hotname(self, name_to_catch):
532 def hotname(self, name_to_catch):
533 self.hotnames.add(name_to_catch)
533 self.hotnames.add(name_to_catch)
534
534
535 def debug_stack(self, msg = None):
535 def debug_stack(self, msg = None):
536 if not self.debugmode:
536 if not self.debugmode:
537 return
537 return
538
538
539 import traceback
539 import traceback
540 if msg is not None:
540 if msg is not None:
541 print '====== %s ========' % msg
541 print '====== %s ========' % msg
542 traceback.print_stack()
542 traceback.print_stack()
543
543
544 def check_hotname(self,name):
544 def check_hotname(self,name):
545 if name in self.hotnames:
545 if name in self.hotnames:
546 self.debug_stack( "HotName '%s' caught" % name)
546 self.debug_stack( "HotName '%s' caught" % name)
547
547
548
548
549 def launch_new_instance(user_ns = None,shellclass = None):
549 def launch_new_instance(user_ns = None,shellclass = None):
550 """ Make and start a new ipython instance.
550 """ Make and start a new ipython instance.
551
551
552 This can be called even without having an already initialized
552 This can be called even without having an already initialized
553 ipython session running.
553 ipython session running.
554
554
555 This is also used as the egg entry point for the 'ipython' script.
555 This is also used as the egg entry point for the 'ipython' script.
556
556
557 """
557 """
558 ses = make_session(user_ns,shellclass)
558 ses = make_session(user_ns,shellclass)
559 ses.mainloop()
559 ses.mainloop()
560
560
561
561
562 def make_user_ns(user_ns = None):
562 def make_user_ns(user_ns = None):
563 """Return a valid user interactive namespace.
563 """Return a valid user interactive namespace.
564
564
565 This builds a dict with the minimal information needed to operate as a
565 This builds a dict with the minimal information needed to operate as a
566 valid IPython user namespace, which you can pass to the various embedding
566 valid IPython user namespace, which you can pass to the various embedding
567 classes in ipython.
567 classes in ipython.
568 """
568 """
569
569
570 if user_ns is None:
570 raise NotImplementedError
571 # Set __name__ to __main__ to better match the behavior of the
572 # normal interpreter.
573 user_ns = {'__name__' :'__main__',
574 '__builtins__' : __builtin__,
575 }
576 else:
577 user_ns.setdefault('__name__','__main__')
578 user_ns.setdefault('__builtins__',__builtin__)
579
580 return user_ns
581
571
582
572
583 def make_user_global_ns(ns = None):
573 def make_user_global_ns(ns = None):
584 """Return a valid user global namespace.
574 """Return a valid user global namespace.
585
575
586 Similar to make_user_ns(), but global namespaces are really only needed in
576 Similar to make_user_ns(), but global namespaces are really only needed in
587 embedded applications, where there is a distinction between the user's
577 embedded applications, where there is a distinction between the user's
588 interactive namespace and the global one where ipython is running."""
578 interactive namespace and the global one where ipython is running."""
589
579
590 if ns is None: ns = {}
580 raise NotImplementedError
591 return ns
581
582 # Record the true objects in order to be able to test if the user has overridden
583 # these API functions.
584 _make_user_ns = make_user_ns
585 _make_user_global_ns = make_user_global_ns
586
587
588 def make_user_namespaces(user_ns = None,user_global_ns = None):
589 """Return a valid local and global user interactive namespaces.
590
591 This builds a dict with the minimal information needed to operate as a
592 valid IPython user namespace, which you can pass to the various embedding
593 classes in ipython. The default implementation returns the same dict for
594 both the locals and the globals to allow functions to refer to variables in
595 the namespace. Customized implementations can return different dicts. The
596 locals dictionary can actually be anything following the basic mapping
597 protocol of a dict, but the globals dict must be a true dict, not even
598 a subclass. It is recommended that any custom object for the locals
599 namespace synchronize with the globals dict somehow.
600
601 Raises TypeError if the provided globals namespace is not a true dict.
602 """
603
604 if user_ns is None:
605 if make_user_ns is not _make_user_ns:
606 # Old API overridden.
607 # FIXME: Issue DeprecationWarning, or just let the old API live on?
608 user_ns = make_user_ns(user_ns)
609 else:
610 # Set __name__ to __main__ to better match the behavior of the
611 # normal interpreter.
612 user_ns = {'__name__' :'__main__',
613 '__builtins__' : __builtin__,
614 }
615 else:
616 user_ns.setdefault('__name__','__main__')
617 user_ns.setdefault('__builtins__',__builtin__)
618
619 if user_global_ns is None:
620 if make_user_global_ns is not _make_user_global_ns:
621 # Old API overridden.
622 user_global_ns = make_user_global_ns(user_global_ns)
623 else:
624 user_global_ns = user_ns
625 if type(user_global_ns) is not dict:
626 raise TypeError("user_global_ns must be a true dict; got %r"
627 % type(user_global_ns))
628
629 return user_ns, user_global_ns
592
630
593
631
594 def make_session(user_ns = None, shellclass = None):
632 def make_session(user_ns = None, shellclass = None):
595 """Makes, but does not launch an IPython session.
633 """Makes, but does not launch an IPython session.
596
634
597 Later on you can call obj.mainloop() on the returned object.
635 Later on you can call obj.mainloop() on the returned object.
598
636
599 Inputs:
637 Inputs:
600
638
601 - user_ns(None): a dict to be used as the user's namespace with initial
639 - user_ns(None): a dict to be used as the user's namespace with initial
602 data.
640 data.
603
641
604 WARNING: This should *not* be run when a session exists already."""
642 WARNING: This should *not* be run when a session exists already."""
605
643
606 import IPython.Shell
644 import IPython.Shell
607 if shellclass is None:
645 if shellclass is None:
608 return IPython.Shell.start(user_ns)
646 return IPython.Shell.start(user_ns)
609 return shellclass(user_ns = user_ns)
647 return shellclass(user_ns = user_ns)
@@ -1,2696 +1,2686 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.3 or newer.
5 Requires Python 2.3 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 """
9 """
10
10
11 #*****************************************************************************
11 #*****************************************************************************
12 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
12 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
13 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
13 # Copyright (C) 2001-2006 Fernando Perez. <fperez@colorado.edu>
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #
17 #
18 # Note: this code originally subclassed code.InteractiveConsole from the
18 # Note: this code originally subclassed code.InteractiveConsole from the
19 # Python standard library. Over time, all of that class has been copied
19 # Python standard library. Over time, all of that class has been copied
20 # verbatim here for modifications which could not be accomplished by
20 # verbatim here for modifications which could not be accomplished by
21 # subclassing. At this point, there are no dependencies at all on the code
21 # subclassing. At this point, there are no dependencies at all on the code
22 # module anymore (it is not even imported). The Python License (sec. 2)
22 # module anymore (it is not even imported). The Python License (sec. 2)
23 # allows for this, but it's always nice to acknowledge credit where credit is
23 # allows for this, but it's always nice to acknowledge credit where credit is
24 # due.
24 # due.
25 #*****************************************************************************
25 #*****************************************************************************
26
26
27 #****************************************************************************
27 #****************************************************************************
28 # Modules and globals
28 # Modules and globals
29
29
30 from IPython import Release
30 from IPython import Release
31 __author__ = '%s <%s>\n%s <%s>' % \
31 __author__ = '%s <%s>\n%s <%s>' % \
32 ( Release.authors['Janko'] + Release.authors['Fernando'] )
32 ( Release.authors['Janko'] + Release.authors['Fernando'] )
33 __license__ = Release.license
33 __license__ = Release.license
34 __version__ = Release.version
34 __version__ = Release.version
35
35
36 # Python standard modules
36 # Python standard modules
37 import __main__
37 import __main__
38 import __builtin__
38 import __builtin__
39 import StringIO
39 import StringIO
40 import bdb
40 import bdb
41 import cPickle as pickle
41 import cPickle as pickle
42 import codeop
42 import codeop
43 import exceptions
43 import exceptions
44 import glob
44 import glob
45 import inspect
45 import inspect
46 import keyword
46 import keyword
47 import new
47 import new
48 import os
48 import os
49 import pydoc
49 import pydoc
50 import re
50 import re
51 import shutil
51 import shutil
52 import string
52 import string
53 import sys
53 import sys
54 import tempfile
54 import tempfile
55 import traceback
55 import traceback
56 import types
56 import types
57 import warnings
57 import warnings
58 warnings.filterwarnings('ignore', r'.*sets module*')
58 warnings.filterwarnings('ignore', r'.*sets module*')
59 from sets import Set
59 from sets import Set
60 from pprint import pprint, pformat
60 from pprint import pprint, pformat
61
61
62 # IPython's own modules
62 # IPython's own modules
63 #import IPython
63 #import IPython
64 from IPython import Debugger,OInspect,PyColorize,ultraTB
64 from IPython import Debugger,OInspect,PyColorize,ultraTB
65 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
65 from IPython.ColorANSI import ColorScheme,ColorSchemeTable # too long names
66 from IPython.Extensions import pickleshare
66 from IPython.Extensions import pickleshare
67 from IPython.FakeModule import FakeModule
67 from IPython.FakeModule import FakeModule
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
68 from IPython.Itpl import Itpl,itpl,printpl,ItplNS,itplns
69 from IPython.Logger import Logger
69 from IPython.Logger import Logger
70 from IPython.Magic import Magic
70 from IPython.Magic import Magic
71 from IPython.Prompts import CachedOutput
71 from IPython.Prompts import CachedOutput
72 from IPython.ipstruct import Struct
72 from IPython.ipstruct import Struct
73 from IPython.background_jobs import BackgroundJobManager
73 from IPython.background_jobs import BackgroundJobManager
74 from IPython.usage import cmd_line_usage,interactive_usage
74 from IPython.usage import cmd_line_usage,interactive_usage
75 from IPython.genutils import *
75 from IPython.genutils import *
76 from IPython.strdispatch import StrDispatch
76 from IPython.strdispatch import StrDispatch
77 import IPython.ipapi
77 import IPython.ipapi
78 import IPython.history
78 import IPython.history
79 import IPython.prefilter as prefilter
79 import IPython.prefilter as prefilter
80 import IPython.shadowns
80 import IPython.shadowns
81 # Globals
81 # Globals
82
82
83 # store the builtin raw_input globally, and use this always, in case user code
83 # store the builtin raw_input globally, and use this always, in case user code
84 # overwrites it (like wx.py.PyShell does)
84 # overwrites it (like wx.py.PyShell does)
85 raw_input_original = raw_input
85 raw_input_original = raw_input
86
86
87 # compiled regexps for autoindent management
87 # compiled regexps for autoindent management
88 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
88 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
89
89
90
90
91 #****************************************************************************
91 #****************************************************************************
92 # Some utility function definitions
92 # Some utility function definitions
93
93
94 ini_spaces_re = re.compile(r'^(\s+)')
94 ini_spaces_re = re.compile(r'^(\s+)')
95
95
96 def num_ini_spaces(strng):
96 def num_ini_spaces(strng):
97 """Return the number of initial spaces in a string"""
97 """Return the number of initial spaces in a string"""
98
98
99 ini_spaces = ini_spaces_re.match(strng)
99 ini_spaces = ini_spaces_re.match(strng)
100 if ini_spaces:
100 if ini_spaces:
101 return ini_spaces.end()
101 return ini_spaces.end()
102 else:
102 else:
103 return 0
103 return 0
104
104
105 def softspace(file, newvalue):
105 def softspace(file, newvalue):
106 """Copied from code.py, to remove the dependency"""
106 """Copied from code.py, to remove the dependency"""
107
107
108 oldvalue = 0
108 oldvalue = 0
109 try:
109 try:
110 oldvalue = file.softspace
110 oldvalue = file.softspace
111 except AttributeError:
111 except AttributeError:
112 pass
112 pass
113 try:
113 try:
114 file.softspace = newvalue
114 file.softspace = newvalue
115 except (AttributeError, TypeError):
115 except (AttributeError, TypeError):
116 # "attribute-less object" or "read-only attributes"
116 # "attribute-less object" or "read-only attributes"
117 pass
117 pass
118 return oldvalue
118 return oldvalue
119
119
120
120
121 #****************************************************************************
121 #****************************************************************************
122 # Local use exceptions
122 # Local use exceptions
123 class SpaceInInput(exceptions.Exception): pass
123 class SpaceInInput(exceptions.Exception): pass
124
124
125
125
126 #****************************************************************************
126 #****************************************************************************
127 # Local use classes
127 # Local use classes
128 class Bunch: pass
128 class Bunch: pass
129
129
130 class Undefined: pass
130 class Undefined: pass
131
131
132 class Quitter(object):
132 class Quitter(object):
133 """Simple class to handle exit, similar to Python 2.5's.
133 """Simple class to handle exit, similar to Python 2.5's.
134
134
135 It handles exiting in an ipython-safe manner, which the one in Python 2.5
135 It handles exiting in an ipython-safe manner, which the one in Python 2.5
136 doesn't do (obviously, since it doesn't know about ipython)."""
136 doesn't do (obviously, since it doesn't know about ipython)."""
137
137
138 def __init__(self,shell,name):
138 def __init__(self,shell,name):
139 self.shell = shell
139 self.shell = shell
140 self.name = name
140 self.name = name
141
141
142 def __repr__(self):
142 def __repr__(self):
143 return 'Type %s() to exit.' % self.name
143 return 'Type %s() to exit.' % self.name
144 __str__ = __repr__
144 __str__ = __repr__
145
145
146 def __call__(self):
146 def __call__(self):
147 self.shell.exit()
147 self.shell.exit()
148
148
149 class InputList(list):
149 class InputList(list):
150 """Class to store user input.
150 """Class to store user input.
151
151
152 It's basically a list, but slices return a string instead of a list, thus
152 It's basically a list, but slices return a string instead of a list, thus
153 allowing things like (assuming 'In' is an instance):
153 allowing things like (assuming 'In' is an instance):
154
154
155 exec In[4:7]
155 exec In[4:7]
156
156
157 or
157 or
158
158
159 exec In[5:9] + In[14] + In[21:25]"""
159 exec In[5:9] + In[14] + In[21:25]"""
160
160
161 def __getslice__(self,i,j):
161 def __getslice__(self,i,j):
162 return ''.join(list.__getslice__(self,i,j))
162 return ''.join(list.__getslice__(self,i,j))
163
163
164 class SyntaxTB(ultraTB.ListTB):
164 class SyntaxTB(ultraTB.ListTB):
165 """Extension which holds some state: the last exception value"""
165 """Extension which holds some state: the last exception value"""
166
166
167 def __init__(self,color_scheme = 'NoColor'):
167 def __init__(self,color_scheme = 'NoColor'):
168 ultraTB.ListTB.__init__(self,color_scheme)
168 ultraTB.ListTB.__init__(self,color_scheme)
169 self.last_syntax_error = None
169 self.last_syntax_error = None
170
170
171 def __call__(self, etype, value, elist):
171 def __call__(self, etype, value, elist):
172 self.last_syntax_error = value
172 self.last_syntax_error = value
173 ultraTB.ListTB.__call__(self,etype,value,elist)
173 ultraTB.ListTB.__call__(self,etype,value,elist)
174
174
175 def clear_err_state(self):
175 def clear_err_state(self):
176 """Return the current error state and clear it"""
176 """Return the current error state and clear it"""
177 e = self.last_syntax_error
177 e = self.last_syntax_error
178 self.last_syntax_error = None
178 self.last_syntax_error = None
179 return e
179 return e
180
180
181 #****************************************************************************
181 #****************************************************************************
182 # Main IPython class
182 # Main IPython class
183
183
184 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
184 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
185 # until a full rewrite is made. I've cleaned all cross-class uses of
185 # until a full rewrite is made. I've cleaned all cross-class uses of
186 # attributes and methods, but too much user code out there relies on the
186 # attributes and methods, but too much user code out there relies on the
187 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
187 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
188 #
188 #
189 # But at least now, all the pieces have been separated and we could, in
189 # But at least now, all the pieces have been separated and we could, in
190 # principle, stop using the mixin. This will ease the transition to the
190 # principle, stop using the mixin. This will ease the transition to the
191 # chainsaw branch.
191 # chainsaw branch.
192
192
193 # For reference, the following is the list of 'self.foo' uses in the Magic
193 # For reference, the following is the list of 'self.foo' uses in the Magic
194 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
194 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
195 # class, to prevent clashes.
195 # class, to prevent clashes.
196
196
197 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
197 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
198 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
198 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
199 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
199 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
200 # 'self.value']
200 # 'self.value']
201
201
202 class InteractiveShell(object,Magic):
202 class InteractiveShell(object,Magic):
203 """An enhanced console for Python."""
203 """An enhanced console for Python."""
204
204
205 # class attribute to indicate whether the class supports threads or not.
205 # class attribute to indicate whether the class supports threads or not.
206 # Subclasses with thread support should override this as needed.
206 # Subclasses with thread support should override this as needed.
207 isthreaded = False
207 isthreaded = False
208
208
209 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
209 def __init__(self,name,usage=None,rc=Struct(opts=None,args=None),
210 user_ns = None,user_global_ns=None,banner2='',
210 user_ns=None,user_global_ns=None,banner2='',
211 custom_exceptions=((),None),embedded=False):
211 custom_exceptions=((),None),embedded=False):
212
212
213 # log system
213 # log system
214 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
214 self.logger = Logger(self,logfname='ipython_log.py',logmode='rotate')
215
215
216 # Job manager (for jobs run as background threads)
216 # Job manager (for jobs run as background threads)
217 self.jobs = BackgroundJobManager()
217 self.jobs = BackgroundJobManager()
218
218
219 # Store the actual shell's name
219 # Store the actual shell's name
220 self.name = name
220 self.name = name
221 self.more = False
221 self.more = False
222
222
223 # We need to know whether the instance is meant for embedding, since
223 # We need to know whether the instance is meant for embedding, since
224 # global/local namespaces need to be handled differently in that case
224 # global/local namespaces need to be handled differently in that case
225 self.embedded = embedded
225 self.embedded = embedded
226 if embedded:
226 if embedded:
227 # Control variable so users can, from within the embedded instance,
227 # Control variable so users can, from within the embedded instance,
228 # permanently deactivate it.
228 # permanently deactivate it.
229 self.embedded_active = True
229 self.embedded_active = True
230
230
231 # command compiler
231 # command compiler
232 self.compile = codeop.CommandCompiler()
232 self.compile = codeop.CommandCompiler()
233
233
234 # User input buffer
234 # User input buffer
235 self.buffer = []
235 self.buffer = []
236
236
237 # Default name given in compilation of code
237 # Default name given in compilation of code
238 self.filename = '<ipython console>'
238 self.filename = '<ipython console>'
239
239
240 # Install our own quitter instead of the builtins. For python2.3-2.4,
240 # Install our own quitter instead of the builtins. For python2.3-2.4,
241 # this brings in behavior like 2.5, and for 2.5 it's identical.
241 # this brings in behavior like 2.5, and for 2.5 it's identical.
242 __builtin__.exit = Quitter(self,'exit')
242 __builtin__.exit = Quitter(self,'exit')
243 __builtin__.quit = Quitter(self,'quit')
243 __builtin__.quit = Quitter(self,'quit')
244
244
245 # Make an empty namespace, which extension writers can rely on both
245 # Make an empty namespace, which extension writers can rely on both
246 # existing and NEVER being used by ipython itself. This gives them a
246 # existing and NEVER being used by ipython itself. This gives them a
247 # convenient location for storing additional information and state
247 # convenient location for storing additional information and state
248 # their extensions may require, without fear of collisions with other
248 # their extensions may require, without fear of collisions with other
249 # ipython names that may develop later.
249 # ipython names that may develop later.
250 self.meta = Struct()
250 self.meta = Struct()
251
251
252 # Create the namespace where the user will operate. user_ns is
252 # Create the namespace where the user will operate. user_ns is
253 # normally the only one used, and it is passed to the exec calls as
253 # normally the only one used, and it is passed to the exec calls as
254 # the locals argument. But we do carry a user_global_ns namespace
254 # the locals argument. But we do carry a user_global_ns namespace
255 # given as the exec 'globals' argument, This is useful in embedding
255 # given as the exec 'globals' argument, This is useful in embedding
256 # situations where the ipython shell opens in a context where the
256 # situations where the ipython shell opens in a context where the
257 # distinction between locals and globals is meaningful.
257 # distinction between locals and globals is meaningful. For
258 # non-embedded contexts, it is just the same object as the user_ns dict.
258
259
259 # FIXME. For some strange reason, __builtins__ is showing up at user
260 # FIXME. For some strange reason, __builtins__ is showing up at user
260 # level as a dict instead of a module. This is a manual fix, but I
261 # level as a dict instead of a module. This is a manual fix, but I
261 # should really track down where the problem is coming from. Alex
262 # should really track down where the problem is coming from. Alex
262 # Schmolck reported this problem first.
263 # Schmolck reported this problem first.
263
264
264 # A useful post by Alex Martelli on this topic:
265 # A useful post by Alex Martelli on this topic:
265 # Re: inconsistent value from __builtins__
266 # Re: inconsistent value from __builtins__
266 # Von: Alex Martelli <aleaxit@yahoo.com>
267 # Von: Alex Martelli <aleaxit@yahoo.com>
267 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
268 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
268 # Gruppen: comp.lang.python
269 # Gruppen: comp.lang.python
269
270
270 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
271 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
271 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
272 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
272 # > <type 'dict'>
273 # > <type 'dict'>
273 # > >>> print type(__builtins__)
274 # > >>> print type(__builtins__)
274 # > <type 'module'>
275 # > <type 'module'>
275 # > Is this difference in return value intentional?
276 # > Is this difference in return value intentional?
276
277
277 # Well, it's documented that '__builtins__' can be either a dictionary
278 # Well, it's documented that '__builtins__' can be either a dictionary
278 # or a module, and it's been that way for a long time. Whether it's
279 # or a module, and it's been that way for a long time. Whether it's
279 # intentional (or sensible), I don't know. In any case, the idea is
280 # intentional (or sensible), I don't know. In any case, the idea is
280 # that if you need to access the built-in namespace directly, you
281 # that if you need to access the built-in namespace directly, you
281 # should start with "import __builtin__" (note, no 's') which will
282 # should start with "import __builtin__" (note, no 's') which will
282 # definitely give you a module. Yeah, it's somewhat confusing:-(.
283 # definitely give you a module. Yeah, it's somewhat confusing:-(.
283
284
284 # These routines return properly built dicts as needed by the rest of
285 # These routines return properly built dicts as needed by the rest of
285 # the code, and can also be used by extension writers to generate
286 # the code, and can also be used by extension writers to generate
286 # properly initialized namespaces.
287 # properly initialized namespaces.
287 user_ns = IPython.ipapi.make_user_ns(user_ns)
288 user_ns, user_global_ns = IPython.ipapi.make_user_namespaces(user_ns,
288 user_global_ns = IPython.ipapi.make_user_global_ns(user_global_ns)
289 user_global_ns)
289
290
290 # Assign namespaces
291 # Assign namespaces
291 # This is the namespace where all normal user variables live
292 # This is the namespace where all normal user variables live
292 self.user_ns = user_ns
293 self.user_ns = user_ns
293 # Embedded instances require a separate namespace for globals.
294 # Normally this one is unused by non-embedded instances.
295 self.user_global_ns = user_global_ns
294 self.user_global_ns = user_global_ns
296 # A namespace to keep track of internal data structures to prevent
295 # A namespace to keep track of internal data structures to prevent
297 # them from cluttering user-visible stuff. Will be updated later
296 # them from cluttering user-visible stuff. Will be updated later
298 self.internal_ns = {}
297 self.internal_ns = {}
299
298
300 # Namespace of system aliases. Each entry in the alias
299 # Namespace of system aliases. Each entry in the alias
301 # table must be a 2-tuple of the form (N,name), where N is the number
300 # table must be a 2-tuple of the form (N,name), where N is the number
302 # of positional arguments of the alias.
301 # of positional arguments of the alias.
303 self.alias_table = {}
302 self.alias_table = {}
304
303
305 # A table holding all the namespaces IPython deals with, so that
304 # A table holding all the namespaces IPython deals with, so that
306 # introspection facilities can search easily.
305 # introspection facilities can search easily.
307 self.ns_table = {'user':user_ns,
306 self.ns_table = {'user':user_ns,
308 'user_global':user_global_ns,
307 'user_global':user_global_ns,
309 'alias':self.alias_table,
308 'alias':self.alias_table,
310 'internal':self.internal_ns,
309 'internal':self.internal_ns,
311 'builtin':__builtin__.__dict__
310 'builtin':__builtin__.__dict__
312 }
311 }
313 # The user namespace MUST have a pointer to the shell itself.
312 # The user namespace MUST have a pointer to the shell itself.
314 self.user_ns[name] = self
313 self.user_ns[name] = self
315
314
316 # We need to insert into sys.modules something that looks like a
315 # We need to insert into sys.modules something that looks like a
317 # module but which accesses the IPython namespace, for shelve and
316 # module but which accesses the IPython namespace, for shelve and
318 # pickle to work interactively. Normally they rely on getting
317 # pickle to work interactively. Normally they rely on getting
319 # everything out of __main__, but for embedding purposes each IPython
318 # everything out of __main__, but for embedding purposes each IPython
320 # instance has its own private namespace, so we can't go shoving
319 # instance has its own private namespace, so we can't go shoving
321 # everything into __main__.
320 # everything into __main__.
322
321
323 # note, however, that we should only do this for non-embedded
322 # note, however, that we should only do this for non-embedded
324 # ipythons, which really mimic the __main__.__dict__ with their own
323 # ipythons, which really mimic the __main__.__dict__ with their own
325 # namespace. Embedded instances, on the other hand, should not do
324 # namespace. Embedded instances, on the other hand, should not do
326 # this because they need to manage the user local/global namespaces
325 # this because they need to manage the user local/global namespaces
327 # only, but they live within a 'normal' __main__ (meaning, they
326 # only, but they live within a 'normal' __main__ (meaning, they
328 # shouldn't overtake the execution environment of the script they're
327 # shouldn't overtake the execution environment of the script they're
329 # embedded in).
328 # embedded in).
330
329
331 if not embedded:
330 if not embedded:
332 try:
331 try:
333 main_name = self.user_ns['__name__']
332 main_name = self.user_ns['__name__']
334 except KeyError:
333 except KeyError:
335 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
334 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
336 else:
335 else:
337 #print "pickle hack in place" # dbg
336 #print "pickle hack in place" # dbg
338 #print 'main_name:',main_name # dbg
337 #print 'main_name:',main_name # dbg
339 sys.modules[main_name] = FakeModule(self.user_ns)
338 sys.modules[main_name] = FakeModule(self.user_ns)
340
339
341 # Now that FakeModule produces a real module, we've run into a nasty
340 # Now that FakeModule produces a real module, we've run into a nasty
342 # problem: after script execution (via %run), the module where the user
341 # problem: after script execution (via %run), the module where the user
343 # code ran is deleted. Now that this object is a true module (needed
342 # code ran is deleted. Now that this object is a true module (needed
344 # so docetst and other tools work correctly), the Python module
343 # so docetst and other tools work correctly), the Python module
345 # teardown mechanism runs over it, and sets to None every variable
344 # teardown mechanism runs over it, and sets to None every variable
346 # present in that module. This means that later calls to functions
345 # present in that module. This means that later calls to functions
347 # defined in the script (which have become interactively visible after
346 # defined in the script (which have become interactively visible after
348 # script exit) fail, because they hold references to objects that have
347 # script exit) fail, because they hold references to objects that have
349 # become overwritten into None. The only solution I see right now is
348 # become overwritten into None. The only solution I see right now is
350 # to protect every FakeModule used by %run by holding an internal
349 # to protect every FakeModule used by %run by holding an internal
351 # reference to it. This private list will be used for that. The
350 # reference to it. This private list will be used for that. The
352 # %reset command will flush it as well.
351 # %reset command will flush it as well.
353 self._user_main_modules = []
352 self._user_main_modules = []
354
353
355 # List of input with multi-line handling.
354 # List of input with multi-line handling.
356 # Fill its zero entry, user counter starts at 1
355 # Fill its zero entry, user counter starts at 1
357 self.input_hist = InputList(['\n'])
356 self.input_hist = InputList(['\n'])
358 # This one will hold the 'raw' input history, without any
357 # This one will hold the 'raw' input history, without any
359 # pre-processing. This will allow users to retrieve the input just as
358 # pre-processing. This will allow users to retrieve the input just as
360 # it was exactly typed in by the user, with %hist -r.
359 # it was exactly typed in by the user, with %hist -r.
361 self.input_hist_raw = InputList(['\n'])
360 self.input_hist_raw = InputList(['\n'])
362
361
363 # list of visited directories
362 # list of visited directories
364 try:
363 try:
365 self.dir_hist = [os.getcwd()]
364 self.dir_hist = [os.getcwd()]
366 except OSError:
365 except OSError:
367 self.dir_hist = []
366 self.dir_hist = []
368
367
369 # dict of output history
368 # dict of output history
370 self.output_hist = {}
369 self.output_hist = {}
371
370
372 # Get system encoding at startup time. Certain terminals (like Emacs
371 # Get system encoding at startup time. Certain terminals (like Emacs
373 # under Win32 have it set to None, and we need to have a known valid
372 # under Win32 have it set to None, and we need to have a known valid
374 # encoding to use in the raw_input() method
373 # encoding to use in the raw_input() method
375 try:
374 try:
376 self.stdin_encoding = sys.stdin.encoding or 'ascii'
375 self.stdin_encoding = sys.stdin.encoding or 'ascii'
377 except AttributeError:
376 except AttributeError:
378 self.stdin_encoding = 'ascii'
377 self.stdin_encoding = 'ascii'
379
378
380 # dict of things NOT to alias (keywords, builtins and some magics)
379 # dict of things NOT to alias (keywords, builtins and some magics)
381 no_alias = {}
380 no_alias = {}
382 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
381 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
383 for key in keyword.kwlist + no_alias_magics:
382 for key in keyword.kwlist + no_alias_magics:
384 no_alias[key] = 1
383 no_alias[key] = 1
385 no_alias.update(__builtin__.__dict__)
384 no_alias.update(__builtin__.__dict__)
386 self.no_alias = no_alias
385 self.no_alias = no_alias
387
386
388 # make global variables for user access to these
387 # make global variables for user access to these
389 self.user_ns['_ih'] = self.input_hist
388 self.user_ns['_ih'] = self.input_hist
390 self.user_ns['_oh'] = self.output_hist
389 self.user_ns['_oh'] = self.output_hist
391 self.user_ns['_dh'] = self.dir_hist
390 self.user_ns['_dh'] = self.dir_hist
392
391
393 # user aliases to input and output histories
392 # user aliases to input and output histories
394 self.user_ns['In'] = self.input_hist
393 self.user_ns['In'] = self.input_hist
395 self.user_ns['Out'] = self.output_hist
394 self.user_ns['Out'] = self.output_hist
396
395
397 self.user_ns['_sh'] = IPython.shadowns
396 self.user_ns['_sh'] = IPython.shadowns
398 # Object variable to store code object waiting execution. This is
397 # Object variable to store code object waiting execution. This is
399 # used mainly by the multithreaded shells, but it can come in handy in
398 # used mainly by the multithreaded shells, but it can come in handy in
400 # other situations. No need to use a Queue here, since it's a single
399 # other situations. No need to use a Queue here, since it's a single
401 # item which gets cleared once run.
400 # item which gets cleared once run.
402 self.code_to_run = None
401 self.code_to_run = None
403
402
404 # escapes for automatic behavior on the command line
403 # escapes for automatic behavior on the command line
405 self.ESC_SHELL = '!'
404 self.ESC_SHELL = '!'
406 self.ESC_SH_CAP = '!!'
405 self.ESC_SH_CAP = '!!'
407 self.ESC_HELP = '?'
406 self.ESC_HELP = '?'
408 self.ESC_MAGIC = '%'
407 self.ESC_MAGIC = '%'
409 self.ESC_QUOTE = ','
408 self.ESC_QUOTE = ','
410 self.ESC_QUOTE2 = ';'
409 self.ESC_QUOTE2 = ';'
411 self.ESC_PAREN = '/'
410 self.ESC_PAREN = '/'
412
411
413 # And their associated handlers
412 # And their associated handlers
414 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
413 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
415 self.ESC_QUOTE : self.handle_auto,
414 self.ESC_QUOTE : self.handle_auto,
416 self.ESC_QUOTE2 : self.handle_auto,
415 self.ESC_QUOTE2 : self.handle_auto,
417 self.ESC_MAGIC : self.handle_magic,
416 self.ESC_MAGIC : self.handle_magic,
418 self.ESC_HELP : self.handle_help,
417 self.ESC_HELP : self.handle_help,
419 self.ESC_SHELL : self.handle_shell_escape,
418 self.ESC_SHELL : self.handle_shell_escape,
420 self.ESC_SH_CAP : self.handle_shell_escape,
419 self.ESC_SH_CAP : self.handle_shell_escape,
421 }
420 }
422
421
423 # class initializations
422 # class initializations
424 Magic.__init__(self,self)
423 Magic.__init__(self,self)
425
424
426 # Python source parser/formatter for syntax highlighting
425 # Python source parser/formatter for syntax highlighting
427 pyformat = PyColorize.Parser().format
426 pyformat = PyColorize.Parser().format
428 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
427 self.pycolorize = lambda src: pyformat(src,'str',self.rc['colors'])
429
428
430 # hooks holds pointers used for user-side customizations
429 # hooks holds pointers used for user-side customizations
431 self.hooks = Struct()
430 self.hooks = Struct()
432
431
433 self.strdispatchers = {}
432 self.strdispatchers = {}
434
433
435 # Set all default hooks, defined in the IPython.hooks module.
434 # Set all default hooks, defined in the IPython.hooks module.
436 hooks = IPython.hooks
435 hooks = IPython.hooks
437 for hook_name in hooks.__all__:
436 for hook_name in hooks.__all__:
438 # default hooks have priority 100, i.e. low; user hooks should have
437 # default hooks have priority 100, i.e. low; user hooks should have
439 # 0-100 priority
438 # 0-100 priority
440 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
439 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
441 #print "bound hook",hook_name
440 #print "bound hook",hook_name
442
441
443 # Flag to mark unconditional exit
442 # Flag to mark unconditional exit
444 self.exit_now = False
443 self.exit_now = False
445
444
446 self.usage_min = """\
445 self.usage_min = """\
447 An enhanced console for Python.
446 An enhanced console for Python.
448 Some of its features are:
447 Some of its features are:
449 - Readline support if the readline library is present.
448 - Readline support if the readline library is present.
450 - Tab completion in the local namespace.
449 - Tab completion in the local namespace.
451 - Logging of input, see command-line options.
450 - Logging of input, see command-line options.
452 - System shell escape via ! , eg !ls.
451 - System shell escape via ! , eg !ls.
453 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
452 - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.)
454 - Keeps track of locally defined variables via %who, %whos.
453 - Keeps track of locally defined variables via %who, %whos.
455 - Show object information with a ? eg ?x or x? (use ?? for more info).
454 - Show object information with a ? eg ?x or x? (use ?? for more info).
456 """
455 """
457 if usage: self.usage = usage
456 if usage: self.usage = usage
458 else: self.usage = self.usage_min
457 else: self.usage = self.usage_min
459
458
460 # Storage
459 # Storage
461 self.rc = rc # This will hold all configuration information
460 self.rc = rc # This will hold all configuration information
462 self.pager = 'less'
461 self.pager = 'less'
463 # temporary files used for various purposes. Deleted at exit.
462 # temporary files used for various purposes. Deleted at exit.
464 self.tempfiles = []
463 self.tempfiles = []
465
464
466 # Keep track of readline usage (later set by init_readline)
465 # Keep track of readline usage (later set by init_readline)
467 self.has_readline = False
466 self.has_readline = False
468
467
469 # template for logfile headers. It gets resolved at runtime by the
468 # template for logfile headers. It gets resolved at runtime by the
470 # logstart method.
469 # logstart method.
471 self.loghead_tpl = \
470 self.loghead_tpl = \
472 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
471 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
473 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
472 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
474 #log# opts = %s
473 #log# opts = %s
475 #log# args = %s
474 #log# args = %s
476 #log# It is safe to make manual edits below here.
475 #log# It is safe to make manual edits below here.
477 #log#-----------------------------------------------------------------------
476 #log#-----------------------------------------------------------------------
478 """
477 """
479 # for pushd/popd management
478 # for pushd/popd management
480 try:
479 try:
481 self.home_dir = get_home_dir()
480 self.home_dir = get_home_dir()
482 except HomeDirError,msg:
481 except HomeDirError,msg:
483 fatal(msg)
482 fatal(msg)
484
483
485 self.dir_stack = []
484 self.dir_stack = []
486
485
487 # Functions to call the underlying shell.
486 # Functions to call the underlying shell.
488
487
489 # The first is similar to os.system, but it doesn't return a value,
488 # The first is similar to os.system, but it doesn't return a value,
490 # and it allows interpolation of variables in the user's namespace.
489 # and it allows interpolation of variables in the user's namespace.
491 self.system = lambda cmd: \
490 self.system = lambda cmd: \
492 self.hooks.shell_hook(self.var_expand(cmd,depth=2))
491 self.hooks.shell_hook(self.var_expand(cmd,depth=2))
493
492
494 # These are for getoutput and getoutputerror:
493 # These are for getoutput and getoutputerror:
495 self.getoutput = lambda cmd: \
494 self.getoutput = lambda cmd: \
496 getoutput(self.var_expand(cmd,depth=2),
495 getoutput(self.var_expand(cmd,depth=2),
497 header=self.rc.system_header,
496 header=self.rc.system_header,
498 verbose=self.rc.system_verbose)
497 verbose=self.rc.system_verbose)
499
498
500 self.getoutputerror = lambda cmd: \
499 self.getoutputerror = lambda cmd: \
501 getoutputerror(self.var_expand(cmd,depth=2),
500 getoutputerror(self.var_expand(cmd,depth=2),
502 header=self.rc.system_header,
501 header=self.rc.system_header,
503 verbose=self.rc.system_verbose)
502 verbose=self.rc.system_verbose)
504
503
505
504
506 # keep track of where we started running (mainly for crash post-mortem)
505 # keep track of where we started running (mainly for crash post-mortem)
507 self.starting_dir = os.getcwd()
506 self.starting_dir = os.getcwd()
508
507
509 # Various switches which can be set
508 # Various switches which can be set
510 self.CACHELENGTH = 5000 # this is cheap, it's just text
509 self.CACHELENGTH = 5000 # this is cheap, it's just text
511 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
510 self.BANNER = "Python %(version)s on %(platform)s\n" % sys.__dict__
512 self.banner2 = banner2
511 self.banner2 = banner2
513
512
514 # TraceBack handlers:
513 # TraceBack handlers:
515
514
516 # Syntax error handler.
515 # Syntax error handler.
517 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
516 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
518
517
519 # The interactive one is initialized with an offset, meaning we always
518 # The interactive one is initialized with an offset, meaning we always
520 # want to remove the topmost item in the traceback, which is our own
519 # want to remove the topmost item in the traceback, which is our own
521 # internal code. Valid modes: ['Plain','Context','Verbose']
520 # internal code. Valid modes: ['Plain','Context','Verbose']
522 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
521 self.InteractiveTB = ultraTB.AutoFormattedTB(mode = 'Plain',
523 color_scheme='NoColor',
522 color_scheme='NoColor',
524 tb_offset = 1)
523 tb_offset = 1)
525
524
526 # IPython itself shouldn't crash. This will produce a detailed
525 # IPython itself shouldn't crash. This will produce a detailed
527 # post-mortem if it does. But we only install the crash handler for
526 # post-mortem if it does. But we only install the crash handler for
528 # non-threaded shells, the threaded ones use a normal verbose reporter
527 # non-threaded shells, the threaded ones use a normal verbose reporter
529 # and lose the crash handler. This is because exceptions in the main
528 # and lose the crash handler. This is because exceptions in the main
530 # thread (such as in GUI code) propagate directly to sys.excepthook,
529 # thread (such as in GUI code) propagate directly to sys.excepthook,
531 # and there's no point in printing crash dumps for every user exception.
530 # and there's no point in printing crash dumps for every user exception.
532 if self.isthreaded:
531 if self.isthreaded:
533 ipCrashHandler = ultraTB.FormattedTB()
532 ipCrashHandler = ultraTB.FormattedTB()
534 else:
533 else:
535 from IPython import CrashHandler
534 from IPython import CrashHandler
536 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
535 ipCrashHandler = CrashHandler.IPythonCrashHandler(self)
537 self.set_crash_handler(ipCrashHandler)
536 self.set_crash_handler(ipCrashHandler)
538
537
539 # and add any custom exception handlers the user may have specified
538 # and add any custom exception handlers the user may have specified
540 self.set_custom_exc(*custom_exceptions)
539 self.set_custom_exc(*custom_exceptions)
541
540
542 # indentation management
541 # indentation management
543 self.autoindent = False
542 self.autoindent = False
544 self.indent_current_nsp = 0
543 self.indent_current_nsp = 0
545
544
546 # Make some aliases automatically
545 # Make some aliases automatically
547 # Prepare list of shell aliases to auto-define
546 # Prepare list of shell aliases to auto-define
548 if os.name == 'posix':
547 if os.name == 'posix':
549 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
548 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
550 'mv mv -i','rm rm -i','cp cp -i',
549 'mv mv -i','rm rm -i','cp cp -i',
551 'cat cat','less less','clear clear',
550 'cat cat','less less','clear clear',
552 # a better ls
551 # a better ls
553 'ls ls -F',
552 'ls ls -F',
554 # long ls
553 # long ls
555 'll ls -lF')
554 'll ls -lF')
556 # Extra ls aliases with color, which need special treatment on BSD
555 # Extra ls aliases with color, which need special treatment on BSD
557 # variants
556 # variants
558 ls_extra = ( # color ls
557 ls_extra = ( # color ls
559 'lc ls -F -o --color',
558 'lc ls -F -o --color',
560 # ls normal files only
559 # ls normal files only
561 'lf ls -F -o --color %l | grep ^-',
560 'lf ls -F -o --color %l | grep ^-',
562 # ls symbolic links
561 # ls symbolic links
563 'lk ls -F -o --color %l | grep ^l',
562 'lk ls -F -o --color %l | grep ^l',
564 # directories or links to directories,
563 # directories or links to directories,
565 'ldir ls -F -o --color %l | grep /$',
564 'ldir ls -F -o --color %l | grep /$',
566 # things which are executable
565 # things which are executable
567 'lx ls -F -o --color %l | grep ^-..x',
566 'lx ls -F -o --color %l | grep ^-..x',
568 )
567 )
569 # The BSDs don't ship GNU ls, so they don't understand the
568 # The BSDs don't ship GNU ls, so they don't understand the
570 # --color switch out of the box
569 # --color switch out of the box
571 if 'bsd' in sys.platform:
570 if 'bsd' in sys.platform:
572 ls_extra = ( # ls normal files only
571 ls_extra = ( # ls normal files only
573 'lf ls -lF | grep ^-',
572 'lf ls -lF | grep ^-',
574 # ls symbolic links
573 # ls symbolic links
575 'lk ls -lF | grep ^l',
574 'lk ls -lF | grep ^l',
576 # directories or links to directories,
575 # directories or links to directories,
577 'ldir ls -lF | grep /$',
576 'ldir ls -lF | grep /$',
578 # things which are executable
577 # things which are executable
579 'lx ls -lF | grep ^-..x',
578 'lx ls -lF | grep ^-..x',
580 )
579 )
581 auto_alias = auto_alias + ls_extra
580 auto_alias = auto_alias + ls_extra
582 elif os.name in ['nt','dos']:
581 elif os.name in ['nt','dos']:
583 auto_alias = ('ls dir /on',
582 auto_alias = ('ls dir /on',
584 'ddir dir /ad /on', 'ldir dir /ad /on',
583 'ddir dir /ad /on', 'ldir dir /ad /on',
585 'mkdir mkdir','rmdir rmdir','echo echo',
584 'mkdir mkdir','rmdir rmdir','echo echo',
586 'ren ren','cls cls','copy copy')
585 'ren ren','cls cls','copy copy')
587 else:
586 else:
588 auto_alias = ()
587 auto_alias = ()
589 self.auto_alias = [s.split(None,1) for s in auto_alias]
588 self.auto_alias = [s.split(None,1) for s in auto_alias]
590
589
591
590
592 # Produce a public API instance
591 # Produce a public API instance
593 self.api = IPython.ipapi.IPApi(self)
592 self.api = IPython.ipapi.IPApi(self)
594
593
595 # Call the actual (public) initializer
594 # Call the actual (public) initializer
596 self.init_auto_alias()
595 self.init_auto_alias()
597
596
598 # track which builtins we add, so we can clean up later
597 # track which builtins we add, so we can clean up later
599 self.builtins_added = {}
598 self.builtins_added = {}
600 # This method will add the necessary builtins for operation, but
599 # This method will add the necessary builtins for operation, but
601 # tracking what it did via the builtins_added dict.
600 # tracking what it did via the builtins_added dict.
602
601
603 #TODO: remove this, redundant
602 #TODO: remove this, redundant
604 self.add_builtins()
603 self.add_builtins()
605
604
606
605
607
606
608
607
609 # end __init__
608 # end __init__
610
609
611 def var_expand(self,cmd,depth=0):
610 def var_expand(self,cmd,depth=0):
612 """Expand python variables in a string.
611 """Expand python variables in a string.
613
612
614 The depth argument indicates how many frames above the caller should
613 The depth argument indicates how many frames above the caller should
615 be walked to look for the local namespace where to expand variables.
614 be walked to look for the local namespace where to expand variables.
616
615
617 The global namespace for expansion is always the user's interactive
616 The global namespace for expansion is always the user's interactive
618 namespace.
617 namespace.
619 """
618 """
620
619
621 return str(ItplNS(cmd,
620 return str(ItplNS(cmd,
622 self.user_ns, # globals
621 self.user_ns, # globals
623 # Skip our own frame in searching for locals:
622 # Skip our own frame in searching for locals:
624 sys._getframe(depth+1).f_locals # locals
623 sys._getframe(depth+1).f_locals # locals
625 ))
624 ))
626
625
627 def pre_config_initialization(self):
626 def pre_config_initialization(self):
628 """Pre-configuration init method
627 """Pre-configuration init method
629
628
630 This is called before the configuration files are processed to
629 This is called before the configuration files are processed to
631 prepare the services the config files might need.
630 prepare the services the config files might need.
632
631
633 self.rc already has reasonable default values at this point.
632 self.rc already has reasonable default values at this point.
634 """
633 """
635 rc = self.rc
634 rc = self.rc
636 try:
635 try:
637 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
636 self.db = pickleshare.PickleShareDB(rc.ipythondir + "/db")
638 except exceptions.UnicodeDecodeError:
637 except exceptions.UnicodeDecodeError:
639 print "Your ipythondir can't be decoded to unicode!"
638 print "Your ipythondir can't be decoded to unicode!"
640 print "Please set HOME environment variable to something that"
639 print "Please set HOME environment variable to something that"
641 print r"only has ASCII characters, e.g. c:\home"
640 print r"only has ASCII characters, e.g. c:\home"
642 print "Now it is",rc.ipythondir
641 print "Now it is",rc.ipythondir
643 sys.exit()
642 sys.exit()
644 self.shadowhist = IPython.history.ShadowHist(self.db)
643 self.shadowhist = IPython.history.ShadowHist(self.db)
645
644
646
645
647 def post_config_initialization(self):
646 def post_config_initialization(self):
648 """Post configuration init method
647 """Post configuration init method
649
648
650 This is called after the configuration files have been processed to
649 This is called after the configuration files have been processed to
651 'finalize' the initialization."""
650 'finalize' the initialization."""
652
651
653 rc = self.rc
652 rc = self.rc
654
653
655 # Object inspector
654 # Object inspector
656 self.inspector = OInspect.Inspector(OInspect.InspectColors,
655 self.inspector = OInspect.Inspector(OInspect.InspectColors,
657 PyColorize.ANSICodeColors,
656 PyColorize.ANSICodeColors,
658 'NoColor',
657 'NoColor',
659 rc.object_info_string_level)
658 rc.object_info_string_level)
660
659
661 self.rl_next_input = None
660 self.rl_next_input = None
662 self.rl_do_indent = False
661 self.rl_do_indent = False
663 # Load readline proper
662 # Load readline proper
664 if rc.readline:
663 if rc.readline:
665 self.init_readline()
664 self.init_readline()
666
665
667
666
668 # local shortcut, this is used a LOT
667 # local shortcut, this is used a LOT
669 self.log = self.logger.log
668 self.log = self.logger.log
670
669
671 # Initialize cache, set in/out prompts and printing system
670 # Initialize cache, set in/out prompts and printing system
672 self.outputcache = CachedOutput(self,
671 self.outputcache = CachedOutput(self,
673 rc.cache_size,
672 rc.cache_size,
674 rc.pprint,
673 rc.pprint,
675 input_sep = rc.separate_in,
674 input_sep = rc.separate_in,
676 output_sep = rc.separate_out,
675 output_sep = rc.separate_out,
677 output_sep2 = rc.separate_out2,
676 output_sep2 = rc.separate_out2,
678 ps1 = rc.prompt_in1,
677 ps1 = rc.prompt_in1,
679 ps2 = rc.prompt_in2,
678 ps2 = rc.prompt_in2,
680 ps_out = rc.prompt_out,
679 ps_out = rc.prompt_out,
681 pad_left = rc.prompts_pad_left)
680 pad_left = rc.prompts_pad_left)
682
681
683 # user may have over-ridden the default print hook:
682 # user may have over-ridden the default print hook:
684 try:
683 try:
685 self.outputcache.__class__.display = self.hooks.display
684 self.outputcache.__class__.display = self.hooks.display
686 except AttributeError:
685 except AttributeError:
687 pass
686 pass
688
687
689 # I don't like assigning globally to sys, because it means when
688 # I don't like assigning globally to sys, because it means when
690 # embedding instances, each embedded instance overrides the previous
689 # embedding instances, each embedded instance overrides the previous
691 # choice. But sys.displayhook seems to be called internally by exec,
690 # choice. But sys.displayhook seems to be called internally by exec,
692 # so I don't see a way around it. We first save the original and then
691 # so I don't see a way around it. We first save the original and then
693 # overwrite it.
692 # overwrite it.
694 self.sys_displayhook = sys.displayhook
693 self.sys_displayhook = sys.displayhook
695 sys.displayhook = self.outputcache
694 sys.displayhook = self.outputcache
696
695
697 # Do a proper resetting of doctest, including the necessary displayhook
696 # Do a proper resetting of doctest, including the necessary displayhook
698 # monkeypatching
697 # monkeypatching
699 try:
698 try:
700 doctest_reload()
699 doctest_reload()
701 except ImportError:
700 except ImportError:
702 warn("doctest module does not exist.")
701 warn("doctest module does not exist.")
703
702
704 # Set user colors (don't do it in the constructor above so that it
703 # Set user colors (don't do it in the constructor above so that it
705 # doesn't crash if colors option is invalid)
704 # doesn't crash if colors option is invalid)
706 self.magic_colors(rc.colors)
705 self.magic_colors(rc.colors)
707
706
708 # Set calling of pdb on exceptions
707 # Set calling of pdb on exceptions
709 self.call_pdb = rc.pdb
708 self.call_pdb = rc.pdb
710
709
711 # Load user aliases
710 # Load user aliases
712 for alias in rc.alias:
711 for alias in rc.alias:
713 self.magic_alias(alias)
712 self.magic_alias(alias)
714
713
715 self.hooks.late_startup_hook()
714 self.hooks.late_startup_hook()
716
715
717 for cmd in self.rc.autoexec:
716 for cmd in self.rc.autoexec:
718 #print "autoexec>",cmd #dbg
717 #print "autoexec>",cmd #dbg
719 self.api.runlines(cmd)
718 self.api.runlines(cmd)
720
719
721 batchrun = False
720 batchrun = False
722 for batchfile in [path(arg) for arg in self.rc.args
721 for batchfile in [path(arg) for arg in self.rc.args
723 if arg.lower().endswith('.ipy')]:
722 if arg.lower().endswith('.ipy')]:
724 if not batchfile.isfile():
723 if not batchfile.isfile():
725 print "No such batch file:", batchfile
724 print "No such batch file:", batchfile
726 continue
725 continue
727 self.api.runlines(batchfile.text())
726 self.api.runlines(batchfile.text())
728 batchrun = True
727 batchrun = True
729 # without -i option, exit after running the batch file
728 # without -i option, exit after running the batch file
730 if batchrun and not self.rc.interact:
729 if batchrun and not self.rc.interact:
731 self.ask_exit()
730 self.ask_exit()
732
731
733 def add_builtins(self):
732 def add_builtins(self):
734 """Store ipython references into the builtin namespace.
733 """Store ipython references into the builtin namespace.
735
734
736 Some parts of ipython operate via builtins injected here, which hold a
735 Some parts of ipython operate via builtins injected here, which hold a
737 reference to IPython itself."""
736 reference to IPython itself."""
738
737
739 # TODO: deprecate all of these, they are unsafe
738 # TODO: deprecate all of these, they are unsafe
740 builtins_new = dict(__IPYTHON__ = self,
739 builtins_new = dict(__IPYTHON__ = self,
741 ip_set_hook = self.set_hook,
740 ip_set_hook = self.set_hook,
742 jobs = self.jobs,
741 jobs = self.jobs,
743 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
742 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
744 ipalias = wrap_deprecated(self.ipalias),
743 ipalias = wrap_deprecated(self.ipalias),
745 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
744 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
746 #_ip = self.api
745 #_ip = self.api
747 )
746 )
748 for biname,bival in builtins_new.items():
747 for biname,bival in builtins_new.items():
749 try:
748 try:
750 # store the orignal value so we can restore it
749 # store the orignal value so we can restore it
751 self.builtins_added[biname] = __builtin__.__dict__[biname]
750 self.builtins_added[biname] = __builtin__.__dict__[biname]
752 except KeyError:
751 except KeyError:
753 # or mark that it wasn't defined, and we'll just delete it at
752 # or mark that it wasn't defined, and we'll just delete it at
754 # cleanup
753 # cleanup
755 self.builtins_added[biname] = Undefined
754 self.builtins_added[biname] = Undefined
756 __builtin__.__dict__[biname] = bival
755 __builtin__.__dict__[biname] = bival
757
756
758 # Keep in the builtins a flag for when IPython is active. We set it
757 # Keep in the builtins a flag for when IPython is active. We set it
759 # with setdefault so that multiple nested IPythons don't clobber one
758 # with setdefault so that multiple nested IPythons don't clobber one
760 # another. Each will increase its value by one upon being activated,
759 # another. Each will increase its value by one upon being activated,
761 # which also gives us a way to determine the nesting level.
760 # which also gives us a way to determine the nesting level.
762 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
761 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
763
762
764 def clean_builtins(self):
763 def clean_builtins(self):
765 """Remove any builtins which might have been added by add_builtins, or
764 """Remove any builtins which might have been added by add_builtins, or
766 restore overwritten ones to their previous values."""
765 restore overwritten ones to their previous values."""
767 for biname,bival in self.builtins_added.items():
766 for biname,bival in self.builtins_added.items():
768 if bival is Undefined:
767 if bival is Undefined:
769 del __builtin__.__dict__[biname]
768 del __builtin__.__dict__[biname]
770 else:
769 else:
771 __builtin__.__dict__[biname] = bival
770 __builtin__.__dict__[biname] = bival
772 self.builtins_added.clear()
771 self.builtins_added.clear()
773
772
774 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
773 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
775 """set_hook(name,hook) -> sets an internal IPython hook.
774 """set_hook(name,hook) -> sets an internal IPython hook.
776
775
777 IPython exposes some of its internal API as user-modifiable hooks. By
776 IPython exposes some of its internal API as user-modifiable hooks. By
778 adding your function to one of these hooks, you can modify IPython's
777 adding your function to one of these hooks, you can modify IPython's
779 behavior to call at runtime your own routines."""
778 behavior to call at runtime your own routines."""
780
779
781 # At some point in the future, this should validate the hook before it
780 # At some point in the future, this should validate the hook before it
782 # accepts it. Probably at least check that the hook takes the number
781 # accepts it. Probably at least check that the hook takes the number
783 # of args it's supposed to.
782 # of args it's supposed to.
784
783
785 f = new.instancemethod(hook,self,self.__class__)
784 f = new.instancemethod(hook,self,self.__class__)
786
785
787 # check if the hook is for strdispatcher first
786 # check if the hook is for strdispatcher first
788 if str_key is not None:
787 if str_key is not None:
789 sdp = self.strdispatchers.get(name, StrDispatch())
788 sdp = self.strdispatchers.get(name, StrDispatch())
790 sdp.add_s(str_key, f, priority )
789 sdp.add_s(str_key, f, priority )
791 self.strdispatchers[name] = sdp
790 self.strdispatchers[name] = sdp
792 return
791 return
793 if re_key is not None:
792 if re_key is not None:
794 sdp = self.strdispatchers.get(name, StrDispatch())
793 sdp = self.strdispatchers.get(name, StrDispatch())
795 sdp.add_re(re.compile(re_key), f, priority )
794 sdp.add_re(re.compile(re_key), f, priority )
796 self.strdispatchers[name] = sdp
795 self.strdispatchers[name] = sdp
797 return
796 return
798
797
799 dp = getattr(self.hooks, name, None)
798 dp = getattr(self.hooks, name, None)
800 if name not in IPython.hooks.__all__:
799 if name not in IPython.hooks.__all__:
801 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
800 print "Warning! Hook '%s' is not one of %s" % (name, IPython.hooks.__all__ )
802 if not dp:
801 if not dp:
803 dp = IPython.hooks.CommandChainDispatcher()
802 dp = IPython.hooks.CommandChainDispatcher()
804
803
805 try:
804 try:
806 dp.add(f,priority)
805 dp.add(f,priority)
807 except AttributeError:
806 except AttributeError:
808 # it was not commandchain, plain old func - replace
807 # it was not commandchain, plain old func - replace
809 dp = f
808 dp = f
810
809
811 setattr(self.hooks,name, dp)
810 setattr(self.hooks,name, dp)
812
811
813
812
814 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
813 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
815
814
816 def set_crash_handler(self,crashHandler):
815 def set_crash_handler(self,crashHandler):
817 """Set the IPython crash handler.
816 """Set the IPython crash handler.
818
817
819 This must be a callable with a signature suitable for use as
818 This must be a callable with a signature suitable for use as
820 sys.excepthook."""
819 sys.excepthook."""
821
820
822 # Install the given crash handler as the Python exception hook
821 # Install the given crash handler as the Python exception hook
823 sys.excepthook = crashHandler
822 sys.excepthook = crashHandler
824
823
825 # The instance will store a pointer to this, so that runtime code
824 # The instance will store a pointer to this, so that runtime code
826 # (such as magics) can access it. This is because during the
825 # (such as magics) can access it. This is because during the
827 # read-eval loop, it gets temporarily overwritten (to deal with GUI
826 # read-eval loop, it gets temporarily overwritten (to deal with GUI
828 # frameworks).
827 # frameworks).
829 self.sys_excepthook = sys.excepthook
828 self.sys_excepthook = sys.excepthook
830
829
831
830
832 def set_custom_exc(self,exc_tuple,handler):
831 def set_custom_exc(self,exc_tuple,handler):
833 """set_custom_exc(exc_tuple,handler)
832 """set_custom_exc(exc_tuple,handler)
834
833
835 Set a custom exception handler, which will be called if any of the
834 Set a custom exception handler, which will be called if any of the
836 exceptions in exc_tuple occur in the mainloop (specifically, in the
835 exceptions in exc_tuple occur in the mainloop (specifically, in the
837 runcode() method.
836 runcode() method.
838
837
839 Inputs:
838 Inputs:
840
839
841 - exc_tuple: a *tuple* of valid exceptions to call the defined
840 - exc_tuple: a *tuple* of valid exceptions to call the defined
842 handler for. It is very important that you use a tuple, and NOT A
841 handler for. It is very important that you use a tuple, and NOT A
843 LIST here, because of the way Python's except statement works. If
842 LIST here, because of the way Python's except statement works. If
844 you only want to trap a single exception, use a singleton tuple:
843 you only want to trap a single exception, use a singleton tuple:
845
844
846 exc_tuple == (MyCustomException,)
845 exc_tuple == (MyCustomException,)
847
846
848 - handler: this must be defined as a function with the following
847 - handler: this must be defined as a function with the following
849 basic interface: def my_handler(self,etype,value,tb).
848 basic interface: def my_handler(self,etype,value,tb).
850
849
851 This will be made into an instance method (via new.instancemethod)
850 This will be made into an instance method (via new.instancemethod)
852 of IPython itself, and it will be called if any of the exceptions
851 of IPython itself, and it will be called if any of the exceptions
853 listed in the exc_tuple are caught. If the handler is None, an
852 listed in the exc_tuple are caught. If the handler is None, an
854 internal basic one is used, which just prints basic info.
853 internal basic one is used, which just prints basic info.
855
854
856 WARNING: by putting in your own exception handler into IPython's main
855 WARNING: by putting in your own exception handler into IPython's main
857 execution loop, you run a very good chance of nasty crashes. This
856 execution loop, you run a very good chance of nasty crashes. This
858 facility should only be used if you really know what you are doing."""
857 facility should only be used if you really know what you are doing."""
859
858
860 assert type(exc_tuple)==type(()) , \
859 assert type(exc_tuple)==type(()) , \
861 "The custom exceptions must be given AS A TUPLE."
860 "The custom exceptions must be given AS A TUPLE."
862
861
863 def dummy_handler(self,etype,value,tb):
862 def dummy_handler(self,etype,value,tb):
864 print '*** Simple custom exception handler ***'
863 print '*** Simple custom exception handler ***'
865 print 'Exception type :',etype
864 print 'Exception type :',etype
866 print 'Exception value:',value
865 print 'Exception value:',value
867 print 'Traceback :',tb
866 print 'Traceback :',tb
868 print 'Source code :','\n'.join(self.buffer)
867 print 'Source code :','\n'.join(self.buffer)
869
868
870 if handler is None: handler = dummy_handler
869 if handler is None: handler = dummy_handler
871
870
872 self.CustomTB = new.instancemethod(handler,self,self.__class__)
871 self.CustomTB = new.instancemethod(handler,self,self.__class__)
873 self.custom_exceptions = exc_tuple
872 self.custom_exceptions = exc_tuple
874
873
875 def set_custom_completer(self,completer,pos=0):
874 def set_custom_completer(self,completer,pos=0):
876 """set_custom_completer(completer,pos=0)
875 """set_custom_completer(completer,pos=0)
877
876
878 Adds a new custom completer function.
877 Adds a new custom completer function.
879
878
880 The position argument (defaults to 0) is the index in the completers
879 The position argument (defaults to 0) is the index in the completers
881 list where you want the completer to be inserted."""
880 list where you want the completer to be inserted."""
882
881
883 newcomp = new.instancemethod(completer,self.Completer,
882 newcomp = new.instancemethod(completer,self.Completer,
884 self.Completer.__class__)
883 self.Completer.__class__)
885 self.Completer.matchers.insert(pos,newcomp)
884 self.Completer.matchers.insert(pos,newcomp)
886
885
887 def set_completer(self):
886 def set_completer(self):
888 """reset readline's completer to be our own."""
887 """reset readline's completer to be our own."""
889 self.readline.set_completer(self.Completer.complete)
888 self.readline.set_completer(self.Completer.complete)
890
889
891 def _get_call_pdb(self):
890 def _get_call_pdb(self):
892 return self._call_pdb
891 return self._call_pdb
893
892
894 def _set_call_pdb(self,val):
893 def _set_call_pdb(self,val):
895
894
896 if val not in (0,1,False,True):
895 if val not in (0,1,False,True):
897 raise ValueError,'new call_pdb value must be boolean'
896 raise ValueError,'new call_pdb value must be boolean'
898
897
899 # store value in instance
898 # store value in instance
900 self._call_pdb = val
899 self._call_pdb = val
901
900
902 # notify the actual exception handlers
901 # notify the actual exception handlers
903 self.InteractiveTB.call_pdb = val
902 self.InteractiveTB.call_pdb = val
904 if self.isthreaded:
903 if self.isthreaded:
905 try:
904 try:
906 self.sys_excepthook.call_pdb = val
905 self.sys_excepthook.call_pdb = val
907 except:
906 except:
908 warn('Failed to activate pdb for threaded exception handler')
907 warn('Failed to activate pdb for threaded exception handler')
909
908
910 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
909 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
911 'Control auto-activation of pdb at exceptions')
910 'Control auto-activation of pdb at exceptions')
912
911
913
912
914 # These special functions get installed in the builtin namespace, to
913 # These special functions get installed in the builtin namespace, to
915 # provide programmatic (pure python) access to magics, aliases and system
914 # provide programmatic (pure python) access to magics, aliases and system
916 # calls. This is important for logging, user scripting, and more.
915 # calls. This is important for logging, user scripting, and more.
917
916
918 # We are basically exposing, via normal python functions, the three
917 # We are basically exposing, via normal python functions, the three
919 # mechanisms in which ipython offers special call modes (magics for
918 # mechanisms in which ipython offers special call modes (magics for
920 # internal control, aliases for direct system access via pre-selected
919 # internal control, aliases for direct system access via pre-selected
921 # names, and !cmd for calling arbitrary system commands).
920 # names, and !cmd for calling arbitrary system commands).
922
921
923 def ipmagic(self,arg_s):
922 def ipmagic(self,arg_s):
924 """Call a magic function by name.
923 """Call a magic function by name.
925
924
926 Input: a string containing the name of the magic function to call and any
925 Input: a string containing the name of the magic function to call and any
927 additional arguments to be passed to the magic.
926 additional arguments to be passed to the magic.
928
927
929 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
928 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
930 prompt:
929 prompt:
931
930
932 In[1]: %name -opt foo bar
931 In[1]: %name -opt foo bar
933
932
934 To call a magic without arguments, simply use ipmagic('name').
933 To call a magic without arguments, simply use ipmagic('name').
935
934
936 This provides a proper Python function to call IPython's magics in any
935 This provides a proper Python function to call IPython's magics in any
937 valid Python code you can type at the interpreter, including loops and
936 valid Python code you can type at the interpreter, including loops and
938 compound statements. It is added by IPython to the Python builtin
937 compound statements. It is added by IPython to the Python builtin
939 namespace upon initialization."""
938 namespace upon initialization."""
940
939
941 args = arg_s.split(' ',1)
940 args = arg_s.split(' ',1)
942 magic_name = args[0]
941 magic_name = args[0]
943 magic_name = magic_name.lstrip(self.ESC_MAGIC)
942 magic_name = magic_name.lstrip(self.ESC_MAGIC)
944
943
945 try:
944 try:
946 magic_args = args[1]
945 magic_args = args[1]
947 except IndexError:
946 except IndexError:
948 magic_args = ''
947 magic_args = ''
949 fn = getattr(self,'magic_'+magic_name,None)
948 fn = getattr(self,'magic_'+magic_name,None)
950 if fn is None:
949 if fn is None:
951 error("Magic function `%s` not found." % magic_name)
950 error("Magic function `%s` not found." % magic_name)
952 else:
951 else:
953 magic_args = self.var_expand(magic_args,1)
952 magic_args = self.var_expand(magic_args,1)
954 return fn(magic_args)
953 return fn(magic_args)
955
954
956 def ipalias(self,arg_s):
955 def ipalias(self,arg_s):
957 """Call an alias by name.
956 """Call an alias by name.
958
957
959 Input: a string containing the name of the alias to call and any
958 Input: a string containing the name of the alias to call and any
960 additional arguments to be passed to the magic.
959 additional arguments to be passed to the magic.
961
960
962 ipalias('name -opt foo bar') is equivalent to typing at the ipython
961 ipalias('name -opt foo bar') is equivalent to typing at the ipython
963 prompt:
962 prompt:
964
963
965 In[1]: name -opt foo bar
964 In[1]: name -opt foo bar
966
965
967 To call an alias without arguments, simply use ipalias('name').
966 To call an alias without arguments, simply use ipalias('name').
968
967
969 This provides a proper Python function to call IPython's aliases in any
968 This provides a proper Python function to call IPython's aliases in any
970 valid Python code you can type at the interpreter, including loops and
969 valid Python code you can type at the interpreter, including loops and
971 compound statements. It is added by IPython to the Python builtin
970 compound statements. It is added by IPython to the Python builtin
972 namespace upon initialization."""
971 namespace upon initialization."""
973
972
974 args = arg_s.split(' ',1)
973 args = arg_s.split(' ',1)
975 alias_name = args[0]
974 alias_name = args[0]
976 try:
975 try:
977 alias_args = args[1]
976 alias_args = args[1]
978 except IndexError:
977 except IndexError:
979 alias_args = ''
978 alias_args = ''
980 if alias_name in self.alias_table:
979 if alias_name in self.alias_table:
981 self.call_alias(alias_name,alias_args)
980 self.call_alias(alias_name,alias_args)
982 else:
981 else:
983 error("Alias `%s` not found." % alias_name)
982 error("Alias `%s` not found." % alias_name)
984
983
985 def ipsystem(self,arg_s):
984 def ipsystem(self,arg_s):
986 """Make a system call, using IPython."""
985 """Make a system call, using IPython."""
987
986
988 self.system(arg_s)
987 self.system(arg_s)
989
988
990 def complete(self,text):
989 def complete(self,text):
991 """Return a sorted list of all possible completions on text.
990 """Return a sorted list of all possible completions on text.
992
991
993 Inputs:
992 Inputs:
994
993
995 - text: a string of text to be completed on.
994 - text: a string of text to be completed on.
996
995
997 This is a wrapper around the completion mechanism, similar to what
996 This is a wrapper around the completion mechanism, similar to what
998 readline does at the command line when the TAB key is hit. By
997 readline does at the command line when the TAB key is hit. By
999 exposing it as a method, it can be used by other non-readline
998 exposing it as a method, it can be used by other non-readline
1000 environments (such as GUIs) for text completion.
999 environments (such as GUIs) for text completion.
1001
1000
1002 Simple usage example:
1001 Simple usage example:
1003
1002
1004 In [7]: x = 'hello'
1003 In [7]: x = 'hello'
1005
1004
1006 In [8]: x
1005 In [8]: x
1007 Out[8]: 'hello'
1006 Out[8]: 'hello'
1008
1007
1009 In [9]: print x
1008 In [9]: print x
1010 hello
1009 hello
1011
1010
1012 In [10]: _ip.IP.complete('x.l')
1011 In [10]: _ip.IP.complete('x.l')
1013 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] # random
1012 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip'] # random
1014 """
1013 """
1015
1014
1016 complete = self.Completer.complete
1015 complete = self.Completer.complete
1017 state = 0
1016 state = 0
1018 # use a dict so we get unique keys, since ipyhton's multiple
1017 # use a dict so we get unique keys, since ipyhton's multiple
1019 # completers can return duplicates. When we make 2.4 a requirement,
1018 # completers can return duplicates. When we make 2.4 a requirement,
1020 # start using sets instead, which are faster.
1019 # start using sets instead, which are faster.
1021 comps = {}
1020 comps = {}
1022 while True:
1021 while True:
1023 newcomp = complete(text,state,line_buffer=text)
1022 newcomp = complete(text,state,line_buffer=text)
1024 if newcomp is None:
1023 if newcomp is None:
1025 break
1024 break
1026 comps[newcomp] = 1
1025 comps[newcomp] = 1
1027 state += 1
1026 state += 1
1028 outcomps = comps.keys()
1027 outcomps = comps.keys()
1029 outcomps.sort()
1028 outcomps.sort()
1030 #print "T:",text,"OC:",outcomps # dbg
1029 #print "T:",text,"OC:",outcomps # dbg
1031 #print "vars:",self.user_ns.keys()
1030 #print "vars:",self.user_ns.keys()
1032 return outcomps
1031 return outcomps
1033
1032
1034 def set_completer_frame(self, frame=None):
1033 def set_completer_frame(self, frame=None):
1035 if frame:
1034 if frame:
1036 self.Completer.namespace = frame.f_locals
1035 self.Completer.namespace = frame.f_locals
1037 self.Completer.global_namespace = frame.f_globals
1036 self.Completer.global_namespace = frame.f_globals
1038 else:
1037 else:
1039 self.Completer.namespace = self.user_ns
1038 self.Completer.namespace = self.user_ns
1040 self.Completer.global_namespace = self.user_global_ns
1039 self.Completer.global_namespace = self.user_global_ns
1041
1040
1042 def init_auto_alias(self):
1041 def init_auto_alias(self):
1043 """Define some aliases automatically.
1042 """Define some aliases automatically.
1044
1043
1045 These are ALL parameter-less aliases"""
1044 These are ALL parameter-less aliases"""
1046
1045
1047 for alias,cmd in self.auto_alias:
1046 for alias,cmd in self.auto_alias:
1048 self.getapi().defalias(alias,cmd)
1047 self.getapi().defalias(alias,cmd)
1049
1048
1050
1049
1051 def alias_table_validate(self,verbose=0):
1050 def alias_table_validate(self,verbose=0):
1052 """Update information about the alias table.
1051 """Update information about the alias table.
1053
1052
1054 In particular, make sure no Python keywords/builtins are in it."""
1053 In particular, make sure no Python keywords/builtins are in it."""
1055
1054
1056 no_alias = self.no_alias
1055 no_alias = self.no_alias
1057 for k in self.alias_table.keys():
1056 for k in self.alias_table.keys():
1058 if k in no_alias:
1057 if k in no_alias:
1059 del self.alias_table[k]
1058 del self.alias_table[k]
1060 if verbose:
1059 if verbose:
1061 print ("Deleting alias <%s>, it's a Python "
1060 print ("Deleting alias <%s>, it's a Python "
1062 "keyword or builtin." % k)
1061 "keyword or builtin." % k)
1063
1062
1064 def set_autoindent(self,value=None):
1063 def set_autoindent(self,value=None):
1065 """Set the autoindent flag, checking for readline support.
1064 """Set the autoindent flag, checking for readline support.
1066
1065
1067 If called with no arguments, it acts as a toggle."""
1066 If called with no arguments, it acts as a toggle."""
1068
1067
1069 if not self.has_readline:
1068 if not self.has_readline:
1070 if os.name == 'posix':
1069 if os.name == 'posix':
1071 warn("The auto-indent feature requires the readline library")
1070 warn("The auto-indent feature requires the readline library")
1072 self.autoindent = 0
1071 self.autoindent = 0
1073 return
1072 return
1074 if value is None:
1073 if value is None:
1075 self.autoindent = not self.autoindent
1074 self.autoindent = not self.autoindent
1076 else:
1075 else:
1077 self.autoindent = value
1076 self.autoindent = value
1078
1077
1079 def rc_set_toggle(self,rc_field,value=None):
1078 def rc_set_toggle(self,rc_field,value=None):
1080 """Set or toggle a field in IPython's rc config. structure.
1079 """Set or toggle a field in IPython's rc config. structure.
1081
1080
1082 If called with no arguments, it acts as a toggle.
1081 If called with no arguments, it acts as a toggle.
1083
1082
1084 If called with a non-existent field, the resulting AttributeError
1083 If called with a non-existent field, the resulting AttributeError
1085 exception will propagate out."""
1084 exception will propagate out."""
1086
1085
1087 rc_val = getattr(self.rc,rc_field)
1086 rc_val = getattr(self.rc,rc_field)
1088 if value is None:
1087 if value is None:
1089 value = not rc_val
1088 value = not rc_val
1090 setattr(self.rc,rc_field,value)
1089 setattr(self.rc,rc_field,value)
1091
1090
1092 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1091 def user_setup(self,ipythondir,rc_suffix,mode='install'):
1093 """Install the user configuration directory.
1092 """Install the user configuration directory.
1094
1093
1095 Can be called when running for the first time or to upgrade the user's
1094 Can be called when running for the first time or to upgrade the user's
1096 .ipython/ directory with the mode parameter. Valid modes are 'install'
1095 .ipython/ directory with the mode parameter. Valid modes are 'install'
1097 and 'upgrade'."""
1096 and 'upgrade'."""
1098
1097
1099 def wait():
1098 def wait():
1100 try:
1099 try:
1101 raw_input("Please press <RETURN> to start IPython.")
1100 raw_input("Please press <RETURN> to start IPython.")
1102 except EOFError:
1101 except EOFError:
1103 print >> Term.cout
1102 print >> Term.cout
1104 print '*'*70
1103 print '*'*70
1105
1104
1106 cwd = os.getcwd() # remember where we started
1105 cwd = os.getcwd() # remember where we started
1107 glb = glob.glob
1106 glb = glob.glob
1108 print '*'*70
1107 print '*'*70
1109 if mode == 'install':
1108 if mode == 'install':
1110 print \
1109 print \
1111 """Welcome to IPython. I will try to create a personal configuration directory
1110 """Welcome to IPython. I will try to create a personal configuration directory
1112 where you can customize many aspects of IPython's functionality in:\n"""
1111 where you can customize many aspects of IPython's functionality in:\n"""
1113 else:
1112 else:
1114 print 'I am going to upgrade your configuration in:'
1113 print 'I am going to upgrade your configuration in:'
1115
1114
1116 print ipythondir
1115 print ipythondir
1117
1116
1118 rcdirend = os.path.join('IPython','UserConfig')
1117 rcdirend = os.path.join('IPython','UserConfig')
1119 cfg = lambda d: os.path.join(d,rcdirend)
1118 cfg = lambda d: os.path.join(d,rcdirend)
1120 try:
1119 try:
1121 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1120 rcdir = filter(os.path.isdir,map(cfg,sys.path))[0]
1122 print "Initializing from configuration",rcdir
1121 print "Initializing from configuration",rcdir
1123 except IndexError:
1122 except IndexError:
1124 warning = """
1123 warning = """
1125 Installation error. IPython's directory was not found.
1124 Installation error. IPython's directory was not found.
1126
1125
1127 Check the following:
1126 Check the following:
1128
1127
1129 The ipython/IPython directory should be in a directory belonging to your
1128 The ipython/IPython directory should be in a directory belonging to your
1130 PYTHONPATH environment variable (that is, it should be in a directory
1129 PYTHONPATH environment variable (that is, it should be in a directory
1131 belonging to sys.path). You can copy it explicitly there or just link to it.
1130 belonging to sys.path). You can copy it explicitly there or just link to it.
1132
1131
1133 IPython will create a minimal default configuration for you.
1132 IPython will create a minimal default configuration for you.
1134
1133
1135 """
1134 """
1136 warn(warning)
1135 warn(warning)
1137 wait()
1136 wait()
1138
1137
1139 if sys.platform =='win32':
1138 if sys.platform =='win32':
1140 inif = 'ipythonrc.ini'
1139 inif = 'ipythonrc.ini'
1141 else:
1140 else:
1142 inif = 'ipythonrc'
1141 inif = 'ipythonrc'
1143 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', inif : '# intentionally left blank' }
1142 minimal_setup = {'ipy_user_conf.py' : 'import ipy_defaults', inif : '# intentionally left blank' }
1144 os.makedirs(ipythondir, mode = 0777)
1143 os.makedirs(ipythondir, mode = 0777)
1145 for f, cont in minimal_setup.items():
1144 for f, cont in minimal_setup.items():
1146 open(ipythondir + '/' + f,'w').write(cont)
1145 open(ipythondir + '/' + f,'w').write(cont)
1147
1146
1148 return
1147 return
1149
1148
1150 if mode == 'install':
1149 if mode == 'install':
1151 try:
1150 try:
1152 shutil.copytree(rcdir,ipythondir)
1151 shutil.copytree(rcdir,ipythondir)
1153 os.chdir(ipythondir)
1152 os.chdir(ipythondir)
1154 rc_files = glb("ipythonrc*")
1153 rc_files = glb("ipythonrc*")
1155 for rc_file in rc_files:
1154 for rc_file in rc_files:
1156 os.rename(rc_file,rc_file+rc_suffix)
1155 os.rename(rc_file,rc_file+rc_suffix)
1157 except:
1156 except:
1158 warning = """
1157 warning = """
1159
1158
1160 There was a problem with the installation:
1159 There was a problem with the installation:
1161 %s
1160 %s
1162 Try to correct it or contact the developers if you think it's a bug.
1161 Try to correct it or contact the developers if you think it's a bug.
1163 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1162 IPython will proceed with builtin defaults.""" % sys.exc_info()[1]
1164 warn(warning)
1163 warn(warning)
1165 wait()
1164 wait()
1166 return
1165 return
1167
1166
1168 elif mode == 'upgrade':
1167 elif mode == 'upgrade':
1169 try:
1168 try:
1170 os.chdir(ipythondir)
1169 os.chdir(ipythondir)
1171 except:
1170 except:
1172 print """
1171 print """
1173 Can not upgrade: changing to directory %s failed. Details:
1172 Can not upgrade: changing to directory %s failed. Details:
1174 %s
1173 %s
1175 """ % (ipythondir,sys.exc_info()[1])
1174 """ % (ipythondir,sys.exc_info()[1])
1176 wait()
1175 wait()
1177 return
1176 return
1178 else:
1177 else:
1179 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1178 sources = glb(os.path.join(rcdir,'[A-Za-z]*'))
1180 for new_full_path in sources:
1179 for new_full_path in sources:
1181 new_filename = os.path.basename(new_full_path)
1180 new_filename = os.path.basename(new_full_path)
1182 if new_filename.startswith('ipythonrc'):
1181 if new_filename.startswith('ipythonrc'):
1183 new_filename = new_filename + rc_suffix
1182 new_filename = new_filename + rc_suffix
1184 # The config directory should only contain files, skip any
1183 # The config directory should only contain files, skip any
1185 # directories which may be there (like CVS)
1184 # directories which may be there (like CVS)
1186 if os.path.isdir(new_full_path):
1185 if os.path.isdir(new_full_path):
1187 continue
1186 continue
1188 if os.path.exists(new_filename):
1187 if os.path.exists(new_filename):
1189 old_file = new_filename+'.old'
1188 old_file = new_filename+'.old'
1190 if os.path.exists(old_file):
1189 if os.path.exists(old_file):
1191 os.remove(old_file)
1190 os.remove(old_file)
1192 os.rename(new_filename,old_file)
1191 os.rename(new_filename,old_file)
1193 shutil.copy(new_full_path,new_filename)
1192 shutil.copy(new_full_path,new_filename)
1194 else:
1193 else:
1195 raise ValueError,'unrecognized mode for install:',`mode`
1194 raise ValueError,'unrecognized mode for install:',`mode`
1196
1195
1197 # Fix line-endings to those native to each platform in the config
1196 # Fix line-endings to those native to each platform in the config
1198 # directory.
1197 # directory.
1199 try:
1198 try:
1200 os.chdir(ipythondir)
1199 os.chdir(ipythondir)
1201 except:
1200 except:
1202 print """
1201 print """
1203 Problem: changing to directory %s failed.
1202 Problem: changing to directory %s failed.
1204 Details:
1203 Details:
1205 %s
1204 %s
1206
1205
1207 Some configuration files may have incorrect line endings. This should not
1206 Some configuration files may have incorrect line endings. This should not
1208 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1207 cause any problems during execution. """ % (ipythondir,sys.exc_info()[1])
1209 wait()
1208 wait()
1210 else:
1209 else:
1211 for fname in glb('ipythonrc*'):
1210 for fname in glb('ipythonrc*'):
1212 try:
1211 try:
1213 native_line_ends(fname,backup=0)
1212 native_line_ends(fname,backup=0)
1214 except IOError:
1213 except IOError:
1215 pass
1214 pass
1216
1215
1217 if mode == 'install':
1216 if mode == 'install':
1218 print """
1217 print """
1219 Successful installation!
1218 Successful installation!
1220
1219
1221 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1220 Please read the sections 'Initial Configuration' and 'Quick Tips' in the
1222 IPython manual (there are both HTML and PDF versions supplied with the
1221 IPython manual (there are both HTML and PDF versions supplied with the
1223 distribution) to make sure that your system environment is properly configured
1222 distribution) to make sure that your system environment is properly configured
1224 to take advantage of IPython's features.
1223 to take advantage of IPython's features.
1225
1224
1226 Important note: the configuration system has changed! The old system is
1225 Important note: the configuration system has changed! The old system is
1227 still in place, but its setting may be partly overridden by the settings in
1226 still in place, but its setting may be partly overridden by the settings in
1228 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1227 "~/.ipython/ipy_user_conf.py" config file. Please take a look at the file
1229 if some of the new settings bother you.
1228 if some of the new settings bother you.
1230
1229
1231 """
1230 """
1232 else:
1231 else:
1233 print """
1232 print """
1234 Successful upgrade!
1233 Successful upgrade!
1235
1234
1236 All files in your directory:
1235 All files in your directory:
1237 %(ipythondir)s
1236 %(ipythondir)s
1238 which would have been overwritten by the upgrade were backed up with a .old
1237 which would have been overwritten by the upgrade were backed up with a .old
1239 extension. If you had made particular customizations in those files you may
1238 extension. If you had made particular customizations in those files you may
1240 want to merge them back into the new files.""" % locals()
1239 want to merge them back into the new files.""" % locals()
1241 wait()
1240 wait()
1242 os.chdir(cwd)
1241 os.chdir(cwd)
1243 # end user_setup()
1242 # end user_setup()
1244
1243
1245 def atexit_operations(self):
1244 def atexit_operations(self):
1246 """This will be executed at the time of exit.
1245 """This will be executed at the time of exit.
1247
1246
1248 Saving of persistent data should be performed here. """
1247 Saving of persistent data should be performed here. """
1249
1248
1250 #print '*** IPython exit cleanup ***' # dbg
1249 #print '*** IPython exit cleanup ***' # dbg
1251 # input history
1250 # input history
1252 self.savehist()
1251 self.savehist()
1253
1252
1254 # Cleanup all tempfiles left around
1253 # Cleanup all tempfiles left around
1255 for tfile in self.tempfiles:
1254 for tfile in self.tempfiles:
1256 try:
1255 try:
1257 os.unlink(tfile)
1256 os.unlink(tfile)
1258 except OSError:
1257 except OSError:
1259 pass
1258 pass
1260
1259
1261 self.hooks.shutdown_hook()
1260 self.hooks.shutdown_hook()
1262
1261
1263 def savehist(self):
1262 def savehist(self):
1264 """Save input history to a file (via readline library)."""
1263 """Save input history to a file (via readline library)."""
1265
1264
1266 if not self.has_readline:
1265 if not self.has_readline:
1267 return
1266 return
1268
1267
1269 try:
1268 try:
1270 self.readline.write_history_file(self.histfile)
1269 self.readline.write_history_file(self.histfile)
1271 except:
1270 except:
1272 print 'Unable to save IPython command history to file: ' + \
1271 print 'Unable to save IPython command history to file: ' + \
1273 `self.histfile`
1272 `self.histfile`
1274
1273
1275 def reloadhist(self):
1274 def reloadhist(self):
1276 """Reload the input history from disk file."""
1275 """Reload the input history from disk file."""
1277
1276
1278 if self.has_readline:
1277 if self.has_readline:
1279 try:
1278 try:
1280 self.readline.clear_history()
1279 self.readline.clear_history()
1281 self.readline.read_history_file(self.shell.histfile)
1280 self.readline.read_history_file(self.shell.histfile)
1282 except AttributeError:
1281 except AttributeError:
1283 pass
1282 pass
1284
1283
1285
1284
1286 def history_saving_wrapper(self, func):
1285 def history_saving_wrapper(self, func):
1287 """ Wrap func for readline history saving
1286 """ Wrap func for readline history saving
1288
1287
1289 Convert func into callable that saves & restores
1288 Convert func into callable that saves & restores
1290 history around the call """
1289 history around the call """
1291
1290
1292 if not self.has_readline:
1291 if not self.has_readline:
1293 return func
1292 return func
1294
1293
1295 def wrapper():
1294 def wrapper():
1296 self.savehist()
1295 self.savehist()
1297 try:
1296 try:
1298 func()
1297 func()
1299 finally:
1298 finally:
1300 readline.read_history_file(self.histfile)
1299 readline.read_history_file(self.histfile)
1301 return wrapper
1300 return wrapper
1302
1301
1303
1302
1304 def pre_readline(self):
1303 def pre_readline(self):
1305 """readline hook to be used at the start of each line.
1304 """readline hook to be used at the start of each line.
1306
1305
1307 Currently it handles auto-indent only."""
1306 Currently it handles auto-indent only."""
1308
1307
1309 #debugx('self.indent_current_nsp','pre_readline:')
1308 #debugx('self.indent_current_nsp','pre_readline:')
1310
1309
1311 if self.rl_do_indent:
1310 if self.rl_do_indent:
1312 self.readline.insert_text(self.indent_current_str())
1311 self.readline.insert_text(self.indent_current_str())
1313 if self.rl_next_input is not None:
1312 if self.rl_next_input is not None:
1314 self.readline.insert_text(self.rl_next_input)
1313 self.readline.insert_text(self.rl_next_input)
1315 self.rl_next_input = None
1314 self.rl_next_input = None
1316
1315
1317 def init_readline(self):
1316 def init_readline(self):
1318 """Command history completion/saving/reloading."""
1317 """Command history completion/saving/reloading."""
1319
1318
1320
1319
1321 import IPython.rlineimpl as readline
1320 import IPython.rlineimpl as readline
1322
1321
1323 if not readline.have_readline:
1322 if not readline.have_readline:
1324 self.has_readline = 0
1323 self.has_readline = 0
1325 self.readline = None
1324 self.readline = None
1326 # no point in bugging windows users with this every time:
1325 # no point in bugging windows users with this every time:
1327 warn('Readline services not available on this platform.')
1326 warn('Readline services not available on this platform.')
1328 else:
1327 else:
1329 sys.modules['readline'] = readline
1328 sys.modules['readline'] = readline
1330 import atexit
1329 import atexit
1331 from IPython.completer import IPCompleter
1330 from IPython.completer import IPCompleter
1332 self.Completer = IPCompleter(self,
1331 self.Completer = IPCompleter(self,
1333 self.user_ns,
1332 self.user_ns,
1334 self.user_global_ns,
1333 self.user_global_ns,
1335 self.rc.readline_omit__names,
1334 self.rc.readline_omit__names,
1336 self.alias_table)
1335 self.alias_table)
1337 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1336 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1338 self.strdispatchers['complete_command'] = sdisp
1337 self.strdispatchers['complete_command'] = sdisp
1339 self.Completer.custom_completers = sdisp
1338 self.Completer.custom_completers = sdisp
1340 # Platform-specific configuration
1339 # Platform-specific configuration
1341 if os.name == 'nt':
1340 if os.name == 'nt':
1342 self.readline_startup_hook = readline.set_pre_input_hook
1341 self.readline_startup_hook = readline.set_pre_input_hook
1343 else:
1342 else:
1344 self.readline_startup_hook = readline.set_startup_hook
1343 self.readline_startup_hook = readline.set_startup_hook
1345
1344
1346 # Load user's initrc file (readline config)
1345 # Load user's initrc file (readline config)
1347 # Or if libedit is used, load editrc.
1346 # Or if libedit is used, load editrc.
1348 inputrc_name = os.environ.get('INPUTRC')
1347 inputrc_name = os.environ.get('INPUTRC')
1349 if inputrc_name is None:
1348 if inputrc_name is None:
1350 home_dir = get_home_dir()
1349 home_dir = get_home_dir()
1351 if home_dir is not None:
1350 if home_dir is not None:
1352 inputrc_name = '.inputrc'
1351 inputrc_name = '.inputrc'
1353 if readline.uses_libedit:
1352 if readline.uses_libedit:
1354 inputrc_name = '.editrc'
1353 inputrc_name = '.editrc'
1355 inputrc_name = os.path.join(home_dir, inputrc_name)
1354 inputrc_name = os.path.join(home_dir, inputrc_name)
1356 if os.path.isfile(inputrc_name):
1355 if os.path.isfile(inputrc_name):
1357 try:
1356 try:
1358 readline.read_init_file(inputrc_name)
1357 readline.read_init_file(inputrc_name)
1359 except:
1358 except:
1360 warn('Problems reading readline initialization file <%s>'
1359 warn('Problems reading readline initialization file <%s>'
1361 % inputrc_name)
1360 % inputrc_name)
1362
1361
1363 self.has_readline = 1
1362 self.has_readline = 1
1364 self.readline = readline
1363 self.readline = readline
1365 # save this in sys so embedded copies can restore it properly
1364 # save this in sys so embedded copies can restore it properly
1366 sys.ipcompleter = self.Completer.complete
1365 sys.ipcompleter = self.Completer.complete
1367 self.set_completer()
1366 self.set_completer()
1368
1367
1369 # Configure readline according to user's prefs
1368 # Configure readline according to user's prefs
1370 # This is only done if GNU readline is being used. If libedit
1369 # This is only done if GNU readline is being used. If libedit
1371 # is being used (as on Leopard) the readline config is
1370 # is being used (as on Leopard) the readline config is
1372 # not run as the syntax for libedit is different.
1371 # not run as the syntax for libedit is different.
1373 if not readline.uses_libedit:
1372 if not readline.uses_libedit:
1374 for rlcommand in self.rc.readline_parse_and_bind:
1373 for rlcommand in self.rc.readline_parse_and_bind:
1375 readline.parse_and_bind(rlcommand)
1374 readline.parse_and_bind(rlcommand)
1376
1375
1377 # remove some chars from the delimiters list
1376 # remove some chars from the delimiters list
1378 delims = readline.get_completer_delims()
1377 delims = readline.get_completer_delims()
1379 delims = delims.translate(string._idmap,
1378 delims = delims.translate(string._idmap,
1380 self.rc.readline_remove_delims)
1379 self.rc.readline_remove_delims)
1381 readline.set_completer_delims(delims)
1380 readline.set_completer_delims(delims)
1382 # otherwise we end up with a monster history after a while:
1381 # otherwise we end up with a monster history after a while:
1383 readline.set_history_length(1000)
1382 readline.set_history_length(1000)
1384 try:
1383 try:
1385 #print '*** Reading readline history' # dbg
1384 #print '*** Reading readline history' # dbg
1386 readline.read_history_file(self.histfile)
1385 readline.read_history_file(self.histfile)
1387 except IOError:
1386 except IOError:
1388 pass # It doesn't exist yet.
1387 pass # It doesn't exist yet.
1389
1388
1390 atexit.register(self.atexit_operations)
1389 atexit.register(self.atexit_operations)
1391 del atexit
1390 del atexit
1392
1391
1393 # Configure auto-indent for all platforms
1392 # Configure auto-indent for all platforms
1394 self.set_autoindent(self.rc.autoindent)
1393 self.set_autoindent(self.rc.autoindent)
1395
1394
1396 def ask_yes_no(self,prompt,default=True):
1395 def ask_yes_no(self,prompt,default=True):
1397 if self.rc.quiet:
1396 if self.rc.quiet:
1398 return True
1397 return True
1399 return ask_yes_no(prompt,default)
1398 return ask_yes_no(prompt,default)
1400
1399
1401 def _should_recompile(self,e):
1400 def _should_recompile(self,e):
1402 """Utility routine for edit_syntax_error"""
1401 """Utility routine for edit_syntax_error"""
1403
1402
1404 if e.filename in ('<ipython console>','<input>','<string>',
1403 if e.filename in ('<ipython console>','<input>','<string>',
1405 '<console>','<BackgroundJob compilation>',
1404 '<console>','<BackgroundJob compilation>',
1406 None):
1405 None):
1407
1406
1408 return False
1407 return False
1409 try:
1408 try:
1410 if (self.rc.autoedit_syntax and
1409 if (self.rc.autoedit_syntax and
1411 not self.ask_yes_no('Return to editor to correct syntax error? '
1410 not self.ask_yes_no('Return to editor to correct syntax error? '
1412 '[Y/n] ','y')):
1411 '[Y/n] ','y')):
1413 return False
1412 return False
1414 except EOFError:
1413 except EOFError:
1415 return False
1414 return False
1416
1415
1417 def int0(x):
1416 def int0(x):
1418 try:
1417 try:
1419 return int(x)
1418 return int(x)
1420 except TypeError:
1419 except TypeError:
1421 return 0
1420 return 0
1422 # always pass integer line and offset values to editor hook
1421 # always pass integer line and offset values to editor hook
1423 self.hooks.fix_error_editor(e.filename,
1422 self.hooks.fix_error_editor(e.filename,
1424 int0(e.lineno),int0(e.offset),e.msg)
1423 int0(e.lineno),int0(e.offset),e.msg)
1425 return True
1424 return True
1426
1425
1427 def edit_syntax_error(self):
1426 def edit_syntax_error(self):
1428 """The bottom half of the syntax error handler called in the main loop.
1427 """The bottom half of the syntax error handler called in the main loop.
1429
1428
1430 Loop until syntax error is fixed or user cancels.
1429 Loop until syntax error is fixed or user cancels.
1431 """
1430 """
1432
1431
1433 while self.SyntaxTB.last_syntax_error:
1432 while self.SyntaxTB.last_syntax_error:
1434 # copy and clear last_syntax_error
1433 # copy and clear last_syntax_error
1435 err = self.SyntaxTB.clear_err_state()
1434 err = self.SyntaxTB.clear_err_state()
1436 if not self._should_recompile(err):
1435 if not self._should_recompile(err):
1437 return
1436 return
1438 try:
1437 try:
1439 # may set last_syntax_error again if a SyntaxError is raised
1438 # may set last_syntax_error again if a SyntaxError is raised
1440 self.safe_execfile(err.filename,self.user_ns)
1439 self.safe_execfile(err.filename,self.user_ns)
1441 except:
1440 except:
1442 self.showtraceback()
1441 self.showtraceback()
1443 else:
1442 else:
1444 try:
1443 try:
1445 f = file(err.filename)
1444 f = file(err.filename)
1446 try:
1445 try:
1447 sys.displayhook(f.read())
1446 sys.displayhook(f.read())
1448 finally:
1447 finally:
1449 f.close()
1448 f.close()
1450 except:
1449 except:
1451 self.showtraceback()
1450 self.showtraceback()
1452
1451
1453 def showsyntaxerror(self, filename=None):
1452 def showsyntaxerror(self, filename=None):
1454 """Display the syntax error that just occurred.
1453 """Display the syntax error that just occurred.
1455
1454
1456 This doesn't display a stack trace because there isn't one.
1455 This doesn't display a stack trace because there isn't one.
1457
1456
1458 If a filename is given, it is stuffed in the exception instead
1457 If a filename is given, it is stuffed in the exception instead
1459 of what was there before (because Python's parser always uses
1458 of what was there before (because Python's parser always uses
1460 "<string>" when reading from a string).
1459 "<string>" when reading from a string).
1461 """
1460 """
1462 etype, value, last_traceback = sys.exc_info()
1461 etype, value, last_traceback = sys.exc_info()
1463
1462
1464 # See note about these variables in showtraceback() below
1463 # See note about these variables in showtraceback() below
1465 sys.last_type = etype
1464 sys.last_type = etype
1466 sys.last_value = value
1465 sys.last_value = value
1467 sys.last_traceback = last_traceback
1466 sys.last_traceback = last_traceback
1468
1467
1469 if filename and etype is SyntaxError:
1468 if filename and etype is SyntaxError:
1470 # Work hard to stuff the correct filename in the exception
1469 # Work hard to stuff the correct filename in the exception
1471 try:
1470 try:
1472 msg, (dummy_filename, lineno, offset, line) = value
1471 msg, (dummy_filename, lineno, offset, line) = value
1473 except:
1472 except:
1474 # Not the format we expect; leave it alone
1473 # Not the format we expect; leave it alone
1475 pass
1474 pass
1476 else:
1475 else:
1477 # Stuff in the right filename
1476 # Stuff in the right filename
1478 try:
1477 try:
1479 # Assume SyntaxError is a class exception
1478 # Assume SyntaxError is a class exception
1480 value = SyntaxError(msg, (filename, lineno, offset, line))
1479 value = SyntaxError(msg, (filename, lineno, offset, line))
1481 except:
1480 except:
1482 # If that failed, assume SyntaxError is a string
1481 # If that failed, assume SyntaxError is a string
1483 value = msg, (filename, lineno, offset, line)
1482 value = msg, (filename, lineno, offset, line)
1484 self.SyntaxTB(etype,value,[])
1483 self.SyntaxTB(etype,value,[])
1485
1484
1486 def debugger(self,force=False):
1485 def debugger(self,force=False):
1487 """Call the pydb/pdb debugger.
1486 """Call the pydb/pdb debugger.
1488
1487
1489 Keywords:
1488 Keywords:
1490
1489
1491 - force(False): by default, this routine checks the instance call_pdb
1490 - force(False): by default, this routine checks the instance call_pdb
1492 flag and does not actually invoke the debugger if the flag is false.
1491 flag and does not actually invoke the debugger if the flag is false.
1493 The 'force' option forces the debugger to activate even if the flag
1492 The 'force' option forces the debugger to activate even if the flag
1494 is false.
1493 is false.
1495 """
1494 """
1496
1495
1497 if not (force or self.call_pdb):
1496 if not (force or self.call_pdb):
1498 return
1497 return
1499
1498
1500 if not hasattr(sys,'last_traceback'):
1499 if not hasattr(sys,'last_traceback'):
1501 error('No traceback has been produced, nothing to debug.')
1500 error('No traceback has been produced, nothing to debug.')
1502 return
1501 return
1503
1502
1504 # use pydb if available
1503 # use pydb if available
1505 if Debugger.has_pydb:
1504 if Debugger.has_pydb:
1506 from pydb import pm
1505 from pydb import pm
1507 else:
1506 else:
1508 # fallback to our internal debugger
1507 # fallback to our internal debugger
1509 pm = lambda : self.InteractiveTB.debugger(force=True)
1508 pm = lambda : self.InteractiveTB.debugger(force=True)
1510 self.history_saving_wrapper(pm)()
1509 self.history_saving_wrapper(pm)()
1511
1510
1512 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1511 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1513 """Display the exception that just occurred.
1512 """Display the exception that just occurred.
1514
1513
1515 If nothing is known about the exception, this is the method which
1514 If nothing is known about the exception, this is the method which
1516 should be used throughout the code for presenting user tracebacks,
1515 should be used throughout the code for presenting user tracebacks,
1517 rather than directly invoking the InteractiveTB object.
1516 rather than directly invoking the InteractiveTB object.
1518
1517
1519 A specific showsyntaxerror() also exists, but this method can take
1518 A specific showsyntaxerror() also exists, but this method can take
1520 care of calling it if needed, so unless you are explicitly catching a
1519 care of calling it if needed, so unless you are explicitly catching a
1521 SyntaxError exception, don't try to analyze the stack manually and
1520 SyntaxError exception, don't try to analyze the stack manually and
1522 simply call this method."""
1521 simply call this method."""
1523
1522
1524
1523
1525 # Though this won't be called by syntax errors in the input line,
1524 # Though this won't be called by syntax errors in the input line,
1526 # there may be SyntaxError cases whith imported code.
1525 # there may be SyntaxError cases whith imported code.
1527
1526
1528 try:
1527 try:
1529 if exc_tuple is None:
1528 if exc_tuple is None:
1530 etype, value, tb = sys.exc_info()
1529 etype, value, tb = sys.exc_info()
1531 else:
1530 else:
1532 etype, value, tb = exc_tuple
1531 etype, value, tb = exc_tuple
1533
1532
1534 if etype is SyntaxError:
1533 if etype is SyntaxError:
1535 self.showsyntaxerror(filename)
1534 self.showsyntaxerror(filename)
1536 elif etype is IPython.ipapi.UsageError:
1535 elif etype is IPython.ipapi.UsageError:
1537 print "UsageError:", value
1536 print "UsageError:", value
1538 else:
1537 else:
1539 # WARNING: these variables are somewhat deprecated and not
1538 # WARNING: these variables are somewhat deprecated and not
1540 # necessarily safe to use in a threaded environment, but tools
1539 # necessarily safe to use in a threaded environment, but tools
1541 # like pdb depend on their existence, so let's set them. If we
1540 # like pdb depend on their existence, so let's set them. If we
1542 # find problems in the field, we'll need to revisit their use.
1541 # find problems in the field, we'll need to revisit their use.
1543 sys.last_type = etype
1542 sys.last_type = etype
1544 sys.last_value = value
1543 sys.last_value = value
1545 sys.last_traceback = tb
1544 sys.last_traceback = tb
1546
1545
1547 if etype in self.custom_exceptions:
1546 if etype in self.custom_exceptions:
1548 self.CustomTB(etype,value,tb)
1547 self.CustomTB(etype,value,tb)
1549 else:
1548 else:
1550 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1549 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1551 if self.InteractiveTB.call_pdb and self.has_readline:
1550 if self.InteractiveTB.call_pdb and self.has_readline:
1552 # pdb mucks up readline, fix it back
1551 # pdb mucks up readline, fix it back
1553 self.set_completer()
1552 self.set_completer()
1554 except KeyboardInterrupt:
1553 except KeyboardInterrupt:
1555 self.write("\nKeyboardInterrupt\n")
1554 self.write("\nKeyboardInterrupt\n")
1556
1555
1557
1556
1558
1557
1559 def mainloop(self,banner=None):
1558 def mainloop(self,banner=None):
1560 """Creates the local namespace and starts the mainloop.
1559 """Creates the local namespace and starts the mainloop.
1561
1560
1562 If an optional banner argument is given, it will override the
1561 If an optional banner argument is given, it will override the
1563 internally created default banner."""
1562 internally created default banner."""
1564
1563
1565 if self.rc.c: # Emulate Python's -c option
1564 if self.rc.c: # Emulate Python's -c option
1566 self.exec_init_cmd()
1565 self.exec_init_cmd()
1567 if banner is None:
1566 if banner is None:
1568 if not self.rc.banner:
1567 if not self.rc.banner:
1569 banner = ''
1568 banner = ''
1570 # banner is string? Use it directly!
1569 # banner is string? Use it directly!
1571 elif isinstance(self.rc.banner,basestring):
1570 elif isinstance(self.rc.banner,basestring):
1572 banner = self.rc.banner
1571 banner = self.rc.banner
1573 else:
1572 else:
1574 banner = self.BANNER+self.banner2
1573 banner = self.BANNER+self.banner2
1575
1574
1576 while 1:
1575 while 1:
1577 try:
1576 try:
1578 self.interact(banner)
1577 self.interact(banner)
1579 #self.interact_with_readline()
1578 #self.interact_with_readline()
1580 # XXX for testing of a readline-decoupled repl loop, call interact_with_readline above
1579 # XXX for testing of a readline-decoupled repl loop, call interact_with_readline above
1581
1580
1582 break
1581 break
1583 except KeyboardInterrupt:
1582 except KeyboardInterrupt:
1584 # this should not be necessary, but KeyboardInterrupt
1583 # this should not be necessary, but KeyboardInterrupt
1585 # handling seems rather unpredictable...
1584 # handling seems rather unpredictable...
1586 self.write("\nKeyboardInterrupt in interact()\n")
1585 self.write("\nKeyboardInterrupt in interact()\n")
1587
1586
1588 def exec_init_cmd(self):
1587 def exec_init_cmd(self):
1589 """Execute a command given at the command line.
1588 """Execute a command given at the command line.
1590
1589
1591 This emulates Python's -c option."""
1590 This emulates Python's -c option."""
1592
1591
1593 #sys.argv = ['-c']
1592 #sys.argv = ['-c']
1594 self.push(self.prefilter(self.rc.c, False))
1593 self.push(self.prefilter(self.rc.c, False))
1595 if not self.rc.interact:
1594 if not self.rc.interact:
1596 self.ask_exit()
1595 self.ask_exit()
1597
1596
1598 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1597 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1599 """Embeds IPython into a running python program.
1598 """Embeds IPython into a running python program.
1600
1599
1601 Input:
1600 Input:
1602
1601
1603 - header: An optional header message can be specified.
1602 - header: An optional header message can be specified.
1604
1603
1605 - local_ns, global_ns: working namespaces. If given as None, the
1604 - local_ns, global_ns: working namespaces. If given as None, the
1606 IPython-initialized one is updated with __main__.__dict__, so that
1605 IPython-initialized one is updated with __main__.__dict__, so that
1607 program variables become visible but user-specific configuration
1606 program variables become visible but user-specific configuration
1608 remains possible.
1607 remains possible.
1609
1608
1610 - stack_depth: specifies how many levels in the stack to go to
1609 - stack_depth: specifies how many levels in the stack to go to
1611 looking for namespaces (when local_ns and global_ns are None). This
1610 looking for namespaces (when local_ns and global_ns are None). This
1612 allows an intermediate caller to make sure that this function gets
1611 allows an intermediate caller to make sure that this function gets
1613 the namespace from the intended level in the stack. By default (0)
1612 the namespace from the intended level in the stack. By default (0)
1614 it will get its locals and globals from the immediate caller.
1613 it will get its locals and globals from the immediate caller.
1615
1614
1616 Warning: it's possible to use this in a program which is being run by
1615 Warning: it's possible to use this in a program which is being run by
1617 IPython itself (via %run), but some funny things will happen (a few
1616 IPython itself (via %run), but some funny things will happen (a few
1618 globals get overwritten). In the future this will be cleaned up, as
1617 globals get overwritten). In the future this will be cleaned up, as
1619 there is no fundamental reason why it can't work perfectly."""
1618 there is no fundamental reason why it can't work perfectly."""
1620
1619
1621 # Get locals and globals from caller
1620 # Get locals and globals from caller
1622 if local_ns is None or global_ns is None:
1621 if local_ns is None or global_ns is None:
1623 call_frame = sys._getframe(stack_depth).f_back
1622 call_frame = sys._getframe(stack_depth).f_back
1624
1623
1625 if local_ns is None:
1624 if local_ns is None:
1626 local_ns = call_frame.f_locals
1625 local_ns = call_frame.f_locals
1627 if global_ns is None:
1626 if global_ns is None:
1628 global_ns = call_frame.f_globals
1627 global_ns = call_frame.f_globals
1629
1628
1630 # Update namespaces and fire up interpreter
1629 # Update namespaces and fire up interpreter
1631
1630
1632 # The global one is easy, we can just throw it in
1631 # The global one is easy, we can just throw it in
1633 self.user_global_ns = global_ns
1632 self.user_global_ns = global_ns
1634
1633
1635 # but the user/local one is tricky: ipython needs it to store internal
1634 # but the user/local one is tricky: ipython needs it to store internal
1636 # data, but we also need the locals. We'll copy locals in the user
1635 # data, but we also need the locals. We'll copy locals in the user
1637 # one, but will track what got copied so we can delete them at exit.
1636 # one, but will track what got copied so we can delete them at exit.
1638 # This is so that a later embedded call doesn't see locals from a
1637 # This is so that a later embedded call doesn't see locals from a
1639 # previous call (which most likely existed in a separate scope).
1638 # previous call (which most likely existed in a separate scope).
1640 local_varnames = local_ns.keys()
1639 local_varnames = local_ns.keys()
1641 self.user_ns.update(local_ns)
1640 self.user_ns.update(local_ns)
1642 #self.user_ns['local_ns'] = local_ns # dbg
1641 #self.user_ns['local_ns'] = local_ns # dbg
1643
1642
1644 # Patch for global embedding to make sure that things don't overwrite
1643 # Patch for global embedding to make sure that things don't overwrite
1645 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1644 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1646 # FIXME. Test this a bit more carefully (the if.. is new)
1645 # FIXME. Test this a bit more carefully (the if.. is new)
1647 if local_ns is None and global_ns is None:
1646 if local_ns is None and global_ns is None:
1648 self.user_global_ns.update(__main__.__dict__)
1647 self.user_global_ns.update(__main__.__dict__)
1649
1648
1650 # make sure the tab-completer has the correct frame information, so it
1649 # make sure the tab-completer has the correct frame information, so it
1651 # actually completes using the frame's locals/globals
1650 # actually completes using the frame's locals/globals
1652 self.set_completer_frame()
1651 self.set_completer_frame()
1653
1652
1654 # before activating the interactive mode, we need to make sure that
1653 # before activating the interactive mode, we need to make sure that
1655 # all names in the builtin namespace needed by ipython point to
1654 # all names in the builtin namespace needed by ipython point to
1656 # ourselves, and not to other instances.
1655 # ourselves, and not to other instances.
1657 self.add_builtins()
1656 self.add_builtins()
1658
1657
1659 self.interact(header)
1658 self.interact(header)
1660
1659
1661 # now, purge out the user namespace from anything we might have added
1660 # now, purge out the user namespace from anything we might have added
1662 # from the caller's local namespace
1661 # from the caller's local namespace
1663 delvar = self.user_ns.pop
1662 delvar = self.user_ns.pop
1664 for var in local_varnames:
1663 for var in local_varnames:
1665 delvar(var,None)
1664 delvar(var,None)
1666 # and clean builtins we may have overridden
1665 # and clean builtins we may have overridden
1667 self.clean_builtins()
1666 self.clean_builtins()
1668
1667
1669 def interact_prompt(self):
1668 def interact_prompt(self):
1670 """ Print the prompt (in read-eval-print loop)
1669 """ Print the prompt (in read-eval-print loop)
1671
1670
1672 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1671 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1673 used in standard IPython flow.
1672 used in standard IPython flow.
1674 """
1673 """
1675 if self.more:
1674 if self.more:
1676 try:
1675 try:
1677 prompt = self.hooks.generate_prompt(True)
1676 prompt = self.hooks.generate_prompt(True)
1678 except:
1677 except:
1679 self.showtraceback()
1678 self.showtraceback()
1680 if self.autoindent:
1679 if self.autoindent:
1681 self.rl_do_indent = True
1680 self.rl_do_indent = True
1682
1681
1683 else:
1682 else:
1684 try:
1683 try:
1685 prompt = self.hooks.generate_prompt(False)
1684 prompt = self.hooks.generate_prompt(False)
1686 except:
1685 except:
1687 self.showtraceback()
1686 self.showtraceback()
1688 self.write(prompt)
1687 self.write(prompt)
1689
1688
1690 def interact_handle_input(self,line):
1689 def interact_handle_input(self,line):
1691 """ Handle the input line (in read-eval-print loop)
1690 """ Handle the input line (in read-eval-print loop)
1692
1691
1693 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1692 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1694 used in standard IPython flow.
1693 used in standard IPython flow.
1695 """
1694 """
1696 if line.lstrip() == line:
1695 if line.lstrip() == line:
1697 self.shadowhist.add(line.strip())
1696 self.shadowhist.add(line.strip())
1698 lineout = self.prefilter(line,self.more)
1697 lineout = self.prefilter(line,self.more)
1699
1698
1700 if line.strip():
1699 if line.strip():
1701 if self.more:
1700 if self.more:
1702 self.input_hist_raw[-1] += '%s\n' % line
1701 self.input_hist_raw[-1] += '%s\n' % line
1703 else:
1702 else:
1704 self.input_hist_raw.append('%s\n' % line)
1703 self.input_hist_raw.append('%s\n' % line)
1705
1704
1706
1705
1707 self.more = self.push(lineout)
1706 self.more = self.push(lineout)
1708 if (self.SyntaxTB.last_syntax_error and
1707 if (self.SyntaxTB.last_syntax_error and
1709 self.rc.autoedit_syntax):
1708 self.rc.autoedit_syntax):
1710 self.edit_syntax_error()
1709 self.edit_syntax_error()
1711
1710
1712 def interact_with_readline(self):
1711 def interact_with_readline(self):
1713 """ Demo of using interact_handle_input, interact_prompt
1712 """ Demo of using interact_handle_input, interact_prompt
1714
1713
1715 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1714 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1716 it should work like this.
1715 it should work like this.
1717 """
1716 """
1718 self.readline_startup_hook(self.pre_readline)
1717 self.readline_startup_hook(self.pre_readline)
1719 while not self.exit_now:
1718 while not self.exit_now:
1720 self.interact_prompt()
1719 self.interact_prompt()
1721 if self.more:
1720 if self.more:
1722 self.rl_do_indent = True
1721 self.rl_do_indent = True
1723 else:
1722 else:
1724 self.rl_do_indent = False
1723 self.rl_do_indent = False
1725 line = raw_input_original().decode(self.stdin_encoding)
1724 line = raw_input_original().decode(self.stdin_encoding)
1726 self.interact_handle_input(line)
1725 self.interact_handle_input(line)
1727
1726
1728
1727
1729 def interact(self, banner=None):
1728 def interact(self, banner=None):
1730 """Closely emulate the interactive Python console.
1729 """Closely emulate the interactive Python console.
1731
1730
1732 The optional banner argument specify the banner to print
1731 The optional banner argument specify the banner to print
1733 before the first interaction; by default it prints a banner
1732 before the first interaction; by default it prints a banner
1734 similar to the one printed by the real Python interpreter,
1733 similar to the one printed by the real Python interpreter,
1735 followed by the current class name in parentheses (so as not
1734 followed by the current class name in parentheses (so as not
1736 to confuse this with the real interpreter -- since it's so
1735 to confuse this with the real interpreter -- since it's so
1737 close!).
1736 close!).
1738
1737
1739 """
1738 """
1740
1739
1741 if self.exit_now:
1740 if self.exit_now:
1742 # batch run -> do not interact
1741 # batch run -> do not interact
1743 return
1742 return
1744 cprt = 'Type "copyright", "credits" or "license" for more information.'
1743 cprt = 'Type "copyright", "credits" or "license" for more information.'
1745 if banner is None:
1744 if banner is None:
1746 self.write("Python %s on %s\n%s\n(%s)\n" %
1745 self.write("Python %s on %s\n%s\n(%s)\n" %
1747 (sys.version, sys.platform, cprt,
1746 (sys.version, sys.platform, cprt,
1748 self.__class__.__name__))
1747 self.__class__.__name__))
1749 else:
1748 else:
1750 self.write(banner)
1749 self.write(banner)
1751
1750
1752 more = 0
1751 more = 0
1753
1752
1754 # Mark activity in the builtins
1753 # Mark activity in the builtins
1755 __builtin__.__dict__['__IPYTHON__active'] += 1
1754 __builtin__.__dict__['__IPYTHON__active'] += 1
1756
1755
1757 if self.has_readline:
1756 if self.has_readline:
1758 self.readline_startup_hook(self.pre_readline)
1757 self.readline_startup_hook(self.pre_readline)
1759 # exit_now is set by a call to %Exit or %Quit, through the
1758 # exit_now is set by a call to %Exit or %Quit, through the
1760 # ask_exit callback.
1759 # ask_exit callback.
1761
1760
1762 while not self.exit_now:
1761 while not self.exit_now:
1763 self.hooks.pre_prompt_hook()
1762 self.hooks.pre_prompt_hook()
1764 if more:
1763 if more:
1765 try:
1764 try:
1766 prompt = self.hooks.generate_prompt(True)
1765 prompt = self.hooks.generate_prompt(True)
1767 except:
1766 except:
1768 self.showtraceback()
1767 self.showtraceback()
1769 if self.autoindent:
1768 if self.autoindent:
1770 self.rl_do_indent = True
1769 self.rl_do_indent = True
1771
1770
1772 else:
1771 else:
1773 try:
1772 try:
1774 prompt = self.hooks.generate_prompt(False)
1773 prompt = self.hooks.generate_prompt(False)
1775 except:
1774 except:
1776 self.showtraceback()
1775 self.showtraceback()
1777 try:
1776 try:
1778 line = self.raw_input(prompt,more)
1777 line = self.raw_input(prompt,more)
1779 if self.exit_now:
1778 if self.exit_now:
1780 # quick exit on sys.std[in|out] close
1779 # quick exit on sys.std[in|out] close
1781 break
1780 break
1782 if self.autoindent:
1781 if self.autoindent:
1783 self.rl_do_indent = False
1782 self.rl_do_indent = False
1784
1783
1785 except KeyboardInterrupt:
1784 except KeyboardInterrupt:
1786 #double-guard against keyboardinterrupts during kbdint handling
1785 #double-guard against keyboardinterrupts during kbdint handling
1787 try:
1786 try:
1788 self.write('\nKeyboardInterrupt\n')
1787 self.write('\nKeyboardInterrupt\n')
1789 self.resetbuffer()
1788 self.resetbuffer()
1790 # keep cache in sync with the prompt counter:
1789 # keep cache in sync with the prompt counter:
1791 self.outputcache.prompt_count -= 1
1790 self.outputcache.prompt_count -= 1
1792
1791
1793 if self.autoindent:
1792 if self.autoindent:
1794 self.indent_current_nsp = 0
1793 self.indent_current_nsp = 0
1795 more = 0
1794 more = 0
1796 except KeyboardInterrupt:
1795 except KeyboardInterrupt:
1797 pass
1796 pass
1798 except EOFError:
1797 except EOFError:
1799 if self.autoindent:
1798 if self.autoindent:
1800 self.rl_do_indent = False
1799 self.rl_do_indent = False
1801 self.readline_startup_hook(None)
1800 self.readline_startup_hook(None)
1802 self.write('\n')
1801 self.write('\n')
1803 self.exit()
1802 self.exit()
1804 except bdb.BdbQuit:
1803 except bdb.BdbQuit:
1805 warn('The Python debugger has exited with a BdbQuit exception.\n'
1804 warn('The Python debugger has exited with a BdbQuit exception.\n'
1806 'Because of how pdb handles the stack, it is impossible\n'
1805 'Because of how pdb handles the stack, it is impossible\n'
1807 'for IPython to properly format this particular exception.\n'
1806 'for IPython to properly format this particular exception.\n'
1808 'IPython will resume normal operation.')
1807 'IPython will resume normal operation.')
1809 except:
1808 except:
1810 # exceptions here are VERY RARE, but they can be triggered
1809 # exceptions here are VERY RARE, but they can be triggered
1811 # asynchronously by signal handlers, for example.
1810 # asynchronously by signal handlers, for example.
1812 self.showtraceback()
1811 self.showtraceback()
1813 else:
1812 else:
1814 more = self.push(line)
1813 more = self.push(line)
1815 if (self.SyntaxTB.last_syntax_error and
1814 if (self.SyntaxTB.last_syntax_error and
1816 self.rc.autoedit_syntax):
1815 self.rc.autoedit_syntax):
1817 self.edit_syntax_error()
1816 self.edit_syntax_error()
1818
1817
1819 # We are off again...
1818 # We are off again...
1820 __builtin__.__dict__['__IPYTHON__active'] -= 1
1819 __builtin__.__dict__['__IPYTHON__active'] -= 1
1821
1820
1822 def excepthook(self, etype, value, tb):
1821 def excepthook(self, etype, value, tb):
1823 """One more defense for GUI apps that call sys.excepthook.
1822 """One more defense for GUI apps that call sys.excepthook.
1824
1823
1825 GUI frameworks like wxPython trap exceptions and call
1824 GUI frameworks like wxPython trap exceptions and call
1826 sys.excepthook themselves. I guess this is a feature that
1825 sys.excepthook themselves. I guess this is a feature that
1827 enables them to keep running after exceptions that would
1826 enables them to keep running after exceptions that would
1828 otherwise kill their mainloop. This is a bother for IPython
1827 otherwise kill their mainloop. This is a bother for IPython
1829 which excepts to catch all of the program exceptions with a try:
1828 which excepts to catch all of the program exceptions with a try:
1830 except: statement.
1829 except: statement.
1831
1830
1832 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1831 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1833 any app directly invokes sys.excepthook, it will look to the user like
1832 any app directly invokes sys.excepthook, it will look to the user like
1834 IPython crashed. In order to work around this, we can disable the
1833 IPython crashed. In order to work around this, we can disable the
1835 CrashHandler and replace it with this excepthook instead, which prints a
1834 CrashHandler and replace it with this excepthook instead, which prints a
1836 regular traceback using our InteractiveTB. In this fashion, apps which
1835 regular traceback using our InteractiveTB. In this fashion, apps which
1837 call sys.excepthook will generate a regular-looking exception from
1836 call sys.excepthook will generate a regular-looking exception from
1838 IPython, and the CrashHandler will only be triggered by real IPython
1837 IPython, and the CrashHandler will only be triggered by real IPython
1839 crashes.
1838 crashes.
1840
1839
1841 This hook should be used sparingly, only in places which are not likely
1840 This hook should be used sparingly, only in places which are not likely
1842 to be true IPython errors.
1841 to be true IPython errors.
1843 """
1842 """
1844 self.showtraceback((etype,value,tb),tb_offset=0)
1843 self.showtraceback((etype,value,tb),tb_offset=0)
1845
1844
1846 def expand_aliases(self,fn,rest):
1845 def expand_aliases(self,fn,rest):
1847 """ Expand multiple levels of aliases:
1846 """ Expand multiple levels of aliases:
1848
1847
1849 if:
1848 if:
1850
1849
1851 alias foo bar /tmp
1850 alias foo bar /tmp
1852 alias baz foo
1851 alias baz foo
1853
1852
1854 then:
1853 then:
1855
1854
1856 baz huhhahhei -> bar /tmp huhhahhei
1855 baz huhhahhei -> bar /tmp huhhahhei
1857
1856
1858 """
1857 """
1859 line = fn + " " + rest
1858 line = fn + " " + rest
1860
1859
1861 done = Set()
1860 done = Set()
1862 while 1:
1861 while 1:
1863 pre,fn,rest = prefilter.splitUserInput(line,
1862 pre,fn,rest = prefilter.splitUserInput(line,
1864 prefilter.shell_line_split)
1863 prefilter.shell_line_split)
1865 if fn in self.alias_table:
1864 if fn in self.alias_table:
1866 if fn in done:
1865 if fn in done:
1867 warn("Cyclic alias definition, repeated '%s'" % fn)
1866 warn("Cyclic alias definition, repeated '%s'" % fn)
1868 return ""
1867 return ""
1869 done.add(fn)
1868 done.add(fn)
1870
1869
1871 l2 = self.transform_alias(fn,rest)
1870 l2 = self.transform_alias(fn,rest)
1872 # dir -> dir
1871 # dir -> dir
1873 # print "alias",line, "->",l2 #dbg
1872 # print "alias",line, "->",l2 #dbg
1874 if l2 == line:
1873 if l2 == line:
1875 break
1874 break
1876 # ls -> ls -F should not recurse forever
1875 # ls -> ls -F should not recurse forever
1877 if l2.split(None,1)[0] == line.split(None,1)[0]:
1876 if l2.split(None,1)[0] == line.split(None,1)[0]:
1878 line = l2
1877 line = l2
1879 break
1878 break
1880
1879
1881 line=l2
1880 line=l2
1882
1881
1883
1882
1884 # print "al expand to",line #dbg
1883 # print "al expand to",line #dbg
1885 else:
1884 else:
1886 break
1885 break
1887
1886
1888 return line
1887 return line
1889
1888
1890 def transform_alias(self, alias,rest=''):
1889 def transform_alias(self, alias,rest=''):
1891 """ Transform alias to system command string.
1890 """ Transform alias to system command string.
1892 """
1891 """
1893 trg = self.alias_table[alias]
1892 trg = self.alias_table[alias]
1894
1893
1895 nargs,cmd = trg
1894 nargs,cmd = trg
1896 # print trg #dbg
1895 # print trg #dbg
1897 if ' ' in cmd and os.path.isfile(cmd):
1896 if ' ' in cmd and os.path.isfile(cmd):
1898 cmd = '"%s"' % cmd
1897 cmd = '"%s"' % cmd
1899
1898
1900 # Expand the %l special to be the user's input line
1899 # Expand the %l special to be the user's input line
1901 if cmd.find('%l') >= 0:
1900 if cmd.find('%l') >= 0:
1902 cmd = cmd.replace('%l',rest)
1901 cmd = cmd.replace('%l',rest)
1903 rest = ''
1902 rest = ''
1904 if nargs==0:
1903 if nargs==0:
1905 # Simple, argument-less aliases
1904 # Simple, argument-less aliases
1906 cmd = '%s %s' % (cmd,rest)
1905 cmd = '%s %s' % (cmd,rest)
1907 else:
1906 else:
1908 # Handle aliases with positional arguments
1907 # Handle aliases with positional arguments
1909 args = rest.split(None,nargs)
1908 args = rest.split(None,nargs)
1910 if len(args)< nargs:
1909 if len(args)< nargs:
1911 error('Alias <%s> requires %s arguments, %s given.' %
1910 error('Alias <%s> requires %s arguments, %s given.' %
1912 (alias,nargs,len(args)))
1911 (alias,nargs,len(args)))
1913 return None
1912 return None
1914 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1913 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
1915 # Now call the macro, evaluating in the user's namespace
1914 # Now call the macro, evaluating in the user's namespace
1916 #print 'new command: <%r>' % cmd # dbg
1915 #print 'new command: <%r>' % cmd # dbg
1917 return cmd
1916 return cmd
1918
1917
1919 def call_alias(self,alias,rest=''):
1918 def call_alias(self,alias,rest=''):
1920 """Call an alias given its name and the rest of the line.
1919 """Call an alias given its name and the rest of the line.
1921
1920
1922 This is only used to provide backwards compatibility for users of
1921 This is only used to provide backwards compatibility for users of
1923 ipalias(), use of which is not recommended for anymore."""
1922 ipalias(), use of which is not recommended for anymore."""
1924
1923
1925 # Now call the macro, evaluating in the user's namespace
1924 # Now call the macro, evaluating in the user's namespace
1926 cmd = self.transform_alias(alias, rest)
1925 cmd = self.transform_alias(alias, rest)
1927 try:
1926 try:
1928 self.system(cmd)
1927 self.system(cmd)
1929 except:
1928 except:
1930 self.showtraceback()
1929 self.showtraceback()
1931
1930
1932 def indent_current_str(self):
1931 def indent_current_str(self):
1933 """return the current level of indentation as a string"""
1932 """return the current level of indentation as a string"""
1934 return self.indent_current_nsp * ' '
1933 return self.indent_current_nsp * ' '
1935
1934
1936 def autoindent_update(self,line):
1935 def autoindent_update(self,line):
1937 """Keep track of the indent level."""
1936 """Keep track of the indent level."""
1938
1937
1939 #debugx('line')
1938 #debugx('line')
1940 #debugx('self.indent_current_nsp')
1939 #debugx('self.indent_current_nsp')
1941 if self.autoindent:
1940 if self.autoindent:
1942 if line:
1941 if line:
1943 inisp = num_ini_spaces(line)
1942 inisp = num_ini_spaces(line)
1944 if inisp < self.indent_current_nsp:
1943 if inisp < self.indent_current_nsp:
1945 self.indent_current_nsp = inisp
1944 self.indent_current_nsp = inisp
1946
1945
1947 if line[-1] == ':':
1946 if line[-1] == ':':
1948 self.indent_current_nsp += 4
1947 self.indent_current_nsp += 4
1949 elif dedent_re.match(line):
1948 elif dedent_re.match(line):
1950 self.indent_current_nsp -= 4
1949 self.indent_current_nsp -= 4
1951 else:
1950 else:
1952 self.indent_current_nsp = 0
1951 self.indent_current_nsp = 0
1953
1952
1954 def runlines(self,lines):
1953 def runlines(self,lines):
1955 """Run a string of one or more lines of source.
1954 """Run a string of one or more lines of source.
1956
1955
1957 This method is capable of running a string containing multiple source
1956 This method is capable of running a string containing multiple source
1958 lines, as if they had been entered at the IPython prompt. Since it
1957 lines, as if they had been entered at the IPython prompt. Since it
1959 exposes IPython's processing machinery, the given strings can contain
1958 exposes IPython's processing machinery, the given strings can contain
1960 magic calls (%magic), special shell access (!cmd), etc."""
1959 magic calls (%magic), special shell access (!cmd), etc."""
1961
1960
1962 # We must start with a clean buffer, in case this is run from an
1961 # We must start with a clean buffer, in case this is run from an
1963 # interactive IPython session (via a magic, for example).
1962 # interactive IPython session (via a magic, for example).
1964 self.resetbuffer()
1963 self.resetbuffer()
1965 lines = lines.split('\n')
1964 lines = lines.split('\n')
1966 more = 0
1965 more = 0
1967
1966
1968 for line in lines:
1967 for line in lines:
1969 # skip blank lines so we don't mess up the prompt counter, but do
1968 # skip blank lines so we don't mess up the prompt counter, but do
1970 # NOT skip even a blank line if we are in a code block (more is
1969 # NOT skip even a blank line if we are in a code block (more is
1971 # true)
1970 # true)
1972
1971
1973
1972
1974 if line or more:
1973 if line or more:
1975 # push to raw history, so hist line numbers stay in sync
1974 # push to raw history, so hist line numbers stay in sync
1976 self.input_hist_raw.append("# " + line + "\n")
1975 self.input_hist_raw.append("# " + line + "\n")
1977 more = self.push(self.prefilter(line,more))
1976 more = self.push(self.prefilter(line,more))
1978 # IPython's runsource returns None if there was an error
1977 # IPython's runsource returns None if there was an error
1979 # compiling the code. This allows us to stop processing right
1978 # compiling the code. This allows us to stop processing right
1980 # away, so the user gets the error message at the right place.
1979 # away, so the user gets the error message at the right place.
1981 if more is None:
1980 if more is None:
1982 break
1981 break
1983 else:
1982 else:
1984 self.input_hist_raw.append("\n")
1983 self.input_hist_raw.append("\n")
1985 # final newline in case the input didn't have it, so that the code
1984 # final newline in case the input didn't have it, so that the code
1986 # actually does get executed
1985 # actually does get executed
1987 if more:
1986 if more:
1988 self.push('\n')
1987 self.push('\n')
1989
1988
1990 def runsource(self, source, filename='<input>', symbol='single'):
1989 def runsource(self, source, filename='<input>', symbol='single'):
1991 """Compile and run some source in the interpreter.
1990 """Compile and run some source in the interpreter.
1992
1991
1993 Arguments are as for compile_command().
1992 Arguments are as for compile_command().
1994
1993
1995 One several things can happen:
1994 One several things can happen:
1996
1995
1997 1) The input is incorrect; compile_command() raised an
1996 1) The input is incorrect; compile_command() raised an
1998 exception (SyntaxError or OverflowError). A syntax traceback
1997 exception (SyntaxError or OverflowError). A syntax traceback
1999 will be printed by calling the showsyntaxerror() method.
1998 will be printed by calling the showsyntaxerror() method.
2000
1999
2001 2) The input is incomplete, and more input is required;
2000 2) The input is incomplete, and more input is required;
2002 compile_command() returned None. Nothing happens.
2001 compile_command() returned None. Nothing happens.
2003
2002
2004 3) The input is complete; compile_command() returned a code
2003 3) The input is complete; compile_command() returned a code
2005 object. The code is executed by calling self.runcode() (which
2004 object. The code is executed by calling self.runcode() (which
2006 also handles run-time exceptions, except for SystemExit).
2005 also handles run-time exceptions, except for SystemExit).
2007
2006
2008 The return value is:
2007 The return value is:
2009
2008
2010 - True in case 2
2009 - True in case 2
2011
2010
2012 - False in the other cases, unless an exception is raised, where
2011 - False in the other cases, unless an exception is raised, where
2013 None is returned instead. This can be used by external callers to
2012 None is returned instead. This can be used by external callers to
2014 know whether to continue feeding input or not.
2013 know whether to continue feeding input or not.
2015
2014
2016 The return value can be used to decide whether to use sys.ps1 or
2015 The return value can be used to decide whether to use sys.ps1 or
2017 sys.ps2 to prompt the next line."""
2016 sys.ps2 to prompt the next line."""
2018
2017
2019 # if the source code has leading blanks, add 'if 1:\n' to it
2018 # if the source code has leading blanks, add 'if 1:\n' to it
2020 # this allows execution of indented pasted code. It is tempting
2019 # this allows execution of indented pasted code. It is tempting
2021 # to add '\n' at the end of source to run commands like ' a=1'
2020 # to add '\n' at the end of source to run commands like ' a=1'
2022 # directly, but this fails for more complicated scenarios
2021 # directly, but this fails for more complicated scenarios
2023 source=source.encode(self.stdin_encoding)
2022 source=source.encode(self.stdin_encoding)
2024 if source[:1] in [' ', '\t']:
2023 if source[:1] in [' ', '\t']:
2025 source = 'if 1:\n%s' % source
2024 source = 'if 1:\n%s' % source
2026
2025
2027 try:
2026 try:
2028 code = self.compile(source,filename,symbol)
2027 code = self.compile(source,filename,symbol)
2029 except (OverflowError, SyntaxError, ValueError, TypeError):
2028 except (OverflowError, SyntaxError, ValueError, TypeError):
2030 # Case 1
2029 # Case 1
2031 self.showsyntaxerror(filename)
2030 self.showsyntaxerror(filename)
2032 return None
2031 return None
2033
2032
2034 if code is None:
2033 if code is None:
2035 # Case 2
2034 # Case 2
2036 return True
2035 return True
2037
2036
2038 # Case 3
2037 # Case 3
2039 # We store the code object so that threaded shells and
2038 # We store the code object so that threaded shells and
2040 # custom exception handlers can access all this info if needed.
2039 # custom exception handlers can access all this info if needed.
2041 # The source corresponding to this can be obtained from the
2040 # The source corresponding to this can be obtained from the
2042 # buffer attribute as '\n'.join(self.buffer).
2041 # buffer attribute as '\n'.join(self.buffer).
2043 self.code_to_run = code
2042 self.code_to_run = code
2044 # now actually execute the code object
2043 # now actually execute the code object
2045 if self.runcode(code) == 0:
2044 if self.runcode(code) == 0:
2046 return False
2045 return False
2047 else:
2046 else:
2048 return None
2047 return None
2049
2048
2050 def runcode(self,code_obj):
2049 def runcode(self,code_obj):
2051 """Execute a code object.
2050 """Execute a code object.
2052
2051
2053 When an exception occurs, self.showtraceback() is called to display a
2052 When an exception occurs, self.showtraceback() is called to display a
2054 traceback.
2053 traceback.
2055
2054
2056 Return value: a flag indicating whether the code to be run completed
2055 Return value: a flag indicating whether the code to be run completed
2057 successfully:
2056 successfully:
2058
2057
2059 - 0: successful execution.
2058 - 0: successful execution.
2060 - 1: an error occurred.
2059 - 1: an error occurred.
2061 """
2060 """
2062
2061
2063 # Set our own excepthook in case the user code tries to call it
2062 # Set our own excepthook in case the user code tries to call it
2064 # directly, so that the IPython crash handler doesn't get triggered
2063 # directly, so that the IPython crash handler doesn't get triggered
2065 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2064 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2066
2065
2067 # we save the original sys.excepthook in the instance, in case config
2066 # we save the original sys.excepthook in the instance, in case config
2068 # code (such as magics) needs access to it.
2067 # code (such as magics) needs access to it.
2069 self.sys_excepthook = old_excepthook
2068 self.sys_excepthook = old_excepthook
2070 outflag = 1 # happens in more places, so it's easier as default
2069 outflag = 1 # happens in more places, so it's easier as default
2071 try:
2070 try:
2072 try:
2071 try:
2073 self.hooks.pre_runcode_hook()
2072 self.hooks.pre_runcode_hook()
2074 # Embedded instances require separate global/local namespaces
2073 exec code_obj in self.user_global_ns, self.user_ns
2075 # so they can see both the surrounding (local) namespace and
2076 # the module-level globals when called inside another function.
2077 if self.embedded:
2078 exec code_obj in self.user_global_ns, self.user_ns
2079 # Normal (non-embedded) instances should only have a single
2080 # namespace for user code execution, otherwise functions won't
2081 # see interactive top-level globals.
2082 else:
2083 exec code_obj in self.user_ns
2084 finally:
2074 finally:
2085 # Reset our crash handler in place
2075 # Reset our crash handler in place
2086 sys.excepthook = old_excepthook
2076 sys.excepthook = old_excepthook
2087 except SystemExit:
2077 except SystemExit:
2088 self.resetbuffer()
2078 self.resetbuffer()
2089 self.showtraceback()
2079 self.showtraceback()
2090 warn("Type %exit or %quit to exit IPython "
2080 warn("Type %exit or %quit to exit IPython "
2091 "(%Exit or %Quit do so unconditionally).",level=1)
2081 "(%Exit or %Quit do so unconditionally).",level=1)
2092 except self.custom_exceptions:
2082 except self.custom_exceptions:
2093 etype,value,tb = sys.exc_info()
2083 etype,value,tb = sys.exc_info()
2094 self.CustomTB(etype,value,tb)
2084 self.CustomTB(etype,value,tb)
2095 except:
2085 except:
2096 self.showtraceback()
2086 self.showtraceback()
2097 else:
2087 else:
2098 outflag = 0
2088 outflag = 0
2099 if softspace(sys.stdout, 0):
2089 if softspace(sys.stdout, 0):
2100 print
2090 print
2101 # Flush out code object which has been run (and source)
2091 # Flush out code object which has been run (and source)
2102 self.code_to_run = None
2092 self.code_to_run = None
2103 return outflag
2093 return outflag
2104
2094
2105 def push(self, line):
2095 def push(self, line):
2106 """Push a line to the interpreter.
2096 """Push a line to the interpreter.
2107
2097
2108 The line should not have a trailing newline; it may have
2098 The line should not have a trailing newline; it may have
2109 internal newlines. The line is appended to a buffer and the
2099 internal newlines. The line is appended to a buffer and the
2110 interpreter's runsource() method is called with the
2100 interpreter's runsource() method is called with the
2111 concatenated contents of the buffer as source. If this
2101 concatenated contents of the buffer as source. If this
2112 indicates that the command was executed or invalid, the buffer
2102 indicates that the command was executed or invalid, the buffer
2113 is reset; otherwise, the command is incomplete, and the buffer
2103 is reset; otherwise, the command is incomplete, and the buffer
2114 is left as it was after the line was appended. The return
2104 is left as it was after the line was appended. The return
2115 value is 1 if more input is required, 0 if the line was dealt
2105 value is 1 if more input is required, 0 if the line was dealt
2116 with in some way (this is the same as runsource()).
2106 with in some way (this is the same as runsource()).
2117 """
2107 """
2118
2108
2119 # autoindent management should be done here, and not in the
2109 # autoindent management should be done here, and not in the
2120 # interactive loop, since that one is only seen by keyboard input. We
2110 # interactive loop, since that one is only seen by keyboard input. We
2121 # need this done correctly even for code run via runlines (which uses
2111 # need this done correctly even for code run via runlines (which uses
2122 # push).
2112 # push).
2123
2113
2124 #print 'push line: <%s>' % line # dbg
2114 #print 'push line: <%s>' % line # dbg
2125 for subline in line.splitlines():
2115 for subline in line.splitlines():
2126 self.autoindent_update(subline)
2116 self.autoindent_update(subline)
2127 self.buffer.append(line)
2117 self.buffer.append(line)
2128 more = self.runsource('\n'.join(self.buffer), self.filename)
2118 more = self.runsource('\n'.join(self.buffer), self.filename)
2129 if not more:
2119 if not more:
2130 self.resetbuffer()
2120 self.resetbuffer()
2131 return more
2121 return more
2132
2122
2133 def split_user_input(self, line):
2123 def split_user_input(self, line):
2134 # This is really a hold-over to support ipapi and some extensions
2124 # This is really a hold-over to support ipapi and some extensions
2135 return prefilter.splitUserInput(line)
2125 return prefilter.splitUserInput(line)
2136
2126
2137 def resetbuffer(self):
2127 def resetbuffer(self):
2138 """Reset the input buffer."""
2128 """Reset the input buffer."""
2139 self.buffer[:] = []
2129 self.buffer[:] = []
2140
2130
2141 def raw_input(self,prompt='',continue_prompt=False):
2131 def raw_input(self,prompt='',continue_prompt=False):
2142 """Write a prompt and read a line.
2132 """Write a prompt and read a line.
2143
2133
2144 The returned line does not include the trailing newline.
2134 The returned line does not include the trailing newline.
2145 When the user enters the EOF key sequence, EOFError is raised.
2135 When the user enters the EOF key sequence, EOFError is raised.
2146
2136
2147 Optional inputs:
2137 Optional inputs:
2148
2138
2149 - prompt(''): a string to be printed to prompt the user.
2139 - prompt(''): a string to be printed to prompt the user.
2150
2140
2151 - continue_prompt(False): whether this line is the first one or a
2141 - continue_prompt(False): whether this line is the first one or a
2152 continuation in a sequence of inputs.
2142 continuation in a sequence of inputs.
2153 """
2143 """
2154
2144
2155 # Code run by the user may have modified the readline completer state.
2145 # Code run by the user may have modified the readline completer state.
2156 # We must ensure that our completer is back in place.
2146 # We must ensure that our completer is back in place.
2157 if self.has_readline:
2147 if self.has_readline:
2158 self.set_completer()
2148 self.set_completer()
2159
2149
2160 try:
2150 try:
2161 line = raw_input_original(prompt).decode(self.stdin_encoding)
2151 line = raw_input_original(prompt).decode(self.stdin_encoding)
2162 except ValueError:
2152 except ValueError:
2163 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2153 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2164 " or sys.stdout.close()!\nExiting IPython!")
2154 " or sys.stdout.close()!\nExiting IPython!")
2165 self.ask_exit()
2155 self.ask_exit()
2166 return ""
2156 return ""
2167
2157
2168 # Try to be reasonably smart about not re-indenting pasted input more
2158 # Try to be reasonably smart about not re-indenting pasted input more
2169 # than necessary. We do this by trimming out the auto-indent initial
2159 # than necessary. We do this by trimming out the auto-indent initial
2170 # spaces, if the user's actual input started itself with whitespace.
2160 # spaces, if the user's actual input started itself with whitespace.
2171 #debugx('self.buffer[-1]')
2161 #debugx('self.buffer[-1]')
2172
2162
2173 if self.autoindent:
2163 if self.autoindent:
2174 if num_ini_spaces(line) > self.indent_current_nsp:
2164 if num_ini_spaces(line) > self.indent_current_nsp:
2175 line = line[self.indent_current_nsp:]
2165 line = line[self.indent_current_nsp:]
2176 self.indent_current_nsp = 0
2166 self.indent_current_nsp = 0
2177
2167
2178 # store the unfiltered input before the user has any chance to modify
2168 # store the unfiltered input before the user has any chance to modify
2179 # it.
2169 # it.
2180 if line.strip():
2170 if line.strip():
2181 if continue_prompt:
2171 if continue_prompt:
2182 self.input_hist_raw[-1] += '%s\n' % line
2172 self.input_hist_raw[-1] += '%s\n' % line
2183 if self.has_readline: # and some config option is set?
2173 if self.has_readline: # and some config option is set?
2184 try:
2174 try:
2185 histlen = self.readline.get_current_history_length()
2175 histlen = self.readline.get_current_history_length()
2186 if histlen > 1:
2176 if histlen > 1:
2187 newhist = self.input_hist_raw[-1].rstrip()
2177 newhist = self.input_hist_raw[-1].rstrip()
2188 self.readline.remove_history_item(histlen-1)
2178 self.readline.remove_history_item(histlen-1)
2189 self.readline.replace_history_item(histlen-2,
2179 self.readline.replace_history_item(histlen-2,
2190 newhist.encode(self.stdin_encoding))
2180 newhist.encode(self.stdin_encoding))
2191 except AttributeError:
2181 except AttributeError:
2192 pass # re{move,place}_history_item are new in 2.4.
2182 pass # re{move,place}_history_item are new in 2.4.
2193 else:
2183 else:
2194 self.input_hist_raw.append('%s\n' % line)
2184 self.input_hist_raw.append('%s\n' % line)
2195 # only entries starting at first column go to shadow history
2185 # only entries starting at first column go to shadow history
2196 if line.lstrip() == line:
2186 if line.lstrip() == line:
2197 self.shadowhist.add(line.strip())
2187 self.shadowhist.add(line.strip())
2198 elif not continue_prompt:
2188 elif not continue_prompt:
2199 self.input_hist_raw.append('\n')
2189 self.input_hist_raw.append('\n')
2200 try:
2190 try:
2201 lineout = self.prefilter(line,continue_prompt)
2191 lineout = self.prefilter(line,continue_prompt)
2202 except:
2192 except:
2203 # blanket except, in case a user-defined prefilter crashes, so it
2193 # blanket except, in case a user-defined prefilter crashes, so it
2204 # can't take all of ipython with it.
2194 # can't take all of ipython with it.
2205 self.showtraceback()
2195 self.showtraceback()
2206 return ''
2196 return ''
2207 else:
2197 else:
2208 return lineout
2198 return lineout
2209
2199
2210 def _prefilter(self, line, continue_prompt):
2200 def _prefilter(self, line, continue_prompt):
2211 """Calls different preprocessors, depending on the form of line."""
2201 """Calls different preprocessors, depending on the form of line."""
2212
2202
2213 # All handlers *must* return a value, even if it's blank ('').
2203 # All handlers *must* return a value, even if it's blank ('').
2214
2204
2215 # Lines are NOT logged here. Handlers should process the line as
2205 # Lines are NOT logged here. Handlers should process the line as
2216 # needed, update the cache AND log it (so that the input cache array
2206 # needed, update the cache AND log it (so that the input cache array
2217 # stays synced).
2207 # stays synced).
2218
2208
2219 #.....................................................................
2209 #.....................................................................
2220 # Code begins
2210 # Code begins
2221
2211
2222 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2212 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2223
2213
2224 # save the line away in case we crash, so the post-mortem handler can
2214 # save the line away in case we crash, so the post-mortem handler can
2225 # record it
2215 # record it
2226 self._last_input_line = line
2216 self._last_input_line = line
2227
2217
2228 #print '***line: <%s>' % line # dbg
2218 #print '***line: <%s>' % line # dbg
2229
2219
2230 if not line:
2220 if not line:
2231 # Return immediately on purely empty lines, so that if the user
2221 # Return immediately on purely empty lines, so that if the user
2232 # previously typed some whitespace that started a continuation
2222 # previously typed some whitespace that started a continuation
2233 # prompt, he can break out of that loop with just an empty line.
2223 # prompt, he can break out of that loop with just an empty line.
2234 # This is how the default python prompt works.
2224 # This is how the default python prompt works.
2235
2225
2236 # Only return if the accumulated input buffer was just whitespace!
2226 # Only return if the accumulated input buffer was just whitespace!
2237 if ''.join(self.buffer).isspace():
2227 if ''.join(self.buffer).isspace():
2238 self.buffer[:] = []
2228 self.buffer[:] = []
2239 return ''
2229 return ''
2240
2230
2241 line_info = prefilter.LineInfo(line, continue_prompt)
2231 line_info = prefilter.LineInfo(line, continue_prompt)
2242
2232
2243 # the input history needs to track even empty lines
2233 # the input history needs to track even empty lines
2244 stripped = line.strip()
2234 stripped = line.strip()
2245
2235
2246 if not stripped:
2236 if not stripped:
2247 if not continue_prompt:
2237 if not continue_prompt:
2248 self.outputcache.prompt_count -= 1
2238 self.outputcache.prompt_count -= 1
2249 return self.handle_normal(line_info)
2239 return self.handle_normal(line_info)
2250
2240
2251 # print '***cont',continue_prompt # dbg
2241 # print '***cont',continue_prompt # dbg
2252 # special handlers are only allowed for single line statements
2242 # special handlers are only allowed for single line statements
2253 if continue_prompt and not self.rc.multi_line_specials:
2243 if continue_prompt and not self.rc.multi_line_specials:
2254 return self.handle_normal(line_info)
2244 return self.handle_normal(line_info)
2255
2245
2256
2246
2257 # See whether any pre-existing handler can take care of it
2247 # See whether any pre-existing handler can take care of it
2258 rewritten = self.hooks.input_prefilter(stripped)
2248 rewritten = self.hooks.input_prefilter(stripped)
2259 if rewritten != stripped: # ok, some prefilter did something
2249 if rewritten != stripped: # ok, some prefilter did something
2260 rewritten = line_info.pre + rewritten # add indentation
2250 rewritten = line_info.pre + rewritten # add indentation
2261 return self.handle_normal(prefilter.LineInfo(rewritten,
2251 return self.handle_normal(prefilter.LineInfo(rewritten,
2262 continue_prompt))
2252 continue_prompt))
2263
2253
2264 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2254 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2265
2255
2266 return prefilter.prefilter(line_info, self)
2256 return prefilter.prefilter(line_info, self)
2267
2257
2268
2258
2269 def _prefilter_dumb(self, line, continue_prompt):
2259 def _prefilter_dumb(self, line, continue_prompt):
2270 """simple prefilter function, for debugging"""
2260 """simple prefilter function, for debugging"""
2271 return self.handle_normal(line,continue_prompt)
2261 return self.handle_normal(line,continue_prompt)
2272
2262
2273
2263
2274 def multiline_prefilter(self, line, continue_prompt):
2264 def multiline_prefilter(self, line, continue_prompt):
2275 """ Run _prefilter for each line of input
2265 """ Run _prefilter for each line of input
2276
2266
2277 Covers cases where there are multiple lines in the user entry,
2267 Covers cases where there are multiple lines in the user entry,
2278 which is the case when the user goes back to a multiline history
2268 which is the case when the user goes back to a multiline history
2279 entry and presses enter.
2269 entry and presses enter.
2280
2270
2281 """
2271 """
2282 out = []
2272 out = []
2283 for l in line.rstrip('\n').split('\n'):
2273 for l in line.rstrip('\n').split('\n'):
2284 out.append(self._prefilter(l, continue_prompt))
2274 out.append(self._prefilter(l, continue_prompt))
2285 return '\n'.join(out)
2275 return '\n'.join(out)
2286
2276
2287 # Set the default prefilter() function (this can be user-overridden)
2277 # Set the default prefilter() function (this can be user-overridden)
2288 prefilter = multiline_prefilter
2278 prefilter = multiline_prefilter
2289
2279
2290 def handle_normal(self,line_info):
2280 def handle_normal(self,line_info):
2291 """Handle normal input lines. Use as a template for handlers."""
2281 """Handle normal input lines. Use as a template for handlers."""
2292
2282
2293 # With autoindent on, we need some way to exit the input loop, and I
2283 # With autoindent on, we need some way to exit the input loop, and I
2294 # don't want to force the user to have to backspace all the way to
2284 # don't want to force the user to have to backspace all the way to
2295 # clear the line. The rule will be in this case, that either two
2285 # clear the line. The rule will be in this case, that either two
2296 # lines of pure whitespace in a row, or a line of pure whitespace but
2286 # lines of pure whitespace in a row, or a line of pure whitespace but
2297 # of a size different to the indent level, will exit the input loop.
2287 # of a size different to the indent level, will exit the input loop.
2298 line = line_info.line
2288 line = line_info.line
2299 continue_prompt = line_info.continue_prompt
2289 continue_prompt = line_info.continue_prompt
2300
2290
2301 if (continue_prompt and self.autoindent and line.isspace() and
2291 if (continue_prompt and self.autoindent and line.isspace() and
2302 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2292 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2303 (self.buffer[-1]).isspace() )):
2293 (self.buffer[-1]).isspace() )):
2304 line = ''
2294 line = ''
2305
2295
2306 self.log(line,line,continue_prompt)
2296 self.log(line,line,continue_prompt)
2307 return line
2297 return line
2308
2298
2309 def handle_alias(self,line_info):
2299 def handle_alias(self,line_info):
2310 """Handle alias input lines. """
2300 """Handle alias input lines. """
2311 tgt = self.alias_table[line_info.iFun]
2301 tgt = self.alias_table[line_info.iFun]
2312 # print "=>",tgt #dbg
2302 # print "=>",tgt #dbg
2313 if callable(tgt):
2303 if callable(tgt):
2314 if '$' in line_info.line:
2304 if '$' in line_info.line:
2315 call_meth = '(_ip, _ip.itpl(%s))'
2305 call_meth = '(_ip, _ip.itpl(%s))'
2316 else:
2306 else:
2317 call_meth = '(_ip,%s)'
2307 call_meth = '(_ip,%s)'
2318 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2308 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2319 line_info.iFun,
2309 line_info.iFun,
2320 make_quoted_expr(line_info.line))
2310 make_quoted_expr(line_info.line))
2321 else:
2311 else:
2322 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2312 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2323
2313
2324 # pre is needed, because it carries the leading whitespace. Otherwise
2314 # pre is needed, because it carries the leading whitespace. Otherwise
2325 # aliases won't work in indented sections.
2315 # aliases won't work in indented sections.
2326 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2316 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2327 make_quoted_expr( transformed ))
2317 make_quoted_expr( transformed ))
2328
2318
2329 self.log(line_info.line,line_out,line_info.continue_prompt)
2319 self.log(line_info.line,line_out,line_info.continue_prompt)
2330 #print 'line out:',line_out # dbg
2320 #print 'line out:',line_out # dbg
2331 return line_out
2321 return line_out
2332
2322
2333 def handle_shell_escape(self, line_info):
2323 def handle_shell_escape(self, line_info):
2334 """Execute the line in a shell, empty return value"""
2324 """Execute the line in a shell, empty return value"""
2335 #print 'line in :', `line` # dbg
2325 #print 'line in :', `line` # dbg
2336 line = line_info.line
2326 line = line_info.line
2337 if line.lstrip().startswith('!!'):
2327 if line.lstrip().startswith('!!'):
2338 # rewrite LineInfo's line, iFun and theRest to properly hold the
2328 # rewrite LineInfo's line, iFun and theRest to properly hold the
2339 # call to %sx and the actual command to be executed, so
2329 # call to %sx and the actual command to be executed, so
2340 # handle_magic can work correctly. Note that this works even if
2330 # handle_magic can work correctly. Note that this works even if
2341 # the line is indented, so it handles multi_line_specials
2331 # the line is indented, so it handles multi_line_specials
2342 # properly.
2332 # properly.
2343 new_rest = line.lstrip()[2:]
2333 new_rest = line.lstrip()[2:]
2344 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2334 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2345 line_info.iFun = 'sx'
2335 line_info.iFun = 'sx'
2346 line_info.theRest = new_rest
2336 line_info.theRest = new_rest
2347 return self.handle_magic(line_info)
2337 return self.handle_magic(line_info)
2348 else:
2338 else:
2349 cmd = line.lstrip().lstrip('!')
2339 cmd = line.lstrip().lstrip('!')
2350 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2340 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2351 make_quoted_expr(cmd))
2341 make_quoted_expr(cmd))
2352 # update cache/log and return
2342 # update cache/log and return
2353 self.log(line,line_out,line_info.continue_prompt)
2343 self.log(line,line_out,line_info.continue_prompt)
2354 return line_out
2344 return line_out
2355
2345
2356 def handle_magic(self, line_info):
2346 def handle_magic(self, line_info):
2357 """Execute magic functions."""
2347 """Execute magic functions."""
2358 iFun = line_info.iFun
2348 iFun = line_info.iFun
2359 theRest = line_info.theRest
2349 theRest = line_info.theRest
2360 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2350 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2361 make_quoted_expr(iFun + " " + theRest))
2351 make_quoted_expr(iFun + " " + theRest))
2362 self.log(line_info.line,cmd,line_info.continue_prompt)
2352 self.log(line_info.line,cmd,line_info.continue_prompt)
2363 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2353 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2364 return cmd
2354 return cmd
2365
2355
2366 def handle_auto(self, line_info):
2356 def handle_auto(self, line_info):
2367 """Hande lines which can be auto-executed, quoting if requested."""
2357 """Hande lines which can be auto-executed, quoting if requested."""
2368
2358
2369 line = line_info.line
2359 line = line_info.line
2370 iFun = line_info.iFun
2360 iFun = line_info.iFun
2371 theRest = line_info.theRest
2361 theRest = line_info.theRest
2372 pre = line_info.pre
2362 pre = line_info.pre
2373 continue_prompt = line_info.continue_prompt
2363 continue_prompt = line_info.continue_prompt
2374 obj = line_info.ofind(self)['obj']
2364 obj = line_info.ofind(self)['obj']
2375
2365
2376 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2366 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2377
2367
2378 # This should only be active for single-line input!
2368 # This should only be active for single-line input!
2379 if continue_prompt:
2369 if continue_prompt:
2380 self.log(line,line,continue_prompt)
2370 self.log(line,line,continue_prompt)
2381 return line
2371 return line
2382
2372
2383 force_auto = isinstance(obj, IPython.ipapi.IPyAutocall)
2373 force_auto = isinstance(obj, IPython.ipapi.IPyAutocall)
2384 auto_rewrite = True
2374 auto_rewrite = True
2385
2375
2386 if pre == self.ESC_QUOTE:
2376 if pre == self.ESC_QUOTE:
2387 # Auto-quote splitting on whitespace
2377 # Auto-quote splitting on whitespace
2388 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2378 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2389 elif pre == self.ESC_QUOTE2:
2379 elif pre == self.ESC_QUOTE2:
2390 # Auto-quote whole string
2380 # Auto-quote whole string
2391 newcmd = '%s("%s")' % (iFun,theRest)
2381 newcmd = '%s("%s")' % (iFun,theRest)
2392 elif pre == self.ESC_PAREN:
2382 elif pre == self.ESC_PAREN:
2393 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2383 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2394 else:
2384 else:
2395 # Auto-paren.
2385 # Auto-paren.
2396 # We only apply it to argument-less calls if the autocall
2386 # We only apply it to argument-less calls if the autocall
2397 # parameter is set to 2. We only need to check that autocall is <
2387 # parameter is set to 2. We only need to check that autocall is <
2398 # 2, since this function isn't called unless it's at least 1.
2388 # 2, since this function isn't called unless it's at least 1.
2399 if not theRest and (self.rc.autocall < 2) and not force_auto:
2389 if not theRest and (self.rc.autocall < 2) and not force_auto:
2400 newcmd = '%s %s' % (iFun,theRest)
2390 newcmd = '%s %s' % (iFun,theRest)
2401 auto_rewrite = False
2391 auto_rewrite = False
2402 else:
2392 else:
2403 if not force_auto and theRest.startswith('['):
2393 if not force_auto and theRest.startswith('['):
2404 if hasattr(obj,'__getitem__'):
2394 if hasattr(obj,'__getitem__'):
2405 # Don't autocall in this case: item access for an object
2395 # Don't autocall in this case: item access for an object
2406 # which is BOTH callable and implements __getitem__.
2396 # which is BOTH callable and implements __getitem__.
2407 newcmd = '%s %s' % (iFun,theRest)
2397 newcmd = '%s %s' % (iFun,theRest)
2408 auto_rewrite = False
2398 auto_rewrite = False
2409 else:
2399 else:
2410 # if the object doesn't support [] access, go ahead and
2400 # if the object doesn't support [] access, go ahead and
2411 # autocall
2401 # autocall
2412 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2402 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2413 elif theRest.endswith(';'):
2403 elif theRest.endswith(';'):
2414 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2404 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2415 else:
2405 else:
2416 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2406 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2417
2407
2418 if auto_rewrite:
2408 if auto_rewrite:
2419 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2409 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2420
2410
2421 try:
2411 try:
2422 # plain ascii works better w/ pyreadline, on some machines, so
2412 # plain ascii works better w/ pyreadline, on some machines, so
2423 # we use it and only print uncolored rewrite if we have unicode
2413 # we use it and only print uncolored rewrite if we have unicode
2424 rw = str(rw)
2414 rw = str(rw)
2425 print >>Term.cout, rw
2415 print >>Term.cout, rw
2426 except UnicodeEncodeError:
2416 except UnicodeEncodeError:
2427 print "-------------->" + newcmd
2417 print "-------------->" + newcmd
2428
2418
2429 # log what is now valid Python, not the actual user input (without the
2419 # log what is now valid Python, not the actual user input (without the
2430 # final newline)
2420 # final newline)
2431 self.log(line,newcmd,continue_prompt)
2421 self.log(line,newcmd,continue_prompt)
2432 return newcmd
2422 return newcmd
2433
2423
2434 def handle_help(self, line_info):
2424 def handle_help(self, line_info):
2435 """Try to get some help for the object.
2425 """Try to get some help for the object.
2436
2426
2437 obj? or ?obj -> basic information.
2427 obj? or ?obj -> basic information.
2438 obj?? or ??obj -> more details.
2428 obj?? or ??obj -> more details.
2439 """
2429 """
2440
2430
2441 line = line_info.line
2431 line = line_info.line
2442 # We need to make sure that we don't process lines which would be
2432 # We need to make sure that we don't process lines which would be
2443 # otherwise valid python, such as "x=1 # what?"
2433 # otherwise valid python, such as "x=1 # what?"
2444 try:
2434 try:
2445 codeop.compile_command(line)
2435 codeop.compile_command(line)
2446 except SyntaxError:
2436 except SyntaxError:
2447 # We should only handle as help stuff which is NOT valid syntax
2437 # We should only handle as help stuff which is NOT valid syntax
2448 if line[0]==self.ESC_HELP:
2438 if line[0]==self.ESC_HELP:
2449 line = line[1:]
2439 line = line[1:]
2450 elif line[-1]==self.ESC_HELP:
2440 elif line[-1]==self.ESC_HELP:
2451 line = line[:-1]
2441 line = line[:-1]
2452 self.log(line,'#?'+line,line_info.continue_prompt)
2442 self.log(line,'#?'+line,line_info.continue_prompt)
2453 if line:
2443 if line:
2454 #print 'line:<%r>' % line # dbg
2444 #print 'line:<%r>' % line # dbg
2455 self.magic_pinfo(line)
2445 self.magic_pinfo(line)
2456 else:
2446 else:
2457 page(self.usage,screen_lines=self.rc.screen_length)
2447 page(self.usage,screen_lines=self.rc.screen_length)
2458 return '' # Empty string is needed here!
2448 return '' # Empty string is needed here!
2459 except:
2449 except:
2460 # Pass any other exceptions through to the normal handler
2450 # Pass any other exceptions through to the normal handler
2461 return self.handle_normal(line_info)
2451 return self.handle_normal(line_info)
2462 else:
2452 else:
2463 # If the code compiles ok, we should handle it normally
2453 # If the code compiles ok, we should handle it normally
2464 return self.handle_normal(line_info)
2454 return self.handle_normal(line_info)
2465
2455
2466 def getapi(self):
2456 def getapi(self):
2467 """ Get an IPApi object for this shell instance
2457 """ Get an IPApi object for this shell instance
2468
2458
2469 Getting an IPApi object is always preferable to accessing the shell
2459 Getting an IPApi object is always preferable to accessing the shell
2470 directly, but this holds true especially for extensions.
2460 directly, but this holds true especially for extensions.
2471
2461
2472 It should always be possible to implement an extension with IPApi
2462 It should always be possible to implement an extension with IPApi
2473 alone. If not, contact maintainer to request an addition.
2463 alone. If not, contact maintainer to request an addition.
2474
2464
2475 """
2465 """
2476 return self.api
2466 return self.api
2477
2467
2478 def handle_emacs(self, line_info):
2468 def handle_emacs(self, line_info):
2479 """Handle input lines marked by python-mode."""
2469 """Handle input lines marked by python-mode."""
2480
2470
2481 # Currently, nothing is done. Later more functionality can be added
2471 # Currently, nothing is done. Later more functionality can be added
2482 # here if needed.
2472 # here if needed.
2483
2473
2484 # The input cache shouldn't be updated
2474 # The input cache shouldn't be updated
2485 return line_info.line
2475 return line_info.line
2486
2476
2487
2477
2488 def mktempfile(self,data=None):
2478 def mktempfile(self,data=None):
2489 """Make a new tempfile and return its filename.
2479 """Make a new tempfile and return its filename.
2490
2480
2491 This makes a call to tempfile.mktemp, but it registers the created
2481 This makes a call to tempfile.mktemp, but it registers the created
2492 filename internally so ipython cleans it up at exit time.
2482 filename internally so ipython cleans it up at exit time.
2493
2483
2494 Optional inputs:
2484 Optional inputs:
2495
2485
2496 - data(None): if data is given, it gets written out to the temp file
2486 - data(None): if data is given, it gets written out to the temp file
2497 immediately, and the file is closed again."""
2487 immediately, and the file is closed again."""
2498
2488
2499 filename = tempfile.mktemp('.py','ipython_edit_')
2489 filename = tempfile.mktemp('.py','ipython_edit_')
2500 self.tempfiles.append(filename)
2490 self.tempfiles.append(filename)
2501
2491
2502 if data:
2492 if data:
2503 tmp_file = open(filename,'w')
2493 tmp_file = open(filename,'w')
2504 tmp_file.write(data)
2494 tmp_file.write(data)
2505 tmp_file.close()
2495 tmp_file.close()
2506 return filename
2496 return filename
2507
2497
2508 def write(self,data):
2498 def write(self,data):
2509 """Write a string to the default output"""
2499 """Write a string to the default output"""
2510 Term.cout.write(data)
2500 Term.cout.write(data)
2511
2501
2512 def write_err(self,data):
2502 def write_err(self,data):
2513 """Write a string to the default error output"""
2503 """Write a string to the default error output"""
2514 Term.cerr.write(data)
2504 Term.cerr.write(data)
2515
2505
2516 def ask_exit(self):
2506 def ask_exit(self):
2517 """ Call for exiting. Can be overiden and used as a callback. """
2507 """ Call for exiting. Can be overiden and used as a callback. """
2518 self.exit_now = True
2508 self.exit_now = True
2519
2509
2520 def exit(self):
2510 def exit(self):
2521 """Handle interactive exit.
2511 """Handle interactive exit.
2522
2512
2523 This method calls the ask_exit callback."""
2513 This method calls the ask_exit callback."""
2524
2514
2525 if self.rc.confirm_exit:
2515 if self.rc.confirm_exit:
2526 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2516 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2527 self.ask_exit()
2517 self.ask_exit()
2528 else:
2518 else:
2529 self.ask_exit()
2519 self.ask_exit()
2530
2520
2531 def safe_execfile(self,fname,*where,**kw):
2521 def safe_execfile(self,fname,*where,**kw):
2532 """A safe version of the builtin execfile().
2522 """A safe version of the builtin execfile().
2533
2523
2534 This version will never throw an exception, and knows how to handle
2524 This version will never throw an exception, and knows how to handle
2535 ipython logs as well.
2525 ipython logs as well.
2536
2526
2537 :Parameters:
2527 :Parameters:
2538 fname : string
2528 fname : string
2539 Name of the file to be executed.
2529 Name of the file to be executed.
2540
2530
2541 where : tuple
2531 where : tuple
2542 One or two namespaces, passed to execfile() as (globals,locals).
2532 One or two namespaces, passed to execfile() as (globals,locals).
2543 If only one is given, it is passed as both.
2533 If only one is given, it is passed as both.
2544
2534
2545 :Keywords:
2535 :Keywords:
2546 islog : boolean (False)
2536 islog : boolean (False)
2547
2537
2548 quiet : boolean (True)
2538 quiet : boolean (True)
2549
2539
2550 exit_ignore : boolean (False)
2540 exit_ignore : boolean (False)
2551 """
2541 """
2552
2542
2553 def syspath_cleanup():
2543 def syspath_cleanup():
2554 """Internal cleanup routine for sys.path."""
2544 """Internal cleanup routine for sys.path."""
2555 if add_dname:
2545 if add_dname:
2556 try:
2546 try:
2557 sys.path.remove(dname)
2547 sys.path.remove(dname)
2558 except ValueError:
2548 except ValueError:
2559 # For some reason the user has already removed it, ignore.
2549 # For some reason the user has already removed it, ignore.
2560 pass
2550 pass
2561
2551
2562 fname = os.path.expanduser(fname)
2552 fname = os.path.expanduser(fname)
2563
2553
2564 # Find things also in current directory. This is needed to mimic the
2554 # Find things also in current directory. This is needed to mimic the
2565 # behavior of running a script from the system command line, where
2555 # behavior of running a script from the system command line, where
2566 # Python inserts the script's directory into sys.path
2556 # Python inserts the script's directory into sys.path
2567 dname = os.path.dirname(os.path.abspath(fname))
2557 dname = os.path.dirname(os.path.abspath(fname))
2568 add_dname = False
2558 add_dname = False
2569 if dname not in sys.path:
2559 if dname not in sys.path:
2570 sys.path.insert(0,dname)
2560 sys.path.insert(0,dname)
2571 add_dname = True
2561 add_dname = True
2572
2562
2573 try:
2563 try:
2574 xfile = open(fname)
2564 xfile = open(fname)
2575 except:
2565 except:
2576 print >> Term.cerr, \
2566 print >> Term.cerr, \
2577 'Could not open file <%s> for safe execution.' % fname
2567 'Could not open file <%s> for safe execution.' % fname
2578 syspath_cleanup()
2568 syspath_cleanup()
2579 return None
2569 return None
2580
2570
2581 kw.setdefault('islog',0)
2571 kw.setdefault('islog',0)
2582 kw.setdefault('quiet',1)
2572 kw.setdefault('quiet',1)
2583 kw.setdefault('exit_ignore',0)
2573 kw.setdefault('exit_ignore',0)
2584
2574
2585 first = xfile.readline()
2575 first = xfile.readline()
2586 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2576 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2587 xfile.close()
2577 xfile.close()
2588 # line by line execution
2578 # line by line execution
2589 if first.startswith(loghead) or kw['islog']:
2579 if first.startswith(loghead) or kw['islog']:
2590 print 'Loading log file <%s> one line at a time...' % fname
2580 print 'Loading log file <%s> one line at a time...' % fname
2591 if kw['quiet']:
2581 if kw['quiet']:
2592 stdout_save = sys.stdout
2582 stdout_save = sys.stdout
2593 sys.stdout = StringIO.StringIO()
2583 sys.stdout = StringIO.StringIO()
2594 try:
2584 try:
2595 globs,locs = where[0:2]
2585 globs,locs = where[0:2]
2596 except:
2586 except:
2597 try:
2587 try:
2598 globs = locs = where[0]
2588 globs = locs = where[0]
2599 except:
2589 except:
2600 globs = locs = globals()
2590 globs = locs = globals()
2601 badblocks = []
2591 badblocks = []
2602
2592
2603 # we also need to identify indented blocks of code when replaying
2593 # we also need to identify indented blocks of code when replaying
2604 # logs and put them together before passing them to an exec
2594 # logs and put them together before passing them to an exec
2605 # statement. This takes a bit of regexp and look-ahead work in the
2595 # statement. This takes a bit of regexp and look-ahead work in the
2606 # file. It's easiest if we swallow the whole thing in memory
2596 # file. It's easiest if we swallow the whole thing in memory
2607 # first, and manually walk through the lines list moving the
2597 # first, and manually walk through the lines list moving the
2608 # counter ourselves.
2598 # counter ourselves.
2609 indent_re = re.compile('\s+\S')
2599 indent_re = re.compile('\s+\S')
2610 xfile = open(fname)
2600 xfile = open(fname)
2611 filelines = xfile.readlines()
2601 filelines = xfile.readlines()
2612 xfile.close()
2602 xfile.close()
2613 nlines = len(filelines)
2603 nlines = len(filelines)
2614 lnum = 0
2604 lnum = 0
2615 while lnum < nlines:
2605 while lnum < nlines:
2616 line = filelines[lnum]
2606 line = filelines[lnum]
2617 lnum += 1
2607 lnum += 1
2618 # don't re-insert logger status info into cache
2608 # don't re-insert logger status info into cache
2619 if line.startswith('#log#'):
2609 if line.startswith('#log#'):
2620 continue
2610 continue
2621 else:
2611 else:
2622 # build a block of code (maybe a single line) for execution
2612 # build a block of code (maybe a single line) for execution
2623 block = line
2613 block = line
2624 try:
2614 try:
2625 next = filelines[lnum] # lnum has already incremented
2615 next = filelines[lnum] # lnum has already incremented
2626 except:
2616 except:
2627 next = None
2617 next = None
2628 while next and indent_re.match(next):
2618 while next and indent_re.match(next):
2629 block += next
2619 block += next
2630 lnum += 1
2620 lnum += 1
2631 try:
2621 try:
2632 next = filelines[lnum]
2622 next = filelines[lnum]
2633 except:
2623 except:
2634 next = None
2624 next = None
2635 # now execute the block of one or more lines
2625 # now execute the block of one or more lines
2636 try:
2626 try:
2637 exec block in globs,locs
2627 exec block in globs,locs
2638 except SystemExit:
2628 except SystemExit:
2639 pass
2629 pass
2640 except:
2630 except:
2641 badblocks.append(block.rstrip())
2631 badblocks.append(block.rstrip())
2642 if kw['quiet']: # restore stdout
2632 if kw['quiet']: # restore stdout
2643 sys.stdout.close()
2633 sys.stdout.close()
2644 sys.stdout = stdout_save
2634 sys.stdout = stdout_save
2645 print 'Finished replaying log file <%s>' % fname
2635 print 'Finished replaying log file <%s>' % fname
2646 if badblocks:
2636 if badblocks:
2647 print >> sys.stderr, ('\nThe following lines/blocks in file '
2637 print >> sys.stderr, ('\nThe following lines/blocks in file '
2648 '<%s> reported errors:' % fname)
2638 '<%s> reported errors:' % fname)
2649
2639
2650 for badline in badblocks:
2640 for badline in badblocks:
2651 print >> sys.stderr, badline
2641 print >> sys.stderr, badline
2652 else: # regular file execution
2642 else: # regular file execution
2653 try:
2643 try:
2654 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2644 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2655 # Work around a bug in Python for Windows. The bug was
2645 # Work around a bug in Python for Windows. The bug was
2656 # fixed in in Python 2.5 r54159 and 54158, but that's still
2646 # fixed in in Python 2.5 r54159 and 54158, but that's still
2657 # SVN Python as of March/07. For details, see:
2647 # SVN Python as of March/07. For details, see:
2658 # http://projects.scipy.org/ipython/ipython/ticket/123
2648 # http://projects.scipy.org/ipython/ipython/ticket/123
2659 try:
2649 try:
2660 globs,locs = where[0:2]
2650 globs,locs = where[0:2]
2661 except:
2651 except:
2662 try:
2652 try:
2663 globs = locs = where[0]
2653 globs = locs = where[0]
2664 except:
2654 except:
2665 globs = locs = globals()
2655 globs = locs = globals()
2666 exec file(fname) in globs,locs
2656 exec file(fname) in globs,locs
2667 else:
2657 else:
2668 execfile(fname,*where)
2658 execfile(fname,*where)
2669 except SyntaxError:
2659 except SyntaxError:
2670 self.showsyntaxerror()
2660 self.showsyntaxerror()
2671 warn('Failure executing file: <%s>' % fname)
2661 warn('Failure executing file: <%s>' % fname)
2672 except SystemExit,status:
2662 except SystemExit,status:
2673 # Code that correctly sets the exit status flag to success (0)
2663 # Code that correctly sets the exit status flag to success (0)
2674 # shouldn't be bothered with a traceback. Note that a plain
2664 # shouldn't be bothered with a traceback. Note that a plain
2675 # sys.exit() does NOT set the message to 0 (it's empty) so that
2665 # sys.exit() does NOT set the message to 0 (it's empty) so that
2676 # will still get a traceback. Note that the structure of the
2666 # will still get a traceback. Note that the structure of the
2677 # SystemExit exception changed between Python 2.4 and 2.5, so
2667 # SystemExit exception changed between Python 2.4 and 2.5, so
2678 # the checks must be done in a version-dependent way.
2668 # the checks must be done in a version-dependent way.
2679 show = False
2669 show = False
2680
2670
2681 if sys.version_info[:2] > (2,5):
2671 if sys.version_info[:2] > (2,5):
2682 if status.message!=0 and not kw['exit_ignore']:
2672 if status.message!=0 and not kw['exit_ignore']:
2683 show = True
2673 show = True
2684 else:
2674 else:
2685 if status.code and not kw['exit_ignore']:
2675 if status.code and not kw['exit_ignore']:
2686 show = True
2676 show = True
2687 if show:
2677 if show:
2688 self.showtraceback()
2678 self.showtraceback()
2689 warn('Failure executing file: <%s>' % fname)
2679 warn('Failure executing file: <%s>' % fname)
2690 except:
2680 except:
2691 self.showtraceback()
2681 self.showtraceback()
2692 warn('Failure executing file: <%s>' % fname)
2682 warn('Failure executing file: <%s>' % fname)
2693
2683
2694 syspath_cleanup()
2684 syspath_cleanup()
2695
2685
2696 #************************* end of file <iplib.py> *****************************
2686 #************************* end of file <iplib.py> *****************************
General Comments 0
You need to be logged in to leave comments. Login now