##// END OF EJS Templates
More work on InteractiveShell and ipmaker. It works!
Brian Granger -
Show More

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

@@ -1,316 +1,318 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 The main IPython application object
4 The main IPython application object
5
5
6 Authors:
6 Authors:
7
7
8 * Brian Granger
8 * Brian Granger
9 * Fernando Perez
9 * Fernando Perez
10
10
11 Notes
11 Notes
12 -----
12 -----
13 """
13 """
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Copyright (C) 2008-2009 The IPython Development Team
16 # Copyright (C) 2008-2009 The IPython Development Team
17 #
17 #
18 # Distributed under the terms of the BSD License. The full license is in
18 # Distributed under the terms of the BSD License. The full license is in
19 # the file COPYING, distributed as part of this software.
19 # the file COPYING, distributed as part of this software.
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21
21
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23 # Imports
23 # Imports
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25
25
26 import os
26 import os
27 import sys
27 import sys
28 import warnings
28 import warnings
29
29
30 from IPython.core.application import Application
30 from IPython.core.application import Application
31 from IPython.core import release
31 from IPython.core import release
32 from IPython.core.iplib import InteractiveShell
32 from IPython.core.iplib import InteractiveShell
33 from IPython.config.loader import IPythonArgParseConfigLoader, NoDefault
33 from IPython.config.loader import IPythonArgParseConfigLoader, NoDefault
34
34
35 from IPython.utils.ipstruct import Struct
35 from IPython.utils.ipstruct import Struct
36
36
37
37
38 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
39 # Utilities and helpers
39 # Utilities and helpers
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41
41
42
42
43 ipython_desc = """
43 ipython_desc = """
44 A Python shell with automatic history (input and output), dynamic object
44 A Python shell with automatic history (input and output), dynamic object
45 introspection, easier configuration, command completion, access to the system
45 introspection, easier configuration, command completion, access to the system
46 shell and more.
46 shell and more.
47 """
47 """
48
48
49 def threaded_shell_warning():
49 def threaded_shell_warning():
50 msg = """
50 msg = """
51
51
52 The IPython threaded shells and their associated command line
52 The IPython threaded shells and their associated command line
53 arguments (pylab/wthread/gthread/qthread/q4thread) have been
53 arguments (pylab/wthread/gthread/qthread/q4thread) have been
54 deprecated. See the %gui magic for information on the new interface.
54 deprecated. See the %gui magic for information on the new interface.
55 """
55 """
56 warnings.warn(msg, category=DeprecationWarning, stacklevel=1)
56 warnings.warn(msg, category=DeprecationWarning, stacklevel=1)
57
57
58
58
59 #-----------------------------------------------------------------------------
59 #-----------------------------------------------------------------------------
60 # Main classes and functions
60 # Main classes and functions
61 #-----------------------------------------------------------------------------
61 #-----------------------------------------------------------------------------
62
62
63 cl_args = (
63 cl_args = (
64 (('-autocall',), dict(
64 (('-autocall',), dict(
65 type=int, dest='AUTOCALL', default=NoDefault,
65 type=int, dest='AUTOCALL', default=NoDefault,
66 help='Set the autocall value (0,1,2).')
66 help='Set the autocall value (0,1,2).')
67 ),
67 ),
68 (('-autoindent',), dict(
68 (('-autoindent',), dict(
69 action='store_true', dest='AUTOINDENT', default=NoDefault,
69 action='store_true', dest='AUTOINDENT', default=NoDefault,
70 help='Turn on autoindenting.')
70 help='Turn on autoindenting.')
71 ),
71 ),
72 (('-noautoindent',), dict(
72 (('-noautoindent',), dict(
73 action='store_false', dest='AUTOINDENT', default=NoDefault,
73 action='store_false', dest='AUTOINDENT', default=NoDefault,
74 help='Turn off autoindenting.')
74 help='Turn off autoindenting.')
75 ),
75 ),
76 (('-automagic',), dict(
76 (('-automagic',), dict(
77 action='store_true', dest='AUTOMAGIC', default=NoDefault,
77 action='store_true', dest='AUTOMAGIC', default=NoDefault,
78 help='Turn on the auto calling of magic commands.')
78 help='Turn on the auto calling of magic commands.')
79 ),
79 ),
80 (('-noautomagic',), dict(
80 (('-noautomagic',), dict(
81 action='store_false', dest='AUTOMAGIC', default=NoDefault,
81 action='store_false', dest='AUTOMAGIC', default=NoDefault,
82 help='Turn off the auto calling of magic commands.')
82 help='Turn off the auto calling of magic commands.')
83 ),
83 ),
84 (('-autoedit_syntax',), dict(
84 (('-autoedit_syntax',), dict(
85 action='store_true', dest='AUTOEDIT_SYNTAX', default=NoDefault,
85 action='store_true', dest='AUTOEDIT_SYNTAX', default=NoDefault,
86 help='Turn on auto editing of files with syntax errors.')
86 help='Turn on auto editing of files with syntax errors.')
87 ),
87 ),
88 (('-noautoedit_syntax',), dict(
88 (('-noautoedit_syntax',), dict(
89 action='store_false', dest='AUTOEDIT_SYNTAX', default=NoDefault,
89 action='store_false', dest='AUTOEDIT_SYNTAX', default=NoDefault,
90 help='Turn off auto editing of files with syntax errors.')
90 help='Turn off auto editing of files with syntax errors.')
91 ),
91 ),
92 (('-banner',), dict(
92 (('-banner',), dict(
93 action='store_true', dest='DISPLAY_BANNER', default=NoDefault,
93 action='store_true', dest='DISPLAY_BANNER', default=NoDefault,
94 help='Display a banner upon starting IPython.')
94 help='Display a banner upon starting IPython.')
95 ),
95 ),
96 (('-nobanner',), dict(
96 (('-nobanner',), dict(
97 action='store_false', dest='DISPLAY_BANNER', default=NoDefault,
97 action='store_false', dest='DISPLAY_BANNER', default=NoDefault,
98 help="Don't display a banner upon starting IPython.")
98 help="Don't display a banner upon starting IPython.")
99 ),
99 ),
100 (('-c',), dict(
100 (('-c',), dict(
101 type=str, dest='C', default=NoDefault,
101 type=str, dest='C', default=NoDefault,
102 help="Execute the given command string.")
102 help="Execute the given command string.")
103 ),
103 ),
104 (('-cache_size',), dict(
104 (('-cache_size',), dict(
105 type=int, dest='CACHE_SIZE', default=NoDefault,
105 type=int, dest='CACHE_SIZE', default=NoDefault,
106 help="Set the size of the output cache.")
106 help="Set the size of the output cache.")
107 ),
107 ),
108 (('-classic',), dict(
108 (('-classic',), dict(
109 action='store_true', dest='CLASSIC', default=NoDefault,
109 action='store_true', dest='CLASSIC', default=NoDefault,
110 help="Gives IPython a similar feel to the classic Python prompt.")
110 help="Gives IPython a similar feel to the classic Python prompt.")
111 ),
111 ),
112 (('-colors',), dict(
112 (('-colors',), dict(
113 type=str, dest='COLORS', default=NoDefault,
113 type=str, dest='COLORS', default=NoDefault,
114 help="Set the color scheme (NoColor, Linux, and LightBG).")
114 help="Set the color scheme (NoColor, Linux, and LightBG).")
115 ),
115 ),
116 (('-color_info',), dict(
116 (('-color_info',), dict(
117 action='store_true', dest='COLOR_INFO', default=NoDefault,
117 action='store_true', dest='COLOR_INFO', default=NoDefault,
118 help="Enable using colors for info related things.")
118 help="Enable using colors for info related things.")
119 ),
119 ),
120 (('-nocolor_info',), dict(
120 (('-nocolor_info',), dict(
121 action='store_false', dest='COLOR_INFO', default=NoDefault,
121 action='store_false', dest='COLOR_INFO', default=NoDefault,
122 help="Disable using colors for info related things.")
122 help="Disable using colors for info related things.")
123 ),
123 ),
124 (('-confirm_exit',), dict(
124 (('-confirm_exit',), dict(
125 action='store_true', dest='CONFIRM_EXIT', default=NoDefault,
125 action='store_true', dest='CONFIRM_EXIT', default=NoDefault,
126 help="Prompt the user when existing.")
126 help="Prompt the user when existing.")
127 ),
127 ),
128 (('-noconfirm_exit',), dict(
128 (('-noconfirm_exit',), dict(
129 action='store_false', dest='CONFIRM_EXIT', default=NoDefault,
129 action='store_false', dest='CONFIRM_EXIT', default=NoDefault,
130 help="Don't prompt the user when existing.")
130 help="Don't prompt the user when existing.")
131 ),
131 ),
132 (('-deep_reload',), dict(
132 (('-deep_reload',), dict(
133 action='store_true', dest='DEEP_RELOAD', default=NoDefault,
133 action='store_true', dest='DEEP_RELOAD', default=NoDefault,
134 help="Enable deep (recursive) reloading by default.")
134 help="Enable deep (recursive) reloading by default.")
135 ),
135 ),
136 (('-nodeep_reload',), dict(
136 (('-nodeep_reload',), dict(
137 action='store_false', dest='DEEP_RELOAD', default=NoDefault,
137 action='store_false', dest='DEEP_RELOAD', default=NoDefault,
138 help="Disable deep (recursive) reloading by default.")
138 help="Disable deep (recursive) reloading by default.")
139 ),
139 ),
140 (('-editor',), dict(
140 (('-editor',), dict(
141 type=str, dest='EDITOR', default=NoDefault,
141 type=str, dest='EDITOR', default=NoDefault,
142 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).")
142 help="Set the editor used by IPython (default to $EDITOR/vi/notepad).")
143 ),
143 ),
144 (('-log','-l'), dict(
144 (('-log','-l'), dict(
145 action='store_true', dest='LOGSTART', default=NoDefault,
145 action='store_true', dest='LOGSTART', default=NoDefault,
146 help="Start logging to the default file (./ipython_log.py).")
146 help="Start logging to the default file (./ipython_log.py).")
147 ),
147 ),
148 (('-logfile','-lf'), dict(
148 (('-logfile','-lf'), dict(
149 type=str, dest='LOGFILE', default=NoDefault,
149 type=str, dest='LOGFILE', default=NoDefault,
150 help="Specify the name of your logfile.")
150 help="Specify the name of your logfile.")
151 ),
151 ),
152 (('-logplay','-lp'), dict(
152 (('-logplay','-lp'), dict(
153 type=str, dest='LOGPLAY', default=NoDefault,
153 type=str, dest='LOGPLAY', default=NoDefault,
154 help="Re-play a log file and then append to it.")
154 help="Re-play a log file and then append to it.")
155 ),
155 ),
156 (('-pdb',), dict(
156 (('-pdb',), dict(
157 action='store_true', dest='PDB', default=NoDefault,
157 action='store_true', dest='PDB', default=NoDefault,
158 help="Enable auto calling the pdb debugger after every exception.")
158 help="Enable auto calling the pdb debugger after every exception.")
159 ),
159 ),
160 (('-nopdb',), dict(
160 (('-nopdb',), dict(
161 action='store_false', dest='PDB', default=NoDefault,
161 action='store_false', dest='PDB', default=NoDefault,
162 help="Disable auto calling the pdb debugger after every exception.")
162 help="Disable auto calling the pdb debugger after every exception.")
163 ),
163 ),
164 (('-pprint',), dict(
164 (('-pprint',), dict(
165 action='store_true', dest='PPRINT', default=NoDefault,
165 action='store_true', dest='PPRINT', default=NoDefault,
166 help="Enable auto pretty printing of results.")
166 help="Enable auto pretty printing of results.")
167 ),
167 ),
168 (('-nopprint',), dict(
168 (('-nopprint',), dict(
169 action='store_false', dest='PPRINT', default=NoDefault,
169 action='store_false', dest='PPRINT', default=NoDefault,
170 help="Disable auto auto pretty printing of results.")
170 help="Disable auto auto pretty printing of results.")
171 ),
171 ),
172 (('-prompt_in1','-pi1'), dict(
172 (('-prompt_in1','-pi1'), dict(
173 type=str, dest='PROMPT_IN1', default=NoDefault,
173 type=str, dest='PROMPT_IN1', default=NoDefault,
174 help="Set the main input prompt ('In [\#]: ')")
174 help="Set the main input prompt ('In [\#]: ')")
175 ),
175 ),
176 (('-prompt_in2','-pi2'), dict(
176 (('-prompt_in2','-pi2'), dict(
177 type=str, dest='PROMPT_IN2', default=NoDefault,
177 type=str, dest='PROMPT_IN2', default=NoDefault,
178 help="Set the secondary input prompt (' .\D.: ')")
178 help="Set the secondary input prompt (' .\D.: ')")
179 ),
179 ),
180 (('-prompt_out','-po'), dict(
180 (('-prompt_out','-po'), dict(
181 type=str, dest='PROMPT_OUT', default=NoDefault,
181 type=str, dest='PROMPT_OUT', default=NoDefault,
182 help="Set the output prompt ('Out[\#]:')")
182 help="Set the output prompt ('Out[\#]:')")
183 ),
183 ),
184 (('-quick',), dict(
184 (('-quick',), dict(
185 action='store_true', dest='QUICK', default=NoDefault,
185 action='store_true', dest='QUICK', default=NoDefault,
186 help="Enable quick startup with no config files.")
186 help="Enable quick startup with no config files.")
187 ),
187 ),
188 (('-readline',), dict(
188 (('-readline',), dict(
189 action='store_true', dest='READLINE_USE', default=NoDefault,
189 action='store_true', dest='READLINE_USE', default=NoDefault,
190 help="Enable readline for command line usage.")
190 help="Enable readline for command line usage.")
191 ),
191 ),
192 (('-noreadline',), dict(
192 (('-noreadline',), dict(
193 action='store_false', dest='READLINE_USE', default=NoDefault,
193 action='store_false', dest='READLINE_USE', default=NoDefault,
194 help="Disable readline for command line usage.")
194 help="Disable readline for command line usage.")
195 ),
195 ),
196 (('-screen_length','-sl'), dict(
196 (('-screen_length','-sl'), dict(
197 type=int, dest='SCREEN_LENGTH', default=NoDefault,
197 type=int, dest='SCREEN_LENGTH', default=NoDefault,
198 help='Number of lines on screen, used to control printing of long strings.')
198 help='Number of lines on screen, used to control printing of long strings.')
199 ),
199 ),
200 (('-separate_in','-si'), dict(
200 (('-separate_in','-si'), dict(
201 type=str, dest='SEPARATE_IN', default=NoDefault,
201 type=str, dest='SEPARATE_IN', default=NoDefault,
202 help="Separator before input prompts. Default '\n'.")
202 help="Separator before input prompts. Default '\n'.")
203 ),
203 ),
204 (('-separate_out','-so'), dict(
204 (('-separate_out','-so'), dict(
205 type=str, dest='SEPARATE_OUT', default=NoDefault,
205 type=str, dest='SEPARATE_OUT', default=NoDefault,
206 help="Separator before output prompts. Default 0 (nothing).")
206 help="Separator before output prompts. Default 0 (nothing).")
207 ),
207 ),
208 (('-separate_out2','-so2'), dict(
208 (('-separate_out2','-so2'), dict(
209 type=str, dest='SEPARATE_OUT2', default=NoDefault,
209 type=str, dest='SEPARATE_OUT2', default=NoDefault,
210 help="Separator after output prompts. Default 0 (nonight).")
210 help="Separator after output prompts. Default 0 (nonight).")
211 ),
211 ),
212 (('-nosep',), dict(
212 (('-nosep',), dict(
213 action='store_true', dest='NOSEP', default=NoDefault,
213 action='store_true', dest='NOSEP', default=NoDefault,
214 help="Eliminate all spacing between prompts.")
214 help="Eliminate all spacing between prompts.")
215 ),
215 ),
216 (('-term_title',), dict(
217 action='store_true', dest='TERM_TITLE', default=NoDefault,
218 help="Enable auto setting the terminal title.")
219 ),
220 (('-noterm_title',), dict(
221 action='store_false', dest='TERM_TITLE', default=NoDefault,
222 help="Disable auto setting the terminal title.")
223 ),
216 (('-xmode',), dict(
224 (('-xmode',), dict(
217 type=str, dest='XMODE', default=NoDefault,
225 type=str, dest='XMODE', default=NoDefault,
218 help="Exception mode ('Plain','Context','Verbose')")
226 help="Exception mode ('Plain','Context','Verbose')")
219 ),
227 ),
228 # These are only here to get the proper deprecation warnings
229 (('-pylab','-wthread','-qthread','-q4thread','-gthread'), dict(
230 action='store_true', dest='THREADED_SHELL', default=NoDefault,
231 help="These command line flags are deprecated, see the 'gui' magic.")
232 ),
220 )
233 )
221
234
222
235
223 class IPythonAppCLConfigLoader(IPythonArgParseConfigLoader):
236 class IPythonAppCLConfigLoader(IPythonArgParseConfigLoader):
224
237
225 arguments = cl_args
238 arguments = cl_args
226
239
227
240
228 class IPythonApp(Application):
241 class IPythonApp(Application):
229 name = 'ipython'
242 name = 'ipython'
230 config_file_name = 'ipython_config.py'
243 config_file_name = 'ipython_config.py'
231
244
232 def create_command_line_config(self):
245 def create_command_line_config(self):
233 """Create and return a command line config loader."""
246 """Create and return a command line config loader."""
234 return IPythonAppCLConfigLoader(
247 return IPythonAppCLConfigLoader(
235 description=ipython_desc,
248 description=ipython_desc,
236 version=release.version)
249 version=release.version)
237
250
238 def post_load_command_line_config(self):
251 def post_load_command_line_config(self):
239 """Do actions after loading cl config."""
252 """Do actions after loading cl config."""
240 clc = self.command_line_config
253 clc = self.command_line_config
241
254
242 # This needs to be set here, the rest are set in pre_construct.
255 # This needs to be set here, the rest are set in pre_construct.
243 if hasattr(clc, 'CLASSIC'):
256 if hasattr(clc, 'CLASSIC'):
244 if clc.CLASSIC: clc.QUICK = 1
257 if clc.CLASSIC: clc.QUICK = 1
245
258
246 # Display the deprecation warnings about threaded shells
259 # Display the deprecation warnings about threaded shells
247 # if opts_all.pylab == 1: threaded_shell_warning()
260 if hasattr(clc, 'THREADED_SHELL'):
248 # if opts_all.wthread == 1: threaded_shell_warning()
261 threaded_shell_warning()
249 # if opts_all.qthread == 1: threaded_shell_warning()
262 del clc['THREADED_SHELL']
250 # if opts_all.q4thread == 1: threaded_shell_warning()
251 # if opts_all.gthread == 1: threaded_shell_warning()
252
263
253 def load_file_config(self):
264 def load_file_config(self):
254 if hasattr(self.command_line_config, 'QUICK'):
265 if hasattr(self.command_line_config, 'QUICK'):
255 if self.command_line_config.QUICK:
266 if self.command_line_config.QUICK:
256 self.file_config = Struct()
267 self.file_config = Struct()
257 return
268 return
258 super(IPythonApp, self).load_file_config()
269 super(IPythonApp, self).load_file_config()
259
270
260 def post_load_file_config(self):
271 def post_load_file_config(self):
261 """Logic goes here."""
272 """Logic goes here."""
262
273
263 def pre_construct(self):
274 def pre_construct(self):
264 config = self.master_config
275 config = self.master_config
265
276
266 if hasattr(config, 'CLASSIC'):
277 if hasattr(config, 'CLASSIC'):
267 if config.CLASSIC:
278 if config.CLASSIC:
268 config.QUICK = 1
279 config.QUICK = 1
269 config.CACHE_SIZE = 0
280 config.CACHE_SIZE = 0
270 config.PPRINT = 0
281 config.PPRINT = 0
271 config.PROMPT_IN1 = '>>> '
282 config.PROMPT_IN1 = '>>> '
272 config.PROMPT_IN2 = '... '
283 config.PROMPT_IN2 = '... '
273 config.PROMPT_OUT = ''
284 config.PROMPT_OUT = ''
274 config.SEPARATE_IN = config.SEPARATE_OUT = config.SEPARATE_OUT2 = ''
285 config.SEPARATE_IN = config.SEPARATE_OUT = config.SEPARATE_OUT2 = ''
275 config.COLORS = 'NoColor'
286 config.COLORS = 'NoColor'
276 config.XMODE = 'Plain'
287 config.XMODE = 'Plain'
277
288
278 # All this should be moved to traitlet handlers in InteractiveShell
289 # All this should be moved to traitlet handlers in InteractiveShell
290 # But, currently InteractiveShell doesn't have support for changing
291 # these values at runtime. Once we support that, this should
292 # be moved there!!!
279 if hasattr(config, 'NOSEP'):
293 if hasattr(config, 'NOSEP'):
280 if config.NOSEP:
294 if config.NOSEP:
281 config.SEPARATE_IN = config.SEPARATE_OUT = config.SEPARATE_OUT2 = '0'
295 config.SEPARATE_IN = config.SEPARATE_OUT = config.SEPARATE_OUT2 = '0'
282
296
283 if hasattr(config, 'SEPARATE_IN'):
284 if config.SEPARATE_IN == '0': config.SEPARATE_IN = ''
285 config.SEPARATE_IN = config.SEPARATE_IN.replace('\\n','\n')
286
287 if hasattr(config, 'SEPARATE_OUT'):
288 if config.SEPARATE_OUT == '0': config.SEPARATE_OUT = ''
289 config.SEPARATE_OUT = config.SEPARATE_OUT.replace('\\n','\n')
290
291 if hasattr(config, 'SEPARATE_OUT'):
292 if config.SEPARATE_OUT2 == '0': config.SEPARATE_OUT2 = ''
293 config.SEPARATE_OUT2 = config.SEPARATE_OUT2.replace('\\n','\n')
294
295 def construct(self):
297 def construct(self):
296 # I am a little hesitant to put these into InteractiveShell itself.
298 # I am a little hesitant to put these into InteractiveShell itself.
297 # But that might be the place for them
299 # But that might be the place for them
298 sys.path.insert(0, '')
300 sys.path.insert(0, '')
299 # add personal ipythondir to sys.path so that users can put things in
301 # add personal ipythondir to sys.path so that users can put things in
300 # there for customization
302 # there for customization
301 sys.path.append(os.path.abspath(self.ipythondir))
303 sys.path.append(os.path.abspath(self.ipythondir))
302
304
303 # Create an InteractiveShell instance
305 # Create an InteractiveShell instance
304 self.shell = InteractiveShell(
306 self.shell = InteractiveShell(
305 name='__IP',
307 name='__IP',
306 parent=None,
308 parent=None,
307 config=self.master_config
309 config=self.master_config
308 )
310 )
309
311
310 def start_app(self):
312 def start_app(self):
311 self.shell.mainloop()
313 self.shell.mainloop()
312
314
313
315
314 if __name__ == '__main__':
316 if __name__ == '__main__':
315 app = IPythonApp()
317 app = IPythonApp()
316 app.start() No newline at end of file
318 app.start()
@@ -1,2809 +1,2840 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Main IPython Component
3 Main IPython Component
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
7 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
8 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
9 # Copyright (C) 2008-2009 The IPython Development Team
9 # Copyright (C) 2008-2009 The IPython Development Team
10 #
10 #
11 # Distributed under the terms of the BSD License. The full license is in
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
12 # the file COPYING, distributed as part of this software.
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Imports
16 # Imports
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 import __main__
19 import __main__
20 import __builtin__
20 import __builtin__
21 import StringIO
21 import StringIO
22 import bdb
22 import bdb
23 import codeop
23 import codeop
24 import exceptions
24 import exceptions
25 import glob
25 import glob
26 import keyword
26 import keyword
27 import new
27 import new
28 import os
28 import os
29 import re
29 import re
30 import shutil
30 import shutil
31 import string
31 import string
32 import sys
32 import sys
33 import tempfile
33 import tempfile
34
34
35 from IPython.core import ultratb
35 from IPython.core import ultratb
36 from IPython.core import debugger, oinspect
36 from IPython.core import debugger, oinspect
37 from IPython.core import ipapi
37 from IPython.core import ipapi
38 from IPython.core import shadowns
38 from IPython.core import shadowns
39 from IPython.core import history as ipcorehist
39 from IPython.core import history as ipcorehist
40 from IPython.core import prefilter
40 from IPython.core import prefilter
41 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
41 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
42 from IPython.core.logger import Logger
42 from IPython.core.logger import Logger
43 from IPython.core.magic import Magic
43 from IPython.core.magic import Magic
44 from IPython.core.prompts import CachedOutput
44 from IPython.core.prompts import CachedOutput
45 from IPython.core.component import Component
45 from IPython.core.component import Component
46 from IPython.core.oldusersetup import user_setup
46 from IPython.core.oldusersetup import user_setup
47 from IPython.core.usage import interactive_usage, default_banner
47 from IPython.core.usage import interactive_usage, default_banner
48
48
49 from IPython.extensions import pickleshare
49 from IPython.extensions import pickleshare
50 from IPython.external.Itpl import ItplNS
50 from IPython.external.Itpl import ItplNS
51 from IPython.lib.backgroundjobs import BackgroundJobManager
51 from IPython.lib.backgroundjobs import BackgroundJobManager
52 from IPython.utils.ipstruct import Struct
52 from IPython.utils.ipstruct import Struct
53 from IPython.utils import PyColorize
53 from IPython.utils import PyColorize
54 from IPython.utils.genutils import *
54 from IPython.utils.genutils import *
55 from IPython.utils.strdispatch import StrDispatch
55 from IPython.utils.strdispatch import StrDispatch
56 from IPython.utils.platutils import toggle_set_term_title, set_term_title
56
57
57 from IPython.utils.traitlets import (
58 from IPython.utils.traitlets import (
58 Int, Float, Str, CBool, CaselessStrEnum, Enum
59 Int, Float, Str, CBool, CaselessStrEnum, Enum, List
59 )
60 )
60
61
61 #-----------------------------------------------------------------------------
62 #-----------------------------------------------------------------------------
62 # Globals
63 # Globals
63 #-----------------------------------------------------------------------------
64 #-----------------------------------------------------------------------------
64
65
65
66
66 # store the builtin raw_input globally, and use this always, in case user code
67 # store the builtin raw_input globally, and use this always, in case user code
67 # overwrites it (like wx.py.PyShell does)
68 # overwrites it (like wx.py.PyShell does)
68 raw_input_original = raw_input
69 raw_input_original = raw_input
69
70
70 # compiled regexps for autoindent management
71 # compiled regexps for autoindent management
71 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
72 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
72
73
73
74
74 #-----------------------------------------------------------------------------
75 #-----------------------------------------------------------------------------
75 # Utilities
76 # Utilities
76 #-----------------------------------------------------------------------------
77 #-----------------------------------------------------------------------------
77
78
78
79
79 ini_spaces_re = re.compile(r'^(\s+)')
80 ini_spaces_re = re.compile(r'^(\s+)')
80
81
81
82
82 def num_ini_spaces(strng):
83 def num_ini_spaces(strng):
83 """Return the number of initial spaces in a string"""
84 """Return the number of initial spaces in a string"""
84
85
85 ini_spaces = ini_spaces_re.match(strng)
86 ini_spaces = ini_spaces_re.match(strng)
86 if ini_spaces:
87 if ini_spaces:
87 return ini_spaces.end()
88 return ini_spaces.end()
88 else:
89 else:
89 return 0
90 return 0
90
91
91
92
92 def softspace(file, newvalue):
93 def softspace(file, newvalue):
93 """Copied from code.py, to remove the dependency"""
94 """Copied from code.py, to remove the dependency"""
94
95
95 oldvalue = 0
96 oldvalue = 0
96 try:
97 try:
97 oldvalue = file.softspace
98 oldvalue = file.softspace
98 except AttributeError:
99 except AttributeError:
99 pass
100 pass
100 try:
101 try:
101 file.softspace = newvalue
102 file.softspace = newvalue
102 except (AttributeError, TypeError):
103 except (AttributeError, TypeError):
103 # "attribute-less object" or "read-only attributes"
104 # "attribute-less object" or "read-only attributes"
104 pass
105 pass
105 return oldvalue
106 return oldvalue
106
107
107
108
108 class SpaceInInput(exceptions.Exception): pass
109 class SpaceInInput(exceptions.Exception): pass
109
110
110 class Bunch: pass
111 class Bunch: pass
111
112
112 class Undefined: pass
113 class Undefined: pass
113
114
114 class Quitter(object):
115 class Quitter(object):
115 """Simple class to handle exit, similar to Python 2.5's.
116 """Simple class to handle exit, similar to Python 2.5's.
116
117
117 It handles exiting in an ipython-safe manner, which the one in Python 2.5
118 It handles exiting in an ipython-safe manner, which the one in Python 2.5
118 doesn't do (obviously, since it doesn't know about ipython)."""
119 doesn't do (obviously, since it doesn't know about ipython)."""
119
120
120 def __init__(self,shell,name):
121 def __init__(self,shell,name):
121 self.shell = shell
122 self.shell = shell
122 self.name = name
123 self.name = name
123
124
124 def __repr__(self):
125 def __repr__(self):
125 return 'Type %s() to exit.' % self.name
126 return 'Type %s() to exit.' % self.name
126 __str__ = __repr__
127 __str__ = __repr__
127
128
128 def __call__(self):
129 def __call__(self):
129 self.shell.exit()
130 self.shell.exit()
130
131
131 class InputList(list):
132 class InputList(list):
132 """Class to store user input.
133 """Class to store user input.
133
134
134 It's basically a list, but slices return a string instead of a list, thus
135 It's basically a list, but slices return a string instead of a list, thus
135 allowing things like (assuming 'In' is an instance):
136 allowing things like (assuming 'In' is an instance):
136
137
137 exec In[4:7]
138 exec In[4:7]
138
139
139 or
140 or
140
141
141 exec In[5:9] + In[14] + In[21:25]"""
142 exec In[5:9] + In[14] + In[21:25]"""
142
143
143 def __getslice__(self,i,j):
144 def __getslice__(self,i,j):
144 return ''.join(list.__getslice__(self,i,j))
145 return ''.join(list.__getslice__(self,i,j))
145
146
146 class SyntaxTB(ultratb.ListTB):
147 class SyntaxTB(ultratb.ListTB):
147 """Extension which holds some state: the last exception value"""
148 """Extension which holds some state: the last exception value"""
148
149
149 def __init__(self,color_scheme = 'NoColor'):
150 def __init__(self,color_scheme = 'NoColor'):
150 ultratb.ListTB.__init__(self,color_scheme)
151 ultratb.ListTB.__init__(self,color_scheme)
151 self.last_syntax_error = None
152 self.last_syntax_error = None
152
153
153 def __call__(self, etype, value, elist):
154 def __call__(self, etype, value, elist):
154 self.last_syntax_error = value
155 self.last_syntax_error = value
155 ultratb.ListTB.__call__(self,etype,value,elist)
156 ultratb.ListTB.__call__(self,etype,value,elist)
156
157
157 def clear_err_state(self):
158 def clear_err_state(self):
158 """Return the current error state and clear it"""
159 """Return the current error state and clear it"""
159 e = self.last_syntax_error
160 e = self.last_syntax_error
160 self.last_syntax_error = None
161 self.last_syntax_error = None
161 return e
162 return e
162
163
163 def get_default_editor():
164 def get_default_editor():
164 try:
165 try:
165 ed = os.environ['EDITOR']
166 ed = os.environ['EDITOR']
166 except KeyError:
167 except KeyError:
167 if os.name == 'posix':
168 if os.name == 'posix':
168 ed = 'vi' # the only one guaranteed to be there!
169 ed = 'vi' # the only one guaranteed to be there!
169 else:
170 else:
170 ed = 'notepad' # same in Windows!
171 ed = 'notepad' # same in Windows!
171 return ed
172 return ed
172
173
174
175 class SeparateStr(Str):
176 """A Str subclass to validate separate_in, separate_out, etc.
177
178 This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'.
179 """
180
181 def validate(self, obj, value):
182 if value == '0': value = ''
183 value = value.replace('\\n','\n')
184 return super(SeparateStr, self).validate(obj, value)
185
186
173 #-----------------------------------------------------------------------------
187 #-----------------------------------------------------------------------------
174 # Main IPython class
188 # Main IPython class
175 #-----------------------------------------------------------------------------
189 #-----------------------------------------------------------------------------
176
190
177 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
191 # FIXME: the Magic class is a mixin for now, and will unfortunately remain so
178 # until a full rewrite is made. I've cleaned all cross-class uses of
192 # until a full rewrite is made. I've cleaned all cross-class uses of
179 # attributes and methods, but too much user code out there relies on the
193 # attributes and methods, but too much user code out there relies on the
180 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
194 # equlity %foo == __IP.magic_foo, so I can't actually remove the mixin usage.
181 #
195 #
182 # But at least now, all the pieces have been separated and we could, in
196 # But at least now, all the pieces have been separated and we could, in
183 # principle, stop using the mixin. This will ease the transition to the
197 # principle, stop using the mixin. This will ease the transition to the
184 # chainsaw branch.
198 # chainsaw branch.
185
199
186 # For reference, the following is the list of 'self.foo' uses in the Magic
200 # For reference, the following is the list of 'self.foo' uses in the Magic
187 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
201 # class as of 2005-12-28. These are names we CAN'T use in the main ipython
188 # class, to prevent clashes.
202 # class, to prevent clashes.
189
203
190 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
204 # ['self.__class__', 'self.__dict__', 'self._inspect', 'self._ofind',
191 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
205 # 'self.arg_err', 'self.extract_input', 'self.format_', 'self.lsmagic',
192 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
206 # 'self.magic_', 'self.options_table', 'self.parse', 'self.shell',
193 # 'self.value']
207 # 'self.value']
194
208
195 class InteractiveShell(Component, Magic):
209 class InteractiveShell(Component, Magic):
196 """An enhanced console for Python."""
210 """An enhanced console for Python."""
197
211
198 alias = []
199 autocall = Enum((0,1,2), config_key='AUTOCALL')
212 autocall = Enum((0,1,2), config_key='AUTOCALL')
200 autoedit_syntax = CBool(False, config_key='AUTOEDIT_SYNTAX')
213 autoedit_syntax = CBool(False, config_key='AUTOEDIT_SYNTAX')
201 autoindent = CBool(True, config_key='AUTOINDENT')
214 autoindent = CBool(True, config_key='AUTOINDENT')
202 automagic = CBool(True, config_key='AUTOMAGIC')
215 automagic = CBool(True, config_key='AUTOMAGIC')
203 autoexec = []
204 display_banner = CBool(True, config_key='DISPLAY_BANNER')
216 display_banner = CBool(True, config_key='DISPLAY_BANNER')
205 banner = Str('')
217 banner = Str('')
206 banner1 = Str(default_banner, config_key='BANNER1')
218 banner1 = Str(default_banner, config_key='BANNER1')
207 banner2 = Str('', config_key='BANNER2')
219 banner2 = Str('', config_key='BANNER2')
208 c = Str('', config_key='C')
220 c = Str('', config_key='C')
209 cache_size = Int(1000, config_key='CACHE_SIZE')
221 cache_size = Int(1000, config_key='CACHE_SIZE')
210 classic = CBool(False, config_key='CLASSIC')
222 classic = CBool(False, config_key='CLASSIC')
211 color_info = CBool(True, config_key='COLOR_INFO')
223 color_info = CBool(True, config_key='COLOR_INFO')
212 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
224 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
213 default_value='LightBG', config_key='COLORS')
225 default_value='LightBG', config_key='COLORS')
214 confirm_exit = CBool(True, config_key='CONFIRM_EXIT')
226 confirm_exit = CBool(True, config_key='CONFIRM_EXIT')
215 debug = CBool(False)
227 debug = CBool(False, config_key='DEBUG')
216 deep_reload = CBool(False, config_key='DEEP_RELOAD')
228 deep_reload = CBool(False, config_key='DEEP_RELOAD')
217 embedded = CBool(False)
229 embedded = CBool(False)
218 editor = Str(get_default_editor(), config_key='EDITOR')
230 editor = Str(get_default_editor(), config_key='EDITOR')
219 filename = Str("<ipython console>")
231 filename = Str("<ipython console>")
220 help = CBool(False)
232 interactive = CBool(False, config_key='INTERACTIVE')
221 interactive = CBool(False)
222 logstart = CBool(False, config_key='LOGSTART')
233 logstart = CBool(False, config_key='LOGSTART')
223 logfile = Str('', config_key='LOGFILE')
234 logfile = Str('', config_key='LOGFILE')
224 logplay = Str('', config_key='LOGPLAY')
235 logplay = Str('', config_key='LOGPLAY')
225 multi_line_specials = CBool(True)
236 multi_line_specials = CBool(True, config_key='MULTI_LINE_SPECIALS')
226 object_info_string_level = Int(0)
237 object_info_string_level = Enum((0,1,2), default_value=0,
227 pager = Str('less')
238 config_keys='OBJECT_INFO_STRING_LEVEL')
239 pager = Str('less', config_key='PAGER')
228 pdb = CBool(False, config_key='PDB')
240 pdb = CBool(False, config_key='PDB')
229 pprint = CBool(True, config_key='PPRINT')
241 pprint = CBool(True, config_key='PPRINT')
230 profile = Str('', config_key='PROFILE')
242 profile = Str('', config_key='PROFILE')
231 prompt_in1 = Str('In [\\#]: ', config_key='PROMPT_IN1')
243 prompt_in1 = Str('In [\\#]: ', config_key='PROMPT_IN1')
232 prompt_in2 = Str(' .\\D.: ', config_key='PROMPT_IN2')
244 prompt_in2 = Str(' .\\D.: ', config_key='PROMPT_IN2')
233 prompt_out = Str('Out[\\#]: ', config_key='PROMPT_OUT1')
245 prompt_out = Str('Out[\\#]: ', config_key='PROMPT_OUT1')
234 prompts_pad_left = CBool(True)
246 prompts_pad_left = CBool(True, config_key='PROMPTS_PAD_LEFT')
235 pydb = CBool(False)
247 quiet = CBool(False, config_key='QUIET')
236 quiet = CBool(False)
237
248
238 readline_use = CBool(True, config_key='READLINE_USE')
249 readline_use = CBool(True, config_key='READLINE_USE')
239 readline_merge_completions = CBool(True)
250 readline_merge_completions = CBool(True,
240 readline_omit__names = Int(0)
251 config_key='READLINE_MERGE_COMPLETIONS')
241 readline_remove_delims = '-/~'
252 readline_omit__names = Enum((0,1,2), default_value=0,
242 readline_parse_and_bind = [
253 config_key='READLINE_OMIT_NAMES')
243 'tab: complete',
254 readline_remove_delims = Str('-/~', config_key='READLINE_REMOVE_DELIMS')
244 '"\C-l": possible-completions',
255 readline_parse_and_bind = List([
245 'set show-all-if-ambiguous on',
256 'tab: complete',
246 '"\C-o": tab-insert',
257 '"\C-l": possible-completions',
247 '"\M-i": " "',
258 'set show-all-if-ambiguous on',
248 '"\M-o": "\d\d\d\d"',
259 '"\C-o": tab-insert',
249 '"\M-I": "\d\d\d\d"',
260 '"\M-i": " "',
250 '"\C-r": reverse-search-history',
261 '"\M-o": "\d\d\d\d"',
251 '"\C-s": forward-search-history',
262 '"\M-I": "\d\d\d\d"',
252 '"\C-p": history-search-backward',
263 '"\C-r": reverse-search-history',
253 '"\C-n": history-search-forward',
264 '"\C-s": forward-search-history',
254 '"\e[A": history-search-backward',
265 '"\C-p": history-search-backward',
255 '"\e[B": history-search-forward',
266 '"\C-n": history-search-forward',
256 '"\C-k": kill-line',
267 '"\e[A": history-search-backward',
257 '"\C-u": unix-line-discard',
268 '"\e[B": history-search-forward',
258 ]
269 '"\C-k": kill-line',
270 '"\C-u": unix-line-discard',
271 ], allow_none=False, config_key='READLINE_PARSE_AND_BIND'
272 )
259
273
260 screen_length = Int(0, config_key='SCREEN_LENGTH')
274 screen_length = Int(0, config_key='SCREEN_LENGTH')
261 separate_in = Str('\n', config_key='SEPARATE_IN')
275
262 separate_out = Str('', config_key='SEPARATE_OUT')
276 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
263 separate_out2 = Str('', config_key='SEPARATE_OUT2')
277 separate_in = SeparateStr('\n', config_key='SEPARATE_IN')
264 system_header = Str('IPython system call: ')
278 separate_out = SeparateStr('', config_key='SEPARATE_OUT')
265 system_verbose = CBool(False)
279 separate_out2 = SeparateStr('', config_key='SEPARATE_OUT2')
266 term_title = CBool(True)
280
267 wildcards_case_sensitive = CBool(True)
281 system_header = Str('IPython system call: ', config_key='SYSTEM_HEADER')
282 system_verbose = CBool(False, config_key='SYSTEM_VERBOSE')
283 term_title = CBool(False, config_key='TERM_TITLE')
284 wildcards_case_sensitive = CBool(True, config_key='WILDCARDS_CASE_SENSITIVE')
268 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
285 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
269 default_value='Context', config_key='XMODE')
286 default_value='Context', config_key='XMODE')
270 magic_docstrings = CBool(False)
287
288 alias = List(allow_none=False, config_key='ALIAS')
289 autoexec = List(allow_none=False)
271
290
272 # class attribute to indicate whether the class supports threads or not.
291 # class attribute to indicate whether the class supports threads or not.
273 # Subclasses with thread support should override this as needed.
292 # Subclasses with thread support should override this as needed.
274 isthreaded = False
293 isthreaded = False
275
294
276 def __init__(self, name, parent=None, config=None, usage=None,
295 def __init__(self, name, parent=None, config=None, usage=None,
277 user_ns=None, user_global_ns=None,
296 user_ns=None, user_global_ns=None,
278 banner1='', banner2='',
297 banner1='', banner2='',
279 custom_exceptions=((),None), embedded=False):
298 custom_exceptions=((),None), embedded=False):
280
299
281 # This is where traitlets with a config_key argument are updated
300 # This is where traitlets with a config_key argument are updated
282 # from the values on config.
301 # from the values on config.
283 # Ideally, from here on out, the config should only be used when
302 # Ideally, from here on out, the config should only be used when
284 # passing it to children components.
303 # passing it to children components.
285 super(InteractiveShell, self).__init__(parent, config=config, name=name)
304 super(InteractiveShell, self).__init__(parent, config=config, name=name)
286
305
287 self.init_instance_attrs()
306 self.init_instance_attrs()
307 self.init_term_title()
288 self.init_usage(usage)
308 self.init_usage(usage)
289 self.init_banner(banner1, banner2)
309 self.init_banner(banner1, banner2)
290 self.init_embedded(embedded)
310 self.init_embedded(embedded)
291 self.init_create_namespaces(user_ns, user_global_ns)
311 self.init_create_namespaces(user_ns, user_global_ns)
292 self.init_history()
312 self.init_history()
293 self.init_encoding()
313 self.init_encoding()
294 self.init_handlers()
314 self.init_handlers()
295
315
296 Magic.__init__(self, self)
316 Magic.__init__(self, self)
297
317
298 self.init_syntax_highlighting()
318 self.init_syntax_highlighting()
299 self.init_hooks()
319 self.init_hooks()
300 self.init_pushd_popd_magic()
320 self.init_pushd_popd_magic()
301 self.init_traceback_handlers(custom_exceptions)
321 self.init_traceback_handlers(custom_exceptions)
302
322
303 # Produce a public API instance
323 # Produce a public API instance
304 self.api = ipapi.IPApi(self)
324 self.api = ipapi.IPApi(self)
305
325
306 self.init_namespaces()
326 self.init_namespaces()
307 self.init_logger()
327 self.init_logger()
308 self.init_aliases()
328 self.init_aliases()
309 self.init_builtins()
329 self.init_builtins()
310
330
311 # pre_config_initialization
331 # pre_config_initialization
312 self.init_shadow_hist()
332 self.init_shadow_hist()
313
333
314 # The next section should contain averything that was in ipmaker.
334 # The next section should contain averything that was in ipmaker.
315 self.init_logstart()
335 self.init_logstart()
316
336
317 # The following was in post_config_initialization
337 # The following was in post_config_initialization
318 self.init_inspector()
338 self.init_inspector()
319 self.init_readline()
339 self.init_readline()
320 self.init_prompts()
340 self.init_prompts()
321 self.init_displayhook()
341 self.init_displayhook()
322 self.init_reload_doctest()
342 self.init_reload_doctest()
323 self.init_magics()
343 self.init_magics()
324 self.init_pdb()
344 self.init_pdb()
325 self.hooks.late_startup_hook()
345 self.hooks.late_startup_hook()
326 self.init_exec_commands()
346 self.init_exec_commands()
327
347
328 #-------------------------------------------------------------------------
348 #-------------------------------------------------------------------------
329 # Traitlet changed handlers
349 # Traitlet changed handlers
330 #-------------------------------------------------------------------------
350 #-------------------------------------------------------------------------
331
351
332 def _banner1_changed(self):
352 def _banner1_changed(self):
333 self.compute_banner()
353 self.compute_banner()
334
354
335 def _banner2_changed(self):
355 def _banner2_changed(self):
336 self.compute_banner()
356 self.compute_banner()
337
357
338 @property
358 @property
339 def usable_screen_length(self):
359 def usable_screen_length(self):
340 if self.screen_length == 0:
360 if self.screen_length == 0:
341 return 0
361 return 0
342 else:
362 else:
343 num_lines_bot = self.separate_in.count('\n')+1
363 num_lines_bot = self.separate_in.count('\n')+1
344 return self.screen_length - num_lines_bot
364 return self.screen_length - num_lines_bot
345
365
366 def _term_title_changed(self, name, new_value):
367 self.init_term_title()
368
346 #-------------------------------------------------------------------------
369 #-------------------------------------------------------------------------
347 # init_* methods called by __init__
370 # init_* methods called by __init__
348 #-------------------------------------------------------------------------
371 #-------------------------------------------------------------------------
349
372
350 def init_instance_attrs(self):
373 def init_instance_attrs(self):
351 self.jobs = BackgroundJobManager()
374 self.jobs = BackgroundJobManager()
352 self.more = False
375 self.more = False
353
376
354 # command compiler
377 # command compiler
355 self.compile = codeop.CommandCompiler()
378 self.compile = codeop.CommandCompiler()
356
379
357 # User input buffer
380 # User input buffer
358 self.buffer = []
381 self.buffer = []
359
382
360 # Make an empty namespace, which extension writers can rely on both
383 # Make an empty namespace, which extension writers can rely on both
361 # existing and NEVER being used by ipython itself. This gives them a
384 # existing and NEVER being used by ipython itself. This gives them a
362 # convenient location for storing additional information and state
385 # convenient location for storing additional information and state
363 # their extensions may require, without fear of collisions with other
386 # their extensions may require, without fear of collisions with other
364 # ipython names that may develop later.
387 # ipython names that may develop later.
365 self.meta = Struct()
388 self.meta = Struct()
366
389
367 # Object variable to store code object waiting execution. This is
390 # Object variable to store code object waiting execution. This is
368 # used mainly by the multithreaded shells, but it can come in handy in
391 # used mainly by the multithreaded shells, but it can come in handy in
369 # other situations. No need to use a Queue here, since it's a single
392 # other situations. No need to use a Queue here, since it's a single
370 # item which gets cleared once run.
393 # item which gets cleared once run.
371 self.code_to_run = None
394 self.code_to_run = None
372
395
373 # Flag to mark unconditional exit
396 # Flag to mark unconditional exit
374 self.exit_now = False
397 self.exit_now = False
375
398
376 # Temporary files used for various purposes. Deleted at exit.
399 # Temporary files used for various purposes. Deleted at exit.
377 self.tempfiles = []
400 self.tempfiles = []
378
401
379 # Keep track of readline usage (later set by init_readline)
402 # Keep track of readline usage (later set by init_readline)
380 self.has_readline = False
403 self.has_readline = False
381
404
382 # keep track of where we started running (mainly for crash post-mortem)
405 # keep track of where we started running (mainly for crash post-mortem)
383 # This is not being used anywhere currently.
406 # This is not being used anywhere currently.
384 self.starting_dir = os.getcwd()
407 self.starting_dir = os.getcwd()
385
408
386 # Indentation management
409 # Indentation management
387 self.indent_current_nsp = 0
410 self.indent_current_nsp = 0
388
411
412 def init_term_title(self):
413 # Enable or disable the terminal title.
414 if self.term_title:
415 toggle_set_term_title(True)
416 set_term_title('IPython: ' + abbrev_cwd())
417 else:
418 toggle_set_term_title(False)
419
389 def init_usage(self, usage=None):
420 def init_usage(self, usage=None):
390 if usage is None:
421 if usage is None:
391 self.usage = interactive_usage
422 self.usage = interactive_usage
392 else:
423 else:
393 self.usage = usage
424 self.usage = usage
394
425
395 def init_banner(self, banner1, banner2):
426 def init_banner(self, banner1, banner2):
396 if self.c: # regular python doesn't print the banner with -c
427 if self.c: # regular python doesn't print the banner with -c
397 self.display_banner = False
428 self.display_banner = False
398 if banner1:
429 if banner1:
399 self.banner1 = banner1
430 self.banner1 = banner1
400 if banner2:
431 if banner2:
401 self.banner2 = banner2
432 self.banner2 = banner2
402 self.compute_banner()
433 self.compute_banner()
403
434
404 def compute_banner(self):
435 def compute_banner(self):
405 self.banner = self.banner1 + '\n'
436 self.banner = self.banner1 + '\n'
406 if self.profile:
437 if self.profile:
407 self.banner += '\nIPython profile: %s\n' % self.profile
438 self.banner += '\nIPython profile: %s\n' % self.profile
408 if self.banner2:
439 if self.banner2:
409 self.banner += '\n' + self.banner2 + '\n'
440 self.banner += '\n' + self.banner2 + '\n'
410
441
411 def init_embedded(self, embedded):
442 def init_embedded(self, embedded):
412 # We need to know whether the instance is meant for embedding, since
443 # We need to know whether the instance is meant for embedding, since
413 # global/local namespaces need to be handled differently in that case
444 # global/local namespaces need to be handled differently in that case
414 self.embedded = embedded
445 self.embedded = embedded
415 if embedded:
446 if embedded:
416 # Control variable so users can, from within the embedded instance,
447 # Control variable so users can, from within the embedded instance,
417 # permanently deactivate it.
448 # permanently deactivate it.
418 self.embedded_active = True
449 self.embedded_active = True
419
450
420 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
451 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
421 # Create the namespace where the user will operate. user_ns is
452 # Create the namespace where the user will operate. user_ns is
422 # normally the only one used, and it is passed to the exec calls as
453 # normally the only one used, and it is passed to the exec calls as
423 # the locals argument. But we do carry a user_global_ns namespace
454 # the locals argument. But we do carry a user_global_ns namespace
424 # given as the exec 'globals' argument, This is useful in embedding
455 # given as the exec 'globals' argument, This is useful in embedding
425 # situations where the ipython shell opens in a context where the
456 # situations where the ipython shell opens in a context where the
426 # distinction between locals and globals is meaningful. For
457 # distinction between locals and globals is meaningful. For
427 # non-embedded contexts, it is just the same object as the user_ns dict.
458 # non-embedded contexts, it is just the same object as the user_ns dict.
428
459
429 # FIXME. For some strange reason, __builtins__ is showing up at user
460 # FIXME. For some strange reason, __builtins__ is showing up at user
430 # level as a dict instead of a module. This is a manual fix, but I
461 # level as a dict instead of a module. This is a manual fix, but I
431 # should really track down where the problem is coming from. Alex
462 # should really track down where the problem is coming from. Alex
432 # Schmolck reported this problem first.
463 # Schmolck reported this problem first.
433
464
434 # A useful post by Alex Martelli on this topic:
465 # A useful post by Alex Martelli on this topic:
435 # Re: inconsistent value from __builtins__
466 # Re: inconsistent value from __builtins__
436 # Von: Alex Martelli <aleaxit@yahoo.com>
467 # Von: Alex Martelli <aleaxit@yahoo.com>
437 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
468 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
438 # Gruppen: comp.lang.python
469 # Gruppen: comp.lang.python
439
470
440 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
471 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
441 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
472 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
442 # > <type 'dict'>
473 # > <type 'dict'>
443 # > >>> print type(__builtins__)
474 # > >>> print type(__builtins__)
444 # > <type 'module'>
475 # > <type 'module'>
445 # > Is this difference in return value intentional?
476 # > Is this difference in return value intentional?
446
477
447 # Well, it's documented that '__builtins__' can be either a dictionary
478 # Well, it's documented that '__builtins__' can be either a dictionary
448 # or a module, and it's been that way for a long time. Whether it's
479 # or a module, and it's been that way for a long time. Whether it's
449 # intentional (or sensible), I don't know. In any case, the idea is
480 # intentional (or sensible), I don't know. In any case, the idea is
450 # that if you need to access the built-in namespace directly, you
481 # that if you need to access the built-in namespace directly, you
451 # should start with "import __builtin__" (note, no 's') which will
482 # should start with "import __builtin__" (note, no 's') which will
452 # definitely give you a module. Yeah, it's somewhat confusing:-(.
483 # definitely give you a module. Yeah, it's somewhat confusing:-(.
453
484
454 # These routines return properly built dicts as needed by the rest of
485 # These routines return properly built dicts as needed by the rest of
455 # the code, and can also be used by extension writers to generate
486 # the code, and can also be used by extension writers to generate
456 # properly initialized namespaces.
487 # properly initialized namespaces.
457 user_ns, user_global_ns = ipapi.make_user_namespaces(user_ns,
488 user_ns, user_global_ns = ipapi.make_user_namespaces(user_ns,
458 user_global_ns)
489 user_global_ns)
459
490
460 # Assign namespaces
491 # Assign namespaces
461 # This is the namespace where all normal user variables live
492 # This is the namespace where all normal user variables live
462 self.user_ns = user_ns
493 self.user_ns = user_ns
463 self.user_global_ns = user_global_ns
494 self.user_global_ns = user_global_ns
464
495
465 # An auxiliary namespace that checks what parts of the user_ns were
496 # An auxiliary namespace that checks what parts of the user_ns were
466 # loaded at startup, so we can list later only variables defined in
497 # loaded at startup, so we can list later only variables defined in
467 # actual interactive use. Since it is always a subset of user_ns, it
498 # actual interactive use. Since it is always a subset of user_ns, it
468 # doesn't need to be seaparately tracked in the ns_table
499 # doesn't need to be seaparately tracked in the ns_table
469 self.user_config_ns = {}
500 self.user_config_ns = {}
470
501
471 # A namespace to keep track of internal data structures to prevent
502 # A namespace to keep track of internal data structures to prevent
472 # them from cluttering user-visible stuff. Will be updated later
503 # them from cluttering user-visible stuff. Will be updated later
473 self.internal_ns = {}
504 self.internal_ns = {}
474
505
475 # Namespace of system aliases. Each entry in the alias
506 # Namespace of system aliases. Each entry in the alias
476 # table must be a 2-tuple of the form (N,name), where N is the number
507 # table must be a 2-tuple of the form (N,name), where N is the number
477 # of positional arguments of the alias.
508 # of positional arguments of the alias.
478 self.alias_table = {}
509 self.alias_table = {}
479
510
480 # Now that FakeModule produces a real module, we've run into a nasty
511 # Now that FakeModule produces a real module, we've run into a nasty
481 # problem: after script execution (via %run), the module where the user
512 # problem: after script execution (via %run), the module where the user
482 # code ran is deleted. Now that this object is a true module (needed
513 # code ran is deleted. Now that this object is a true module (needed
483 # so docetst and other tools work correctly), the Python module
514 # so docetst and other tools work correctly), the Python module
484 # teardown mechanism runs over it, and sets to None every variable
515 # teardown mechanism runs over it, and sets to None every variable
485 # present in that module. Top-level references to objects from the
516 # present in that module. Top-level references to objects from the
486 # script survive, because the user_ns is updated with them. However,
517 # script survive, because the user_ns is updated with them. However,
487 # calling functions defined in the script that use other things from
518 # calling functions defined in the script that use other things from
488 # the script will fail, because the function's closure had references
519 # the script will fail, because the function's closure had references
489 # to the original objects, which are now all None. So we must protect
520 # to the original objects, which are now all None. So we must protect
490 # these modules from deletion by keeping a cache.
521 # these modules from deletion by keeping a cache.
491 #
522 #
492 # To avoid keeping stale modules around (we only need the one from the
523 # To avoid keeping stale modules around (we only need the one from the
493 # last run), we use a dict keyed with the full path to the script, so
524 # last run), we use a dict keyed with the full path to the script, so
494 # only the last version of the module is held in the cache. Note,
525 # only the last version of the module is held in the cache. Note,
495 # however, that we must cache the module *namespace contents* (their
526 # however, that we must cache the module *namespace contents* (their
496 # __dict__). Because if we try to cache the actual modules, old ones
527 # __dict__). Because if we try to cache the actual modules, old ones
497 # (uncached) could be destroyed while still holding references (such as
528 # (uncached) could be destroyed while still holding references (such as
498 # those held by GUI objects that tend to be long-lived)>
529 # those held by GUI objects that tend to be long-lived)>
499 #
530 #
500 # The %reset command will flush this cache. See the cache_main_mod()
531 # The %reset command will flush this cache. See the cache_main_mod()
501 # and clear_main_mod_cache() methods for details on use.
532 # and clear_main_mod_cache() methods for details on use.
502
533
503 # This is the cache used for 'main' namespaces
534 # This is the cache used for 'main' namespaces
504 self._main_ns_cache = {}
535 self._main_ns_cache = {}
505 # And this is the single instance of FakeModule whose __dict__ we keep
536 # And this is the single instance of FakeModule whose __dict__ we keep
506 # copying and clearing for reuse on each %run
537 # copying and clearing for reuse on each %run
507 self._user_main_module = FakeModule()
538 self._user_main_module = FakeModule()
508
539
509 # A table holding all the namespaces IPython deals with, so that
540 # A table holding all the namespaces IPython deals with, so that
510 # introspection facilities can search easily.
541 # introspection facilities can search easily.
511 self.ns_table = {'user':user_ns,
542 self.ns_table = {'user':user_ns,
512 'user_global':user_global_ns,
543 'user_global':user_global_ns,
513 'alias':self.alias_table,
544 'alias':self.alias_table,
514 'internal':self.internal_ns,
545 'internal':self.internal_ns,
515 'builtin':__builtin__.__dict__
546 'builtin':__builtin__.__dict__
516 }
547 }
517
548
518 # Similarly, track all namespaces where references can be held and that
549 # Similarly, track all namespaces where references can be held and that
519 # we can safely clear (so it can NOT include builtin). This one can be
550 # we can safely clear (so it can NOT include builtin). This one can be
520 # a simple list.
551 # a simple list.
521 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
552 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
522 self.alias_table, self.internal_ns,
553 self.alias_table, self.internal_ns,
523 self._main_ns_cache ]
554 self._main_ns_cache ]
524
555
525 # We need to insert into sys.modules something that looks like a
556 # We need to insert into sys.modules something that looks like a
526 # module but which accesses the IPython namespace, for shelve and
557 # module but which accesses the IPython namespace, for shelve and
527 # pickle to work interactively. Normally they rely on getting
558 # pickle to work interactively. Normally they rely on getting
528 # everything out of __main__, but for embedding purposes each IPython
559 # everything out of __main__, but for embedding purposes each IPython
529 # instance has its own private namespace, so we can't go shoving
560 # instance has its own private namespace, so we can't go shoving
530 # everything into __main__.
561 # everything into __main__.
531
562
532 # note, however, that we should only do this for non-embedded
563 # note, however, that we should only do this for non-embedded
533 # ipythons, which really mimic the __main__.__dict__ with their own
564 # ipythons, which really mimic the __main__.__dict__ with their own
534 # namespace. Embedded instances, on the other hand, should not do
565 # namespace. Embedded instances, on the other hand, should not do
535 # this because they need to manage the user local/global namespaces
566 # this because they need to manage the user local/global namespaces
536 # only, but they live within a 'normal' __main__ (meaning, they
567 # only, but they live within a 'normal' __main__ (meaning, they
537 # shouldn't overtake the execution environment of the script they're
568 # shouldn't overtake the execution environment of the script they're
538 # embedded in).
569 # embedded in).
539
570
540 if not self.embedded:
571 if not self.embedded:
541 try:
572 try:
542 main_name = self.user_ns['__name__']
573 main_name = self.user_ns['__name__']
543 except KeyError:
574 except KeyError:
544 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
575 raise KeyError,'user_ns dictionary MUST have a "__name__" key'
545 else:
576 else:
546 sys.modules[main_name] = FakeModule(self.user_ns)
577 sys.modules[main_name] = FakeModule(self.user_ns)
547
578
548 def init_history(self):
579 def init_history(self):
549 # List of input with multi-line handling.
580 # List of input with multi-line handling.
550 self.input_hist = InputList()
581 self.input_hist = InputList()
551 # This one will hold the 'raw' input history, without any
582 # This one will hold the 'raw' input history, without any
552 # pre-processing. This will allow users to retrieve the input just as
583 # pre-processing. This will allow users to retrieve the input just as
553 # it was exactly typed in by the user, with %hist -r.
584 # it was exactly typed in by the user, with %hist -r.
554 self.input_hist_raw = InputList()
585 self.input_hist_raw = InputList()
555
586
556 # list of visited directories
587 # list of visited directories
557 try:
588 try:
558 self.dir_hist = [os.getcwd()]
589 self.dir_hist = [os.getcwd()]
559 except OSError:
590 except OSError:
560 self.dir_hist = []
591 self.dir_hist = []
561
592
562 # dict of output history
593 # dict of output history
563 self.output_hist = {}
594 self.output_hist = {}
564
595
565 # Now the history file
596 # Now the history file
566 try:
597 try:
567 histfname = 'history-%s' % self.config.PROFILE
598 histfname = 'history-%s' % self.profile
568 except AttributeError:
599 except AttributeError:
569 histfname = 'history'
600 histfname = 'history'
570 self.histfile = os.path.join(self.config.IPYTHONDIR, histfname)
601 self.histfile = os.path.join(self.config.IPYTHONDIR, histfname)
571
602
572 # Fill the history zero entry, user counter starts at 1
603 # Fill the history zero entry, user counter starts at 1
573 self.input_hist.append('\n')
604 self.input_hist.append('\n')
574 self.input_hist_raw.append('\n')
605 self.input_hist_raw.append('\n')
575
606
576 def init_encoding(self):
607 def init_encoding(self):
577 # Get system encoding at startup time. Certain terminals (like Emacs
608 # Get system encoding at startup time. Certain terminals (like Emacs
578 # under Win32 have it set to None, and we need to have a known valid
609 # under Win32 have it set to None, and we need to have a known valid
579 # encoding to use in the raw_input() method
610 # encoding to use in the raw_input() method
580 try:
611 try:
581 self.stdin_encoding = sys.stdin.encoding or 'ascii'
612 self.stdin_encoding = sys.stdin.encoding or 'ascii'
582 except AttributeError:
613 except AttributeError:
583 self.stdin_encoding = 'ascii'
614 self.stdin_encoding = 'ascii'
584
615
585 def init_handlers(self):
616 def init_handlers(self):
586 # escapes for automatic behavior on the command line
617 # escapes for automatic behavior on the command line
587 self.ESC_SHELL = '!'
618 self.ESC_SHELL = '!'
588 self.ESC_SH_CAP = '!!'
619 self.ESC_SH_CAP = '!!'
589 self.ESC_HELP = '?'
620 self.ESC_HELP = '?'
590 self.ESC_MAGIC = '%'
621 self.ESC_MAGIC = '%'
591 self.ESC_QUOTE = ','
622 self.ESC_QUOTE = ','
592 self.ESC_QUOTE2 = ';'
623 self.ESC_QUOTE2 = ';'
593 self.ESC_PAREN = '/'
624 self.ESC_PAREN = '/'
594
625
595 # And their associated handlers
626 # And their associated handlers
596 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
627 self.esc_handlers = {self.ESC_PAREN : self.handle_auto,
597 self.ESC_QUOTE : self.handle_auto,
628 self.ESC_QUOTE : self.handle_auto,
598 self.ESC_QUOTE2 : self.handle_auto,
629 self.ESC_QUOTE2 : self.handle_auto,
599 self.ESC_MAGIC : self.handle_magic,
630 self.ESC_MAGIC : self.handle_magic,
600 self.ESC_HELP : self.handle_help,
631 self.ESC_HELP : self.handle_help,
601 self.ESC_SHELL : self.handle_shell_escape,
632 self.ESC_SHELL : self.handle_shell_escape,
602 self.ESC_SH_CAP : self.handle_shell_escape,
633 self.ESC_SH_CAP : self.handle_shell_escape,
603 }
634 }
604
635
605 def init_syntax_highlighting(self):
636 def init_syntax_highlighting(self):
606 # Python source parser/formatter for syntax highlighting
637 # Python source parser/formatter for syntax highlighting
607 pyformat = PyColorize.Parser().format
638 pyformat = PyColorize.Parser().format
608 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
639 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
609
640
610 def init_hooks(self):
641 def init_hooks(self):
611 # hooks holds pointers used for user-side customizations
642 # hooks holds pointers used for user-side customizations
612 self.hooks = Struct()
643 self.hooks = Struct()
613
644
614 self.strdispatchers = {}
645 self.strdispatchers = {}
615
646
616 # Set all default hooks, defined in the IPython.hooks module.
647 # Set all default hooks, defined in the IPython.hooks module.
617 import IPython.core.hooks
648 import IPython.core.hooks
618 hooks = IPython.core.hooks
649 hooks = IPython.core.hooks
619 for hook_name in hooks.__all__:
650 for hook_name in hooks.__all__:
620 # default hooks have priority 100, i.e. low; user hooks should have
651 # default hooks have priority 100, i.e. low; user hooks should have
621 # 0-100 priority
652 # 0-100 priority
622 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
653 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
623
654
624 def init_pushd_popd_magic(self):
655 def init_pushd_popd_magic(self):
625 # for pushd/popd management
656 # for pushd/popd management
626 try:
657 try:
627 self.home_dir = get_home_dir()
658 self.home_dir = get_home_dir()
628 except HomeDirError, msg:
659 except HomeDirError, msg:
629 fatal(msg)
660 fatal(msg)
630
661
631 self.dir_stack = []
662 self.dir_stack = []
632
663
633 def init_traceback_handlers(self, custom_exceptions):
664 def init_traceback_handlers(self, custom_exceptions):
634 # Syntax error handler.
665 # Syntax error handler.
635 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
666 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
636
667
637 # The interactive one is initialized with an offset, meaning we always
668 # The interactive one is initialized with an offset, meaning we always
638 # want to remove the topmost item in the traceback, which is our own
669 # want to remove the topmost item in the traceback, which is our own
639 # internal code. Valid modes: ['Plain','Context','Verbose']
670 # internal code. Valid modes: ['Plain','Context','Verbose']
640 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
671 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
641 color_scheme='NoColor',
672 color_scheme='NoColor',
642 tb_offset = 1)
673 tb_offset = 1)
643
674
644 # IPython itself shouldn't crash. This will produce a detailed
675 # IPython itself shouldn't crash. This will produce a detailed
645 # post-mortem if it does. But we only install the crash handler for
676 # post-mortem if it does. But we only install the crash handler for
646 # non-threaded shells, the threaded ones use a normal verbose reporter
677 # non-threaded shells, the threaded ones use a normal verbose reporter
647 # and lose the crash handler. This is because exceptions in the main
678 # and lose the crash handler. This is because exceptions in the main
648 # thread (such as in GUI code) propagate directly to sys.excepthook,
679 # thread (such as in GUI code) propagate directly to sys.excepthook,
649 # and there's no point in printing crash dumps for every user exception.
680 # and there's no point in printing crash dumps for every user exception.
650 if self.isthreaded:
681 if self.isthreaded:
651 ipCrashHandler = ultratb.FormattedTB()
682 ipCrashHandler = ultratb.FormattedTB()
652 else:
683 else:
653 from IPython.core import crashhandler
684 from IPython.core import crashhandler
654 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
685 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
655 self.set_crash_handler(ipCrashHandler)
686 self.set_crash_handler(ipCrashHandler)
656
687
657 # and add any custom exception handlers the user may have specified
688 # and add any custom exception handlers the user may have specified
658 self.set_custom_exc(*custom_exceptions)
689 self.set_custom_exc(*custom_exceptions)
659
690
660 def init_logger(self):
691 def init_logger(self):
661 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
692 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
662 # local shortcut, this is used a LOT
693 # local shortcut, this is used a LOT
663 self.log = self.logger.log
694 self.log = self.logger.log
664 # template for logfile headers. It gets resolved at runtime by the
695 # template for logfile headers. It gets resolved at runtime by the
665 # logstart method.
696 # logstart method.
666 self.loghead_tpl = \
697 self.loghead_tpl = \
667 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
698 """#log# Automatic Logger file. *** THIS MUST BE THE FIRST LINE ***
668 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
699 #log# DO NOT CHANGE THIS LINE OR THE TWO BELOW
669 #log# opts = %s
700 #log# opts = %s
670 #log# args = %s
701 #log# args = %s
671 #log# It is safe to make manual edits below here.
702 #log# It is safe to make manual edits below here.
672 #log#-----------------------------------------------------------------------
703 #log#-----------------------------------------------------------------------
673 """
704 """
674
705
675 def init_logstart(self):
706 def init_logstart(self):
676 if self.logplay:
707 if self.logplay:
677 self.magic_logstart(self.logplay + ' append')
708 self.magic_logstart(self.logplay + ' append')
678 elif self.logfile:
709 elif self.logfile:
679 self.magic_logstart(self.logfile)
710 self.magic_logstart(self.logfile)
680 elif self.logstart:
711 elif self.logstart:
681 self.magic_logstart()
712 self.magic_logstart()
682
713
683 def init_aliases(self):
714 def init_aliases(self):
684 # dict of things NOT to alias (keywords, builtins and some magics)
715 # dict of things NOT to alias (keywords, builtins and some magics)
685 no_alias = {}
716 no_alias = {}
686 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
717 no_alias_magics = ['cd','popd','pushd','dhist','alias','unalias']
687 for key in keyword.kwlist + no_alias_magics:
718 for key in keyword.kwlist + no_alias_magics:
688 no_alias[key] = 1
719 no_alias[key] = 1
689 no_alias.update(__builtin__.__dict__)
720 no_alias.update(__builtin__.__dict__)
690 self.no_alias = no_alias
721 self.no_alias = no_alias
691
722
692 # Make some aliases automatically
723 # Make some aliases automatically
693 # Prepare list of shell aliases to auto-define
724 # Prepare list of shell aliases to auto-define
694 if os.name == 'posix':
725 if os.name == 'posix':
695 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
726 auto_alias = ('mkdir mkdir', 'rmdir rmdir',
696 'mv mv -i','rm rm -i','cp cp -i',
727 'mv mv -i','rm rm -i','cp cp -i',
697 'cat cat','less less','clear clear',
728 'cat cat','less less','clear clear',
698 # a better ls
729 # a better ls
699 'ls ls -F',
730 'ls ls -F',
700 # long ls
731 # long ls
701 'll ls -lF')
732 'll ls -lF')
702 # Extra ls aliases with color, which need special treatment on BSD
733 # Extra ls aliases with color, which need special treatment on BSD
703 # variants
734 # variants
704 ls_extra = ( # color ls
735 ls_extra = ( # color ls
705 'lc ls -F -o --color',
736 'lc ls -F -o --color',
706 # ls normal files only
737 # ls normal files only
707 'lf ls -F -o --color %l | grep ^-',
738 'lf ls -F -o --color %l | grep ^-',
708 # ls symbolic links
739 # ls symbolic links
709 'lk ls -F -o --color %l | grep ^l',
740 'lk ls -F -o --color %l | grep ^l',
710 # directories or links to directories,
741 # directories or links to directories,
711 'ldir ls -F -o --color %l | grep /$',
742 'ldir ls -F -o --color %l | grep /$',
712 # things which are executable
743 # things which are executable
713 'lx ls -F -o --color %l | grep ^-..x',
744 'lx ls -F -o --color %l | grep ^-..x',
714 )
745 )
715 # The BSDs don't ship GNU ls, so they don't understand the
746 # The BSDs don't ship GNU ls, so they don't understand the
716 # --color switch out of the box
747 # --color switch out of the box
717 if 'bsd' in sys.platform:
748 if 'bsd' in sys.platform:
718 ls_extra = ( # ls normal files only
749 ls_extra = ( # ls normal files only
719 'lf ls -lF | grep ^-',
750 'lf ls -lF | grep ^-',
720 # ls symbolic links
751 # ls symbolic links
721 'lk ls -lF | grep ^l',
752 'lk ls -lF | grep ^l',
722 # directories or links to directories,
753 # directories or links to directories,
723 'ldir ls -lF | grep /$',
754 'ldir ls -lF | grep /$',
724 # things which are executable
755 # things which are executable
725 'lx ls -lF | grep ^-..x',
756 'lx ls -lF | grep ^-..x',
726 )
757 )
727 auto_alias = auto_alias + ls_extra
758 auto_alias = auto_alias + ls_extra
728 elif os.name in ['nt','dos']:
759 elif os.name in ['nt','dos']:
729 auto_alias = ('ls dir /on',
760 auto_alias = ('ls dir /on',
730 'ddir dir /ad /on', 'ldir dir /ad /on',
761 'ddir dir /ad /on', 'ldir dir /ad /on',
731 'mkdir mkdir','rmdir rmdir','echo echo',
762 'mkdir mkdir','rmdir rmdir','echo echo',
732 'ren ren','cls cls','copy copy')
763 'ren ren','cls cls','copy copy')
733 else:
764 else:
734 auto_alias = ()
765 auto_alias = ()
735 self.auto_alias = [s.split(None,1) for s in auto_alias]
766 self.auto_alias = [s.split(None,1) for s in auto_alias]
736
767
737 # Load default aliases
768 # Load default aliases
738 for alias, cmd in self.auto_alias:
769 for alias, cmd in self.auto_alias:
739 self.define_alias(alias,cmd)
770 self.define_alias(alias,cmd)
740
771
741 # Load user aliases
772 # Load user aliases
742 for alias in self.alias:
773 for alias in self.alias:
743 self.magic_alias(alias)
774 self.magic_alias(alias)
744
775
745 def init_builtins(self):
776 def init_builtins(self):
746 # track which builtins we add, so we can clean up later
777 # track which builtins we add, so we can clean up later
747 self.builtins_added = {}
778 self.builtins_added = {}
748 # This method will add the necessary builtins for operation, but
779 # This method will add the necessary builtins for operation, but
749 # tracking what it did via the builtins_added dict.
780 # tracking what it did via the builtins_added dict.
750
781
751 #TODO: remove this, redundant. I don't understand why this is
782 #TODO: remove this, redundant. I don't understand why this is
752 # redundant?
783 # redundant?
753 self.add_builtins()
784 self.add_builtins()
754
785
755 def init_shadow_hist(self):
786 def init_shadow_hist(self):
756 try:
787 try:
757 self.db = pickleshare.PickleShareDB(self.config.IPYTHONDIR + "/db")
788 self.db = pickleshare.PickleShareDB(self.config.IPYTHONDIR + "/db")
758 except exceptions.UnicodeDecodeError:
789 except exceptions.UnicodeDecodeError:
759 print "Your ipythondir can't be decoded to unicode!"
790 print "Your ipythondir can't be decoded to unicode!"
760 print "Please set HOME environment variable to something that"
791 print "Please set HOME environment variable to something that"
761 print r"only has ASCII characters, e.g. c:\home"
792 print r"only has ASCII characters, e.g. c:\home"
762 print "Now it is", self.config.IPYTHONDIR
793 print "Now it is", self.config.IPYTHONDIR
763 sys.exit()
794 sys.exit()
764 self.shadowhist = ipcorehist.ShadowHist(self.db)
795 self.shadowhist = ipcorehist.ShadowHist(self.db)
765
796
766 def init_inspector(self):
797 def init_inspector(self):
767 # Object inspector
798 # Object inspector
768 self.inspector = oinspect.Inspector(oinspect.InspectColors,
799 self.inspector = oinspect.Inspector(oinspect.InspectColors,
769 PyColorize.ANSICodeColors,
800 PyColorize.ANSICodeColors,
770 'NoColor',
801 'NoColor',
771 self.object_info_string_level)
802 self.object_info_string_level)
772
803
773 def init_readline(self):
804 def init_readline(self):
774 """Command history completion/saving/reloading."""
805 """Command history completion/saving/reloading."""
775
806
776 self.rl_next_input = None
807 self.rl_next_input = None
777 self.rl_do_indent = False
808 self.rl_do_indent = False
778
809
779 if not self.readline_use:
810 if not self.readline_use:
780 return
811 return
781
812
782 import IPython.utils.rlineimpl as readline
813 import IPython.utils.rlineimpl as readline
783
814
784 if not readline.have_readline:
815 if not readline.have_readline:
785 self.has_readline = 0
816 self.has_readline = 0
786 self.readline = None
817 self.readline = None
787 # no point in bugging windows users with this every time:
818 # no point in bugging windows users with this every time:
788 warn('Readline services not available on this platform.')
819 warn('Readline services not available on this platform.')
789 else:
820 else:
790 sys.modules['readline'] = readline
821 sys.modules['readline'] = readline
791 import atexit
822 import atexit
792 from IPython.core.completer import IPCompleter
823 from IPython.core.completer import IPCompleter
793 self.Completer = IPCompleter(self,
824 self.Completer = IPCompleter(self,
794 self.user_ns,
825 self.user_ns,
795 self.user_global_ns,
826 self.user_global_ns,
796 self.readline_omit__names,
827 self.readline_omit__names,
797 self.alias_table)
828 self.alias_table)
798 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
829 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
799 self.strdispatchers['complete_command'] = sdisp
830 self.strdispatchers['complete_command'] = sdisp
800 self.Completer.custom_completers = sdisp
831 self.Completer.custom_completers = sdisp
801 # Platform-specific configuration
832 # Platform-specific configuration
802 if os.name == 'nt':
833 if os.name == 'nt':
803 self.readline_startup_hook = readline.set_pre_input_hook
834 self.readline_startup_hook = readline.set_pre_input_hook
804 else:
835 else:
805 self.readline_startup_hook = readline.set_startup_hook
836 self.readline_startup_hook = readline.set_startup_hook
806
837
807 # Load user's initrc file (readline config)
838 # Load user's initrc file (readline config)
808 # Or if libedit is used, load editrc.
839 # Or if libedit is used, load editrc.
809 inputrc_name = os.environ.get('INPUTRC')
840 inputrc_name = os.environ.get('INPUTRC')
810 if inputrc_name is None:
841 if inputrc_name is None:
811 home_dir = get_home_dir()
842 home_dir = get_home_dir()
812 if home_dir is not None:
843 if home_dir is not None:
813 inputrc_name = '.inputrc'
844 inputrc_name = '.inputrc'
814 if readline.uses_libedit:
845 if readline.uses_libedit:
815 inputrc_name = '.editrc'
846 inputrc_name = '.editrc'
816 inputrc_name = os.path.join(home_dir, inputrc_name)
847 inputrc_name = os.path.join(home_dir, inputrc_name)
817 if os.path.isfile(inputrc_name):
848 if os.path.isfile(inputrc_name):
818 try:
849 try:
819 readline.read_init_file(inputrc_name)
850 readline.read_init_file(inputrc_name)
820 except:
851 except:
821 warn('Problems reading readline initialization file <%s>'
852 warn('Problems reading readline initialization file <%s>'
822 % inputrc_name)
853 % inputrc_name)
823
854
824 self.has_readline = 1
855 self.has_readline = 1
825 self.readline = readline
856 self.readline = readline
826 # save this in sys so embedded copies can restore it properly
857 # save this in sys so embedded copies can restore it properly
827 sys.ipcompleter = self.Completer.complete
858 sys.ipcompleter = self.Completer.complete
828 self.set_completer()
859 self.set_completer()
829
860
830 # Configure readline according to user's prefs
861 # Configure readline according to user's prefs
831 # This is only done if GNU readline is being used. If libedit
862 # This is only done if GNU readline is being used. If libedit
832 # is being used (as on Leopard) the readline config is
863 # is being used (as on Leopard) the readline config is
833 # not run as the syntax for libedit is different.
864 # not run as the syntax for libedit is different.
834 if not readline.uses_libedit:
865 if not readline.uses_libedit:
835 for rlcommand in self.readline_parse_and_bind:
866 for rlcommand in self.readline_parse_and_bind:
836 #print "loading rl:",rlcommand # dbg
867 #print "loading rl:",rlcommand # dbg
837 readline.parse_and_bind(rlcommand)
868 readline.parse_and_bind(rlcommand)
838
869
839 # Remove some chars from the delimiters list. If we encounter
870 # Remove some chars from the delimiters list. If we encounter
840 # unicode chars, discard them.
871 # unicode chars, discard them.
841 delims = readline.get_completer_delims().encode("ascii", "ignore")
872 delims = readline.get_completer_delims().encode("ascii", "ignore")
842 delims = delims.translate(string._idmap,
873 delims = delims.translate(string._idmap,
843 self.readline_remove_delims)
874 self.readline_remove_delims)
844 readline.set_completer_delims(delims)
875 readline.set_completer_delims(delims)
845 # otherwise we end up with a monster history after a while:
876 # otherwise we end up with a monster history after a while:
846 readline.set_history_length(1000)
877 readline.set_history_length(1000)
847 try:
878 try:
848 #print '*** Reading readline history' # dbg
879 #print '*** Reading readline history' # dbg
849 readline.read_history_file(self.histfile)
880 readline.read_history_file(self.histfile)
850 except IOError:
881 except IOError:
851 pass # It doesn't exist yet.
882 pass # It doesn't exist yet.
852
883
853 atexit.register(self.atexit_operations)
884 atexit.register(self.atexit_operations)
854 del atexit
885 del atexit
855
886
856 # Configure auto-indent for all platforms
887 # Configure auto-indent for all platforms
857 self.set_autoindent(self.autoindent)
888 self.set_autoindent(self.autoindent)
858
889
859 def init_prompts(self):
890 def init_prompts(self):
860 # Initialize cache, set in/out prompts and printing system
891 # Initialize cache, set in/out prompts and printing system
861 self.outputcache = CachedOutput(self,
892 self.outputcache = CachedOutput(self,
862 self.cache_size,
893 self.cache_size,
863 self.pprint,
894 self.pprint,
864 input_sep = self.separate_in,
895 input_sep = self.separate_in,
865 output_sep = self.separate_out,
896 output_sep = self.separate_out,
866 output_sep2 = self.separate_out2,
897 output_sep2 = self.separate_out2,
867 ps1 = self.prompt_in1,
898 ps1 = self.prompt_in1,
868 ps2 = self.prompt_in2,
899 ps2 = self.prompt_in2,
869 ps_out = self.prompt_out,
900 ps_out = self.prompt_out,
870 pad_left = self.prompts_pad_left)
901 pad_left = self.prompts_pad_left)
871
902
872 # user may have over-ridden the default print hook:
903 # user may have over-ridden the default print hook:
873 try:
904 try:
874 self.outputcache.__class__.display = self.hooks.display
905 self.outputcache.__class__.display = self.hooks.display
875 except AttributeError:
906 except AttributeError:
876 pass
907 pass
877
908
878 def init_displayhook(self):
909 def init_displayhook(self):
879 # I don't like assigning globally to sys, because it means when
910 # I don't like assigning globally to sys, because it means when
880 # embedding instances, each embedded instance overrides the previous
911 # embedding instances, each embedded instance overrides the previous
881 # choice. But sys.displayhook seems to be called internally by exec,
912 # choice. But sys.displayhook seems to be called internally by exec,
882 # so I don't see a way around it. We first save the original and then
913 # so I don't see a way around it. We first save the original and then
883 # overwrite it.
914 # overwrite it.
884 self.sys_displayhook = sys.displayhook
915 self.sys_displayhook = sys.displayhook
885 sys.displayhook = self.outputcache
916 sys.displayhook = self.outputcache
886
917
887 def init_reload_doctest(self):
918 def init_reload_doctest(self):
888 # Do a proper resetting of doctest, including the necessary displayhook
919 # Do a proper resetting of doctest, including the necessary displayhook
889 # monkeypatching
920 # monkeypatching
890 try:
921 try:
891 doctest_reload()
922 doctest_reload()
892 except ImportError:
923 except ImportError:
893 warn("doctest module does not exist.")
924 warn("doctest module does not exist.")
894
925
895 def init_magics(self):
926 def init_magics(self):
896 # Set user colors (don't do it in the constructor above so that it
927 # Set user colors (don't do it in the constructor above so that it
897 # doesn't crash if colors option is invalid)
928 # doesn't crash if colors option is invalid)
898 self.magic_colors(self.colors)
929 self.magic_colors(self.colors)
899
930
900 def init_pdb(self):
931 def init_pdb(self):
901 # Set calling of pdb on exceptions
932 # Set calling of pdb on exceptions
902 # self.call_pdb is a property
933 # self.call_pdb is a property
903 self.call_pdb = self.pdb
934 self.call_pdb = self.pdb
904
935
905 def init_exec_commands(self):
936 def init_exec_commands(self):
906 for cmd in self.autoexec:
937 for cmd in self.config.EXECUTE:
907 #print "autoexec>",cmd #dbg
938 print "execute:", cmd
908 self.api.runlines(cmd)
939 self.api.runlines(cmd)
909
940
910 batchrun = False
941 batchrun = False
911 if self.config.has_key('EXECFILE'):
942 if self.config.has_key('EXECFILE'):
912 for batchfile in [path(arg) for arg in self.config.EXECFILE
943 for batchfile in [path(arg) for arg in self.config.EXECFILE
913 if arg.lower().endswith('.ipy')]:
944 if arg.lower().endswith('.ipy')]:
914 if not batchfile.isfile():
945 if not batchfile.isfile():
915 print "No such batch file:", batchfile
946 print "No such batch file:", batchfile
916 continue
947 continue
917 self.api.runlines(batchfile.text())
948 self.api.runlines(batchfile.text())
918 batchrun = True
949 batchrun = True
919 # without -i option, exit after running the batch file
950 # without -i option, exit after running the batch file
920 if batchrun and not self.interactive:
951 if batchrun and not self.interactive:
921 self.ask_exit()
952 self.ask_exit()
922
953
923 def init_namespaces(self):
954 def init_namespaces(self):
924 """Initialize all user-visible namespaces to their minimum defaults.
955 """Initialize all user-visible namespaces to their minimum defaults.
925
956
926 Certain history lists are also initialized here, as they effectively
957 Certain history lists are also initialized here, as they effectively
927 act as user namespaces.
958 act as user namespaces.
928
959
929 Notes
960 Notes
930 -----
961 -----
931 All data structures here are only filled in, they are NOT reset by this
962 All data structures here are only filled in, they are NOT reset by this
932 method. If they were not empty before, data will simply be added to
963 method. If they were not empty before, data will simply be added to
933 therm.
964 therm.
934 """
965 """
935 # The user namespace MUST have a pointer to the shell itself.
966 # The user namespace MUST have a pointer to the shell itself.
936 self.user_ns[self.name] = self
967 self.user_ns[self.name] = self
937
968
938 # Store the public api instance
969 # Store the public api instance
939 self.user_ns['_ip'] = self.api
970 self.user_ns['_ip'] = self.api
940
971
941 # make global variables for user access to the histories
972 # make global variables for user access to the histories
942 self.user_ns['_ih'] = self.input_hist
973 self.user_ns['_ih'] = self.input_hist
943 self.user_ns['_oh'] = self.output_hist
974 self.user_ns['_oh'] = self.output_hist
944 self.user_ns['_dh'] = self.dir_hist
975 self.user_ns['_dh'] = self.dir_hist
945
976
946 # user aliases to input and output histories
977 # user aliases to input and output histories
947 self.user_ns['In'] = self.input_hist
978 self.user_ns['In'] = self.input_hist
948 self.user_ns['Out'] = self.output_hist
979 self.user_ns['Out'] = self.output_hist
949
980
950 self.user_ns['_sh'] = shadowns
981 self.user_ns['_sh'] = shadowns
951
982
952 # Put 'help' in the user namespace
983 # Put 'help' in the user namespace
953 try:
984 try:
954 from site import _Helper
985 from site import _Helper
955 self.user_ns['help'] = _Helper()
986 self.user_ns['help'] = _Helper()
956 except ImportError:
987 except ImportError:
957 warn('help() not available - check site.py')
988 warn('help() not available - check site.py')
958
989
959 def add_builtins(self):
990 def add_builtins(self):
960 """Store ipython references into the builtin namespace.
991 """Store ipython references into the builtin namespace.
961
992
962 Some parts of ipython operate via builtins injected here, which hold a
993 Some parts of ipython operate via builtins injected here, which hold a
963 reference to IPython itself."""
994 reference to IPython itself."""
964
995
965 # Install our own quitter instead of the builtins.
996 # Install our own quitter instead of the builtins.
966 # This used to be in the __init__ method, but this is a better
997 # This used to be in the __init__ method, but this is a better
967 # place for it. These can be incorporated to the logic below
998 # place for it. These can be incorporated to the logic below
968 # when it is refactored.
999 # when it is refactored.
969 __builtin__.exit = Quitter(self,'exit')
1000 __builtin__.exit = Quitter(self,'exit')
970 __builtin__.quit = Quitter(self,'quit')
1001 __builtin__.quit = Quitter(self,'quit')
971
1002
972 # Recursive reload
1003 # Recursive reload
973 try:
1004 try:
974 from IPython.lib import deepreload
1005 from IPython.lib import deepreload
975 if self.deep_reload:
1006 if self.deep_reload:
976 __builtin__.reload = deepreload.reload
1007 __builtin__.reload = deepreload.reload
977 else:
1008 else:
978 __builtin__.dreload = deepreload.reload
1009 __builtin__.dreload = deepreload.reload
979 del deepreload
1010 del deepreload
980 except ImportError:
1011 except ImportError:
981 pass
1012 pass
982
1013
983 # TODO: deprecate all of these, they are unsafe. Why though?
1014 # TODO: deprecate all of these, they are unsafe. Why though?
984 builtins_new = dict(__IPYTHON__ = self,
1015 builtins_new = dict(__IPYTHON__ = self,
985 ip_set_hook = self.set_hook,
1016 ip_set_hook = self.set_hook,
986 jobs = self.jobs,
1017 jobs = self.jobs,
987 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
1018 ipmagic = wrap_deprecated(self.ipmagic,'_ip.magic()'),
988 ipalias = wrap_deprecated(self.ipalias),
1019 ipalias = wrap_deprecated(self.ipalias),
989 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
1020 ipsystem = wrap_deprecated(self.ipsystem,'_ip.system()'),
990 #_ip = self.api
1021 #_ip = self.api
991 )
1022 )
992 for biname,bival in builtins_new.items():
1023 for biname,bival in builtins_new.items():
993 try:
1024 try:
994 # store the orignal value so we can restore it
1025 # store the orignal value so we can restore it
995 self.builtins_added[biname] = __builtin__.__dict__[biname]
1026 self.builtins_added[biname] = __builtin__.__dict__[biname]
996 except KeyError:
1027 except KeyError:
997 # or mark that it wasn't defined, and we'll just delete it at
1028 # or mark that it wasn't defined, and we'll just delete it at
998 # cleanup
1029 # cleanup
999 self.builtins_added[biname] = Undefined
1030 self.builtins_added[biname] = Undefined
1000 __builtin__.__dict__[biname] = bival
1031 __builtin__.__dict__[biname] = bival
1001
1032
1002 # Keep in the builtins a flag for when IPython is active. We set it
1033 # Keep in the builtins a flag for when IPython is active. We set it
1003 # with setdefault so that multiple nested IPythons don't clobber one
1034 # with setdefault so that multiple nested IPythons don't clobber one
1004 # another. Each will increase its value by one upon being activated,
1035 # another. Each will increase its value by one upon being activated,
1005 # which also gives us a way to determine the nesting level.
1036 # which also gives us a way to determine the nesting level.
1006 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
1037 __builtin__.__dict__.setdefault('__IPYTHON__active',0)
1007
1038
1008 def clean_builtins(self):
1039 def clean_builtins(self):
1009 """Remove any builtins which might have been added by add_builtins, or
1040 """Remove any builtins which might have been added by add_builtins, or
1010 restore overwritten ones to their previous values."""
1041 restore overwritten ones to their previous values."""
1011 for biname,bival in self.builtins_added.items():
1042 for biname,bival in self.builtins_added.items():
1012 if bival is Undefined:
1043 if bival is Undefined:
1013 del __builtin__.__dict__[biname]
1044 del __builtin__.__dict__[biname]
1014 else:
1045 else:
1015 __builtin__.__dict__[biname] = bival
1046 __builtin__.__dict__[biname] = bival
1016 self.builtins_added.clear()
1047 self.builtins_added.clear()
1017
1048
1018 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
1049 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
1019 """set_hook(name,hook) -> sets an internal IPython hook.
1050 """set_hook(name,hook) -> sets an internal IPython hook.
1020
1051
1021 IPython exposes some of its internal API as user-modifiable hooks. By
1052 IPython exposes some of its internal API as user-modifiable hooks. By
1022 adding your function to one of these hooks, you can modify IPython's
1053 adding your function to one of these hooks, you can modify IPython's
1023 behavior to call at runtime your own routines."""
1054 behavior to call at runtime your own routines."""
1024
1055
1025 # At some point in the future, this should validate the hook before it
1056 # At some point in the future, this should validate the hook before it
1026 # accepts it. Probably at least check that the hook takes the number
1057 # accepts it. Probably at least check that the hook takes the number
1027 # of args it's supposed to.
1058 # of args it's supposed to.
1028
1059
1029 f = new.instancemethod(hook,self,self.__class__)
1060 f = new.instancemethod(hook,self,self.__class__)
1030
1061
1031 # check if the hook is for strdispatcher first
1062 # check if the hook is for strdispatcher first
1032 if str_key is not None:
1063 if str_key is not None:
1033 sdp = self.strdispatchers.get(name, StrDispatch())
1064 sdp = self.strdispatchers.get(name, StrDispatch())
1034 sdp.add_s(str_key, f, priority )
1065 sdp.add_s(str_key, f, priority )
1035 self.strdispatchers[name] = sdp
1066 self.strdispatchers[name] = sdp
1036 return
1067 return
1037 if re_key is not None:
1068 if re_key is not None:
1038 sdp = self.strdispatchers.get(name, StrDispatch())
1069 sdp = self.strdispatchers.get(name, StrDispatch())
1039 sdp.add_re(re.compile(re_key), f, priority )
1070 sdp.add_re(re.compile(re_key), f, priority )
1040 self.strdispatchers[name] = sdp
1071 self.strdispatchers[name] = sdp
1041 return
1072 return
1042
1073
1043 dp = getattr(self.hooks, name, None)
1074 dp = getattr(self.hooks, name, None)
1044 if name not in IPython.core.hooks.__all__:
1075 if name not in IPython.core.hooks.__all__:
1045 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
1076 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
1046 if not dp:
1077 if not dp:
1047 dp = IPython.core.hooks.CommandChainDispatcher()
1078 dp = IPython.core.hooks.CommandChainDispatcher()
1048
1079
1049 try:
1080 try:
1050 dp.add(f,priority)
1081 dp.add(f,priority)
1051 except AttributeError:
1082 except AttributeError:
1052 # it was not commandchain, plain old func - replace
1083 # it was not commandchain, plain old func - replace
1053 dp = f
1084 dp = f
1054
1085
1055 setattr(self.hooks,name, dp)
1086 setattr(self.hooks,name, dp)
1056
1087
1057
1088
1058 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
1089 #setattr(self.hooks,name,new.instancemethod(hook,self,self.__class__))
1059
1090
1060 def set_crash_handler(self,crashHandler):
1091 def set_crash_handler(self,crashHandler):
1061 """Set the IPython crash handler.
1092 """Set the IPython crash handler.
1062
1093
1063 This must be a callable with a signature suitable for use as
1094 This must be a callable with a signature suitable for use as
1064 sys.excepthook."""
1095 sys.excepthook."""
1065
1096
1066 # Install the given crash handler as the Python exception hook
1097 # Install the given crash handler as the Python exception hook
1067 sys.excepthook = crashHandler
1098 sys.excepthook = crashHandler
1068
1099
1069 # The instance will store a pointer to this, so that runtime code
1100 # The instance will store a pointer to this, so that runtime code
1070 # (such as magics) can access it. This is because during the
1101 # (such as magics) can access it. This is because during the
1071 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1102 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1072 # frameworks).
1103 # frameworks).
1073 self.sys_excepthook = sys.excepthook
1104 self.sys_excepthook = sys.excepthook
1074
1105
1075
1106
1076 def set_custom_exc(self,exc_tuple,handler):
1107 def set_custom_exc(self,exc_tuple,handler):
1077 """set_custom_exc(exc_tuple,handler)
1108 """set_custom_exc(exc_tuple,handler)
1078
1109
1079 Set a custom exception handler, which will be called if any of the
1110 Set a custom exception handler, which will be called if any of the
1080 exceptions in exc_tuple occur in the mainloop (specifically, in the
1111 exceptions in exc_tuple occur in the mainloop (specifically, in the
1081 runcode() method.
1112 runcode() method.
1082
1113
1083 Inputs:
1114 Inputs:
1084
1115
1085 - exc_tuple: a *tuple* of valid exceptions to call the defined
1116 - exc_tuple: a *tuple* of valid exceptions to call the defined
1086 handler for. It is very important that you use a tuple, and NOT A
1117 handler for. It is very important that you use a tuple, and NOT A
1087 LIST here, because of the way Python's except statement works. If
1118 LIST here, because of the way Python's except statement works. If
1088 you only want to trap a single exception, use a singleton tuple:
1119 you only want to trap a single exception, use a singleton tuple:
1089
1120
1090 exc_tuple == (MyCustomException,)
1121 exc_tuple == (MyCustomException,)
1091
1122
1092 - handler: this must be defined as a function with the following
1123 - handler: this must be defined as a function with the following
1093 basic interface: def my_handler(self,etype,value,tb).
1124 basic interface: def my_handler(self,etype,value,tb).
1094
1125
1095 This will be made into an instance method (via new.instancemethod)
1126 This will be made into an instance method (via new.instancemethod)
1096 of IPython itself, and it will be called if any of the exceptions
1127 of IPython itself, and it will be called if any of the exceptions
1097 listed in the exc_tuple are caught. If the handler is None, an
1128 listed in the exc_tuple are caught. If the handler is None, an
1098 internal basic one is used, which just prints basic info.
1129 internal basic one is used, which just prints basic info.
1099
1130
1100 WARNING: by putting in your own exception handler into IPython's main
1131 WARNING: by putting in your own exception handler into IPython's main
1101 execution loop, you run a very good chance of nasty crashes. This
1132 execution loop, you run a very good chance of nasty crashes. This
1102 facility should only be used if you really know what you are doing."""
1133 facility should only be used if you really know what you are doing."""
1103
1134
1104 assert type(exc_tuple)==type(()) , \
1135 assert type(exc_tuple)==type(()) , \
1105 "The custom exceptions must be given AS A TUPLE."
1136 "The custom exceptions must be given AS A TUPLE."
1106
1137
1107 def dummy_handler(self,etype,value,tb):
1138 def dummy_handler(self,etype,value,tb):
1108 print '*** Simple custom exception handler ***'
1139 print '*** Simple custom exception handler ***'
1109 print 'Exception type :',etype
1140 print 'Exception type :',etype
1110 print 'Exception value:',value
1141 print 'Exception value:',value
1111 print 'Traceback :',tb
1142 print 'Traceback :',tb
1112 print 'Source code :','\n'.join(self.buffer)
1143 print 'Source code :','\n'.join(self.buffer)
1113
1144
1114 if handler is None: handler = dummy_handler
1145 if handler is None: handler = dummy_handler
1115
1146
1116 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1147 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1117 self.custom_exceptions = exc_tuple
1148 self.custom_exceptions = exc_tuple
1118
1149
1119 def set_custom_completer(self,completer,pos=0):
1150 def set_custom_completer(self,completer,pos=0):
1120 """set_custom_completer(completer,pos=0)
1151 """set_custom_completer(completer,pos=0)
1121
1152
1122 Adds a new custom completer function.
1153 Adds a new custom completer function.
1123
1154
1124 The position argument (defaults to 0) is the index in the completers
1155 The position argument (defaults to 0) is the index in the completers
1125 list where you want the completer to be inserted."""
1156 list where you want the completer to be inserted."""
1126
1157
1127 newcomp = new.instancemethod(completer,self.Completer,
1158 newcomp = new.instancemethod(completer,self.Completer,
1128 self.Completer.__class__)
1159 self.Completer.__class__)
1129 self.Completer.matchers.insert(pos,newcomp)
1160 self.Completer.matchers.insert(pos,newcomp)
1130
1161
1131 def set_completer(self):
1162 def set_completer(self):
1132 """reset readline's completer to be our own."""
1163 """reset readline's completer to be our own."""
1133 self.readline.set_completer(self.Completer.complete)
1164 self.readline.set_completer(self.Completer.complete)
1134
1165
1135 def _get_call_pdb(self):
1166 def _get_call_pdb(self):
1136 return self._call_pdb
1167 return self._call_pdb
1137
1168
1138 def _set_call_pdb(self,val):
1169 def _set_call_pdb(self,val):
1139
1170
1140 if val not in (0,1,False,True):
1171 if val not in (0,1,False,True):
1141 raise ValueError,'new call_pdb value must be boolean'
1172 raise ValueError,'new call_pdb value must be boolean'
1142
1173
1143 # store value in instance
1174 # store value in instance
1144 self._call_pdb = val
1175 self._call_pdb = val
1145
1176
1146 # notify the actual exception handlers
1177 # notify the actual exception handlers
1147 self.InteractiveTB.call_pdb = val
1178 self.InteractiveTB.call_pdb = val
1148 if self.isthreaded:
1179 if self.isthreaded:
1149 try:
1180 try:
1150 self.sys_excepthook.call_pdb = val
1181 self.sys_excepthook.call_pdb = val
1151 except:
1182 except:
1152 warn('Failed to activate pdb for threaded exception handler')
1183 warn('Failed to activate pdb for threaded exception handler')
1153
1184
1154 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1185 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
1155 'Control auto-activation of pdb at exceptions')
1186 'Control auto-activation of pdb at exceptions')
1156
1187
1157 # These special functions get installed in the builtin namespace, to
1188 # These special functions get installed in the builtin namespace, to
1158 # provide programmatic (pure python) access to magics, aliases and system
1189 # provide programmatic (pure python) access to magics, aliases and system
1159 # calls. This is important for logging, user scripting, and more.
1190 # calls. This is important for logging, user scripting, and more.
1160
1191
1161 # We are basically exposing, via normal python functions, the three
1192 # We are basically exposing, via normal python functions, the three
1162 # mechanisms in which ipython offers special call modes (magics for
1193 # mechanisms in which ipython offers special call modes (magics for
1163 # internal control, aliases for direct system access via pre-selected
1194 # internal control, aliases for direct system access via pre-selected
1164 # names, and !cmd for calling arbitrary system commands).
1195 # names, and !cmd for calling arbitrary system commands).
1165
1196
1166 def ipmagic(self,arg_s):
1197 def ipmagic(self,arg_s):
1167 """Call a magic function by name.
1198 """Call a magic function by name.
1168
1199
1169 Input: a string containing the name of the magic function to call and any
1200 Input: a string containing the name of the magic function to call and any
1170 additional arguments to be passed to the magic.
1201 additional arguments to be passed to the magic.
1171
1202
1172 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
1203 ipmagic('name -opt foo bar') is equivalent to typing at the ipython
1173 prompt:
1204 prompt:
1174
1205
1175 In[1]: %name -opt foo bar
1206 In[1]: %name -opt foo bar
1176
1207
1177 To call a magic without arguments, simply use ipmagic('name').
1208 To call a magic without arguments, simply use ipmagic('name').
1178
1209
1179 This provides a proper Python function to call IPython's magics in any
1210 This provides a proper Python function to call IPython's magics in any
1180 valid Python code you can type at the interpreter, including loops and
1211 valid Python code you can type at the interpreter, including loops and
1181 compound statements. It is added by IPython to the Python builtin
1212 compound statements. It is added by IPython to the Python builtin
1182 namespace upon initialization."""
1213 namespace upon initialization."""
1183
1214
1184 args = arg_s.split(' ',1)
1215 args = arg_s.split(' ',1)
1185 magic_name = args[0]
1216 magic_name = args[0]
1186 magic_name = magic_name.lstrip(self.ESC_MAGIC)
1217 magic_name = magic_name.lstrip(self.ESC_MAGIC)
1187
1218
1188 try:
1219 try:
1189 magic_args = args[1]
1220 magic_args = args[1]
1190 except IndexError:
1221 except IndexError:
1191 magic_args = ''
1222 magic_args = ''
1192 fn = getattr(self,'magic_'+magic_name,None)
1223 fn = getattr(self,'magic_'+magic_name,None)
1193 if fn is None:
1224 if fn is None:
1194 error("Magic function `%s` not found." % magic_name)
1225 error("Magic function `%s` not found." % magic_name)
1195 else:
1226 else:
1196 magic_args = self.var_expand(magic_args,1)
1227 magic_args = self.var_expand(magic_args,1)
1197 return fn(magic_args)
1228 return fn(magic_args)
1198
1229
1199 def define_alias(self, name, cmd):
1230 def define_alias(self, name, cmd):
1200 """ Define a new alias."""
1231 """ Define a new alias."""
1201
1232
1202 if callable(cmd):
1233 if callable(cmd):
1203 self.alias_table[name] = cmd
1234 self.alias_table[name] = cmd
1204 from IPython.core import shadowns
1235 from IPython.core import shadowns
1205 setattr(shadowns, name, cmd)
1236 setattr(shadowns, name, cmd)
1206 return
1237 return
1207
1238
1208 if isinstance(cmd, basestring):
1239 if isinstance(cmd, basestring):
1209 nargs = cmd.count('%s')
1240 nargs = cmd.count('%s')
1210 if nargs>0 and cmd.find('%l')>=0:
1241 if nargs>0 and cmd.find('%l')>=0:
1211 raise Exception('The %s and %l specifiers are mutually '
1242 raise Exception('The %s and %l specifiers are mutually '
1212 'exclusive in alias definitions.')
1243 'exclusive in alias definitions.')
1213
1244
1214 self.alias_table[name] = (nargs,cmd)
1245 self.alias_table[name] = (nargs,cmd)
1215 return
1246 return
1216
1247
1217 self.alias_table[name] = cmd
1248 self.alias_table[name] = cmd
1218
1249
1219 def ipalias(self,arg_s):
1250 def ipalias(self,arg_s):
1220 """Call an alias by name.
1251 """Call an alias by name.
1221
1252
1222 Input: a string containing the name of the alias to call and any
1253 Input: a string containing the name of the alias to call and any
1223 additional arguments to be passed to the magic.
1254 additional arguments to be passed to the magic.
1224
1255
1225 ipalias('name -opt foo bar') is equivalent to typing at the ipython
1256 ipalias('name -opt foo bar') is equivalent to typing at the ipython
1226 prompt:
1257 prompt:
1227
1258
1228 In[1]: name -opt foo bar
1259 In[1]: name -opt foo bar
1229
1260
1230 To call an alias without arguments, simply use ipalias('name').
1261 To call an alias without arguments, simply use ipalias('name').
1231
1262
1232 This provides a proper Python function to call IPython's aliases in any
1263 This provides a proper Python function to call IPython's aliases in any
1233 valid Python code you can type at the interpreter, including loops and
1264 valid Python code you can type at the interpreter, including loops and
1234 compound statements. It is added by IPython to the Python builtin
1265 compound statements. It is added by IPython to the Python builtin
1235 namespace upon initialization."""
1266 namespace upon initialization."""
1236
1267
1237 args = arg_s.split(' ',1)
1268 args = arg_s.split(' ',1)
1238 alias_name = args[0]
1269 alias_name = args[0]
1239 try:
1270 try:
1240 alias_args = args[1]
1271 alias_args = args[1]
1241 except IndexError:
1272 except IndexError:
1242 alias_args = ''
1273 alias_args = ''
1243 if alias_name in self.alias_table:
1274 if alias_name in self.alias_table:
1244 self.call_alias(alias_name,alias_args)
1275 self.call_alias(alias_name,alias_args)
1245 else:
1276 else:
1246 error("Alias `%s` not found." % alias_name)
1277 error("Alias `%s` not found." % alias_name)
1247
1278
1248 def system(self, cmd):
1279 def system(self, cmd):
1249 """Make a system call, using IPython."""
1280 """Make a system call, using IPython."""
1250 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1281 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1251
1282
1252 ipsystem = system
1283 ipsystem = system
1253
1284
1254 def getoutput(self, cmd):
1285 def getoutput(self, cmd):
1255 return getoutput(self.var_expand(cmd,depth=2),
1286 return getoutput(self.var_expand(cmd,depth=2),
1256 header=self.system_header,
1287 header=self.system_header,
1257 verbose=self.system_verbose)
1288 verbose=self.system_verbose)
1258
1289
1259 def getoutputerror(self, cmd):
1290 def getoutputerror(self, cmd):
1260 return getoutputerror(self.var_expand(cmd,depth=2),
1291 return getoutputerror(self.var_expand(cmd,depth=2),
1261 header=self.system_header,
1292 header=self.system_header,
1262 verbose=self.system_verbose)
1293 verbose=self.system_verbose)
1263
1294
1264 def complete(self,text):
1295 def complete(self,text):
1265 """Return a sorted list of all possible completions on text.
1296 """Return a sorted list of all possible completions on text.
1266
1297
1267 Inputs:
1298 Inputs:
1268
1299
1269 - text: a string of text to be completed on.
1300 - text: a string of text to be completed on.
1270
1301
1271 This is a wrapper around the completion mechanism, similar to what
1302 This is a wrapper around the completion mechanism, similar to what
1272 readline does at the command line when the TAB key is hit. By
1303 readline does at the command line when the TAB key is hit. By
1273 exposing it as a method, it can be used by other non-readline
1304 exposing it as a method, it can be used by other non-readline
1274 environments (such as GUIs) for text completion.
1305 environments (such as GUIs) for text completion.
1275
1306
1276 Simple usage example:
1307 Simple usage example:
1277
1308
1278 In [7]: x = 'hello'
1309 In [7]: x = 'hello'
1279
1310
1280 In [8]: x
1311 In [8]: x
1281 Out[8]: 'hello'
1312 Out[8]: 'hello'
1282
1313
1283 In [9]: print x
1314 In [9]: print x
1284 hello
1315 hello
1285
1316
1286 In [10]: _ip.IP.complete('x.l')
1317 In [10]: _ip.IP.complete('x.l')
1287 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1318 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1288 """
1319 """
1289
1320
1290 complete = self.Completer.complete
1321 complete = self.Completer.complete
1291 state = 0
1322 state = 0
1292 # use a dict so we get unique keys, since ipyhton's multiple
1323 # use a dict so we get unique keys, since ipyhton's multiple
1293 # completers can return duplicates. When we make 2.4 a requirement,
1324 # completers can return duplicates. When we make 2.4 a requirement,
1294 # start using sets instead, which are faster.
1325 # start using sets instead, which are faster.
1295 comps = {}
1326 comps = {}
1296 while True:
1327 while True:
1297 newcomp = complete(text,state,line_buffer=text)
1328 newcomp = complete(text,state,line_buffer=text)
1298 if newcomp is None:
1329 if newcomp is None:
1299 break
1330 break
1300 comps[newcomp] = 1
1331 comps[newcomp] = 1
1301 state += 1
1332 state += 1
1302 outcomps = comps.keys()
1333 outcomps = comps.keys()
1303 outcomps.sort()
1334 outcomps.sort()
1304 #print "T:",text,"OC:",outcomps # dbg
1335 #print "T:",text,"OC:",outcomps # dbg
1305 #print "vars:",self.user_ns.keys()
1336 #print "vars:",self.user_ns.keys()
1306 return outcomps
1337 return outcomps
1307
1338
1308 def set_completer_frame(self, frame=None):
1339 def set_completer_frame(self, frame=None):
1309 if frame:
1340 if frame:
1310 self.Completer.namespace = frame.f_locals
1341 self.Completer.namespace = frame.f_locals
1311 self.Completer.global_namespace = frame.f_globals
1342 self.Completer.global_namespace = frame.f_globals
1312 else:
1343 else:
1313 self.Completer.namespace = self.user_ns
1344 self.Completer.namespace = self.user_ns
1314 self.Completer.global_namespace = self.user_global_ns
1345 self.Completer.global_namespace = self.user_global_ns
1315
1346
1316 def init_auto_alias(self):
1347 def init_auto_alias(self):
1317 """Define some aliases automatically.
1348 """Define some aliases automatically.
1318
1349
1319 These are ALL parameter-less aliases"""
1350 These are ALL parameter-less aliases"""
1320
1351
1321 for alias,cmd in self.auto_alias:
1352 for alias,cmd in self.auto_alias:
1322 self.getapi().defalias(alias,cmd)
1353 self.getapi().defalias(alias,cmd)
1323
1354
1324
1355
1325 def alias_table_validate(self,verbose=0):
1356 def alias_table_validate(self,verbose=0):
1326 """Update information about the alias table.
1357 """Update information about the alias table.
1327
1358
1328 In particular, make sure no Python keywords/builtins are in it."""
1359 In particular, make sure no Python keywords/builtins are in it."""
1329
1360
1330 no_alias = self.no_alias
1361 no_alias = self.no_alias
1331 for k in self.alias_table.keys():
1362 for k in self.alias_table.keys():
1332 if k in no_alias:
1363 if k in no_alias:
1333 del self.alias_table[k]
1364 del self.alias_table[k]
1334 if verbose:
1365 if verbose:
1335 print ("Deleting alias <%s>, it's a Python "
1366 print ("Deleting alias <%s>, it's a Python "
1336 "keyword or builtin." % k)
1367 "keyword or builtin." % k)
1337
1368
1338 def set_autoindent(self,value=None):
1369 def set_autoindent(self,value=None):
1339 """Set the autoindent flag, checking for readline support.
1370 """Set the autoindent flag, checking for readline support.
1340
1371
1341 If called with no arguments, it acts as a toggle."""
1372 If called with no arguments, it acts as a toggle."""
1342
1373
1343 if not self.has_readline:
1374 if not self.has_readline:
1344 if os.name == 'posix':
1375 if os.name == 'posix':
1345 warn("The auto-indent feature requires the readline library")
1376 warn("The auto-indent feature requires the readline library")
1346 self.autoindent = 0
1377 self.autoindent = 0
1347 return
1378 return
1348 if value is None:
1379 if value is None:
1349 self.autoindent = not self.autoindent
1380 self.autoindent = not self.autoindent
1350 else:
1381 else:
1351 self.autoindent = value
1382 self.autoindent = value
1352
1383
1353 def atexit_operations(self):
1384 def atexit_operations(self):
1354 """This will be executed at the time of exit.
1385 """This will be executed at the time of exit.
1355
1386
1356 Saving of persistent data should be performed here. """
1387 Saving of persistent data should be performed here. """
1357
1388
1358 #print '*** IPython exit cleanup ***' # dbg
1389 #print '*** IPython exit cleanup ***' # dbg
1359 # input history
1390 # input history
1360 self.savehist()
1391 self.savehist()
1361
1392
1362 # Cleanup all tempfiles left around
1393 # Cleanup all tempfiles left around
1363 for tfile in self.tempfiles:
1394 for tfile in self.tempfiles:
1364 try:
1395 try:
1365 os.unlink(tfile)
1396 os.unlink(tfile)
1366 except OSError:
1397 except OSError:
1367 pass
1398 pass
1368
1399
1369 # Clear all user namespaces to release all references cleanly.
1400 # Clear all user namespaces to release all references cleanly.
1370 self.reset()
1401 self.reset()
1371
1402
1372 # Run user hooks
1403 # Run user hooks
1373 self.hooks.shutdown_hook()
1404 self.hooks.shutdown_hook()
1374
1405
1375 def reset(self):
1406 def reset(self):
1376 """Clear all internal namespaces.
1407 """Clear all internal namespaces.
1377
1408
1378 Note that this is much more aggressive than %reset, since it clears
1409 Note that this is much more aggressive than %reset, since it clears
1379 fully all namespaces, as well as all input/output lists.
1410 fully all namespaces, as well as all input/output lists.
1380 """
1411 """
1381 for ns in self.ns_refs_table:
1412 for ns in self.ns_refs_table:
1382 ns.clear()
1413 ns.clear()
1383
1414
1384 # Clear input and output histories
1415 # Clear input and output histories
1385 self.input_hist[:] = []
1416 self.input_hist[:] = []
1386 self.input_hist_raw[:] = []
1417 self.input_hist_raw[:] = []
1387 self.output_hist.clear()
1418 self.output_hist.clear()
1388 # Restore the user namespaces to minimal usability
1419 # Restore the user namespaces to minimal usability
1389 self.init_namespaces()
1420 self.init_namespaces()
1390
1421
1391 def savehist(self):
1422 def savehist(self):
1392 """Save input history to a file (via readline library)."""
1423 """Save input history to a file (via readline library)."""
1393
1424
1394 if not self.has_readline:
1425 if not self.has_readline:
1395 return
1426 return
1396
1427
1397 try:
1428 try:
1398 self.readline.write_history_file(self.histfile)
1429 self.readline.write_history_file(self.histfile)
1399 except:
1430 except:
1400 print 'Unable to save IPython command history to file: ' + \
1431 print 'Unable to save IPython command history to file: ' + \
1401 `self.histfile`
1432 `self.histfile`
1402
1433
1403 def reloadhist(self):
1434 def reloadhist(self):
1404 """Reload the input history from disk file."""
1435 """Reload the input history from disk file."""
1405
1436
1406 if self.has_readline:
1437 if self.has_readline:
1407 try:
1438 try:
1408 self.readline.clear_history()
1439 self.readline.clear_history()
1409 self.readline.read_history_file(self.shell.histfile)
1440 self.readline.read_history_file(self.shell.histfile)
1410 except AttributeError:
1441 except AttributeError:
1411 pass
1442 pass
1412
1443
1413
1444
1414 def history_saving_wrapper(self, func):
1445 def history_saving_wrapper(self, func):
1415 """ Wrap func for readline history saving
1446 """ Wrap func for readline history saving
1416
1447
1417 Convert func into callable that saves & restores
1448 Convert func into callable that saves & restores
1418 history around the call """
1449 history around the call """
1419
1450
1420 if not self.has_readline:
1451 if not self.has_readline:
1421 return func
1452 return func
1422
1453
1423 def wrapper():
1454 def wrapper():
1424 self.savehist()
1455 self.savehist()
1425 try:
1456 try:
1426 func()
1457 func()
1427 finally:
1458 finally:
1428 readline.read_history_file(self.histfile)
1459 readline.read_history_file(self.histfile)
1429 return wrapper
1460 return wrapper
1430
1461
1431 def pre_readline(self):
1462 def pre_readline(self):
1432 """readline hook to be used at the start of each line.
1463 """readline hook to be used at the start of each line.
1433
1464
1434 Currently it handles auto-indent only."""
1465 Currently it handles auto-indent only."""
1435
1466
1436 #debugx('self.indent_current_nsp','pre_readline:')
1467 #debugx('self.indent_current_nsp','pre_readline:')
1437
1468
1438 if self.rl_do_indent:
1469 if self.rl_do_indent:
1439 self.readline.insert_text(self.indent_current_str())
1470 self.readline.insert_text(self.indent_current_str())
1440 if self.rl_next_input is not None:
1471 if self.rl_next_input is not None:
1441 self.readline.insert_text(self.rl_next_input)
1472 self.readline.insert_text(self.rl_next_input)
1442 self.rl_next_input = None
1473 self.rl_next_input = None
1443
1474
1444 def ask_yes_no(self,prompt,default=True):
1475 def ask_yes_no(self,prompt,default=True):
1445 if self.quiet:
1476 if self.quiet:
1446 return True
1477 return True
1447 return ask_yes_no(prompt,default)
1478 return ask_yes_no(prompt,default)
1448
1479
1449 def new_main_mod(self,ns=None):
1480 def new_main_mod(self,ns=None):
1450 """Return a new 'main' module object for user code execution.
1481 """Return a new 'main' module object for user code execution.
1451 """
1482 """
1452 main_mod = self._user_main_module
1483 main_mod = self._user_main_module
1453 init_fakemod_dict(main_mod,ns)
1484 init_fakemod_dict(main_mod,ns)
1454 return main_mod
1485 return main_mod
1455
1486
1456 def cache_main_mod(self,ns,fname):
1487 def cache_main_mod(self,ns,fname):
1457 """Cache a main module's namespace.
1488 """Cache a main module's namespace.
1458
1489
1459 When scripts are executed via %run, we must keep a reference to the
1490 When scripts are executed via %run, we must keep a reference to the
1460 namespace of their __main__ module (a FakeModule instance) around so
1491 namespace of their __main__ module (a FakeModule instance) around so
1461 that Python doesn't clear it, rendering objects defined therein
1492 that Python doesn't clear it, rendering objects defined therein
1462 useless.
1493 useless.
1463
1494
1464 This method keeps said reference in a private dict, keyed by the
1495 This method keeps said reference in a private dict, keyed by the
1465 absolute path of the module object (which corresponds to the script
1496 absolute path of the module object (which corresponds to the script
1466 path). This way, for multiple executions of the same script we only
1497 path). This way, for multiple executions of the same script we only
1467 keep one copy of the namespace (the last one), thus preventing memory
1498 keep one copy of the namespace (the last one), thus preventing memory
1468 leaks from old references while allowing the objects from the last
1499 leaks from old references while allowing the objects from the last
1469 execution to be accessible.
1500 execution to be accessible.
1470
1501
1471 Note: we can not allow the actual FakeModule instances to be deleted,
1502 Note: we can not allow the actual FakeModule instances to be deleted,
1472 because of how Python tears down modules (it hard-sets all their
1503 because of how Python tears down modules (it hard-sets all their
1473 references to None without regard for reference counts). This method
1504 references to None without regard for reference counts). This method
1474 must therefore make a *copy* of the given namespace, to allow the
1505 must therefore make a *copy* of the given namespace, to allow the
1475 original module's __dict__ to be cleared and reused.
1506 original module's __dict__ to be cleared and reused.
1476
1507
1477
1508
1478 Parameters
1509 Parameters
1479 ----------
1510 ----------
1480 ns : a namespace (a dict, typically)
1511 ns : a namespace (a dict, typically)
1481
1512
1482 fname : str
1513 fname : str
1483 Filename associated with the namespace.
1514 Filename associated with the namespace.
1484
1515
1485 Examples
1516 Examples
1486 --------
1517 --------
1487
1518
1488 In [10]: import IPython
1519 In [10]: import IPython
1489
1520
1490 In [11]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)
1521 In [11]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)
1491
1522
1492 In [12]: IPython.__file__ in _ip.IP._main_ns_cache
1523 In [12]: IPython.__file__ in _ip.IP._main_ns_cache
1493 Out[12]: True
1524 Out[12]: True
1494 """
1525 """
1495 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
1526 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
1496
1527
1497 def clear_main_mod_cache(self):
1528 def clear_main_mod_cache(self):
1498 """Clear the cache of main modules.
1529 """Clear the cache of main modules.
1499
1530
1500 Mainly for use by utilities like %reset.
1531 Mainly for use by utilities like %reset.
1501
1532
1502 Examples
1533 Examples
1503 --------
1534 --------
1504
1535
1505 In [15]: import IPython
1536 In [15]: import IPython
1506
1537
1507 In [16]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)
1538 In [16]: _ip.IP.cache_main_mod(IPython.__dict__,IPython.__file__)
1508
1539
1509 In [17]: len(_ip.IP._main_ns_cache) > 0
1540 In [17]: len(_ip.IP._main_ns_cache) > 0
1510 Out[17]: True
1541 Out[17]: True
1511
1542
1512 In [18]: _ip.IP.clear_main_mod_cache()
1543 In [18]: _ip.IP.clear_main_mod_cache()
1513
1544
1514 In [19]: len(_ip.IP._main_ns_cache) == 0
1545 In [19]: len(_ip.IP._main_ns_cache) == 0
1515 Out[19]: True
1546 Out[19]: True
1516 """
1547 """
1517 self._main_ns_cache.clear()
1548 self._main_ns_cache.clear()
1518
1549
1519 def _should_recompile(self,e):
1550 def _should_recompile(self,e):
1520 """Utility routine for edit_syntax_error"""
1551 """Utility routine for edit_syntax_error"""
1521
1552
1522 if e.filename in ('<ipython console>','<input>','<string>',
1553 if e.filename in ('<ipython console>','<input>','<string>',
1523 '<console>','<BackgroundJob compilation>',
1554 '<console>','<BackgroundJob compilation>',
1524 None):
1555 None):
1525
1556
1526 return False
1557 return False
1527 try:
1558 try:
1528 if (self.autoedit_syntax and
1559 if (self.autoedit_syntax and
1529 not self.ask_yes_no('Return to editor to correct syntax error? '
1560 not self.ask_yes_no('Return to editor to correct syntax error? '
1530 '[Y/n] ','y')):
1561 '[Y/n] ','y')):
1531 return False
1562 return False
1532 except EOFError:
1563 except EOFError:
1533 return False
1564 return False
1534
1565
1535 def int0(x):
1566 def int0(x):
1536 try:
1567 try:
1537 return int(x)
1568 return int(x)
1538 except TypeError:
1569 except TypeError:
1539 return 0
1570 return 0
1540 # always pass integer line and offset values to editor hook
1571 # always pass integer line and offset values to editor hook
1541 try:
1572 try:
1542 self.hooks.fix_error_editor(e.filename,
1573 self.hooks.fix_error_editor(e.filename,
1543 int0(e.lineno),int0(e.offset),e.msg)
1574 int0(e.lineno),int0(e.offset),e.msg)
1544 except ipapi.TryNext:
1575 except ipapi.TryNext:
1545 warn('Could not open editor')
1576 warn('Could not open editor')
1546 return False
1577 return False
1547 return True
1578 return True
1548
1579
1549 def edit_syntax_error(self):
1580 def edit_syntax_error(self):
1550 """The bottom half of the syntax error handler called in the main loop.
1581 """The bottom half of the syntax error handler called in the main loop.
1551
1582
1552 Loop until syntax error is fixed or user cancels.
1583 Loop until syntax error is fixed or user cancels.
1553 """
1584 """
1554
1585
1555 while self.SyntaxTB.last_syntax_error:
1586 while self.SyntaxTB.last_syntax_error:
1556 # copy and clear last_syntax_error
1587 # copy and clear last_syntax_error
1557 err = self.SyntaxTB.clear_err_state()
1588 err = self.SyntaxTB.clear_err_state()
1558 if not self._should_recompile(err):
1589 if not self._should_recompile(err):
1559 return
1590 return
1560 try:
1591 try:
1561 # may set last_syntax_error again if a SyntaxError is raised
1592 # may set last_syntax_error again if a SyntaxError is raised
1562 self.safe_execfile(err.filename,self.user_ns)
1593 self.safe_execfile(err.filename,self.user_ns)
1563 except:
1594 except:
1564 self.showtraceback()
1595 self.showtraceback()
1565 else:
1596 else:
1566 try:
1597 try:
1567 f = file(err.filename)
1598 f = file(err.filename)
1568 try:
1599 try:
1569 sys.displayhook(f.read())
1600 sys.displayhook(f.read())
1570 finally:
1601 finally:
1571 f.close()
1602 f.close()
1572 except:
1603 except:
1573 self.showtraceback()
1604 self.showtraceback()
1574
1605
1575 def showsyntaxerror(self, filename=None):
1606 def showsyntaxerror(self, filename=None):
1576 """Display the syntax error that just occurred.
1607 """Display the syntax error that just occurred.
1577
1608
1578 This doesn't display a stack trace because there isn't one.
1609 This doesn't display a stack trace because there isn't one.
1579
1610
1580 If a filename is given, it is stuffed in the exception instead
1611 If a filename is given, it is stuffed in the exception instead
1581 of what was there before (because Python's parser always uses
1612 of what was there before (because Python's parser always uses
1582 "<string>" when reading from a string).
1613 "<string>" when reading from a string).
1583 """
1614 """
1584 etype, value, last_traceback = sys.exc_info()
1615 etype, value, last_traceback = sys.exc_info()
1585
1616
1586 # See note about these variables in showtraceback() below
1617 # See note about these variables in showtraceback() below
1587 sys.last_type = etype
1618 sys.last_type = etype
1588 sys.last_value = value
1619 sys.last_value = value
1589 sys.last_traceback = last_traceback
1620 sys.last_traceback = last_traceback
1590
1621
1591 if filename and etype is SyntaxError:
1622 if filename and etype is SyntaxError:
1592 # Work hard to stuff the correct filename in the exception
1623 # Work hard to stuff the correct filename in the exception
1593 try:
1624 try:
1594 msg, (dummy_filename, lineno, offset, line) = value
1625 msg, (dummy_filename, lineno, offset, line) = value
1595 except:
1626 except:
1596 # Not the format we expect; leave it alone
1627 # Not the format we expect; leave it alone
1597 pass
1628 pass
1598 else:
1629 else:
1599 # Stuff in the right filename
1630 # Stuff in the right filename
1600 try:
1631 try:
1601 # Assume SyntaxError is a class exception
1632 # Assume SyntaxError is a class exception
1602 value = SyntaxError(msg, (filename, lineno, offset, line))
1633 value = SyntaxError(msg, (filename, lineno, offset, line))
1603 except:
1634 except:
1604 # If that failed, assume SyntaxError is a string
1635 # If that failed, assume SyntaxError is a string
1605 value = msg, (filename, lineno, offset, line)
1636 value = msg, (filename, lineno, offset, line)
1606 self.SyntaxTB(etype,value,[])
1637 self.SyntaxTB(etype,value,[])
1607
1638
1608 def debugger(self,force=False):
1639 def debugger(self,force=False):
1609 """Call the pydb/pdb debugger.
1640 """Call the pydb/pdb debugger.
1610
1641
1611 Keywords:
1642 Keywords:
1612
1643
1613 - force(False): by default, this routine checks the instance call_pdb
1644 - force(False): by default, this routine checks the instance call_pdb
1614 flag and does not actually invoke the debugger if the flag is false.
1645 flag and does not actually invoke the debugger if the flag is false.
1615 The 'force' option forces the debugger to activate even if the flag
1646 The 'force' option forces the debugger to activate even if the flag
1616 is false.
1647 is false.
1617 """
1648 """
1618
1649
1619 if not (force or self.call_pdb):
1650 if not (force or self.call_pdb):
1620 return
1651 return
1621
1652
1622 if not hasattr(sys,'last_traceback'):
1653 if not hasattr(sys,'last_traceback'):
1623 error('No traceback has been produced, nothing to debug.')
1654 error('No traceback has been produced, nothing to debug.')
1624 return
1655 return
1625
1656
1626 # use pydb if available
1657 # use pydb if available
1627 if debugger.has_pydb:
1658 if debugger.has_pydb:
1628 from pydb import pm
1659 from pydb import pm
1629 else:
1660 else:
1630 # fallback to our internal debugger
1661 # fallback to our internal debugger
1631 pm = lambda : self.InteractiveTB.debugger(force=True)
1662 pm = lambda : self.InteractiveTB.debugger(force=True)
1632 self.history_saving_wrapper(pm)()
1663 self.history_saving_wrapper(pm)()
1633
1664
1634 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1665 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1635 """Display the exception that just occurred.
1666 """Display the exception that just occurred.
1636
1667
1637 If nothing is known about the exception, this is the method which
1668 If nothing is known about the exception, this is the method which
1638 should be used throughout the code for presenting user tracebacks,
1669 should be used throughout the code for presenting user tracebacks,
1639 rather than directly invoking the InteractiveTB object.
1670 rather than directly invoking the InteractiveTB object.
1640
1671
1641 A specific showsyntaxerror() also exists, but this method can take
1672 A specific showsyntaxerror() also exists, but this method can take
1642 care of calling it if needed, so unless you are explicitly catching a
1673 care of calling it if needed, so unless you are explicitly catching a
1643 SyntaxError exception, don't try to analyze the stack manually and
1674 SyntaxError exception, don't try to analyze the stack manually and
1644 simply call this method."""
1675 simply call this method."""
1645
1676
1646
1677
1647 # Though this won't be called by syntax errors in the input line,
1678 # Though this won't be called by syntax errors in the input line,
1648 # there may be SyntaxError cases whith imported code.
1679 # there may be SyntaxError cases whith imported code.
1649
1680
1650 try:
1681 try:
1651 if exc_tuple is None:
1682 if exc_tuple is None:
1652 etype, value, tb = sys.exc_info()
1683 etype, value, tb = sys.exc_info()
1653 else:
1684 else:
1654 etype, value, tb = exc_tuple
1685 etype, value, tb = exc_tuple
1655
1686
1656 if etype is SyntaxError:
1687 if etype is SyntaxError:
1657 self.showsyntaxerror(filename)
1688 self.showsyntaxerror(filename)
1658 elif etype is ipapi.UsageError:
1689 elif etype is ipapi.UsageError:
1659 print "UsageError:", value
1690 print "UsageError:", value
1660 else:
1691 else:
1661 # WARNING: these variables are somewhat deprecated and not
1692 # WARNING: these variables are somewhat deprecated and not
1662 # necessarily safe to use in a threaded environment, but tools
1693 # necessarily safe to use in a threaded environment, but tools
1663 # like pdb depend on their existence, so let's set them. If we
1694 # like pdb depend on their existence, so let's set them. If we
1664 # find problems in the field, we'll need to revisit their use.
1695 # find problems in the field, we'll need to revisit their use.
1665 sys.last_type = etype
1696 sys.last_type = etype
1666 sys.last_value = value
1697 sys.last_value = value
1667 sys.last_traceback = tb
1698 sys.last_traceback = tb
1668
1699
1669 if etype in self.custom_exceptions:
1700 if etype in self.custom_exceptions:
1670 self.CustomTB(etype,value,tb)
1701 self.CustomTB(etype,value,tb)
1671 else:
1702 else:
1672 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1703 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1673 if self.InteractiveTB.call_pdb and self.has_readline:
1704 if self.InteractiveTB.call_pdb and self.has_readline:
1674 # pdb mucks up readline, fix it back
1705 # pdb mucks up readline, fix it back
1675 self.set_completer()
1706 self.set_completer()
1676 except KeyboardInterrupt:
1707 except KeyboardInterrupt:
1677 self.write("\nKeyboardInterrupt\n")
1708 self.write("\nKeyboardInterrupt\n")
1678
1709
1679 def mainloop(self, banner=None):
1710 def mainloop(self, banner=None):
1680 """Start the mainloop.
1711 """Start the mainloop.
1681
1712
1682 If an optional banner argument is given, it will override the
1713 If an optional banner argument is given, it will override the
1683 internally created default banner.
1714 internally created default banner.
1684 """
1715 """
1685 if self.c: # Emulate Python's -c option
1716 if self.c: # Emulate Python's -c option
1686 self.exec_init_cmd()
1717 self.exec_init_cmd()
1687
1718
1688 if self.display_banner:
1719 if self.display_banner:
1689 if banner is None:
1720 if banner is None:
1690 banner = self.banner
1721 banner = self.banner
1691
1722
1692 # if you run stuff with -c <cmd>, raw hist is not updated
1723 # if you run stuff with -c <cmd>, raw hist is not updated
1693 # ensure that it's in sync
1724 # ensure that it's in sync
1694 if len(self.input_hist) != len (self.input_hist_raw):
1725 if len(self.input_hist) != len (self.input_hist_raw):
1695 self.input_hist_raw = InputList(self.input_hist)
1726 self.input_hist_raw = InputList(self.input_hist)
1696
1727
1697 while 1:
1728 while 1:
1698 try:
1729 try:
1699 self.interact()
1730 self.interact()
1700 #self.interact_with_readline()
1731 #self.interact_with_readline()
1701 # XXX for testing of a readline-decoupled repl loop, call
1732 # XXX for testing of a readline-decoupled repl loop, call
1702 # interact_with_readline above
1733 # interact_with_readline above
1703 break
1734 break
1704 except KeyboardInterrupt:
1735 except KeyboardInterrupt:
1705 # this should not be necessary, but KeyboardInterrupt
1736 # this should not be necessary, but KeyboardInterrupt
1706 # handling seems rather unpredictable...
1737 # handling seems rather unpredictable...
1707 self.write("\nKeyboardInterrupt in interact()\n")
1738 self.write("\nKeyboardInterrupt in interact()\n")
1708
1739
1709 def exec_init_cmd(self):
1740 def exec_init_cmd(self):
1710 """Execute a command given at the command line.
1741 """Execute a command given at the command line.
1711
1742
1712 This emulates Python's -c option."""
1743 This emulates Python's -c option."""
1713
1744
1714 #sys.argv = ['-c']
1745 #sys.argv = ['-c']
1715 self.push(self.prefilter(self.c, False))
1746 self.push(self.prefilter(self.c, False))
1716 if not self.interactive:
1747 if not self.interactive:
1717 self.ask_exit()
1748 self.ask_exit()
1718
1749
1719 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1750 def embed_mainloop(self,header='',local_ns=None,global_ns=None,stack_depth=0):
1720 """Embeds IPython into a running python program.
1751 """Embeds IPython into a running python program.
1721
1752
1722 Input:
1753 Input:
1723
1754
1724 - header: An optional header message can be specified.
1755 - header: An optional header message can be specified.
1725
1756
1726 - local_ns, global_ns: working namespaces. If given as None, the
1757 - local_ns, global_ns: working namespaces. If given as None, the
1727 IPython-initialized one is updated with __main__.__dict__, so that
1758 IPython-initialized one is updated with __main__.__dict__, so that
1728 program variables become visible but user-specific configuration
1759 program variables become visible but user-specific configuration
1729 remains possible.
1760 remains possible.
1730
1761
1731 - stack_depth: specifies how many levels in the stack to go to
1762 - stack_depth: specifies how many levels in the stack to go to
1732 looking for namespaces (when local_ns and global_ns are None). This
1763 looking for namespaces (when local_ns and global_ns are None). This
1733 allows an intermediate caller to make sure that this function gets
1764 allows an intermediate caller to make sure that this function gets
1734 the namespace from the intended level in the stack. By default (0)
1765 the namespace from the intended level in the stack. By default (0)
1735 it will get its locals and globals from the immediate caller.
1766 it will get its locals and globals from the immediate caller.
1736
1767
1737 Warning: it's possible to use this in a program which is being run by
1768 Warning: it's possible to use this in a program which is being run by
1738 IPython itself (via %run), but some funny things will happen (a few
1769 IPython itself (via %run), but some funny things will happen (a few
1739 globals get overwritten). In the future this will be cleaned up, as
1770 globals get overwritten). In the future this will be cleaned up, as
1740 there is no fundamental reason why it can't work perfectly."""
1771 there is no fundamental reason why it can't work perfectly."""
1741
1772
1742 # Get locals and globals from caller
1773 # Get locals and globals from caller
1743 if local_ns is None or global_ns is None:
1774 if local_ns is None or global_ns is None:
1744 call_frame = sys._getframe(stack_depth).f_back
1775 call_frame = sys._getframe(stack_depth).f_back
1745
1776
1746 if local_ns is None:
1777 if local_ns is None:
1747 local_ns = call_frame.f_locals
1778 local_ns = call_frame.f_locals
1748 if global_ns is None:
1779 if global_ns is None:
1749 global_ns = call_frame.f_globals
1780 global_ns = call_frame.f_globals
1750
1781
1751 # Update namespaces and fire up interpreter
1782 # Update namespaces and fire up interpreter
1752
1783
1753 # The global one is easy, we can just throw it in
1784 # The global one is easy, we can just throw it in
1754 self.user_global_ns = global_ns
1785 self.user_global_ns = global_ns
1755
1786
1756 # but the user/local one is tricky: ipython needs it to store internal
1787 # but the user/local one is tricky: ipython needs it to store internal
1757 # data, but we also need the locals. We'll copy locals in the user
1788 # data, but we also need the locals. We'll copy locals in the user
1758 # one, but will track what got copied so we can delete them at exit.
1789 # one, but will track what got copied so we can delete them at exit.
1759 # This is so that a later embedded call doesn't see locals from a
1790 # This is so that a later embedded call doesn't see locals from a
1760 # previous call (which most likely existed in a separate scope).
1791 # previous call (which most likely existed in a separate scope).
1761 local_varnames = local_ns.keys()
1792 local_varnames = local_ns.keys()
1762 self.user_ns.update(local_ns)
1793 self.user_ns.update(local_ns)
1763 #self.user_ns['local_ns'] = local_ns # dbg
1794 #self.user_ns['local_ns'] = local_ns # dbg
1764
1795
1765 # Patch for global embedding to make sure that things don't overwrite
1796 # Patch for global embedding to make sure that things don't overwrite
1766 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1797 # user globals accidentally. Thanks to Richard <rxe@renre-europe.com>
1767 # FIXME. Test this a bit more carefully (the if.. is new)
1798 # FIXME. Test this a bit more carefully (the if.. is new)
1768 if local_ns is None and global_ns is None:
1799 if local_ns is None and global_ns is None:
1769 self.user_global_ns.update(__main__.__dict__)
1800 self.user_global_ns.update(__main__.__dict__)
1770
1801
1771 # make sure the tab-completer has the correct frame information, so it
1802 # make sure the tab-completer has the correct frame information, so it
1772 # actually completes using the frame's locals/globals
1803 # actually completes using the frame's locals/globals
1773 self.set_completer_frame()
1804 self.set_completer_frame()
1774
1805
1775 # before activating the interactive mode, we need to make sure that
1806 # before activating the interactive mode, we need to make sure that
1776 # all names in the builtin namespace needed by ipython point to
1807 # all names in the builtin namespace needed by ipython point to
1777 # ourselves, and not to other instances.
1808 # ourselves, and not to other instances.
1778 self.add_builtins()
1809 self.add_builtins()
1779
1810
1780 self.interact(header)
1811 self.interact(header)
1781
1812
1782 # now, purge out the user namespace from anything we might have added
1813 # now, purge out the user namespace from anything we might have added
1783 # from the caller's local namespace
1814 # from the caller's local namespace
1784 delvar = self.user_ns.pop
1815 delvar = self.user_ns.pop
1785 for var in local_varnames:
1816 for var in local_varnames:
1786 delvar(var,None)
1817 delvar(var,None)
1787 # and clean builtins we may have overridden
1818 # and clean builtins we may have overridden
1788 self.clean_builtins()
1819 self.clean_builtins()
1789
1820
1790 def interact_prompt(self):
1821 def interact_prompt(self):
1791 """ Print the prompt (in read-eval-print loop)
1822 """ Print the prompt (in read-eval-print loop)
1792
1823
1793 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1824 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1794 used in standard IPython flow.
1825 used in standard IPython flow.
1795 """
1826 """
1796 if self.more:
1827 if self.more:
1797 try:
1828 try:
1798 prompt = self.hooks.generate_prompt(True)
1829 prompt = self.hooks.generate_prompt(True)
1799 except:
1830 except:
1800 self.showtraceback()
1831 self.showtraceback()
1801 if self.autoindent:
1832 if self.autoindent:
1802 self.rl_do_indent = True
1833 self.rl_do_indent = True
1803
1834
1804 else:
1835 else:
1805 try:
1836 try:
1806 prompt = self.hooks.generate_prompt(False)
1837 prompt = self.hooks.generate_prompt(False)
1807 except:
1838 except:
1808 self.showtraceback()
1839 self.showtraceback()
1809 self.write(prompt)
1840 self.write(prompt)
1810
1841
1811 def interact_handle_input(self,line):
1842 def interact_handle_input(self,line):
1812 """ Handle the input line (in read-eval-print loop)
1843 """ Handle the input line (in read-eval-print loop)
1813
1844
1814 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1845 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1815 used in standard IPython flow.
1846 used in standard IPython flow.
1816 """
1847 """
1817 if line.lstrip() == line:
1848 if line.lstrip() == line:
1818 self.shadowhist.add(line.strip())
1849 self.shadowhist.add(line.strip())
1819 lineout = self.prefilter(line,self.more)
1850 lineout = self.prefilter(line,self.more)
1820
1851
1821 if line.strip():
1852 if line.strip():
1822 if self.more:
1853 if self.more:
1823 self.input_hist_raw[-1] += '%s\n' % line
1854 self.input_hist_raw[-1] += '%s\n' % line
1824 else:
1855 else:
1825 self.input_hist_raw.append('%s\n' % line)
1856 self.input_hist_raw.append('%s\n' % line)
1826
1857
1827
1858
1828 self.more = self.push(lineout)
1859 self.more = self.push(lineout)
1829 if (self.SyntaxTB.last_syntax_error and
1860 if (self.SyntaxTB.last_syntax_error and
1830 self.autoedit_syntax):
1861 self.autoedit_syntax):
1831 self.edit_syntax_error()
1862 self.edit_syntax_error()
1832
1863
1833 def interact_with_readline(self):
1864 def interact_with_readline(self):
1834 """ Demo of using interact_handle_input, interact_prompt
1865 """ Demo of using interact_handle_input, interact_prompt
1835
1866
1836 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1867 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1837 it should work like this.
1868 it should work like this.
1838 """
1869 """
1839 self.readline_startup_hook(self.pre_readline)
1870 self.readline_startup_hook(self.pre_readline)
1840 while not self.exit_now:
1871 while not self.exit_now:
1841 self.interact_prompt()
1872 self.interact_prompt()
1842 if self.more:
1873 if self.more:
1843 self.rl_do_indent = True
1874 self.rl_do_indent = True
1844 else:
1875 else:
1845 self.rl_do_indent = False
1876 self.rl_do_indent = False
1846 line = raw_input_original().decode(self.stdin_encoding)
1877 line = raw_input_original().decode(self.stdin_encoding)
1847 self.interact_handle_input(line)
1878 self.interact_handle_input(line)
1848
1879
1849 def interact(self, banner=None):
1880 def interact(self, banner=None):
1850 """Closely emulate the interactive Python console."""
1881 """Closely emulate the interactive Python console."""
1851
1882
1852 # batch run -> do not interact
1883 # batch run -> do not interact
1853 if self.exit_now:
1884 if self.exit_now:
1854 return
1885 return
1855
1886
1856 if self.display_banner:
1887 if self.display_banner:
1857 if banner is None:
1888 if banner is None:
1858 banner = self.banner
1889 banner = self.banner
1859 self.write(banner)
1890 self.write(banner)
1860
1891
1861 more = 0
1892 more = 0
1862
1893
1863 # Mark activity in the builtins
1894 # Mark activity in the builtins
1864 __builtin__.__dict__['__IPYTHON__active'] += 1
1895 __builtin__.__dict__['__IPYTHON__active'] += 1
1865
1896
1866 if self.has_readline:
1897 if self.has_readline:
1867 self.readline_startup_hook(self.pre_readline)
1898 self.readline_startup_hook(self.pre_readline)
1868 # exit_now is set by a call to %Exit or %Quit, through the
1899 # exit_now is set by a call to %Exit or %Quit, through the
1869 # ask_exit callback.
1900 # ask_exit callback.
1870
1901
1871 while not self.exit_now:
1902 while not self.exit_now:
1872 self.hooks.pre_prompt_hook()
1903 self.hooks.pre_prompt_hook()
1873 if more:
1904 if more:
1874 try:
1905 try:
1875 prompt = self.hooks.generate_prompt(True)
1906 prompt = self.hooks.generate_prompt(True)
1876 except:
1907 except:
1877 self.showtraceback()
1908 self.showtraceback()
1878 if self.autoindent:
1909 if self.autoindent:
1879 self.rl_do_indent = True
1910 self.rl_do_indent = True
1880
1911
1881 else:
1912 else:
1882 try:
1913 try:
1883 prompt = self.hooks.generate_prompt(False)
1914 prompt = self.hooks.generate_prompt(False)
1884 except:
1915 except:
1885 self.showtraceback()
1916 self.showtraceback()
1886 try:
1917 try:
1887 line = self.raw_input(prompt, more)
1918 line = self.raw_input(prompt, more)
1888 if self.exit_now:
1919 if self.exit_now:
1889 # quick exit on sys.std[in|out] close
1920 # quick exit on sys.std[in|out] close
1890 break
1921 break
1891 if self.autoindent:
1922 if self.autoindent:
1892 self.rl_do_indent = False
1923 self.rl_do_indent = False
1893
1924
1894 except KeyboardInterrupt:
1925 except KeyboardInterrupt:
1895 #double-guard against keyboardinterrupts during kbdint handling
1926 #double-guard against keyboardinterrupts during kbdint handling
1896 try:
1927 try:
1897 self.write('\nKeyboardInterrupt\n')
1928 self.write('\nKeyboardInterrupt\n')
1898 self.resetbuffer()
1929 self.resetbuffer()
1899 # keep cache in sync with the prompt counter:
1930 # keep cache in sync with the prompt counter:
1900 self.outputcache.prompt_count -= 1
1931 self.outputcache.prompt_count -= 1
1901
1932
1902 if self.autoindent:
1933 if self.autoindent:
1903 self.indent_current_nsp = 0
1934 self.indent_current_nsp = 0
1904 more = 0
1935 more = 0
1905 except KeyboardInterrupt:
1936 except KeyboardInterrupt:
1906 pass
1937 pass
1907 except EOFError:
1938 except EOFError:
1908 if self.autoindent:
1939 if self.autoindent:
1909 self.rl_do_indent = False
1940 self.rl_do_indent = False
1910 self.readline_startup_hook(None)
1941 self.readline_startup_hook(None)
1911 self.write('\n')
1942 self.write('\n')
1912 self.exit()
1943 self.exit()
1913 except bdb.BdbQuit:
1944 except bdb.BdbQuit:
1914 warn('The Python debugger has exited with a BdbQuit exception.\n'
1945 warn('The Python debugger has exited with a BdbQuit exception.\n'
1915 'Because of how pdb handles the stack, it is impossible\n'
1946 'Because of how pdb handles the stack, it is impossible\n'
1916 'for IPython to properly format this particular exception.\n'
1947 'for IPython to properly format this particular exception.\n'
1917 'IPython will resume normal operation.')
1948 'IPython will resume normal operation.')
1918 except:
1949 except:
1919 # exceptions here are VERY RARE, but they can be triggered
1950 # exceptions here are VERY RARE, but they can be triggered
1920 # asynchronously by signal handlers, for example.
1951 # asynchronously by signal handlers, for example.
1921 self.showtraceback()
1952 self.showtraceback()
1922 else:
1953 else:
1923 more = self.push(line)
1954 more = self.push(line)
1924 if (self.SyntaxTB.last_syntax_error and
1955 if (self.SyntaxTB.last_syntax_error and
1925 self.autoedit_syntax):
1956 self.autoedit_syntax):
1926 self.edit_syntax_error()
1957 self.edit_syntax_error()
1927
1958
1928 # We are off again...
1959 # We are off again...
1929 __builtin__.__dict__['__IPYTHON__active'] -= 1
1960 __builtin__.__dict__['__IPYTHON__active'] -= 1
1930
1961
1931 def excepthook(self, etype, value, tb):
1962 def excepthook(self, etype, value, tb):
1932 """One more defense for GUI apps that call sys.excepthook.
1963 """One more defense for GUI apps that call sys.excepthook.
1933
1964
1934 GUI frameworks like wxPython trap exceptions and call
1965 GUI frameworks like wxPython trap exceptions and call
1935 sys.excepthook themselves. I guess this is a feature that
1966 sys.excepthook themselves. I guess this is a feature that
1936 enables them to keep running after exceptions that would
1967 enables them to keep running after exceptions that would
1937 otherwise kill their mainloop. This is a bother for IPython
1968 otherwise kill their mainloop. This is a bother for IPython
1938 which excepts to catch all of the program exceptions with a try:
1969 which excepts to catch all of the program exceptions with a try:
1939 except: statement.
1970 except: statement.
1940
1971
1941 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1972 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1942 any app directly invokes sys.excepthook, it will look to the user like
1973 any app directly invokes sys.excepthook, it will look to the user like
1943 IPython crashed. In order to work around this, we can disable the
1974 IPython crashed. In order to work around this, we can disable the
1944 CrashHandler and replace it with this excepthook instead, which prints a
1975 CrashHandler and replace it with this excepthook instead, which prints a
1945 regular traceback using our InteractiveTB. In this fashion, apps which
1976 regular traceback using our InteractiveTB. In this fashion, apps which
1946 call sys.excepthook will generate a regular-looking exception from
1977 call sys.excepthook will generate a regular-looking exception from
1947 IPython, and the CrashHandler will only be triggered by real IPython
1978 IPython, and the CrashHandler will only be triggered by real IPython
1948 crashes.
1979 crashes.
1949
1980
1950 This hook should be used sparingly, only in places which are not likely
1981 This hook should be used sparingly, only in places which are not likely
1951 to be true IPython errors.
1982 to be true IPython errors.
1952 """
1983 """
1953 self.showtraceback((etype,value,tb),tb_offset=0)
1984 self.showtraceback((etype,value,tb),tb_offset=0)
1954
1985
1955 def expand_aliases(self,fn,rest):
1986 def expand_aliases(self,fn,rest):
1956 """ Expand multiple levels of aliases:
1987 """ Expand multiple levels of aliases:
1957
1988
1958 if:
1989 if:
1959
1990
1960 alias foo bar /tmp
1991 alias foo bar /tmp
1961 alias baz foo
1992 alias baz foo
1962
1993
1963 then:
1994 then:
1964
1995
1965 baz huhhahhei -> bar /tmp huhhahhei
1996 baz huhhahhei -> bar /tmp huhhahhei
1966
1997
1967 """
1998 """
1968 line = fn + " " + rest
1999 line = fn + " " + rest
1969
2000
1970 done = set()
2001 done = set()
1971 while 1:
2002 while 1:
1972 pre,fn,rest = prefilter.splitUserInput(line,
2003 pre,fn,rest = prefilter.splitUserInput(line,
1973 prefilter.shell_line_split)
2004 prefilter.shell_line_split)
1974 if fn in self.alias_table:
2005 if fn in self.alias_table:
1975 if fn in done:
2006 if fn in done:
1976 warn("Cyclic alias definition, repeated '%s'" % fn)
2007 warn("Cyclic alias definition, repeated '%s'" % fn)
1977 return ""
2008 return ""
1978 done.add(fn)
2009 done.add(fn)
1979
2010
1980 l2 = self.transform_alias(fn,rest)
2011 l2 = self.transform_alias(fn,rest)
1981 # dir -> dir
2012 # dir -> dir
1982 # print "alias",line, "->",l2 #dbg
2013 # print "alias",line, "->",l2 #dbg
1983 if l2 == line:
2014 if l2 == line:
1984 break
2015 break
1985 # ls -> ls -F should not recurse forever
2016 # ls -> ls -F should not recurse forever
1986 if l2.split(None,1)[0] == line.split(None,1)[0]:
2017 if l2.split(None,1)[0] == line.split(None,1)[0]:
1987 line = l2
2018 line = l2
1988 break
2019 break
1989
2020
1990 line=l2
2021 line=l2
1991
2022
1992
2023
1993 # print "al expand to",line #dbg
2024 # print "al expand to",line #dbg
1994 else:
2025 else:
1995 break
2026 break
1996
2027
1997 return line
2028 return line
1998
2029
1999 def transform_alias(self, alias,rest=''):
2030 def transform_alias(self, alias,rest=''):
2000 """ Transform alias to system command string.
2031 """ Transform alias to system command string.
2001 """
2032 """
2002 trg = self.alias_table[alias]
2033 trg = self.alias_table[alias]
2003
2034
2004 nargs,cmd = trg
2035 nargs,cmd = trg
2005 # print trg #dbg
2036 # print trg #dbg
2006 if ' ' in cmd and os.path.isfile(cmd):
2037 if ' ' in cmd and os.path.isfile(cmd):
2007 cmd = '"%s"' % cmd
2038 cmd = '"%s"' % cmd
2008
2039
2009 # Expand the %l special to be the user's input line
2040 # Expand the %l special to be the user's input line
2010 if cmd.find('%l') >= 0:
2041 if cmd.find('%l') >= 0:
2011 cmd = cmd.replace('%l',rest)
2042 cmd = cmd.replace('%l',rest)
2012 rest = ''
2043 rest = ''
2013 if nargs==0:
2044 if nargs==0:
2014 # Simple, argument-less aliases
2045 # Simple, argument-less aliases
2015 cmd = '%s %s' % (cmd,rest)
2046 cmd = '%s %s' % (cmd,rest)
2016 else:
2047 else:
2017 # Handle aliases with positional arguments
2048 # Handle aliases with positional arguments
2018 args = rest.split(None,nargs)
2049 args = rest.split(None,nargs)
2019 if len(args)< nargs:
2050 if len(args)< nargs:
2020 error('Alias <%s> requires %s arguments, %s given.' %
2051 error('Alias <%s> requires %s arguments, %s given.' %
2021 (alias,nargs,len(args)))
2052 (alias,nargs,len(args)))
2022 return None
2053 return None
2023 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
2054 cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
2024 # Now call the macro, evaluating in the user's namespace
2055 # Now call the macro, evaluating in the user's namespace
2025 #print 'new command: <%r>' % cmd # dbg
2056 #print 'new command: <%r>' % cmd # dbg
2026 return cmd
2057 return cmd
2027
2058
2028 def call_alias(self,alias,rest=''):
2059 def call_alias(self,alias,rest=''):
2029 """Call an alias given its name and the rest of the line.
2060 """Call an alias given its name and the rest of the line.
2030
2061
2031 This is only used to provide backwards compatibility for users of
2062 This is only used to provide backwards compatibility for users of
2032 ipalias(), use of which is not recommended for anymore."""
2063 ipalias(), use of which is not recommended for anymore."""
2033
2064
2034 # Now call the macro, evaluating in the user's namespace
2065 # Now call the macro, evaluating in the user's namespace
2035 cmd = self.transform_alias(alias, rest)
2066 cmd = self.transform_alias(alias, rest)
2036 try:
2067 try:
2037 self.system(cmd)
2068 self.system(cmd)
2038 except:
2069 except:
2039 self.showtraceback()
2070 self.showtraceback()
2040
2071
2041 def indent_current_str(self):
2072 def indent_current_str(self):
2042 """return the current level of indentation as a string"""
2073 """return the current level of indentation as a string"""
2043 return self.indent_current_nsp * ' '
2074 return self.indent_current_nsp * ' '
2044
2075
2045 def autoindent_update(self,line):
2076 def autoindent_update(self,line):
2046 """Keep track of the indent level."""
2077 """Keep track of the indent level."""
2047
2078
2048 #debugx('line')
2079 #debugx('line')
2049 #debugx('self.indent_current_nsp')
2080 #debugx('self.indent_current_nsp')
2050 if self.autoindent:
2081 if self.autoindent:
2051 if line:
2082 if line:
2052 inisp = num_ini_spaces(line)
2083 inisp = num_ini_spaces(line)
2053 if inisp < self.indent_current_nsp:
2084 if inisp < self.indent_current_nsp:
2054 self.indent_current_nsp = inisp
2085 self.indent_current_nsp = inisp
2055
2086
2056 if line[-1] == ':':
2087 if line[-1] == ':':
2057 self.indent_current_nsp += 4
2088 self.indent_current_nsp += 4
2058 elif dedent_re.match(line):
2089 elif dedent_re.match(line):
2059 self.indent_current_nsp -= 4
2090 self.indent_current_nsp -= 4
2060 else:
2091 else:
2061 self.indent_current_nsp = 0
2092 self.indent_current_nsp = 0
2062
2093
2063 def runlines(self,lines):
2094 def runlines(self,lines):
2064 """Run a string of one or more lines of source.
2095 """Run a string of one or more lines of source.
2065
2096
2066 This method is capable of running a string containing multiple source
2097 This method is capable of running a string containing multiple source
2067 lines, as if they had been entered at the IPython prompt. Since it
2098 lines, as if they had been entered at the IPython prompt. Since it
2068 exposes IPython's processing machinery, the given strings can contain
2099 exposes IPython's processing machinery, the given strings can contain
2069 magic calls (%magic), special shell access (!cmd), etc."""
2100 magic calls (%magic), special shell access (!cmd), etc."""
2070
2101
2071 # We must start with a clean buffer, in case this is run from an
2102 # We must start with a clean buffer, in case this is run from an
2072 # interactive IPython session (via a magic, for example).
2103 # interactive IPython session (via a magic, for example).
2073 self.resetbuffer()
2104 self.resetbuffer()
2074 lines = lines.split('\n')
2105 lines = lines.split('\n')
2075 more = 0
2106 more = 0
2076
2107
2077 for line in lines:
2108 for line in lines:
2078 # skip blank lines so we don't mess up the prompt counter, but do
2109 # skip blank lines so we don't mess up the prompt counter, but do
2079 # NOT skip even a blank line if we are in a code block (more is
2110 # NOT skip even a blank line if we are in a code block (more is
2080 # true)
2111 # true)
2081
2112
2082 if line or more:
2113 if line or more:
2083 # push to raw history, so hist line numbers stay in sync
2114 # push to raw history, so hist line numbers stay in sync
2084 self.input_hist_raw.append("# " + line + "\n")
2115 self.input_hist_raw.append("# " + line + "\n")
2085 more = self.push(self.prefilter(line,more))
2116 more = self.push(self.prefilter(line,more))
2086 # IPython's runsource returns None if there was an error
2117 # IPython's runsource returns None if there was an error
2087 # compiling the code. This allows us to stop processing right
2118 # compiling the code. This allows us to stop processing right
2088 # away, so the user gets the error message at the right place.
2119 # away, so the user gets the error message at the right place.
2089 if more is None:
2120 if more is None:
2090 break
2121 break
2091 else:
2122 else:
2092 self.input_hist_raw.append("\n")
2123 self.input_hist_raw.append("\n")
2093 # final newline in case the input didn't have it, so that the code
2124 # final newline in case the input didn't have it, so that the code
2094 # actually does get executed
2125 # actually does get executed
2095 if more:
2126 if more:
2096 self.push('\n')
2127 self.push('\n')
2097
2128
2098 def runsource(self, source, filename='<input>', symbol='single'):
2129 def runsource(self, source, filename='<input>', symbol='single'):
2099 """Compile and run some source in the interpreter.
2130 """Compile and run some source in the interpreter.
2100
2131
2101 Arguments are as for compile_command().
2132 Arguments are as for compile_command().
2102
2133
2103 One several things can happen:
2134 One several things can happen:
2104
2135
2105 1) The input is incorrect; compile_command() raised an
2136 1) The input is incorrect; compile_command() raised an
2106 exception (SyntaxError or OverflowError). A syntax traceback
2137 exception (SyntaxError or OverflowError). A syntax traceback
2107 will be printed by calling the showsyntaxerror() method.
2138 will be printed by calling the showsyntaxerror() method.
2108
2139
2109 2) The input is incomplete, and more input is required;
2140 2) The input is incomplete, and more input is required;
2110 compile_command() returned None. Nothing happens.
2141 compile_command() returned None. Nothing happens.
2111
2142
2112 3) The input is complete; compile_command() returned a code
2143 3) The input is complete; compile_command() returned a code
2113 object. The code is executed by calling self.runcode() (which
2144 object. The code is executed by calling self.runcode() (which
2114 also handles run-time exceptions, except for SystemExit).
2145 also handles run-time exceptions, except for SystemExit).
2115
2146
2116 The return value is:
2147 The return value is:
2117
2148
2118 - True in case 2
2149 - True in case 2
2119
2150
2120 - False in the other cases, unless an exception is raised, where
2151 - False in the other cases, unless an exception is raised, where
2121 None is returned instead. This can be used by external callers to
2152 None is returned instead. This can be used by external callers to
2122 know whether to continue feeding input or not.
2153 know whether to continue feeding input or not.
2123
2154
2124 The return value can be used to decide whether to use sys.ps1 or
2155 The return value can be used to decide whether to use sys.ps1 or
2125 sys.ps2 to prompt the next line."""
2156 sys.ps2 to prompt the next line."""
2126
2157
2127 # if the source code has leading blanks, add 'if 1:\n' to it
2158 # if the source code has leading blanks, add 'if 1:\n' to it
2128 # this allows execution of indented pasted code. It is tempting
2159 # this allows execution of indented pasted code. It is tempting
2129 # to add '\n' at the end of source to run commands like ' a=1'
2160 # to add '\n' at the end of source to run commands like ' a=1'
2130 # directly, but this fails for more complicated scenarios
2161 # directly, but this fails for more complicated scenarios
2131 source=source.encode(self.stdin_encoding)
2162 source=source.encode(self.stdin_encoding)
2132 if source[:1] in [' ', '\t']:
2163 if source[:1] in [' ', '\t']:
2133 source = 'if 1:\n%s' % source
2164 source = 'if 1:\n%s' % source
2134
2165
2135 try:
2166 try:
2136 code = self.compile(source,filename,symbol)
2167 code = self.compile(source,filename,symbol)
2137 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2168 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2138 # Case 1
2169 # Case 1
2139 self.showsyntaxerror(filename)
2170 self.showsyntaxerror(filename)
2140 return None
2171 return None
2141
2172
2142 if code is None:
2173 if code is None:
2143 # Case 2
2174 # Case 2
2144 return True
2175 return True
2145
2176
2146 # Case 3
2177 # Case 3
2147 # We store the code object so that threaded shells and
2178 # We store the code object so that threaded shells and
2148 # custom exception handlers can access all this info if needed.
2179 # custom exception handlers can access all this info if needed.
2149 # The source corresponding to this can be obtained from the
2180 # The source corresponding to this can be obtained from the
2150 # buffer attribute as '\n'.join(self.buffer).
2181 # buffer attribute as '\n'.join(self.buffer).
2151 self.code_to_run = code
2182 self.code_to_run = code
2152 # now actually execute the code object
2183 # now actually execute the code object
2153 if self.runcode(code) == 0:
2184 if self.runcode(code) == 0:
2154 return False
2185 return False
2155 else:
2186 else:
2156 return None
2187 return None
2157
2188
2158 def runcode(self,code_obj):
2189 def runcode(self,code_obj):
2159 """Execute a code object.
2190 """Execute a code object.
2160
2191
2161 When an exception occurs, self.showtraceback() is called to display a
2192 When an exception occurs, self.showtraceback() is called to display a
2162 traceback.
2193 traceback.
2163
2194
2164 Return value: a flag indicating whether the code to be run completed
2195 Return value: a flag indicating whether the code to be run completed
2165 successfully:
2196 successfully:
2166
2197
2167 - 0: successful execution.
2198 - 0: successful execution.
2168 - 1: an error occurred.
2199 - 1: an error occurred.
2169 """
2200 """
2170
2201
2171 # Set our own excepthook in case the user code tries to call it
2202 # Set our own excepthook in case the user code tries to call it
2172 # directly, so that the IPython crash handler doesn't get triggered
2203 # directly, so that the IPython crash handler doesn't get triggered
2173 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2204 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2174
2205
2175 # we save the original sys.excepthook in the instance, in case config
2206 # we save the original sys.excepthook in the instance, in case config
2176 # code (such as magics) needs access to it.
2207 # code (such as magics) needs access to it.
2177 self.sys_excepthook = old_excepthook
2208 self.sys_excepthook = old_excepthook
2178 outflag = 1 # happens in more places, so it's easier as default
2209 outflag = 1 # happens in more places, so it's easier as default
2179 try:
2210 try:
2180 try:
2211 try:
2181 self.hooks.pre_runcode_hook()
2212 self.hooks.pre_runcode_hook()
2182 exec code_obj in self.user_global_ns, self.user_ns
2213 exec code_obj in self.user_global_ns, self.user_ns
2183 finally:
2214 finally:
2184 # Reset our crash handler in place
2215 # Reset our crash handler in place
2185 sys.excepthook = old_excepthook
2216 sys.excepthook = old_excepthook
2186 except SystemExit:
2217 except SystemExit:
2187 self.resetbuffer()
2218 self.resetbuffer()
2188 self.showtraceback()
2219 self.showtraceback()
2189 warn("Type %exit or %quit to exit IPython "
2220 warn("Type %exit or %quit to exit IPython "
2190 "(%Exit or %Quit do so unconditionally).",level=1)
2221 "(%Exit or %Quit do so unconditionally).",level=1)
2191 except self.custom_exceptions:
2222 except self.custom_exceptions:
2192 etype,value,tb = sys.exc_info()
2223 etype,value,tb = sys.exc_info()
2193 self.CustomTB(etype,value,tb)
2224 self.CustomTB(etype,value,tb)
2194 except:
2225 except:
2195 self.showtraceback()
2226 self.showtraceback()
2196 else:
2227 else:
2197 outflag = 0
2228 outflag = 0
2198 if softspace(sys.stdout, 0):
2229 if softspace(sys.stdout, 0):
2199 print
2230 print
2200 # Flush out code object which has been run (and source)
2231 # Flush out code object which has been run (and source)
2201 self.code_to_run = None
2232 self.code_to_run = None
2202 return outflag
2233 return outflag
2203
2234
2204 def push(self, line):
2235 def push(self, line):
2205 """Push a line to the interpreter.
2236 """Push a line to the interpreter.
2206
2237
2207 The line should not have a trailing newline; it may have
2238 The line should not have a trailing newline; it may have
2208 internal newlines. The line is appended to a buffer and the
2239 internal newlines. The line is appended to a buffer and the
2209 interpreter's runsource() method is called with the
2240 interpreter's runsource() method is called with the
2210 concatenated contents of the buffer as source. If this
2241 concatenated contents of the buffer as source. If this
2211 indicates that the command was executed or invalid, the buffer
2242 indicates that the command was executed or invalid, the buffer
2212 is reset; otherwise, the command is incomplete, and the buffer
2243 is reset; otherwise, the command is incomplete, and the buffer
2213 is left as it was after the line was appended. The return
2244 is left as it was after the line was appended. The return
2214 value is 1 if more input is required, 0 if the line was dealt
2245 value is 1 if more input is required, 0 if the line was dealt
2215 with in some way (this is the same as runsource()).
2246 with in some way (this is the same as runsource()).
2216 """
2247 """
2217
2248
2218 # autoindent management should be done here, and not in the
2249 # autoindent management should be done here, and not in the
2219 # interactive loop, since that one is only seen by keyboard input. We
2250 # interactive loop, since that one is only seen by keyboard input. We
2220 # need this done correctly even for code run via runlines (which uses
2251 # need this done correctly even for code run via runlines (which uses
2221 # push).
2252 # push).
2222
2253
2223 #print 'push line: <%s>' % line # dbg
2254 #print 'push line: <%s>' % line # dbg
2224 for subline in line.splitlines():
2255 for subline in line.splitlines():
2225 self.autoindent_update(subline)
2256 self.autoindent_update(subline)
2226 self.buffer.append(line)
2257 self.buffer.append(line)
2227 more = self.runsource('\n'.join(self.buffer), self.filename)
2258 more = self.runsource('\n'.join(self.buffer), self.filename)
2228 if not more:
2259 if not more:
2229 self.resetbuffer()
2260 self.resetbuffer()
2230 return more
2261 return more
2231
2262
2232 def split_user_input(self, line):
2263 def split_user_input(self, line):
2233 # This is really a hold-over to support ipapi and some extensions
2264 # This is really a hold-over to support ipapi and some extensions
2234 return prefilter.splitUserInput(line)
2265 return prefilter.splitUserInput(line)
2235
2266
2236 def resetbuffer(self):
2267 def resetbuffer(self):
2237 """Reset the input buffer."""
2268 """Reset the input buffer."""
2238 self.buffer[:] = []
2269 self.buffer[:] = []
2239
2270
2240 def raw_input(self,prompt='',continue_prompt=False):
2271 def raw_input(self,prompt='',continue_prompt=False):
2241 """Write a prompt and read a line.
2272 """Write a prompt and read a line.
2242
2273
2243 The returned line does not include the trailing newline.
2274 The returned line does not include the trailing newline.
2244 When the user enters the EOF key sequence, EOFError is raised.
2275 When the user enters the EOF key sequence, EOFError is raised.
2245
2276
2246 Optional inputs:
2277 Optional inputs:
2247
2278
2248 - prompt(''): a string to be printed to prompt the user.
2279 - prompt(''): a string to be printed to prompt the user.
2249
2280
2250 - continue_prompt(False): whether this line is the first one or a
2281 - continue_prompt(False): whether this line is the first one or a
2251 continuation in a sequence of inputs.
2282 continuation in a sequence of inputs.
2252 """
2283 """
2253
2284
2254 # Code run by the user may have modified the readline completer state.
2285 # Code run by the user may have modified the readline completer state.
2255 # We must ensure that our completer is back in place.
2286 # We must ensure that our completer is back in place.
2256 if self.has_readline:
2287 if self.has_readline:
2257 self.set_completer()
2288 self.set_completer()
2258
2289
2259 try:
2290 try:
2260 line = raw_input_original(prompt).decode(self.stdin_encoding)
2291 line = raw_input_original(prompt).decode(self.stdin_encoding)
2261 except ValueError:
2292 except ValueError:
2262 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2293 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2263 " or sys.stdout.close()!\nExiting IPython!")
2294 " or sys.stdout.close()!\nExiting IPython!")
2264 self.ask_exit()
2295 self.ask_exit()
2265 return ""
2296 return ""
2266
2297
2267 # Try to be reasonably smart about not re-indenting pasted input more
2298 # Try to be reasonably smart about not re-indenting pasted input more
2268 # than necessary. We do this by trimming out the auto-indent initial
2299 # than necessary. We do this by trimming out the auto-indent initial
2269 # spaces, if the user's actual input started itself with whitespace.
2300 # spaces, if the user's actual input started itself with whitespace.
2270 #debugx('self.buffer[-1]')
2301 #debugx('self.buffer[-1]')
2271
2302
2272 if self.autoindent:
2303 if self.autoindent:
2273 if num_ini_spaces(line) > self.indent_current_nsp:
2304 if num_ini_spaces(line) > self.indent_current_nsp:
2274 line = line[self.indent_current_nsp:]
2305 line = line[self.indent_current_nsp:]
2275 self.indent_current_nsp = 0
2306 self.indent_current_nsp = 0
2276
2307
2277 # store the unfiltered input before the user has any chance to modify
2308 # store the unfiltered input before the user has any chance to modify
2278 # it.
2309 # it.
2279 if line.strip():
2310 if line.strip():
2280 if continue_prompt:
2311 if continue_prompt:
2281 self.input_hist_raw[-1] += '%s\n' % line
2312 self.input_hist_raw[-1] += '%s\n' % line
2282 if self.has_readline: # and some config option is set?
2313 if self.has_readline: # and some config option is set?
2283 try:
2314 try:
2284 histlen = self.readline.get_current_history_length()
2315 histlen = self.readline.get_current_history_length()
2285 if histlen > 1:
2316 if histlen > 1:
2286 newhist = self.input_hist_raw[-1].rstrip()
2317 newhist = self.input_hist_raw[-1].rstrip()
2287 self.readline.remove_history_item(histlen-1)
2318 self.readline.remove_history_item(histlen-1)
2288 self.readline.replace_history_item(histlen-2,
2319 self.readline.replace_history_item(histlen-2,
2289 newhist.encode(self.stdin_encoding))
2320 newhist.encode(self.stdin_encoding))
2290 except AttributeError:
2321 except AttributeError:
2291 pass # re{move,place}_history_item are new in 2.4.
2322 pass # re{move,place}_history_item are new in 2.4.
2292 else:
2323 else:
2293 self.input_hist_raw.append('%s\n' % line)
2324 self.input_hist_raw.append('%s\n' % line)
2294 # only entries starting at first column go to shadow history
2325 # only entries starting at first column go to shadow history
2295 if line.lstrip() == line:
2326 if line.lstrip() == line:
2296 self.shadowhist.add(line.strip())
2327 self.shadowhist.add(line.strip())
2297 elif not continue_prompt:
2328 elif not continue_prompt:
2298 self.input_hist_raw.append('\n')
2329 self.input_hist_raw.append('\n')
2299 try:
2330 try:
2300 lineout = self.prefilter(line,continue_prompt)
2331 lineout = self.prefilter(line,continue_prompt)
2301 except:
2332 except:
2302 # blanket except, in case a user-defined prefilter crashes, so it
2333 # blanket except, in case a user-defined prefilter crashes, so it
2303 # can't take all of ipython with it.
2334 # can't take all of ipython with it.
2304 self.showtraceback()
2335 self.showtraceback()
2305 return ''
2336 return ''
2306 else:
2337 else:
2307 return lineout
2338 return lineout
2308
2339
2309 def _prefilter(self, line, continue_prompt):
2340 def _prefilter(self, line, continue_prompt):
2310 """Calls different preprocessors, depending on the form of line."""
2341 """Calls different preprocessors, depending on the form of line."""
2311
2342
2312 # All handlers *must* return a value, even if it's blank ('').
2343 # All handlers *must* return a value, even if it's blank ('').
2313
2344
2314 # Lines are NOT logged here. Handlers should process the line as
2345 # Lines are NOT logged here. Handlers should process the line as
2315 # needed, update the cache AND log it (so that the input cache array
2346 # needed, update the cache AND log it (so that the input cache array
2316 # stays synced).
2347 # stays synced).
2317
2348
2318 #.....................................................................
2349 #.....................................................................
2319 # Code begins
2350 # Code begins
2320
2351
2321 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2352 #if line.startswith('%crash'): raise RuntimeError,'Crash now!' # dbg
2322
2353
2323 # save the line away in case we crash, so the post-mortem handler can
2354 # save the line away in case we crash, so the post-mortem handler can
2324 # record it
2355 # record it
2325 self._last_input_line = line
2356 self._last_input_line = line
2326
2357
2327 #print '***line: <%s>' % line # dbg
2358 #print '***line: <%s>' % line # dbg
2328
2359
2329 if not line:
2360 if not line:
2330 # Return immediately on purely empty lines, so that if the user
2361 # Return immediately on purely empty lines, so that if the user
2331 # previously typed some whitespace that started a continuation
2362 # previously typed some whitespace that started a continuation
2332 # prompt, he can break out of that loop with just an empty line.
2363 # prompt, he can break out of that loop with just an empty line.
2333 # This is how the default python prompt works.
2364 # This is how the default python prompt works.
2334
2365
2335 # Only return if the accumulated input buffer was just whitespace!
2366 # Only return if the accumulated input buffer was just whitespace!
2336 if ''.join(self.buffer).isspace():
2367 if ''.join(self.buffer).isspace():
2337 self.buffer[:] = []
2368 self.buffer[:] = []
2338 return ''
2369 return ''
2339
2370
2340 line_info = prefilter.LineInfo(line, continue_prompt)
2371 line_info = prefilter.LineInfo(line, continue_prompt)
2341
2372
2342 # the input history needs to track even empty lines
2373 # the input history needs to track even empty lines
2343 stripped = line.strip()
2374 stripped = line.strip()
2344
2375
2345 if not stripped:
2376 if not stripped:
2346 if not continue_prompt:
2377 if not continue_prompt:
2347 self.outputcache.prompt_count -= 1
2378 self.outputcache.prompt_count -= 1
2348 return self.handle_normal(line_info)
2379 return self.handle_normal(line_info)
2349
2380
2350 # print '***cont',continue_prompt # dbg
2381 # print '***cont',continue_prompt # dbg
2351 # special handlers are only allowed for single line statements
2382 # special handlers are only allowed for single line statements
2352 if continue_prompt and not self.multi_line_specials:
2383 if continue_prompt and not self.multi_line_specials:
2353 return self.handle_normal(line_info)
2384 return self.handle_normal(line_info)
2354
2385
2355
2386
2356 # See whether any pre-existing handler can take care of it
2387 # See whether any pre-existing handler can take care of it
2357 rewritten = self.hooks.input_prefilter(stripped)
2388 rewritten = self.hooks.input_prefilter(stripped)
2358 if rewritten != stripped: # ok, some prefilter did something
2389 if rewritten != stripped: # ok, some prefilter did something
2359 rewritten = line_info.pre + rewritten # add indentation
2390 rewritten = line_info.pre + rewritten # add indentation
2360 return self.handle_normal(prefilter.LineInfo(rewritten,
2391 return self.handle_normal(prefilter.LineInfo(rewritten,
2361 continue_prompt))
2392 continue_prompt))
2362
2393
2363 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2394 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2364
2395
2365 return prefilter.prefilter(line_info, self)
2396 return prefilter.prefilter(line_info, self)
2366
2397
2367
2398
2368 def _prefilter_dumb(self, line, continue_prompt):
2399 def _prefilter_dumb(self, line, continue_prompt):
2369 """simple prefilter function, for debugging"""
2400 """simple prefilter function, for debugging"""
2370 return self.handle_normal(line,continue_prompt)
2401 return self.handle_normal(line,continue_prompt)
2371
2402
2372
2403
2373 def multiline_prefilter(self, line, continue_prompt):
2404 def multiline_prefilter(self, line, continue_prompt):
2374 """ Run _prefilter for each line of input
2405 """ Run _prefilter for each line of input
2375
2406
2376 Covers cases where there are multiple lines in the user entry,
2407 Covers cases where there are multiple lines in the user entry,
2377 which is the case when the user goes back to a multiline history
2408 which is the case when the user goes back to a multiline history
2378 entry and presses enter.
2409 entry and presses enter.
2379
2410
2380 """
2411 """
2381 out = []
2412 out = []
2382 for l in line.rstrip('\n').split('\n'):
2413 for l in line.rstrip('\n').split('\n'):
2383 out.append(self._prefilter(l, continue_prompt))
2414 out.append(self._prefilter(l, continue_prompt))
2384 return '\n'.join(out)
2415 return '\n'.join(out)
2385
2416
2386 # Set the default prefilter() function (this can be user-overridden)
2417 # Set the default prefilter() function (this can be user-overridden)
2387 prefilter = multiline_prefilter
2418 prefilter = multiline_prefilter
2388
2419
2389 def handle_normal(self,line_info):
2420 def handle_normal(self,line_info):
2390 """Handle normal input lines. Use as a template for handlers."""
2421 """Handle normal input lines. Use as a template for handlers."""
2391
2422
2392 # With autoindent on, we need some way to exit the input loop, and I
2423 # With autoindent on, we need some way to exit the input loop, and I
2393 # don't want to force the user to have to backspace all the way to
2424 # don't want to force the user to have to backspace all the way to
2394 # clear the line. The rule will be in this case, that either two
2425 # clear the line. The rule will be in this case, that either two
2395 # lines of pure whitespace in a row, or a line of pure whitespace but
2426 # lines of pure whitespace in a row, or a line of pure whitespace but
2396 # of a size different to the indent level, will exit the input loop.
2427 # of a size different to the indent level, will exit the input loop.
2397 line = line_info.line
2428 line = line_info.line
2398 continue_prompt = line_info.continue_prompt
2429 continue_prompt = line_info.continue_prompt
2399
2430
2400 if (continue_prompt and self.autoindent and line.isspace() and
2431 if (continue_prompt and self.autoindent and line.isspace() and
2401 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2432 (0 < abs(len(line) - self.indent_current_nsp) <= 2 or
2402 (self.buffer[-1]).isspace() )):
2433 (self.buffer[-1]).isspace() )):
2403 line = ''
2434 line = ''
2404
2435
2405 self.log(line,line,continue_prompt)
2436 self.log(line,line,continue_prompt)
2406 return line
2437 return line
2407
2438
2408 def handle_alias(self,line_info):
2439 def handle_alias(self,line_info):
2409 """Handle alias input lines. """
2440 """Handle alias input lines. """
2410 tgt = self.alias_table[line_info.iFun]
2441 tgt = self.alias_table[line_info.iFun]
2411 # print "=>",tgt #dbg
2442 # print "=>",tgt #dbg
2412 if callable(tgt):
2443 if callable(tgt):
2413 if '$' in line_info.line:
2444 if '$' in line_info.line:
2414 call_meth = '(_ip, _ip.itpl(%s))'
2445 call_meth = '(_ip, _ip.itpl(%s))'
2415 else:
2446 else:
2416 call_meth = '(_ip,%s)'
2447 call_meth = '(_ip,%s)'
2417 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2448 line_out = ("%s_sh.%s" + call_meth) % (line_info.preWhitespace,
2418 line_info.iFun,
2449 line_info.iFun,
2419 make_quoted_expr(line_info.line))
2450 make_quoted_expr(line_info.line))
2420 else:
2451 else:
2421 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2452 transformed = self.expand_aliases(line_info.iFun,line_info.theRest)
2422
2453
2423 # pre is needed, because it carries the leading whitespace. Otherwise
2454 # pre is needed, because it carries the leading whitespace. Otherwise
2424 # aliases won't work in indented sections.
2455 # aliases won't work in indented sections.
2425 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2456 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2426 make_quoted_expr( transformed ))
2457 make_quoted_expr( transformed ))
2427
2458
2428 self.log(line_info.line,line_out,line_info.continue_prompt)
2459 self.log(line_info.line,line_out,line_info.continue_prompt)
2429 #print 'line out:',line_out # dbg
2460 #print 'line out:',line_out # dbg
2430 return line_out
2461 return line_out
2431
2462
2432 def handle_shell_escape(self, line_info):
2463 def handle_shell_escape(self, line_info):
2433 """Execute the line in a shell, empty return value"""
2464 """Execute the line in a shell, empty return value"""
2434 #print 'line in :', `line` # dbg
2465 #print 'line in :', `line` # dbg
2435 line = line_info.line
2466 line = line_info.line
2436 if line.lstrip().startswith('!!'):
2467 if line.lstrip().startswith('!!'):
2437 # rewrite LineInfo's line, iFun and theRest to properly hold the
2468 # rewrite LineInfo's line, iFun and theRest to properly hold the
2438 # call to %sx and the actual command to be executed, so
2469 # call to %sx and the actual command to be executed, so
2439 # handle_magic can work correctly. Note that this works even if
2470 # handle_magic can work correctly. Note that this works even if
2440 # the line is indented, so it handles multi_line_specials
2471 # the line is indented, so it handles multi_line_specials
2441 # properly.
2472 # properly.
2442 new_rest = line.lstrip()[2:]
2473 new_rest = line.lstrip()[2:]
2443 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2474 line_info.line = '%ssx %s' % (self.ESC_MAGIC,new_rest)
2444 line_info.iFun = 'sx'
2475 line_info.iFun = 'sx'
2445 line_info.theRest = new_rest
2476 line_info.theRest = new_rest
2446 return self.handle_magic(line_info)
2477 return self.handle_magic(line_info)
2447 else:
2478 else:
2448 cmd = line.lstrip().lstrip('!')
2479 cmd = line.lstrip().lstrip('!')
2449 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2480 line_out = '%s_ip.system(%s)' % (line_info.preWhitespace,
2450 make_quoted_expr(cmd))
2481 make_quoted_expr(cmd))
2451 # update cache/log and return
2482 # update cache/log and return
2452 self.log(line,line_out,line_info.continue_prompt)
2483 self.log(line,line_out,line_info.continue_prompt)
2453 return line_out
2484 return line_out
2454
2485
2455 def handle_magic(self, line_info):
2486 def handle_magic(self, line_info):
2456 """Execute magic functions."""
2487 """Execute magic functions."""
2457 iFun = line_info.iFun
2488 iFun = line_info.iFun
2458 theRest = line_info.theRest
2489 theRest = line_info.theRest
2459 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2490 cmd = '%s_ip.magic(%s)' % (line_info.preWhitespace,
2460 make_quoted_expr(iFun + " " + theRest))
2491 make_quoted_expr(iFun + " " + theRest))
2461 self.log(line_info.line,cmd,line_info.continue_prompt)
2492 self.log(line_info.line,cmd,line_info.continue_prompt)
2462 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2493 #print 'in handle_magic, cmd=<%s>' % cmd # dbg
2463 return cmd
2494 return cmd
2464
2495
2465 def handle_auto(self, line_info):
2496 def handle_auto(self, line_info):
2466 """Hande lines which can be auto-executed, quoting if requested."""
2497 """Hande lines which can be auto-executed, quoting if requested."""
2467
2498
2468 line = line_info.line
2499 line = line_info.line
2469 iFun = line_info.iFun
2500 iFun = line_info.iFun
2470 theRest = line_info.theRest
2501 theRest = line_info.theRest
2471 pre = line_info.pre
2502 pre = line_info.pre
2472 continue_prompt = line_info.continue_prompt
2503 continue_prompt = line_info.continue_prompt
2473 obj = line_info.ofind(self)['obj']
2504 obj = line_info.ofind(self)['obj']
2474
2505
2475 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2506 #print 'pre <%s> iFun <%s> rest <%s>' % (pre,iFun,theRest) # dbg
2476
2507
2477 # This should only be active for single-line input!
2508 # This should only be active for single-line input!
2478 if continue_prompt:
2509 if continue_prompt:
2479 self.log(line,line,continue_prompt)
2510 self.log(line,line,continue_prompt)
2480 return line
2511 return line
2481
2512
2482 force_auto = isinstance(obj, ipapi.IPyAutocall)
2513 force_auto = isinstance(obj, ipapi.IPyAutocall)
2483 auto_rewrite = True
2514 auto_rewrite = True
2484
2515
2485 if pre == self.ESC_QUOTE:
2516 if pre == self.ESC_QUOTE:
2486 # Auto-quote splitting on whitespace
2517 # Auto-quote splitting on whitespace
2487 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2518 newcmd = '%s("%s")' % (iFun,'", "'.join(theRest.split()) )
2488 elif pre == self.ESC_QUOTE2:
2519 elif pre == self.ESC_QUOTE2:
2489 # Auto-quote whole string
2520 # Auto-quote whole string
2490 newcmd = '%s("%s")' % (iFun,theRest)
2521 newcmd = '%s("%s")' % (iFun,theRest)
2491 elif pre == self.ESC_PAREN:
2522 elif pre == self.ESC_PAREN:
2492 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2523 newcmd = '%s(%s)' % (iFun,",".join(theRest.split()))
2493 else:
2524 else:
2494 # Auto-paren.
2525 # Auto-paren.
2495 # We only apply it to argument-less calls if the autocall
2526 # We only apply it to argument-less calls if the autocall
2496 # parameter is set to 2. We only need to check that autocall is <
2527 # parameter is set to 2. We only need to check that autocall is <
2497 # 2, since this function isn't called unless it's at least 1.
2528 # 2, since this function isn't called unless it's at least 1.
2498 if not theRest and (self.autocall < 2) and not force_auto:
2529 if not theRest and (self.autocall < 2) and not force_auto:
2499 newcmd = '%s %s' % (iFun,theRest)
2530 newcmd = '%s %s' % (iFun,theRest)
2500 auto_rewrite = False
2531 auto_rewrite = False
2501 else:
2532 else:
2502 if not force_auto and theRest.startswith('['):
2533 if not force_auto and theRest.startswith('['):
2503 if hasattr(obj,'__getitem__'):
2534 if hasattr(obj,'__getitem__'):
2504 # Don't autocall in this case: item access for an object
2535 # Don't autocall in this case: item access for an object
2505 # which is BOTH callable and implements __getitem__.
2536 # which is BOTH callable and implements __getitem__.
2506 newcmd = '%s %s' % (iFun,theRest)
2537 newcmd = '%s %s' % (iFun,theRest)
2507 auto_rewrite = False
2538 auto_rewrite = False
2508 else:
2539 else:
2509 # if the object doesn't support [] access, go ahead and
2540 # if the object doesn't support [] access, go ahead and
2510 # autocall
2541 # autocall
2511 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2542 newcmd = '%s(%s)' % (iFun.rstrip(),theRest)
2512 elif theRest.endswith(';'):
2543 elif theRest.endswith(';'):
2513 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2544 newcmd = '%s(%s);' % (iFun.rstrip(),theRest[:-1])
2514 else:
2545 else:
2515 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2546 newcmd = '%s(%s)' % (iFun.rstrip(), theRest)
2516
2547
2517 if auto_rewrite:
2548 if auto_rewrite:
2518 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2549 rw = self.outputcache.prompt1.auto_rewrite() + newcmd
2519
2550
2520 try:
2551 try:
2521 # plain ascii works better w/ pyreadline, on some machines, so
2552 # plain ascii works better w/ pyreadline, on some machines, so
2522 # we use it and only print uncolored rewrite if we have unicode
2553 # we use it and only print uncolored rewrite if we have unicode
2523 rw = str(rw)
2554 rw = str(rw)
2524 print >>Term.cout, rw
2555 print >>Term.cout, rw
2525 except UnicodeEncodeError:
2556 except UnicodeEncodeError:
2526 print "-------------->" + newcmd
2557 print "-------------->" + newcmd
2527
2558
2528 # log what is now valid Python, not the actual user input (without the
2559 # log what is now valid Python, not the actual user input (without the
2529 # final newline)
2560 # final newline)
2530 self.log(line,newcmd,continue_prompt)
2561 self.log(line,newcmd,continue_prompt)
2531 return newcmd
2562 return newcmd
2532
2563
2533 def handle_help(self, line_info):
2564 def handle_help(self, line_info):
2534 """Try to get some help for the object.
2565 """Try to get some help for the object.
2535
2566
2536 obj? or ?obj -> basic information.
2567 obj? or ?obj -> basic information.
2537 obj?? or ??obj -> more details.
2568 obj?? or ??obj -> more details.
2538 """
2569 """
2539
2570
2540 line = line_info.line
2571 line = line_info.line
2541 # We need to make sure that we don't process lines which would be
2572 # We need to make sure that we don't process lines which would be
2542 # otherwise valid python, such as "x=1 # what?"
2573 # otherwise valid python, such as "x=1 # what?"
2543 try:
2574 try:
2544 codeop.compile_command(line)
2575 codeop.compile_command(line)
2545 except SyntaxError:
2576 except SyntaxError:
2546 # We should only handle as help stuff which is NOT valid syntax
2577 # We should only handle as help stuff which is NOT valid syntax
2547 if line[0]==self.ESC_HELP:
2578 if line[0]==self.ESC_HELP:
2548 line = line[1:]
2579 line = line[1:]
2549 elif line[-1]==self.ESC_HELP:
2580 elif line[-1]==self.ESC_HELP:
2550 line = line[:-1]
2581 line = line[:-1]
2551 self.log(line,'#?'+line,line_info.continue_prompt)
2582 self.log(line,'#?'+line,line_info.continue_prompt)
2552 if line:
2583 if line:
2553 #print 'line:<%r>' % line # dbg
2584 #print 'line:<%r>' % line # dbg
2554 self.magic_pinfo(line)
2585 self.magic_pinfo(line)
2555 else:
2586 else:
2556 page(self.usage,screen_lines=self.usable_screen_length)
2587 page(self.usage,screen_lines=self.usable_screen_length)
2557 return '' # Empty string is needed here!
2588 return '' # Empty string is needed here!
2558 except:
2589 except:
2559 # Pass any other exceptions through to the normal handler
2590 # Pass any other exceptions through to the normal handler
2560 return self.handle_normal(line_info)
2591 return self.handle_normal(line_info)
2561 else:
2592 else:
2562 # If the code compiles ok, we should handle it normally
2593 # If the code compiles ok, we should handle it normally
2563 return self.handle_normal(line_info)
2594 return self.handle_normal(line_info)
2564
2595
2565 def getapi(self):
2596 def getapi(self):
2566 """ Get an IPApi object for this shell instance
2597 """ Get an IPApi object for this shell instance
2567
2598
2568 Getting an IPApi object is always preferable to accessing the shell
2599 Getting an IPApi object is always preferable to accessing the shell
2569 directly, but this holds true especially for extensions.
2600 directly, but this holds true especially for extensions.
2570
2601
2571 It should always be possible to implement an extension with IPApi
2602 It should always be possible to implement an extension with IPApi
2572 alone. If not, contact maintainer to request an addition.
2603 alone. If not, contact maintainer to request an addition.
2573
2604
2574 """
2605 """
2575 return self.api
2606 return self.api
2576
2607
2577 def handle_emacs(self, line_info):
2608 def handle_emacs(self, line_info):
2578 """Handle input lines marked by python-mode."""
2609 """Handle input lines marked by python-mode."""
2579
2610
2580 # Currently, nothing is done. Later more functionality can be added
2611 # Currently, nothing is done. Later more functionality can be added
2581 # here if needed.
2612 # here if needed.
2582
2613
2583 # The input cache shouldn't be updated
2614 # The input cache shouldn't be updated
2584 return line_info.line
2615 return line_info.line
2585
2616
2586 def var_expand(self,cmd,depth=0):
2617 def var_expand(self,cmd,depth=0):
2587 """Expand python variables in a string.
2618 """Expand python variables in a string.
2588
2619
2589 The depth argument indicates how many frames above the caller should
2620 The depth argument indicates how many frames above the caller should
2590 be walked to look for the local namespace where to expand variables.
2621 be walked to look for the local namespace where to expand variables.
2591
2622
2592 The global namespace for expansion is always the user's interactive
2623 The global namespace for expansion is always the user's interactive
2593 namespace.
2624 namespace.
2594 """
2625 """
2595
2626
2596 return str(ItplNS(cmd,
2627 return str(ItplNS(cmd,
2597 self.user_ns, # globals
2628 self.user_ns, # globals
2598 # Skip our own frame in searching for locals:
2629 # Skip our own frame in searching for locals:
2599 sys._getframe(depth+1).f_locals # locals
2630 sys._getframe(depth+1).f_locals # locals
2600 ))
2631 ))
2601
2632
2602 def mktempfile(self,data=None):
2633 def mktempfile(self,data=None):
2603 """Make a new tempfile and return its filename.
2634 """Make a new tempfile and return its filename.
2604
2635
2605 This makes a call to tempfile.mktemp, but it registers the created
2636 This makes a call to tempfile.mktemp, but it registers the created
2606 filename internally so ipython cleans it up at exit time.
2637 filename internally so ipython cleans it up at exit time.
2607
2638
2608 Optional inputs:
2639 Optional inputs:
2609
2640
2610 - data(None): if data is given, it gets written out to the temp file
2641 - data(None): if data is given, it gets written out to the temp file
2611 immediately, and the file is closed again."""
2642 immediately, and the file is closed again."""
2612
2643
2613 filename = tempfile.mktemp('.py','ipython_edit_')
2644 filename = tempfile.mktemp('.py','ipython_edit_')
2614 self.tempfiles.append(filename)
2645 self.tempfiles.append(filename)
2615
2646
2616 if data:
2647 if data:
2617 tmp_file = open(filename,'w')
2648 tmp_file = open(filename,'w')
2618 tmp_file.write(data)
2649 tmp_file.write(data)
2619 tmp_file.close()
2650 tmp_file.close()
2620 return filename
2651 return filename
2621
2652
2622 def write(self,data):
2653 def write(self,data):
2623 """Write a string to the default output"""
2654 """Write a string to the default output"""
2624 Term.cout.write(data)
2655 Term.cout.write(data)
2625
2656
2626 def write_err(self,data):
2657 def write_err(self,data):
2627 """Write a string to the default error output"""
2658 """Write a string to the default error output"""
2628 Term.cerr.write(data)
2659 Term.cerr.write(data)
2629
2660
2630 def ask_exit(self):
2661 def ask_exit(self):
2631 """ Call for exiting. Can be overiden and used as a callback. """
2662 """ Call for exiting. Can be overiden and used as a callback. """
2632 self.exit_now = True
2663 self.exit_now = True
2633
2664
2634 def exit(self):
2665 def exit(self):
2635 """Handle interactive exit.
2666 """Handle interactive exit.
2636
2667
2637 This method calls the ask_exit callback."""
2668 This method calls the ask_exit callback."""
2638 if self.confirm_exit:
2669 if self.confirm_exit:
2639 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2670 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2640 self.ask_exit()
2671 self.ask_exit()
2641 else:
2672 else:
2642 self.ask_exit()
2673 self.ask_exit()
2643
2674
2644 def safe_execfile(self,fname,*where,**kw):
2675 def safe_execfile(self,fname,*where,**kw):
2645 """A safe version of the builtin execfile().
2676 """A safe version of the builtin execfile().
2646
2677
2647 This version will never throw an exception, and knows how to handle
2678 This version will never throw an exception, and knows how to handle
2648 ipython logs as well.
2679 ipython logs as well.
2649
2680
2650 :Parameters:
2681 :Parameters:
2651 fname : string
2682 fname : string
2652 Name of the file to be executed.
2683 Name of the file to be executed.
2653
2684
2654 where : tuple
2685 where : tuple
2655 One or two namespaces, passed to execfile() as (globals,locals).
2686 One or two namespaces, passed to execfile() as (globals,locals).
2656 If only one is given, it is passed as both.
2687 If only one is given, it is passed as both.
2657
2688
2658 :Keywords:
2689 :Keywords:
2659 islog : boolean (False)
2690 islog : boolean (False)
2660
2691
2661 quiet : boolean (True)
2692 quiet : boolean (True)
2662
2693
2663 exit_ignore : boolean (False)
2694 exit_ignore : boolean (False)
2664 """
2695 """
2665
2696
2666 def syspath_cleanup():
2697 def syspath_cleanup():
2667 """Internal cleanup routine for sys.path."""
2698 """Internal cleanup routine for sys.path."""
2668 if add_dname:
2699 if add_dname:
2669 try:
2700 try:
2670 sys.path.remove(dname)
2701 sys.path.remove(dname)
2671 except ValueError:
2702 except ValueError:
2672 # For some reason the user has already removed it, ignore.
2703 # For some reason the user has already removed it, ignore.
2673 pass
2704 pass
2674
2705
2675 fname = os.path.expanduser(fname)
2706 fname = os.path.expanduser(fname)
2676
2707
2677 # Find things also in current directory. This is needed to mimic the
2708 # Find things also in current directory. This is needed to mimic the
2678 # behavior of running a script from the system command line, where
2709 # behavior of running a script from the system command line, where
2679 # Python inserts the script's directory into sys.path
2710 # Python inserts the script's directory into sys.path
2680 dname = os.path.dirname(os.path.abspath(fname))
2711 dname = os.path.dirname(os.path.abspath(fname))
2681 add_dname = False
2712 add_dname = False
2682 if dname not in sys.path:
2713 if dname not in sys.path:
2683 sys.path.insert(0,dname)
2714 sys.path.insert(0,dname)
2684 add_dname = True
2715 add_dname = True
2685
2716
2686 try:
2717 try:
2687 xfile = open(fname)
2718 xfile = open(fname)
2688 except:
2719 except:
2689 print >> Term.cerr, \
2720 print >> Term.cerr, \
2690 'Could not open file <%s> for safe execution.' % fname
2721 'Could not open file <%s> for safe execution.' % fname
2691 syspath_cleanup()
2722 syspath_cleanup()
2692 return None
2723 return None
2693
2724
2694 kw.setdefault('islog',0)
2725 kw.setdefault('islog',0)
2695 kw.setdefault('quiet',1)
2726 kw.setdefault('quiet',1)
2696 kw.setdefault('exit_ignore',0)
2727 kw.setdefault('exit_ignore',0)
2697
2728
2698 first = xfile.readline()
2729 first = xfile.readline()
2699 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2730 loghead = str(self.loghead_tpl).split('\n',1)[0].strip()
2700 xfile.close()
2731 xfile.close()
2701 # line by line execution
2732 # line by line execution
2702 if first.startswith(loghead) or kw['islog']:
2733 if first.startswith(loghead) or kw['islog']:
2703 print 'Loading log file <%s> one line at a time...' % fname
2734 print 'Loading log file <%s> one line at a time...' % fname
2704 if kw['quiet']:
2735 if kw['quiet']:
2705 stdout_save = sys.stdout
2736 stdout_save = sys.stdout
2706 sys.stdout = StringIO.StringIO()
2737 sys.stdout = StringIO.StringIO()
2707 try:
2738 try:
2708 globs,locs = where[0:2]
2739 globs,locs = where[0:2]
2709 except:
2740 except:
2710 try:
2741 try:
2711 globs = locs = where[0]
2742 globs = locs = where[0]
2712 except:
2743 except:
2713 globs = locs = globals()
2744 globs = locs = globals()
2714 badblocks = []
2745 badblocks = []
2715
2746
2716 # we also need to identify indented blocks of code when replaying
2747 # we also need to identify indented blocks of code when replaying
2717 # logs and put them together before passing them to an exec
2748 # logs and put them together before passing them to an exec
2718 # statement. This takes a bit of regexp and look-ahead work in the
2749 # statement. This takes a bit of regexp and look-ahead work in the
2719 # file. It's easiest if we swallow the whole thing in memory
2750 # file. It's easiest if we swallow the whole thing in memory
2720 # first, and manually walk through the lines list moving the
2751 # first, and manually walk through the lines list moving the
2721 # counter ourselves.
2752 # counter ourselves.
2722 indent_re = re.compile('\s+\S')
2753 indent_re = re.compile('\s+\S')
2723 xfile = open(fname)
2754 xfile = open(fname)
2724 filelines = xfile.readlines()
2755 filelines = xfile.readlines()
2725 xfile.close()
2756 xfile.close()
2726 nlines = len(filelines)
2757 nlines = len(filelines)
2727 lnum = 0
2758 lnum = 0
2728 while lnum < nlines:
2759 while lnum < nlines:
2729 line = filelines[lnum]
2760 line = filelines[lnum]
2730 lnum += 1
2761 lnum += 1
2731 # don't re-insert logger status info into cache
2762 # don't re-insert logger status info into cache
2732 if line.startswith('#log#'):
2763 if line.startswith('#log#'):
2733 continue
2764 continue
2734 else:
2765 else:
2735 # build a block of code (maybe a single line) for execution
2766 # build a block of code (maybe a single line) for execution
2736 block = line
2767 block = line
2737 try:
2768 try:
2738 next = filelines[lnum] # lnum has already incremented
2769 next = filelines[lnum] # lnum has already incremented
2739 except:
2770 except:
2740 next = None
2771 next = None
2741 while next and indent_re.match(next):
2772 while next and indent_re.match(next):
2742 block += next
2773 block += next
2743 lnum += 1
2774 lnum += 1
2744 try:
2775 try:
2745 next = filelines[lnum]
2776 next = filelines[lnum]
2746 except:
2777 except:
2747 next = None
2778 next = None
2748 # now execute the block of one or more lines
2779 # now execute the block of one or more lines
2749 try:
2780 try:
2750 exec block in globs,locs
2781 exec block in globs,locs
2751 except SystemExit:
2782 except SystemExit:
2752 pass
2783 pass
2753 except:
2784 except:
2754 badblocks.append(block.rstrip())
2785 badblocks.append(block.rstrip())
2755 if kw['quiet']: # restore stdout
2786 if kw['quiet']: # restore stdout
2756 sys.stdout.close()
2787 sys.stdout.close()
2757 sys.stdout = stdout_save
2788 sys.stdout = stdout_save
2758 print 'Finished replaying log file <%s>' % fname
2789 print 'Finished replaying log file <%s>' % fname
2759 if badblocks:
2790 if badblocks:
2760 print >> sys.stderr, ('\nThe following lines/blocks in file '
2791 print >> sys.stderr, ('\nThe following lines/blocks in file '
2761 '<%s> reported errors:' % fname)
2792 '<%s> reported errors:' % fname)
2762
2793
2763 for badline in badblocks:
2794 for badline in badblocks:
2764 print >> sys.stderr, badline
2795 print >> sys.stderr, badline
2765 else: # regular file execution
2796 else: # regular file execution
2766 try:
2797 try:
2767 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2798 if sys.platform == 'win32' and sys.version_info < (2,5,1):
2768 # Work around a bug in Python for Windows. The bug was
2799 # Work around a bug in Python for Windows. The bug was
2769 # fixed in in Python 2.5 r54159 and 54158, but that's still
2800 # fixed in in Python 2.5 r54159 and 54158, but that's still
2770 # SVN Python as of March/07. For details, see:
2801 # SVN Python as of March/07. For details, see:
2771 # http://projects.scipy.org/ipython/ipython/ticket/123
2802 # http://projects.scipy.org/ipython/ipython/ticket/123
2772 try:
2803 try:
2773 globs,locs = where[0:2]
2804 globs,locs = where[0:2]
2774 except:
2805 except:
2775 try:
2806 try:
2776 globs = locs = where[0]
2807 globs = locs = where[0]
2777 except:
2808 except:
2778 globs = locs = globals()
2809 globs = locs = globals()
2779 exec file(fname) in globs,locs
2810 exec file(fname) in globs,locs
2780 else:
2811 else:
2781 execfile(fname,*where)
2812 execfile(fname,*where)
2782 except SyntaxError:
2813 except SyntaxError:
2783 self.showsyntaxerror()
2814 self.showsyntaxerror()
2784 warn('Failure executing file: <%s>' % fname)
2815 warn('Failure executing file: <%s>' % fname)
2785 except SystemExit,status:
2816 except SystemExit,status:
2786 # Code that correctly sets the exit status flag to success (0)
2817 # Code that correctly sets the exit status flag to success (0)
2787 # shouldn't be bothered with a traceback. Note that a plain
2818 # shouldn't be bothered with a traceback. Note that a plain
2788 # sys.exit() does NOT set the message to 0 (it's empty) so that
2819 # sys.exit() does NOT set the message to 0 (it's empty) so that
2789 # will still get a traceback. Note that the structure of the
2820 # will still get a traceback. Note that the structure of the
2790 # SystemExit exception changed between Python 2.4 and 2.5, so
2821 # SystemExit exception changed between Python 2.4 and 2.5, so
2791 # the checks must be done in a version-dependent way.
2822 # the checks must be done in a version-dependent way.
2792 show = False
2823 show = False
2793
2824
2794 if sys.version_info[:2] > (2,5):
2825 if sys.version_info[:2] > (2,5):
2795 if status.message!=0 and not kw['exit_ignore']:
2826 if status.message!=0 and not kw['exit_ignore']:
2796 show = True
2827 show = True
2797 else:
2828 else:
2798 if status.code and not kw['exit_ignore']:
2829 if status.code and not kw['exit_ignore']:
2799 show = True
2830 show = True
2800 if show:
2831 if show:
2801 self.showtraceback()
2832 self.showtraceback()
2802 warn('Failure executing file: <%s>' % fname)
2833 warn('Failure executing file: <%s>' % fname)
2803 except:
2834 except:
2804 self.showtraceback()
2835 self.showtraceback()
2805 warn('Failure executing file: <%s>' % fname)
2836 warn('Failure executing file: <%s>' % fname)
2806
2837
2807 syspath_cleanup()
2838 syspath_cleanup()
2808
2839
2809 #************************* end of file <iplib.py> *****************************
2840 #************************* end of file <iplib.py> *****************************
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,103 +1,102 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """ Proxy module for accessing platform specific utility functions.
2 """ Proxy module for accessing platform specific utility functions.
3
3
4 Importing this module should give you the implementations that are correct
4 Importing this module should give you the implementations that are correct
5 for your operation system, from platutils_PLATFORMNAME module.
5 for your operation system, from platutils_PLATFORMNAME module.
6 """
6 """
7
7
8 #*****************************************************************************
8 #*****************************************************************************
9 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
10 #
10 #
11 # Distributed under the terms of the BSD License. The full license is in
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
12 # the file COPYING, distributed as part of this software.
13 #*****************************************************************************
13 #*****************************************************************************
14
14
15 import os
15 import os
16 import sys
16 import sys
17 import warnings
17 import warnings
18
18
19 # Import the platform-specific implementations
19 # Import the platform-specific implementations
20 if os.name == 'posix':
20 if os.name == 'posix':
21 import platutils_posix as _platutils
21 import platutils_posix as _platutils
22 elif sys.platform == 'win32':
22 elif sys.platform == 'win32':
23 import platutils_win32 as _platutils
23 import platutils_win32 as _platutils
24 else:
24 else:
25 import platutils_dummy as _platutils
25 import platutils_dummy as _platutils
26
26
27 # Functionality that's logically common to all platforms goes here, each
27 # Functionality that's logically common to all platforms goes here, each
28 # platform-specific module only provides the bits that are OS-dependent.
28 # platform-specific module only provides the bits that are OS-dependent.
29
29
30 # XXX - I'm still not happy with a module global for this, but at least now
30 # XXX - I'm still not happy with a module global for this, but at least now
31 # there is a public, cross-platform way of toggling the term title control on
31 # there is a public, cross-platform way of toggling the term title control on
32 # and off. We should make this a stateful object later on so that each user
32 # and off. We should make this a stateful object later on so that each user
33 # can have its own instance if needed.
33 # can have its own instance if needed.
34 def term_clear():
34 def term_clear():
35 _platutils.term_clear()
35 _platutils.term_clear()
36
36
37 def toggle_set_term_title(val):
37 def toggle_set_term_title(val):
38 """Control whether set_term_title is active or not.
38 """Control whether set_term_title is active or not.
39
39
40 set_term_title() allows writing to the console titlebar. In embedded
40 set_term_title() allows writing to the console titlebar. In embedded
41 widgets this can cause problems, so this call can be used to toggle it on
41 widgets this can cause problems, so this call can be used to toggle it on
42 or off as needed.
42 or off as needed.
43
43
44 The default state of the module is for the function to be disabled.
44 The default state of the module is for the function to be disabled.
45
45
46 Parameters
46 Parameters
47 ----------
47 ----------
48 val : bool
48 val : bool
49 If True, set_term_title() actually writes to the terminal (using the
49 If True, set_term_title() actually writes to the terminal (using the
50 appropriate platform-specific module). If False, it is a no-op.
50 appropriate platform-specific module). If False, it is a no-op.
51 """
51 """
52 _platutils.ignore_termtitle = not(val)
52 _platutils.ignore_termtitle = not(val)
53
53
54
54
55 def set_term_title(title):
55 def set_term_title(title):
56 """Set terminal title using the necessary platform-dependent calls."""
56 """Set terminal title using the necessary platform-dependent calls."""
57
58 if _platutils.ignore_termtitle:
57 if _platutils.ignore_termtitle:
59 return
58 return
60 _platutils.set_term_title(title)
59 _platutils.set_term_title(title)
61
60
62
61
63 class FindCmdError(Exception):
62 class FindCmdError(Exception):
64 pass
63 pass
65
64
66 def find_cmd(cmd):
65 def find_cmd(cmd):
67 """Find full path to executable cmd in a cross platform manner.
66 """Find full path to executable cmd in a cross platform manner.
68
67
69 This function tries to determine the full path to a command line program
68 This function tries to determine the full path to a command line program
70 using `which` on Unix/Linux/OS X and `win32api` on Windows. Most of the
69 using `which` on Unix/Linux/OS X and `win32api` on Windows. Most of the
71 time it will use the version that is first on the users `PATH`. If
70 time it will use the version that is first on the users `PATH`. If
72 cmd is `python` return `sys.executable`.
71 cmd is `python` return `sys.executable`.
73
72
74 Parameters
73 Parameters
75 ----------
74 ----------
76 cmd : str
75 cmd : str
77 The command line program to look for.
76 The command line program to look for.
78 """
77 """
79 if cmd == 'python':
78 if cmd == 'python':
80 return sys.executable
79 return sys.executable
81 try:
80 try:
82 path = _platutils.find_cmd(cmd)
81 path = _platutils.find_cmd(cmd)
83 except:
82 except:
84 raise FindCmdError('command could not be found: %s' % cmd)
83 raise FindCmdError('command could not be found: %s' % cmd)
85 # which returns empty if not found
84 # which returns empty if not found
86 if path == '':
85 if path == '':
87 raise FindCmdError('command could not be found: %s' % cmd)
86 raise FindCmdError('command could not be found: %s' % cmd)
88 return path
87 return path
89
88
90 def get_long_path_name(path):
89 def get_long_path_name(path):
91 """Expand a path into its long form.
90 """Expand a path into its long form.
92
91
93 On Windows this expands any ~ in the paths. On other platforms, it is
92 On Windows this expands any ~ in the paths. On other platforms, it is
94 a null operation.
93 a null operation.
95 """
94 """
96 return _platutils.get_long_path_name(path)
95 return _platutils.get_long_path_name(path)
97
96
98 #-----------------------------------------------------------------------------
97 #-----------------------------------------------------------------------------
99 # Deprecated functions
98 # Deprecated functions
100 #-----------------------------------------------------------------------------
99 #-----------------------------------------------------------------------------
101 def freeze_term_title():
100 def freeze_term_title():
102 warnings.warn("This function is deprecated, use toggle_set_term_title()")
101 warnings.warn("This function is deprecated, use toggle_set_term_title()")
103 _platutils.ignore_termtitle = True
102 _platutils.ignore_termtitle = True
@@ -1,47 +1,48 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """ Platform specific utility functions, posix version
2 """ Platform specific utility functions, posix version
3
3
4 Importing this module directly is not portable - rather, import platutils
4 Importing this module directly is not portable - rather, import platutils
5 to use these functions in platform agnostic fashion.
5 to use these functions in platform agnostic fashion.
6 """
6 """
7
7
8 #*****************************************************************************
8 #*****************************************************************************
9 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
10 #
10 #
11 # Distributed under the terms of the BSD License. The full license is in
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
12 # the file COPYING, distributed as part of this software.
13 #*****************************************************************************
13 #*****************************************************************************
14
14
15 import sys
15 import sys
16 import os
16 import os
17
17
18 ignore_termtitle = True
18 ignore_termtitle = True
19
19
20
20 def _dummy_op(*a, **b):
21 def _dummy_op(*a, **b):
21 """ A no-op function """
22 """ A no-op function """
22
23
23
24
24 def _set_term_title_xterm(title):
25 def _set_term_title_xterm(title):
25 """ Change virtual terminal title in xterm-workalikes """
26 """ Change virtual terminal title in xterm-workalikes """
26
27 sys.stdout.write('\033]0;%s\007' % title)
27 sys.stdout.write('\033]0;%s\007' % title)
28
28
29 TERM = os.environ.get('TERM','')
29
30
30 if os.environ.get('TERM','') == 'xterm':
31 if (TERM == 'xterm') or (TERM == 'xterm-color'):
31 set_term_title = _set_term_title_xterm
32 set_term_title = _set_term_title_xterm
32 else:
33 else:
33 set_term_title = _dummy_op
34 set_term_title = _dummy_op
34
35
35
36
36 def find_cmd(cmd):
37 def find_cmd(cmd):
37 """Find the full path to a command using which."""
38 """Find the full path to a command using which."""
38 return os.popen('which %s' % cmd).read().strip()
39 return os.popen('which %s' % cmd).read().strip()
39
40
40
41
41 def get_long_path_name(path):
42 def get_long_path_name(path):
42 """Dummy no-op."""
43 """Dummy no-op."""
43 return path
44 return path
44
45
45
46
46 def term_clear():
47 def term_clear():
47 os.system('clear')
48 os.system('clear')
@@ -1,94 +1,95 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """ Platform specific utility functions, win32 version
2 """ Platform specific utility functions, win32 version
3
3
4 Importing this module directly is not portable - rather, import platutils
4 Importing this module directly is not portable - rather, import platutils
5 to use these functions in platform agnostic fashion.
5 to use these functions in platform agnostic fashion.
6 """
6 """
7
7
8 #*****************************************************************************
8 #*****************************************************************************
9 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
9 # Copyright (C) 2001-2006 Fernando Perez <fperez@colorado.edu>
10 #
10 #
11 # Distributed under the terms of the BSD License. The full license is in
11 # Distributed under the terms of the BSD License. The full license is in
12 # the file COPYING, distributed as part of this software.
12 # the file COPYING, distributed as part of this software.
13 #*****************************************************************************
13 #*****************************************************************************
14
14
15 import os
15 import os
16
16
17 ignore_termtitle = True
17 ignore_termtitle = True
18
18
19 try:
19 try:
20 import ctypes
20 import ctypes
21
21
22 SetConsoleTitleW = ctypes.windll.kernel32.SetConsoleTitleW
22 SetConsoleTitleW = ctypes.windll.kernel32.SetConsoleTitleW
23 SetConsoleTitleW.argtypes = [ctypes.c_wchar_p]
23 SetConsoleTitleW.argtypes = [ctypes.c_wchar_p]
24
24
25 def set_term_title(title):
25 def set_term_title(title):
26 """Set terminal title using ctypes to access the Win32 APIs."""
26 """Set terminal title using ctypes to access the Win32 APIs."""
27 SetConsoleTitleW(title)
27 SetConsoleTitleW(title)
28
28
29
29 except ImportError:
30 except ImportError:
30 def set_term_title(title):
31 def set_term_title(title):
31 """Set terminal title using the 'title' command."""
32 """Set terminal title using the 'title' command."""
32 global ignore_termtitle
33 global ignore_termtitle
33
34
34 try:
35 try:
35 # Cannot be on network share when issuing system commands
36 # Cannot be on network share when issuing system commands
36 curr = os.getcwd()
37 curr = os.getcwd()
37 os.chdir("C:")
38 os.chdir("C:")
38 ret = os.system("title " + title)
39 ret = os.system("title " + title)
39 finally:
40 finally:
40 os.chdir(curr)
41 os.chdir(curr)
41 if ret:
42 if ret:
42 # non-zero return code signals error, don't try again
43 # non-zero return code signals error, don't try again
43 ignore_termtitle = True
44 ignore_termtitle = True
44
45
45
46
46 def find_cmd(cmd):
47 def find_cmd(cmd):
47 """Find the full path to a .bat or .exe using the win32api module."""
48 """Find the full path to a .bat or .exe using the win32api module."""
48 try:
49 try:
49 from win32api import SearchPath
50 from win32api import SearchPath
50 except ImportError:
51 except ImportError:
51 raise ImportError('you need to have pywin32 installed for this to work')
52 raise ImportError('you need to have pywin32 installed for this to work')
52 else:
53 else:
53 PATH = os.environ['PATH']
54 PATH = os.environ['PATH']
54 extensions = ['.exe', '.com', '.bat', '.py']
55 extensions = ['.exe', '.com', '.bat', '.py']
55 path = None
56 path = None
56 for ext in extensions:
57 for ext in extensions:
57 try:
58 try:
58 path = SearchPath(PATH,cmd + ext)[0]
59 path = SearchPath(PATH,cmd + ext)[0]
59 except:
60 except:
60 pass
61 pass
61 if path is None:
62 if path is None:
62 raise OSError("command %r not found" % cmd)
63 raise OSError("command %r not found" % cmd)
63 else:
64 else:
64 return path
65 return path
65
66
66
67
67 def get_long_path_name(path):
68 def get_long_path_name(path):
68 """Get a long path name (expand ~) on Windows using ctypes.
69 """Get a long path name (expand ~) on Windows using ctypes.
69
70
70 Examples
71 Examples
71 --------
72 --------
72
73
73 >>> get_long_path_name('c:\\docume~1')
74 >>> get_long_path_name('c:\\docume~1')
74 u'c:\\\\Documents and Settings'
75 u'c:\\\\Documents and Settings'
75
76
76 """
77 """
77 try:
78 try:
78 import ctypes
79 import ctypes
79 except ImportError:
80 except ImportError:
80 raise ImportError('you need to have ctypes installed for this to work')
81 raise ImportError('you need to have ctypes installed for this to work')
81 _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
82 _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
82 _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
83 _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
83 ctypes.c_uint ]
84 ctypes.c_uint ]
84
85
85 buf = ctypes.create_unicode_buffer(260)
86 buf = ctypes.create_unicode_buffer(260)
86 rv = _GetLongPathName(path, buf, 260)
87 rv = _GetLongPathName(path, buf, 260)
87 if rv == 0 or rv > 260:
88 if rv == 0 or rv > 260:
88 return path
89 return path
89 else:
90 else:
90 return buf.value
91 return buf.value
91
92
92
93
93 def term_clear():
94 def term_clear():
94 os.system('cls')
95 os.system('cls')
@@ -1,899 +1,925 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 # encoding: utf-8
2 # encoding: utf-8
3 """
3 """
4 A lightweight Traits like module.
4 A lightweight Traits like module.
5
5
6 This is designed to provide a lightweight, simple, pure Python version of
6 This is designed to provide a lightweight, simple, pure Python version of
7 many of the capabilities of enthought.traits. This includes:
7 many of the capabilities of enthought.traits. This includes:
8
8
9 * Validation
9 * Validation
10 * Type specification with defaults
10 * Type specification with defaults
11 * Static and dynamic notification
11 * Static and dynamic notification
12 * Basic predefined types
12 * Basic predefined types
13 * An API that is similar to enthought.traits
13 * An API that is similar to enthought.traits
14
14
15 We don't support:
15 We don't support:
16
16
17 * Delegation
17 * Delegation
18 * Automatic GUI generation
18 * Automatic GUI generation
19 * A full set of trait types. Most importantly, we don't provide container
19 * A full set of trait types. Most importantly, we don't provide container
20 traitlets (list, dict, tuple) that can trigger notifications if their
20 traitlets (list, dict, tuple) that can trigger notifications if their
21 contents change.
21 contents change.
22 * API compatibility with enthought.traits
22 * API compatibility with enthought.traits
23
23
24 There are also some important difference in our design:
24 There are also some important difference in our design:
25
25
26 * enthought.traits does not validate default values. We do.
26 * enthought.traits does not validate default values. We do.
27
27
28 We choose to create this module because we need these capabilities, but
28 We choose to create this module because we need these capabilities, but
29 we need them to be pure Python so they work in all Python implementations,
29 we need them to be pure Python so they work in all Python implementations,
30 including Jython and IronPython.
30 including Jython and IronPython.
31
31
32 Authors:
32 Authors:
33
33
34 * Brian Granger
34 * Brian Granger
35 * Enthought, Inc. Some of the code in this file comes from enthought.traits
35 * Enthought, Inc. Some of the code in this file comes from enthought.traits
36 and is licensed under the BSD license. Also, many of the ideas also come
36 and is licensed under the BSD license. Also, many of the ideas also come
37 from enthought.traits even though our implementation is very different.
37 from enthought.traits even though our implementation is very different.
38 """
38 """
39
39
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41 # Copyright (C) 2008-2009 The IPython Development Team
41 # Copyright (C) 2008-2009 The IPython Development Team
42 #
42 #
43 # Distributed under the terms of the BSD License. The full license is in
43 # Distributed under the terms of the BSD License. The full license is in
44 # the file COPYING, distributed as part of this software.
44 # the file COPYING, distributed as part of this software.
45 #-----------------------------------------------------------------------------
45 #-----------------------------------------------------------------------------
46
46
47 #-----------------------------------------------------------------------------
47 #-----------------------------------------------------------------------------
48 # Imports
48 # Imports
49 #-----------------------------------------------------------------------------
49 #-----------------------------------------------------------------------------
50
50
51
51
52 import inspect
52 import inspect
53 import sys
53 import sys
54 import types
54 import types
55 from types import InstanceType, ClassType, FunctionType
55 from types import (
56 InstanceType, ClassType, FunctionType,
57 ListType, TupleType
58 )
56
59
57 ClassTypes = (ClassType, type)
60 ClassTypes = (ClassType, type)
58
61
62 SequenceTypes = (ListType, TupleType)
63
59 #-----------------------------------------------------------------------------
64 #-----------------------------------------------------------------------------
60 # Basic classes
65 # Basic classes
61 #-----------------------------------------------------------------------------
66 #-----------------------------------------------------------------------------
62
67
63
68
64 class NoDefaultSpecified ( object ): pass
69 class NoDefaultSpecified ( object ): pass
65 NoDefaultSpecified = NoDefaultSpecified()
70 NoDefaultSpecified = NoDefaultSpecified()
66
71
67
72
68 class Undefined ( object ): pass
73 class Undefined ( object ): pass
69 Undefined = Undefined()
74 Undefined = Undefined()
70
75
71
76
72 class TraitletError(Exception):
77 class TraitletError(Exception):
73 pass
78 pass
74
79
75
80
76 #-----------------------------------------------------------------------------
81 #-----------------------------------------------------------------------------
77 # Utilities
82 # Utilities
78 #-----------------------------------------------------------------------------
83 #-----------------------------------------------------------------------------
79
84
80
85
81 def class_of ( object ):
86 def class_of ( object ):
82 """ Returns a string containing the class name of an object with the
87 """ Returns a string containing the class name of an object with the
83 correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
88 correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
84 'a PlotValue').
89 'a PlotValue').
85 """
90 """
86 if isinstance( object, basestring ):
91 if isinstance( object, basestring ):
87 return add_article( object )
92 return add_article( object )
88
93
89 return add_article( object.__class__.__name__ )
94 return add_article( object.__class__.__name__ )
90
95
91
96
92 def add_article ( name ):
97 def add_article ( name ):
93 """ Returns a string containing the correct indefinite article ('a' or 'an')
98 """ Returns a string containing the correct indefinite article ('a' or 'an')
94 prefixed to the specified string.
99 prefixed to the specified string.
95 """
100 """
96 if name[:1].lower() in 'aeiou':
101 if name[:1].lower() in 'aeiou':
97 return 'an ' + name
102 return 'an ' + name
98
103
99 return 'a ' + name
104 return 'a ' + name
100
105
101
106
102 def repr_type(obj):
107 def repr_type(obj):
103 """ Return a string representation of a value and its type for readable
108 """ Return a string representation of a value and its type for readable
104 error messages.
109 error messages.
105 """
110 """
106 the_type = type(obj)
111 the_type = type(obj)
107 if the_type is InstanceType:
112 if the_type is InstanceType:
108 # Old-style class.
113 # Old-style class.
109 the_type = obj.__class__
114 the_type = obj.__class__
110 msg = '%r %r' % (obj, the_type)
115 msg = '%r %r' % (obj, the_type)
111 return msg
116 return msg
112
117
113
118
114 def parse_notifier_name(name):
119 def parse_notifier_name(name):
115 """Convert the name argument to a list of names.
120 """Convert the name argument to a list of names.
116
121
117 Examples
122 Examples
118 --------
123 --------
119
124
120 >>> parse_notifier_name('a')
125 >>> parse_notifier_name('a')
121 ['a']
126 ['a']
122 >>> parse_notifier_name(['a','b'])
127 >>> parse_notifier_name(['a','b'])
123 ['a', 'b']
128 ['a', 'b']
124 >>> parse_notifier_name(None)
129 >>> parse_notifier_name(None)
125 ['anytraitlet']
130 ['anytraitlet']
126 """
131 """
127 if isinstance(name, str):
132 if isinstance(name, str):
128 return [name]
133 return [name]
129 elif name is None:
134 elif name is None:
130 return ['anytraitlet']
135 return ['anytraitlet']
131 elif isinstance(name, (list, tuple)):
136 elif isinstance(name, (list, tuple)):
132 for n in name:
137 for n in name:
133 assert isinstance(n, str), "names must be strings"
138 assert isinstance(n, str), "names must be strings"
134 return name
139 return name
135
140
136
141
137 class _SimpleTest:
142 class _SimpleTest:
138 def __init__ ( self, value ): self.value = value
143 def __init__ ( self, value ): self.value = value
139 def __call__ ( self, test ):
144 def __call__ ( self, test ):
140 print test, self.value
145 print test, self.value
141 return test == self.value
146 return test == self.value
142 def __repr__(self):
147 def __repr__(self):
143 return "<SimpleTest(%r)" % self.value
148 return "<SimpleTest(%r)" % self.value
144 def __str__(self):
149 def __str__(self):
145 return self.__repr__()
150 return self.__repr__()
146
151
147
152
148 #-----------------------------------------------------------------------------
153 #-----------------------------------------------------------------------------
149 # Base TraitletType for all traitlets
154 # Base TraitletType for all traitlets
150 #-----------------------------------------------------------------------------
155 #-----------------------------------------------------------------------------
151
156
152
157
153 class TraitletType(object):
158 class TraitletType(object):
154 """A base class for all traitlet descriptors.
159 """A base class for all traitlet descriptors.
155
160
156 Notes
161 Notes
157 -----
162 -----
158 Our implementation of traitlets is based on Python's descriptor
163 Our implementation of traitlets is based on Python's descriptor
159 prototol. This class is the base class for all such descriptors. The
164 prototol. This class is the base class for all such descriptors. The
160 only magic we use is a custom metaclass for the main :class:`HasTraitlets`
165 only magic we use is a custom metaclass for the main :class:`HasTraitlets`
161 class that does the following:
166 class that does the following:
162
167
163 1. Sets the :attr:`name` attribute of every :class:`TraitletType`
168 1. Sets the :attr:`name` attribute of every :class:`TraitletType`
164 instance in the class dict to the name of the attribute.
169 instance in the class dict to the name of the attribute.
165 2. Sets the :attr:`this_class` attribute of every :class:`TraitletType`
170 2. Sets the :attr:`this_class` attribute of every :class:`TraitletType`
166 instance in the class dict to the *class* that declared the traitlet.
171 instance in the class dict to the *class* that declared the traitlet.
167 This is used by the :class:`This` traitlet to allow subclasses to
172 This is used by the :class:`This` traitlet to allow subclasses to
168 accept superclasses for :class:`This` values.
173 accept superclasses for :class:`This` values.
169 """
174 """
170
175
171
176
172 metadata = {}
177 metadata = {}
173 default_value = Undefined
178 default_value = Undefined
174 info_text = 'any value'
179 info_text = 'any value'
175
180
176 def __init__(self, default_value=NoDefaultSpecified, **metadata):
181 def __init__(self, default_value=NoDefaultSpecified, **metadata):
177 """Create a TraitletType.
182 """Create a TraitletType.
178 """
183 """
179 if default_value is not NoDefaultSpecified:
184 if default_value is not NoDefaultSpecified:
180 self.default_value = default_value
185 self.default_value = default_value
181
186
182 if len(metadata) > 0:
187 if len(metadata) > 0:
183 if len(self.metadata) > 0:
188 if len(self.metadata) > 0:
184 self._metadata = self.metadata.copy()
189 self._metadata = self.metadata.copy()
185 self._metadata.update(metadata)
190 self._metadata.update(metadata)
186 else:
191 else:
187 self._metadata = metadata
192 self._metadata = metadata
188 else:
193 else:
189 self._metadata = self.metadata
194 self._metadata = self.metadata
190
195
191 self.init()
196 self.init()
192
197
193 def init(self):
198 def init(self):
194 pass
199 pass
195
200
196 def get_default_value(self):
201 def get_default_value(self):
197 """Create a new instance of the default value."""
202 """Create a new instance of the default value."""
198 dv = self.default_value
203 dv = self.default_value
199 return dv
204 return dv
200
205
201 def set_default_value(self, obj):
206 def set_default_value(self, obj):
202 dv = self.get_default_value()
207 dv = self.get_default_value()
203 newdv = self._validate(obj, dv)
208 newdv = self._validate(obj, dv)
204 obj._traitlet_values[self.name] = newdv
209 obj._traitlet_values[self.name] = newdv
205
210
206
211
207 def __get__(self, obj, cls=None):
212 def __get__(self, obj, cls=None):
208 """Get the value of the traitlet by self.name for the instance.
213 """Get the value of the traitlet by self.name for the instance.
209
214
210 Default values are instantiated when :meth:`HasTraitlets.__new__`
215 Default values are instantiated when :meth:`HasTraitlets.__new__`
211 is called. Thus by the time this method gets called either the
216 is called. Thus by the time this method gets called either the
212 default value or a user defined value (they called :meth:`__set__`)
217 default value or a user defined value (they called :meth:`__set__`)
213 is in the :class:`HasTraitlets` instance.
218 is in the :class:`HasTraitlets` instance.
214 """
219 """
215 if obj is None:
220 if obj is None:
216 return self
221 return self
217 else:
222 else:
218 try:
223 try:
219 value = obj._traitlet_values[self.name]
224 value = obj._traitlet_values[self.name]
220 except:
225 except:
221 # HasTraitlets should call set_default_value to populate
226 # HasTraitlets should call set_default_value to populate
222 # this. So this should never be reached.
227 # this. So this should never be reached.
223 raise TraitletError('Unexpected error in TraitletType: '
228 raise TraitletError('Unexpected error in TraitletType: '
224 'default value not set properly')
229 'default value not set properly')
225 else:
230 else:
226 return value
231 return value
227
232
228 def __set__(self, obj, value):
233 def __set__(self, obj, value):
229 new_value = self._validate(obj, value)
234 new_value = self._validate(obj, value)
230 old_value = self.__get__(obj)
235 old_value = self.__get__(obj)
231 if old_value != new_value:
236 if old_value != new_value:
232 obj._traitlet_values[self.name] = new_value
237 obj._traitlet_values[self.name] = new_value
233 obj._notify_traitlet(self.name, old_value, new_value)
238 obj._notify_traitlet(self.name, old_value, new_value)
234
239
235 def _validate(self, obj, value):
240 def _validate(self, obj, value):
236 if hasattr(self, 'validate'):
241 if hasattr(self, 'validate'):
237 return self.validate(obj, value)
242 return self.validate(obj, value)
238 elif hasattr(self, 'is_valid_for'):
243 elif hasattr(self, 'is_valid_for'):
239 valid = self.is_valid_for(value)
244 valid = self.is_valid_for(value)
240 if valid:
245 if valid:
241 return value
246 return value
242 else:
247 else:
243 raise TraitletError('invalid value for type: %r' % value)
248 raise TraitletError('invalid value for type: %r' % value)
244 elif hasattr(self, 'value_for'):
249 elif hasattr(self, 'value_for'):
245 return self.value_for(value)
250 return self.value_for(value)
246 else:
251 else:
247 return value
252 return value
248
253
249 def info(self):
254 def info(self):
250 return self.info_text
255 return self.info_text
251
256
252 def error(self, obj, value):
257 def error(self, obj, value):
253 if obj is not None:
258 if obj is not None:
254 e = "The '%s' traitlet of %s instance must be %s, but a value of %s was specified." \
259 e = "The '%s' traitlet of %s instance must be %s, but a value of %s was specified." \
255 % (self.name, class_of(obj),
260 % (self.name, class_of(obj),
256 self.info(), repr_type(value))
261 self.info(), repr_type(value))
257 else:
262 else:
258 e = "The '%s' traitlet must be %s, but a value of %r was specified." \
263 e = "The '%s' traitlet must be %s, but a value of %r was specified." \
259 % (self.name, self.info(), repr_type(value))
264 % (self.name, self.info(), repr_type(value))
260 raise TraitletError(e)
265 raise TraitletError(e)
261
266
262 def get_metadata(self, key):
267 def get_metadata(self, key):
263 return getattr(self, '_metadata', {}).get(key, None)
268 return getattr(self, '_metadata', {}).get(key, None)
264
269
265 def set_metadata(self, key, value):
270 def set_metadata(self, key, value):
266 getattr(self, '_metadata', {})[key] = value
271 getattr(self, '_metadata', {})[key] = value
267
272
268
273
269 #-----------------------------------------------------------------------------
274 #-----------------------------------------------------------------------------
270 # The HasTraitlets implementation
275 # The HasTraitlets implementation
271 #-----------------------------------------------------------------------------
276 #-----------------------------------------------------------------------------
272
277
273
278
274 class MetaHasTraitlets(type):
279 class MetaHasTraitlets(type):
275 """A metaclass for HasTraitlets.
280 """A metaclass for HasTraitlets.
276
281
277 This metaclass makes sure that any TraitletType class attributes are
282 This metaclass makes sure that any TraitletType class attributes are
278 instantiated and sets their name attribute.
283 instantiated and sets their name attribute.
279 """
284 """
280
285
281 def __new__(mcls, name, bases, classdict):
286 def __new__(mcls, name, bases, classdict):
282 """Create the HasTraitlets class.
287 """Create the HasTraitlets class.
283
288
284 This instantiates all TraitletTypes in the class dict and sets their
289 This instantiates all TraitletTypes in the class dict and sets their
285 :attr:`name` attribute.
290 :attr:`name` attribute.
286 """
291 """
287 # print "========================="
292 # print "========================="
288 # print "MetaHasTraitlets.__new__"
293 # print "MetaHasTraitlets.__new__"
289 # print "mcls, ", mcls
294 # print "mcls, ", mcls
290 # print "name, ", name
295 # print "name, ", name
291 # print "bases, ", bases
296 # print "bases, ", bases
292 # print "classdict, ", classdict
297 # print "classdict, ", classdict
293 for k,v in classdict.iteritems():
298 for k,v in classdict.iteritems():
294 if isinstance(v, TraitletType):
299 if isinstance(v, TraitletType):
295 v.name = k
300 v.name = k
296 elif inspect.isclass(v):
301 elif inspect.isclass(v):
297 if issubclass(v, TraitletType):
302 if issubclass(v, TraitletType):
298 vinst = v()
303 vinst = v()
299 vinst.name = k
304 vinst.name = k
300 classdict[k] = vinst
305 classdict[k] = vinst
301 return super(MetaHasTraitlets, mcls).__new__(mcls, name, bases, classdict)
306 return super(MetaHasTraitlets, mcls).__new__(mcls, name, bases, classdict)
302
307
303 def __init__(cls, name, bases, classdict):
308 def __init__(cls, name, bases, classdict):
304 """Finish initializing the HasTraitlets class.
309 """Finish initializing the HasTraitlets class.
305
310
306 This sets the :attr:`this_class` attribute of each TraitletType in the
311 This sets the :attr:`this_class` attribute of each TraitletType in the
307 class dict to the newly created class ``cls``.
312 class dict to the newly created class ``cls``.
308 """
313 """
309 # print "========================="
314 # print "========================="
310 # print "MetaHasTraitlets.__init__"
315 # print "MetaHasTraitlets.__init__"
311 # print "cls, ", cls
316 # print "cls, ", cls
312 # print "name, ", name
317 # print "name, ", name
313 # print "bases, ", bases
318 # print "bases, ", bases
314 # print "classdict, ", classdict
319 # print "classdict, ", classdict
315 for k, v in classdict.iteritems():
320 for k, v in classdict.iteritems():
316 if isinstance(v, TraitletType):
321 if isinstance(v, TraitletType):
317 v.this_class = cls
322 v.this_class = cls
318 super(MetaHasTraitlets, cls).__init__(name, bases, classdict)
323 super(MetaHasTraitlets, cls).__init__(name, bases, classdict)
319
324
320 class HasTraitlets(object):
325 class HasTraitlets(object):
321
326
322 __metaclass__ = MetaHasTraitlets
327 __metaclass__ = MetaHasTraitlets
323
328
324 def __new__(cls, *args, **kw):
329 def __new__(cls, *args, **kw):
325 inst = super(HasTraitlets, cls).__new__(cls, *args, **kw)
330 inst = super(HasTraitlets, cls).__new__(cls, *args, **kw)
326 inst._traitlet_values = {}
331 inst._traitlet_values = {}
327 inst._traitlet_notifiers = {}
332 inst._traitlet_notifiers = {}
328 # Here we tell all the TraitletType instances to set their default
333 # Here we tell all the TraitletType instances to set their default
329 # values on the instance.
334 # values on the instance.
330 for key in dir(cls):
335 for key in dir(cls):
331 value = getattr(cls, key)
336 value = getattr(cls, key)
332 if isinstance(value, TraitletType):
337 if isinstance(value, TraitletType):
333 value.set_default_value(inst)
338 value.set_default_value(inst)
334 return inst
339 return inst
335
340
336 # def __init__(self):
341 # def __init__(self):
337 # self._traitlet_values = {}
342 # self._traitlet_values = {}
338 # self._traitlet_notifiers = {}
343 # self._traitlet_notifiers = {}
339
344
340 def _notify_traitlet(self, name, old_value, new_value):
345 def _notify_traitlet(self, name, old_value, new_value):
341
346
342 # First dynamic ones
347 # First dynamic ones
343 callables = self._traitlet_notifiers.get(name,[])
348 callables = self._traitlet_notifiers.get(name,[])
344 more_callables = self._traitlet_notifiers.get('anytraitlet',[])
349 more_callables = self._traitlet_notifiers.get('anytraitlet',[])
345 callables.extend(more_callables)
350 callables.extend(more_callables)
346
351
347 # Now static ones
352 # Now static ones
348 try:
353 try:
349 cb = getattr(self, '_%s_changed' % name)
354 cb = getattr(self, '_%s_changed' % name)
350 except:
355 except:
351 pass
356 pass
352 else:
357 else:
353 callables.append(cb)
358 callables.append(cb)
354
359
355 # Call them all now
360 # Call them all now
356 for c in callables:
361 for c in callables:
357 # Traits catches and logs errors here. I allow them to raise
362 # Traits catches and logs errors here. I allow them to raise
358 if callable(c):
363 if callable(c):
359 argspec = inspect.getargspec(c)
364 argspec = inspect.getargspec(c)
360 nargs = len(argspec[0])
365 nargs = len(argspec[0])
361 # Bound methods have an additional 'self' argument
366 # Bound methods have an additional 'self' argument
362 # I don't know how to treat unbound methods, but they
367 # I don't know how to treat unbound methods, but they
363 # can't really be used for callbacks.
368 # can't really be used for callbacks.
364 if isinstance(c, types.MethodType):
369 if isinstance(c, types.MethodType):
365 offset = -1
370 offset = -1
366 else:
371 else:
367 offset = 0
372 offset = 0
368 if nargs + offset == 0:
373 if nargs + offset == 0:
369 c()
374 c()
370 elif nargs + offset == 1:
375 elif nargs + offset == 1:
371 c(name)
376 c(name)
372 elif nargs + offset == 2:
377 elif nargs + offset == 2:
373 c(name, new_value)
378 c(name, new_value)
374 elif nargs + offset == 3:
379 elif nargs + offset == 3:
375 c(name, old_value, new_value)
380 c(name, old_value, new_value)
376 else:
381 else:
377 raise TraitletError('a traitlet changed callback '
382 raise TraitletError('a traitlet changed callback '
378 'must have 0-3 arguments.')
383 'must have 0-3 arguments.')
379 else:
384 else:
380 raise TraitletError('a traitlet changed callback '
385 raise TraitletError('a traitlet changed callback '
381 'must be callable.')
386 'must be callable.')
382
387
383
388
384 def _add_notifiers(self, handler, name):
389 def _add_notifiers(self, handler, name):
385 if not self._traitlet_notifiers.has_key(name):
390 if not self._traitlet_notifiers.has_key(name):
386 nlist = []
391 nlist = []
387 self._traitlet_notifiers[name] = nlist
392 self._traitlet_notifiers[name] = nlist
388 else:
393 else:
389 nlist = self._traitlet_notifiers[name]
394 nlist = self._traitlet_notifiers[name]
390 if handler not in nlist:
395 if handler not in nlist:
391 nlist.append(handler)
396 nlist.append(handler)
392
397
393 def _remove_notifiers(self, handler, name):
398 def _remove_notifiers(self, handler, name):
394 if self._traitlet_notifiers.has_key(name):
399 if self._traitlet_notifiers.has_key(name):
395 nlist = self._traitlet_notifiers[name]
400 nlist = self._traitlet_notifiers[name]
396 try:
401 try:
397 index = nlist.index(handler)
402 index = nlist.index(handler)
398 except ValueError:
403 except ValueError:
399 pass
404 pass
400 else:
405 else:
401 del nlist[index]
406 del nlist[index]
402
407
403 def on_traitlet_change(self, handler, name=None, remove=False):
408 def on_traitlet_change(self, handler, name=None, remove=False):
404 """Setup a handler to be called when a traitlet changes.
409 """Setup a handler to be called when a traitlet changes.
405
410
406 This is used to setup dynamic notifications of traitlet changes.
411 This is used to setup dynamic notifications of traitlet changes.
407
412
408 Static handlers can be created by creating methods on a HasTraitlets
413 Static handlers can be created by creating methods on a HasTraitlets
409 subclass with the naming convention '_[traitletname]_changed'. Thus,
414 subclass with the naming convention '_[traitletname]_changed'. Thus,
410 to create static handler for the traitlet 'a', create the method
415 to create static handler for the traitlet 'a', create the method
411 _a_changed(self, name, old, new) (fewer arguments can be used, see
416 _a_changed(self, name, old, new) (fewer arguments can be used, see
412 below).
417 below).
413
418
414 Parameters
419 Parameters
415 ----------
420 ----------
416 handler : callable
421 handler : callable
417 A callable that is called when a traitlet changes. Its
422 A callable that is called when a traitlet changes. Its
418 signature can be handler(), handler(name), handler(name, new)
423 signature can be handler(), handler(name), handler(name, new)
419 or handler(name, old, new).
424 or handler(name, old, new).
420 name : list, str, None
425 name : list, str, None
421 If None, the handler will apply to all traitlets. If a list
426 If None, the handler will apply to all traitlets. If a list
422 of str, handler will apply to all names in the list. If a
427 of str, handler will apply to all names in the list. If a
423 str, the handler will apply just to that name.
428 str, the handler will apply just to that name.
424 remove : bool
429 remove : bool
425 If False (the default), then install the handler. If True
430 If False (the default), then install the handler. If True
426 then unintall it.
431 then unintall it.
427 """
432 """
428 if remove:
433 if remove:
429 names = parse_notifier_name(name)
434 names = parse_notifier_name(name)
430 for n in names:
435 for n in names:
431 self._remove_notifiers(handler, n)
436 self._remove_notifiers(handler, n)
432 else:
437 else:
433 names = parse_notifier_name(name)
438 names = parse_notifier_name(name)
434 for n in names:
439 for n in names:
435 self._add_notifiers(handler, n)
440 self._add_notifiers(handler, n)
436
441
437 def traitlet_names(self, **metadata):
442 def traitlet_names(self, **metadata):
438 """Get a list of all the names of this classes traitlets."""
443 """Get a list of all the names of this classes traitlets."""
439 return self.traitlets(**metadata).keys()
444 return self.traitlets(**metadata).keys()
440
445
441 def traitlets(self, *args, **metadata):
446 def traitlets(self, *args, **metadata):
442 """Get a list of all the traitlets of this class.
447 """Get a list of all the traitlets of this class.
443
448
444 The TraitletTypes returned don't know anything about the values
449 The TraitletTypes returned don't know anything about the values
445 that the various HasTraitlet's instances are holding.
450 that the various HasTraitlet's instances are holding.
446 """
451 """
447 traitlets = dict([memb for memb in inspect.getmembers(self.__class__) if \
452 traitlets = dict([memb for memb in inspect.getmembers(self.__class__) if \
448 isinstance(memb[1], TraitletType)])
453 isinstance(memb[1], TraitletType)])
449 if len(metadata) == 0 and len(args) == 0:
454 if len(metadata) == 0 and len(args) == 0:
450 return traitlets
455 return traitlets
451
456
452 for meta_name in args:
457 for meta_name in args:
453 metadata[meta_name] = lambda _: True
458 metadata[meta_name] = lambda _: True
454
459
455 for meta_name, meta_eval in metadata.items():
460 for meta_name, meta_eval in metadata.items():
456 if type(meta_eval) is not FunctionType:
461 if type(meta_eval) is not FunctionType:
457 metadata[meta_name] = _SimpleTest(meta_eval)
462 metadata[meta_name] = _SimpleTest(meta_eval)
458
463
459 result = {}
464 result = {}
460 for name, traitlet in traitlets.items():
465 for name, traitlet in traitlets.items():
461 for meta_name, meta_eval in metadata.items():
466 for meta_name, meta_eval in metadata.items():
462 if not meta_eval(traitlet.get_metadata(meta_name)):
467 if not meta_eval(traitlet.get_metadata(meta_name)):
463 break
468 break
464 else:
469 else:
465 result[name] = traitlet
470 result[name] = traitlet
466
471
467 return result
472 return result
468
473
469 def traitlet_metadata(self, traitletname, key):
474 def traitlet_metadata(self, traitletname, key):
470 """Get metadata values for traitlet by key."""
475 """Get metadata values for traitlet by key."""
471 try:
476 try:
472 traitlet = getattr(self.__class__, traitletname)
477 traitlet = getattr(self.__class__, traitletname)
473 except AttributeError:
478 except AttributeError:
474 raise TraitletError("Class %s does not have a traitlet named %s" %
479 raise TraitletError("Class %s does not have a traitlet named %s" %
475 (self.__class__.__name__, traitletname))
480 (self.__class__.__name__, traitletname))
476 else:
481 else:
477 return traitlet.get_metadata(key)
482 return traitlet.get_metadata(key)
478
483
479 #-----------------------------------------------------------------------------
484 #-----------------------------------------------------------------------------
480 # Actual TraitletTypes implementations/subclasses
485 # Actual TraitletTypes implementations/subclasses
481 #-----------------------------------------------------------------------------
486 #-----------------------------------------------------------------------------
482
487
483 #-----------------------------------------------------------------------------
488 #-----------------------------------------------------------------------------
484 # TraitletTypes subclasses for handling classes and instances of classes
489 # TraitletTypes subclasses for handling classes and instances of classes
485 #-----------------------------------------------------------------------------
490 #-----------------------------------------------------------------------------
486
491
487
492
488 class ClassBasedTraitletType(TraitletType):
493 class ClassBasedTraitletType(TraitletType):
489 """A traitlet with error reporting for Type, Instance and This."""
494 """A traitlet with error reporting for Type, Instance and This."""
490
495
491 def error(self, obj, value):
496 def error(self, obj, value):
492 kind = type(value)
497 kind = type(value)
493 if kind is InstanceType:
498 if kind is InstanceType:
494 msg = 'class %s' % value.__class__.__name__
499 msg = 'class %s' % value.__class__.__name__
495 else:
500 else:
496 msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )
501 msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )
497
502
498 super(ClassBasedTraitletType, self).error(obj, msg)
503 super(ClassBasedTraitletType, self).error(obj, msg)
499
504
500
505
501 class Type(ClassBasedTraitletType):
506 class Type(ClassBasedTraitletType):
502 """A traitlet whose value must be a subclass of a specified class."""
507 """A traitlet whose value must be a subclass of a specified class."""
503
508
504 def __init__ (self, default_value=None, klass=None, allow_none=True, **metadata ):
509 def __init__ (self, default_value=None, klass=None, allow_none=True, **metadata ):
505 """Construct a Type traitlet
510 """Construct a Type traitlet
506
511
507 A Type traitlet specifies that its values must be subclasses of
512 A Type traitlet specifies that its values must be subclasses of
508 a particular class.
513 a particular class.
509
514
510 Parameters
515 Parameters
511 ----------
516 ----------
512 default_value : class
517 default_value : class
513 The default value must be a subclass of klass.
518 The default value must be a subclass of klass.
514 klass : class, str, None
519 klass : class, str, None
515 Values of this traitlet must be a subclass of klass. The klass
520 Values of this traitlet must be a subclass of klass. The klass
516 may be specified in a string like: 'foo.bar.MyClass'.
521 may be specified in a string like: 'foo.bar.MyClass'.
517 allow_none : boolean
522 allow_none : boolean
518 Indicates whether None is allowed as an assignable value. Even if
523 Indicates whether None is allowed as an assignable value. Even if
519 ``False``, the default value may be ``None``.
524 ``False``, the default value may be ``None``.
520 """
525 """
521 if default_value is None:
526 if default_value is None:
522 if klass is None:
527 if klass is None:
523 klass = object
528 klass = object
524 elif klass is None:
529 elif klass is None:
525 klass = default_value
530 klass = default_value
526
531
527 if not inspect.isclass(klass):
532 if not inspect.isclass(klass):
528 raise TraitletError("A Type traitlet must specify a class.")
533 raise TraitletError("A Type traitlet must specify a class.")
529
534
530 self.klass = klass
535 self.klass = klass
531 self._allow_none = allow_none
536 self._allow_none = allow_none
532
537
533 super(Type, self).__init__(default_value, **metadata)
538 super(Type, self).__init__(default_value, **metadata)
534
539
535 def validate(self, obj, value):
540 def validate(self, obj, value):
536 """Validates that the value is a valid object instance."""
541 """Validates that the value is a valid object instance."""
537 try:
542 try:
538 if issubclass(value, self.klass):
543 if issubclass(value, self.klass):
539 return value
544 return value
540 except:
545 except:
541 if (value is None) and (self._allow_none):
546 if (value is None) and (self._allow_none):
542 return value
547 return value
543
548
544 self.error(obj, value)
549 self.error(obj, value)
545
550
546 def info(self):
551 def info(self):
547 """ Returns a description of the trait."""
552 """ Returns a description of the trait."""
548 klass = self.klass.__name__
553 klass = self.klass.__name__
549 result = 'a subclass of ' + klass
554 result = 'a subclass of ' + klass
550 if self._allow_none:
555 if self._allow_none:
551 return result + ' or None'
556 return result + ' or None'
552 return result
557 return result
553
558
554
559
555 class DefaultValueGenerator(object):
560 class DefaultValueGenerator(object):
556 """A class for generating new default value instances."""
561 """A class for generating new default value instances."""
557
562
558 def __init__(self, klass, *args, **kw):
563 def __init__(self, klass, *args, **kw):
559 self.klass = klass
564 self.klass = klass
560 self.args = args
565 self.args = args
561 self.kw = kw
566 self.kw = kw
562
567
563 def generate(self):
568 def generate(self):
564 return self.klass(*self.args, **self.kw)
569 return self.klass(*self.args, **self.kw)
565
570
566
571
567 class Instance(ClassBasedTraitletType):
572 class Instance(ClassBasedTraitletType):
568 """A trait whose value must be an instance of a specified class.
573 """A trait whose value must be an instance of a specified class.
569
574
570 The value can also be an instance of a subclass of the specified class.
575 The value can also be an instance of a subclass of the specified class.
571 """
576 """
572
577
573 def __init__(self, klass=None, args=None, kw=None,
578 def __init__(self, klass=None, args=None, kw=None,
574 allow_none=True, **metadata ):
579 allow_none=True, **metadata ):
575 """Construct an Instance traitlet.
580 """Construct an Instance traitlet.
576
581
577 This traitlet allows values that are instances of a particular
582 This traitlet allows values that are instances of a particular
578 class or its sublclasses. Our implementation is quite different
583 class or its sublclasses. Our implementation is quite different
579 from that of enthough.traits as we don't allow instances to be used
584 from that of enthough.traits as we don't allow instances to be used
580 for klass and we handle the ``args`` and ``kw`` arguments differently.
585 for klass and we handle the ``args`` and ``kw`` arguments differently.
581
586
582 Parameters
587 Parameters
583 ----------
588 ----------
584 klass : class
589 klass : class
585 The class that forms the basis for the traitlet. Instances
590 The class that forms the basis for the traitlet. Instances
586 and strings are not allowed.
591 and strings are not allowed.
587 args : tuple
592 args : tuple
588 Positional arguments for generating the default value.
593 Positional arguments for generating the default value.
589 kw : dict
594 kw : dict
590 Keyword arguments for generating the default value.
595 Keyword arguments for generating the default value.
591 allow_none : bool
596 allow_none : bool
592 Indicates whether None is allowed as a value.
597 Indicates whether None is allowed as a value.
593
598
594 Default Value
599 Default Value
595 -------------
600 -------------
596 If both ``args`` and ``kw`` are None, then the default value is None.
601 If both ``args`` and ``kw`` are None, then the default value is None.
597 If ``args`` is a tuple and ``kw`` is a dict, then the default is
602 If ``args`` is a tuple and ``kw`` is a dict, then the default is
598 created as ``klass(*args, **kw)``. If either ``args`` or ``kw`` is
603 created as ``klass(*args, **kw)``. If either ``args`` or ``kw`` is
599 not (but not both), None is replace by ``()`` or ``{}``.
604 not (but not both), None is replace by ``()`` or ``{}``.
600 """
605 """
601
606
602 self._allow_none = allow_none
607 self._allow_none = allow_none
603
608
604 if (klass is None) or (not inspect.isclass(klass)):
609 if (klass is None) or (not inspect.isclass(klass)):
605 raise TraitletError('The klass argument must be a class'
610 raise TraitletError('The klass argument must be a class'
606 ' you gave: %r' % klass)
611 ' you gave: %r' % klass)
607 self.klass = klass
612 self.klass = klass
608
613
609 # self.klass is a class, so handle default_value
614 # self.klass is a class, so handle default_value
610 if args is None and kw is None:
615 if args is None and kw is None:
611 default_value = None
616 default_value = None
612 else:
617 else:
613 if args is None:
618 if args is None:
614 # kw is not None
619 # kw is not None
615 args = ()
620 args = ()
616 elif kw is None:
621 elif kw is None:
617 # args is not None
622 # args is not None
618 kw = {}
623 kw = {}
619
624
620 if not isinstance(kw, dict):
625 if not isinstance(kw, dict):
621 raise TraitletError("The 'kw' argument must be a dict or None.")
626 raise TraitletError("The 'kw' argument must be a dict or None.")
622 if not isinstance(args, tuple):
627 if not isinstance(args, tuple):
623 raise TraitletError("The 'args' argument must be a tuple or None.")
628 raise TraitletError("The 'args' argument must be a tuple or None.")
624
629
625 default_value = DefaultValueGenerator(self.klass, *args, **kw)
630 default_value = DefaultValueGenerator(self.klass, *args, **kw)
626
631
627 super(Instance, self).__init__(default_value, **metadata)
632 super(Instance, self).__init__(default_value, **metadata)
628
633
629 def validate(self, obj, value):
634 def validate(self, obj, value):
630 if value is None:
635 if value is None:
631 if self._allow_none:
636 if self._allow_none:
632 return value
637 return value
633 self.error(obj, value)
638 self.error(obj, value)
634
639
635 if isinstance(value, self.klass):
640 if isinstance(value, self.klass):
636 return value
641 return value
637 else:
642 else:
638 self.error(obj, value)
643 self.error(obj, value)
639
644
640 def info(self):
645 def info(self):
641 klass = self.klass.__name__
646 klass = self.klass.__name__
642 result = class_of(klass)
647 result = class_of(klass)
643 if self._allow_none:
648 if self._allow_none:
644 return result + ' or None'
649 return result + ' or None'
645
650
646 return result
651 return result
647
652
648 def get_default_value(self):
653 def get_default_value(self):
649 """Instantiate a default value instance.
654 """Instantiate a default value instance.
650
655
651 This is called when the containing HasTraitlets classes'
656 This is called when the containing HasTraitlets classes'
652 :meth:`__new__` method is called to ensure that a unique instance
657 :meth:`__new__` method is called to ensure that a unique instance
653 is created for each HasTraitlets instance.
658 is created for each HasTraitlets instance.
654 """
659 """
655 dv = self.default_value
660 dv = self.default_value
656 if isinstance(dv, DefaultValueGenerator):
661 if isinstance(dv, DefaultValueGenerator):
657 return dv.generate()
662 return dv.generate()
658 else:
663 else:
659 return dv
664 return dv
660
665
661
666
662 class This(ClassBasedTraitletType):
667 class This(ClassBasedTraitletType):
663 """A traitlet for instances of the class containing this trait.
668 """A traitlet for instances of the class containing this trait.
664
669
665 Because how how and when class bodies are executed, the ``This``
670 Because how how and when class bodies are executed, the ``This``
666 traitlet can only have a default value of None. This, and because we
671 traitlet can only have a default value of None. This, and because we
667 always validate default values, ``allow_none`` is *always* true.
672 always validate default values, ``allow_none`` is *always* true.
668 """
673 """
669
674
670 info_text = 'an instance of the same type as the receiver or None'
675 info_text = 'an instance of the same type as the receiver or None'
671
676
672 def __init__(self, **metadata):
677 def __init__(self, **metadata):
673 super(This, self).__init__(None, **metadata)
678 super(This, self).__init__(None, **metadata)
674
679
675 def validate(self, obj, value):
680 def validate(self, obj, value):
676 # What if value is a superclass of obj.__class__? This is
681 # What if value is a superclass of obj.__class__? This is
677 # complicated if it was the superclass that defined the This
682 # complicated if it was the superclass that defined the This
678 # traitlet.
683 # traitlet.
679 if isinstance(value, self.this_class) or (value is None):
684 if isinstance(value, self.this_class) or (value is None):
680 return value
685 return value
681 else:
686 else:
682 self.error(obj, value)
687 self.error(obj, value)
683
688
684
689
685 #-----------------------------------------------------------------------------
690 #-----------------------------------------------------------------------------
686 # Basic TraitletTypes implementations/subclasses
691 # Basic TraitletTypes implementations/subclasses
687 #-----------------------------------------------------------------------------
692 #-----------------------------------------------------------------------------
688
693
689
694
690 class Any(TraitletType):
695 class Any(TraitletType):
691 default_value = None
696 default_value = None
692 info_text = 'any value'
697 info_text = 'any value'
693
698
694
699
695 class Int(TraitletType):
700 class Int(TraitletType):
696 """A integer traitlet."""
701 """A integer traitlet."""
697
702
698 evaluate = int
703 evaluate = int
699 default_value = 0
704 default_value = 0
700 info_text = 'an integer'
705 info_text = 'an integer'
701
706
702 def validate(self, obj, value):
707 def validate(self, obj, value):
703 if isinstance(value, int):
708 if isinstance(value, int):
704 return value
709 return value
705 self.error(obj, value)
710 self.error(obj, value)
706
711
707 class CInt(Int):
712 class CInt(Int):
708 """A casting version of the int traitlet."""
713 """A casting version of the int traitlet."""
709
714
710 def validate(self, obj, value):
715 def validate(self, obj, value):
711 try:
716 try:
712 return int(value)
717 return int(value)
713 except:
718 except:
714 self.error(obj, value)
719 self.error(obj, value)
715
720
716
721
717 class Long(TraitletType):
722 class Long(TraitletType):
718 """A long integer traitlet."""
723 """A long integer traitlet."""
719
724
720 evaluate = long
725 evaluate = long
721 default_value = 0L
726 default_value = 0L
722 info_text = 'a long'
727 info_text = 'a long'
723
728
724 def validate(self, obj, value):
729 def validate(self, obj, value):
725 if isinstance(value, long):
730 if isinstance(value, long):
726 return value
731 return value
727 if isinstance(value, int):
732 if isinstance(value, int):
728 return long(value)
733 return long(value)
729 self.error(obj, value)
734 self.error(obj, value)
730
735
731
736
732 class CLong(Long):
737 class CLong(Long):
733 """A casting version of the long integer traitlet."""
738 """A casting version of the long integer traitlet."""
734
739
735 def validate(self, obj, value):
740 def validate(self, obj, value):
736 try:
741 try:
737 return long(value)
742 return long(value)
738 except:
743 except:
739 self.error(obj, value)
744 self.error(obj, value)
740
745
741
746
742 class Float(TraitletType):
747 class Float(TraitletType):
743 """A float traitlet."""
748 """A float traitlet."""
744
749
745 evaluate = float
750 evaluate = float
746 default_value = 0.0
751 default_value = 0.0
747 info_text = 'a float'
752 info_text = 'a float'
748
753
749 def validate(self, obj, value):
754 def validate(self, obj, value):
750 if isinstance(value, float):
755 if isinstance(value, float):
751 return value
756 return value
752 if isinstance(value, int):
757 if isinstance(value, int):
753 return float(value)
758 return float(value)
754 self.error(obj, value)
759 self.error(obj, value)
755
760
756
761
757 class CFloat(Float):
762 class CFloat(Float):
758 """A casting version of the float traitlet."""
763 """A casting version of the float traitlet."""
759
764
760 def validate(self, obj, value):
765 def validate(self, obj, value):
761 try:
766 try:
762 return float(value)
767 return float(value)
763 except:
768 except:
764 self.error(obj, value)
769 self.error(obj, value)
765
770
766 class Complex(TraitletType):
771 class Complex(TraitletType):
767 """A traitlet for complex numbers."""
772 """A traitlet for complex numbers."""
768
773
769 evaluate = complex
774 evaluate = complex
770 default_value = 0.0 + 0.0j
775 default_value = 0.0 + 0.0j
771 info_text = 'a complex number'
776 info_text = 'a complex number'
772
777
773 def validate(self, obj, value):
778 def validate(self, obj, value):
774 if isinstance(value, complex):
779 if isinstance(value, complex):
775 return value
780 return value
776 if isinstance(value, (float, int)):
781 if isinstance(value, (float, int)):
777 return complex(value)
782 return complex(value)
778 self.error(obj, value)
783 self.error(obj, value)
779
784
780
785
781 class CComplex(Complex):
786 class CComplex(Complex):
782 """A casting version of the complex number traitlet."""
787 """A casting version of the complex number traitlet."""
783
788
784 def validate (self, obj, value):
789 def validate (self, obj, value):
785 try:
790 try:
786 return complex(value)
791 return complex(value)
787 except:
792 except:
788 self.error(obj, value)
793 self.error(obj, value)
789
794
790
795
791 class Str(TraitletType):
796 class Str(TraitletType):
792 """A traitlet for strings."""
797 """A traitlet for strings."""
793
798
794 evaluate = lambda x: x
799 evaluate = lambda x: x
795 default_value = ''
800 default_value = ''
796 info_text = 'a string'
801 info_text = 'a string'
797
802
798 def validate(self, obj, value):
803 def validate(self, obj, value):
799 if isinstance(value, str):
804 if isinstance(value, str):
800 return value
805 return value
801 self.error(obj, value)
806 self.error(obj, value)
802
807
803
808
804 class CStr(Str):
809 class CStr(Str):
805 """A casting version of the string traitlet."""
810 """A casting version of the string traitlet."""
806
811
807 def validate(self, obj, value):
812 def validate(self, obj, value):
808 try:
813 try:
809 return str(value)
814 return str(value)
810 except:
815 except:
811 try:
816 try:
812 return unicode(value)
817 return unicode(value)
813 except:
818 except:
814 self.error(obj, value)
819 self.error(obj, value)
815
820
816
821
817 class Unicode(TraitletType):
822 class Unicode(TraitletType):
818 """A traitlet for unicode strings."""
823 """A traitlet for unicode strings."""
819
824
820 evaluate = unicode
825 evaluate = unicode
821 default_value = u''
826 default_value = u''
822 info_text = 'a unicode string'
827 info_text = 'a unicode string'
823
828
824 def validate(self, obj, value):
829 def validate(self, obj, value):
825 if isinstance(value, unicode):
830 if isinstance(value, unicode):
826 return value
831 return value
827 if isinstance(value, str):
832 if isinstance(value, str):
828 return unicode(value)
833 return unicode(value)
829 self.error(obj, value)
834 self.error(obj, value)
830
835
831
836
832 class CUnicode(Unicode):
837 class CUnicode(Unicode):
833 """A casting version of the unicode traitlet."""
838 """A casting version of the unicode traitlet."""
834
839
835 def validate(self, obj, value):
840 def validate(self, obj, value):
836 try:
841 try:
837 return unicode(value)
842 return unicode(value)
838 except:
843 except:
839 self.error(obj, value)
844 self.error(obj, value)
840
845
841
846
842 class Bool(TraitletType):
847 class Bool(TraitletType):
843 """A boolean (True, False) traitlet."""
848 """A boolean (True, False) traitlet."""
844 evaluate = bool
849 evaluate = bool
845 default_value = False
850 default_value = False
846 info_text = 'a boolean'
851 info_text = 'a boolean'
847
852
848 def validate(self, obj, value):
853 def validate(self, obj, value):
849 if isinstance(value, bool):
854 if isinstance(value, bool):
850 return value
855 return value
851 self.error(obj, value)
856 self.error(obj, value)
852
857
853
858
854 class CBool(Bool):
859 class CBool(Bool):
855 """A casting version of the boolean traitlet."""
860 """A casting version of the boolean traitlet."""
856
861
857 def validate(self, obj, value):
862 def validate(self, obj, value):
858 try:
863 try:
859 return bool(value)
864 return bool(value)
860 except:
865 except:
861 self.error(obj, value)
866 self.error(obj, value)
862
867
868
863 class Enum(TraitletType):
869 class Enum(TraitletType):
870 """An enum that whose value must be in a given sequence."""
864
871
865 def __init__(self, values, default_value=None, allow_none=True, **metadata):
872 def __init__(self, values, default_value=None, allow_none=True, **metadata):
866 self.values = values
873 self.values = values
867 self._allow_none = allow_none
874 self._allow_none = allow_none
868 super(Enum, self).__init__(default_value, **metadata)
875 super(Enum, self).__init__(default_value, **metadata)
869
876
870 def validate(self, obj, value):
877 def validate(self, obj, value):
871 if value is None:
878 if value is None:
872 if self._allow_none:
879 if self._allow_none:
873 return value
880 return value
874
881
875 if value in self.values:
882 if value in self.values:
876 return value
883 return value
877 self.error(obj, value)
884 self.error(obj, value)
878
885
879 def info(self):
886 def info(self):
880 """ Returns a description of the trait."""
887 """ Returns a description of the trait."""
881 result = 'any of ' + repr(self.values)
888 result = 'any of ' + repr(self.values)
882 if self._allow_none:
889 if self._allow_none:
883 return result + ' or None'
890 return result + ' or None'
884 return result
891 return result
885
892
886 class CaselessStrEnum(Enum):
893 class CaselessStrEnum(Enum):
894 """An enum of strings that are caseless in validate."""
887
895
888 def validate(self, obj, value):
896 def validate(self, obj, value):
889 if value is None:
897 if value is None:
890 if self._allow_none:
898 if self._allow_none:
891 return value
899 return value
892
900
893 if not isinstance(value, str):
901 if not isinstance(value, str):
894 self.error(obj, value)
902 self.error(obj, value)
895
903
896 for v in self.values:
904 for v in self.values:
897 if v.lower() == value.lower():
905 if v.lower() == value.lower():
898 return v
906 return v
899 self.error(obj, value) No newline at end of file
907 self.error(obj, value)
908
909
910 class List(Instance):
911 """An instance of a Python list."""
912
913 def __init__(self, default_value=None, allow_none=True, **metadata):
914 """Create a list traitlet type from a list or tuple.
915
916 The default value is created by doing ``list(default_value)``,
917 which creates a copy of the ``default_value``.
918 """
919 if default_value is None:
920 args = ((),)
921 elif isinstance(default_value, SequenceTypes):
922 args = (default_value,)
923
924 super(List,self).__init__(klass=list, args=args,
925 allow_none=allow_none, **metadata)
General Comments 0
You need to be logged in to leave comments. Login now