##// END OF EJS Templates
Fixing small bug in activate....
Brian Granger -
Show More
@@ -1,2486 +1,2488 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 from __future__ import with_statement
19 from __future__ import with_statement
20
20
21 import __builtin__
21 import __builtin__
22 import StringIO
22 import StringIO
23 import bdb
23 import bdb
24 import codeop
24 import codeop
25 import exceptions
25 import exceptions
26 import new
26 import new
27 import os
27 import os
28 import re
28 import re
29 import string
29 import string
30 import sys
30 import sys
31 import tempfile
31 import tempfile
32 from contextlib import nested
32 from contextlib import nested
33
33
34 from IPython.core import ultratb
34 from IPython.core import ultratb
35 from IPython.core import debugger, oinspect
35 from IPython.core import debugger, oinspect
36 from IPython.core import shadowns
36 from IPython.core import shadowns
37 from IPython.core import history as ipcorehist
37 from IPython.core import history as ipcorehist
38 from IPython.core import prefilter
38 from IPython.core import prefilter
39 from IPython.core.alias import AliasManager
39 from IPython.core.alias import AliasManager
40 from IPython.core.builtin_trap import BuiltinTrap
40 from IPython.core.builtin_trap import BuiltinTrap
41 from IPython.core.display_trap import DisplayTrap
41 from IPython.core.display_trap import DisplayTrap
42 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
42 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
43 from IPython.core.logger import Logger
43 from IPython.core.logger import Logger
44 from IPython.core.magic import Magic
44 from IPython.core.magic import Magic
45 from IPython.core.prompts import CachedOutput
45 from IPython.core.prompts import CachedOutput
46 from IPython.core.prefilter import PrefilterManager
46 from IPython.core.prefilter import PrefilterManager
47 from IPython.core.component import Component
47 from IPython.core.component import Component
48 from IPython.core.usage import interactive_usage, default_banner
48 from IPython.core.usage import interactive_usage, default_banner
49 from IPython.core.error import TryNext, UsageError
49 from IPython.core.error import TryNext, UsageError
50
50
51 from IPython.utils import pickleshare
51 from IPython.utils import pickleshare
52 from IPython.external.Itpl import ItplNS
52 from IPython.external.Itpl import ItplNS
53 from IPython.lib.backgroundjobs import BackgroundJobManager
53 from IPython.lib.backgroundjobs import BackgroundJobManager
54 from IPython.utils.ipstruct import Struct
54 from IPython.utils.ipstruct import Struct
55 from IPython.utils import PyColorize
55 from IPython.utils import PyColorize
56 from IPython.utils.genutils import *
56 from IPython.utils.genutils import *
57 from IPython.utils.genutils import get_ipython_dir
57 from IPython.utils.genutils import get_ipython_dir
58 from IPython.utils.platutils import toggle_set_term_title, set_term_title
58 from IPython.utils.platutils import toggle_set_term_title, set_term_title
59 from IPython.utils.strdispatch import StrDispatch
59 from IPython.utils.strdispatch import StrDispatch
60 from IPython.utils.syspathcontext import prepended_to_syspath
60 from IPython.utils.syspathcontext import prepended_to_syspath
61
61
62 # from IPython.utils import growl
62 # from IPython.utils import growl
63 # growl.start("IPython")
63 # growl.start("IPython")
64
64
65 from IPython.utils.traitlets import (
65 from IPython.utils.traitlets import (
66 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode
66 Int, Str, CBool, CaselessStrEnum, Enum, List, Unicode
67 )
67 )
68
68
69 #-----------------------------------------------------------------------------
69 #-----------------------------------------------------------------------------
70 # Globals
70 # Globals
71 #-----------------------------------------------------------------------------
71 #-----------------------------------------------------------------------------
72
72
73
73
74 # store the builtin raw_input globally, and use this always, in case user code
74 # store the builtin raw_input globally, and use this always, in case user code
75 # overwrites it (like wx.py.PyShell does)
75 # overwrites it (like wx.py.PyShell does)
76 raw_input_original = raw_input
76 raw_input_original = raw_input
77
77
78 # compiled regexps for autoindent management
78 # compiled regexps for autoindent management
79 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
79 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
80
80
81
81
82 #-----------------------------------------------------------------------------
82 #-----------------------------------------------------------------------------
83 # Utilities
83 # Utilities
84 #-----------------------------------------------------------------------------
84 #-----------------------------------------------------------------------------
85
85
86
86
87 ini_spaces_re = re.compile(r'^(\s+)')
87 ini_spaces_re = re.compile(r'^(\s+)')
88
88
89
89
90 def num_ini_spaces(strng):
90 def num_ini_spaces(strng):
91 """Return the number of initial spaces in a string"""
91 """Return the number of initial spaces in a string"""
92
92
93 ini_spaces = ini_spaces_re.match(strng)
93 ini_spaces = ini_spaces_re.match(strng)
94 if ini_spaces:
94 if ini_spaces:
95 return ini_spaces.end()
95 return ini_spaces.end()
96 else:
96 else:
97 return 0
97 return 0
98
98
99
99
100 def softspace(file, newvalue):
100 def softspace(file, newvalue):
101 """Copied from code.py, to remove the dependency"""
101 """Copied from code.py, to remove the dependency"""
102
102
103 oldvalue = 0
103 oldvalue = 0
104 try:
104 try:
105 oldvalue = file.softspace
105 oldvalue = file.softspace
106 except AttributeError:
106 except AttributeError:
107 pass
107 pass
108 try:
108 try:
109 file.softspace = newvalue
109 file.softspace = newvalue
110 except (AttributeError, TypeError):
110 except (AttributeError, TypeError):
111 # "attribute-less object" or "read-only attributes"
111 # "attribute-less object" or "read-only attributes"
112 pass
112 pass
113 return oldvalue
113 return oldvalue
114
114
115
115
116 class SpaceInInput(exceptions.Exception): pass
116 class SpaceInInput(exceptions.Exception): pass
117
117
118 class Bunch: pass
118 class Bunch: pass
119
119
120 class InputList(list):
120 class InputList(list):
121 """Class to store user input.
121 """Class to store user input.
122
122
123 It's basically a list, but slices return a string instead of a list, thus
123 It's basically a list, but slices return a string instead of a list, thus
124 allowing things like (assuming 'In' is an instance):
124 allowing things like (assuming 'In' is an instance):
125
125
126 exec In[4:7]
126 exec In[4:7]
127
127
128 or
128 or
129
129
130 exec In[5:9] + In[14] + In[21:25]"""
130 exec In[5:9] + In[14] + In[21:25]"""
131
131
132 def __getslice__(self,i,j):
132 def __getslice__(self,i,j):
133 return ''.join(list.__getslice__(self,i,j))
133 return ''.join(list.__getslice__(self,i,j))
134
134
135
135
136 class SyntaxTB(ultratb.ListTB):
136 class SyntaxTB(ultratb.ListTB):
137 """Extension which holds some state: the last exception value"""
137 """Extension which holds some state: the last exception value"""
138
138
139 def __init__(self,color_scheme = 'NoColor'):
139 def __init__(self,color_scheme = 'NoColor'):
140 ultratb.ListTB.__init__(self,color_scheme)
140 ultratb.ListTB.__init__(self,color_scheme)
141 self.last_syntax_error = None
141 self.last_syntax_error = None
142
142
143 def __call__(self, etype, value, elist):
143 def __call__(self, etype, value, elist):
144 self.last_syntax_error = value
144 self.last_syntax_error = value
145 ultratb.ListTB.__call__(self,etype,value,elist)
145 ultratb.ListTB.__call__(self,etype,value,elist)
146
146
147 def clear_err_state(self):
147 def clear_err_state(self):
148 """Return the current error state and clear it"""
148 """Return the current error state and clear it"""
149 e = self.last_syntax_error
149 e = self.last_syntax_error
150 self.last_syntax_error = None
150 self.last_syntax_error = None
151 return e
151 return e
152
152
153
153
154 def get_default_editor():
154 def get_default_editor():
155 try:
155 try:
156 ed = os.environ['EDITOR']
156 ed = os.environ['EDITOR']
157 except KeyError:
157 except KeyError:
158 if os.name == 'posix':
158 if os.name == 'posix':
159 ed = 'vi' # the only one guaranteed to be there!
159 ed = 'vi' # the only one guaranteed to be there!
160 else:
160 else:
161 ed = 'notepad' # same in Windows!
161 ed = 'notepad' # same in Windows!
162 return ed
162 return ed
163
163
164
164
165 def get_default_colors():
165 def get_default_colors():
166 if sys.platform=='darwin':
166 if sys.platform=='darwin':
167 return "LightBG"
167 return "LightBG"
168 elif os.name=='nt':
168 elif os.name=='nt':
169 return 'Linux'
169 return 'Linux'
170 else:
170 else:
171 return 'Linux'
171 return 'Linux'
172
172
173
173
174 class SeparateStr(Str):
174 class SeparateStr(Str):
175 """A Str subclass to validate separate_in, separate_out, etc.
175 """A Str subclass to validate separate_in, separate_out, etc.
176
176
177 This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'.
177 This is a Str based traitlet that converts '0'->'' and '\\n'->'\n'.
178 """
178 """
179
179
180 def validate(self, obj, value):
180 def validate(self, obj, value):
181 if value == '0': value = ''
181 if value == '0': value = ''
182 value = value.replace('\\n','\n')
182 value = value.replace('\\n','\n')
183 return super(SeparateStr, self).validate(obj, value)
183 return super(SeparateStr, self).validate(obj, value)
184
184
185
185
186 #-----------------------------------------------------------------------------
186 #-----------------------------------------------------------------------------
187 # Main IPython class
187 # Main IPython class
188 #-----------------------------------------------------------------------------
188 #-----------------------------------------------------------------------------
189
189
190
190
191 class InteractiveShell(Component, Magic):
191 class InteractiveShell(Component, Magic):
192 """An enhanced, interactive shell for Python."""
192 """An enhanced, interactive shell for Python."""
193
193
194 autocall = Enum((0,1,2), default_value=1, config=True)
194 autocall = Enum((0,1,2), default_value=1, config=True)
195 autoedit_syntax = CBool(False, config=True)
195 autoedit_syntax = CBool(False, config=True)
196 autoindent = CBool(True, config=True)
196 autoindent = CBool(True, config=True)
197 automagic = CBool(True, config=True)
197 automagic = CBool(True, config=True)
198 banner = Str('')
198 banner = Str('')
199 banner1 = Str(default_banner, config=True)
199 banner1 = Str(default_banner, config=True)
200 banner2 = Str('', config=True)
200 banner2 = Str('', config=True)
201 cache_size = Int(1000, config=True)
201 cache_size = Int(1000, config=True)
202 color_info = CBool(True, config=True)
202 color_info = CBool(True, config=True)
203 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
203 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
204 default_value=get_default_colors(), config=True)
204 default_value=get_default_colors(), config=True)
205 confirm_exit = CBool(True, config=True)
205 confirm_exit = CBool(True, config=True)
206 debug = CBool(False, config=True)
206 debug = CBool(False, config=True)
207 deep_reload = CBool(False, config=True)
207 deep_reload = CBool(False, config=True)
208 # This display_banner only controls whether or not self.show_banner()
208 # This display_banner only controls whether or not self.show_banner()
209 # is called when mainloop/interact are called. The default is False
209 # is called when mainloop/interact are called. The default is False
210 # because for the terminal based application, the banner behavior
210 # because for the terminal based application, the banner behavior
211 # is controlled by Global.display_banner, which IPythonApp looks at
211 # is controlled by Global.display_banner, which IPythonApp looks at
212 # to determine if *it* should call show_banner() by hand or not.
212 # to determine if *it* should call show_banner() by hand or not.
213 display_banner = CBool(False) # This isn't configurable!
213 display_banner = CBool(False) # This isn't configurable!
214 embedded = CBool(False)
214 embedded = CBool(False)
215 embedded_active = CBool(False)
215 embedded_active = CBool(False)
216 editor = Str(get_default_editor(), config=True)
216 editor = Str(get_default_editor(), config=True)
217 filename = Str("<ipython console>")
217 filename = Str("<ipython console>")
218 ipythondir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
218 ipythondir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
219 logstart = CBool(False, config=True)
219 logstart = CBool(False, config=True)
220 logfile = Str('', config=True)
220 logfile = Str('', config=True)
221 logappend = Str('', config=True)
221 logappend = Str('', config=True)
222 object_info_string_level = Enum((0,1,2), default_value=0,
222 object_info_string_level = Enum((0,1,2), default_value=0,
223 config=True)
223 config=True)
224 pager = Str('less', config=True)
224 pager = Str('less', config=True)
225 pdb = CBool(False, config=True)
225 pdb = CBool(False, config=True)
226 pprint = CBool(True, config=True)
226 pprint = CBool(True, config=True)
227 profile = Str('', config=True)
227 profile = Str('', config=True)
228 prompt_in1 = Str('In [\\#]: ', config=True)
228 prompt_in1 = Str('In [\\#]: ', config=True)
229 prompt_in2 = Str(' .\\D.: ', config=True)
229 prompt_in2 = Str(' .\\D.: ', config=True)
230 prompt_out = Str('Out[\\#]: ', config=True)
230 prompt_out = Str('Out[\\#]: ', config=True)
231 prompts_pad_left = CBool(True, config=True)
231 prompts_pad_left = CBool(True, config=True)
232 quiet = CBool(False, config=True)
232 quiet = CBool(False, config=True)
233
233
234 readline_use = CBool(True, config=True)
234 readline_use = CBool(True, config=True)
235 readline_merge_completions = CBool(True, config=True)
235 readline_merge_completions = CBool(True, config=True)
236 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
236 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
237 readline_remove_delims = Str('-/~', config=True)
237 readline_remove_delims = Str('-/~', config=True)
238 readline_parse_and_bind = List([
238 readline_parse_and_bind = List([
239 'tab: complete',
239 'tab: complete',
240 '"\C-l": possible-completions',
240 '"\C-l": possible-completions',
241 'set show-all-if-ambiguous on',
241 'set show-all-if-ambiguous on',
242 '"\C-o": tab-insert',
242 '"\C-o": tab-insert',
243 '"\M-i": " "',
243 '"\M-i": " "',
244 '"\M-o": "\d\d\d\d"',
244 '"\M-o": "\d\d\d\d"',
245 '"\M-I": "\d\d\d\d"',
245 '"\M-I": "\d\d\d\d"',
246 '"\C-r": reverse-search-history',
246 '"\C-r": reverse-search-history',
247 '"\C-s": forward-search-history',
247 '"\C-s": forward-search-history',
248 '"\C-p": history-search-backward',
248 '"\C-p": history-search-backward',
249 '"\C-n": history-search-forward',
249 '"\C-n": history-search-forward',
250 '"\e[A": history-search-backward',
250 '"\e[A": history-search-backward',
251 '"\e[B": history-search-forward',
251 '"\e[B": history-search-forward',
252 '"\C-k": kill-line',
252 '"\C-k": kill-line',
253 '"\C-u": unix-line-discard',
253 '"\C-u": unix-line-discard',
254 ], allow_none=False, config=True)
254 ], allow_none=False, config=True)
255
255
256 screen_length = Int(0, config=True)
256 screen_length = Int(0, config=True)
257
257
258 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
258 # Use custom TraitletTypes that convert '0'->'' and '\\n'->'\n'
259 separate_in = SeparateStr('\n', config=True)
259 separate_in = SeparateStr('\n', config=True)
260 separate_out = SeparateStr('', config=True)
260 separate_out = SeparateStr('', config=True)
261 separate_out2 = SeparateStr('', config=True)
261 separate_out2 = SeparateStr('', config=True)
262
262
263 system_header = Str('IPython system call: ', config=True)
263 system_header = Str('IPython system call: ', config=True)
264 system_verbose = CBool(False, config=True)
264 system_verbose = CBool(False, config=True)
265 term_title = CBool(False, config=True)
265 term_title = CBool(False, config=True)
266 wildcards_case_sensitive = CBool(True, config=True)
266 wildcards_case_sensitive = CBool(True, config=True)
267 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
267 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
268 default_value='Context', config=True)
268 default_value='Context', config=True)
269
269
270 autoexec = List(allow_none=False)
270 autoexec = List(allow_none=False)
271
271
272 # class attribute to indicate whether the class supports threads or not.
272 # class attribute to indicate whether the class supports threads or not.
273 # Subclasses with thread support should override this as needed.
273 # Subclasses with thread support should override this as needed.
274 isthreaded = False
274 isthreaded = False
275
275
276 def __init__(self, parent=None, config=None, ipythondir=None, usage=None,
276 def __init__(self, parent=None, config=None, ipythondir=None, usage=None,
277 user_ns=None, user_global_ns=None,
277 user_ns=None, user_global_ns=None,
278 banner1=None, banner2=None, display_banner=None,
278 banner1=None, banner2=None, display_banner=None,
279 custom_exceptions=((),None)):
279 custom_exceptions=((),None)):
280
280
281 # This is where traitlets with a config_key argument are updated
281 # This is where traitlets with a config_key argument are updated
282 # from the values on config.
282 # from the values on config.
283 super(InteractiveShell, self).__init__(parent, config=config)
283 super(InteractiveShell, self).__init__(parent, config=config)
284
284
285 # These are relatively independent and stateless
285 # These are relatively independent and stateless
286 self.init_ipythondir(ipythondir)
286 self.init_ipythondir(ipythondir)
287 self.init_instance_attrs()
287 self.init_instance_attrs()
288 self.init_term_title()
288 self.init_term_title()
289 self.init_usage(usage)
289 self.init_usage(usage)
290 self.init_banner(banner1, banner2, display_banner)
290 self.init_banner(banner1, banner2, display_banner)
291
291
292 # Create namespaces (user_ns, user_global_ns, etc.)
292 # Create namespaces (user_ns, user_global_ns, etc.)
293 self.init_create_namespaces(user_ns, user_global_ns)
293 self.init_create_namespaces(user_ns, user_global_ns)
294 # This has to be done after init_create_namespaces because it uses
294 # This has to be done after init_create_namespaces because it uses
295 # something in self.user_ns, but before init_sys_modules, which
295 # something in self.user_ns, but before init_sys_modules, which
296 # is the first thing to modify sys.
296 # is the first thing to modify sys.
297 self.save_sys_module_state()
297 self.save_sys_module_state()
298 self.init_sys_modules()
298 self.init_sys_modules()
299
299
300 self.init_history()
300 self.init_history()
301 self.init_encoding()
301 self.init_encoding()
302 self.init_prefilter()
302 self.init_prefilter()
303
303
304 Magic.__init__(self, self)
304 Magic.__init__(self, self)
305
305
306 self.init_syntax_highlighting()
306 self.init_syntax_highlighting()
307 self.init_hooks()
307 self.init_hooks()
308 self.init_pushd_popd_magic()
308 self.init_pushd_popd_magic()
309 self.init_traceback_handlers(custom_exceptions)
309 self.init_traceback_handlers(custom_exceptions)
310 self.init_user_ns()
310 self.init_user_ns()
311 self.init_logger()
311 self.init_logger()
312 self.init_alias()
312 self.init_alias()
313 self.init_builtins()
313 self.init_builtins()
314
314
315 # pre_config_initialization
315 # pre_config_initialization
316 self.init_shadow_hist()
316 self.init_shadow_hist()
317
317
318 # The next section should contain averything that was in ipmaker.
318 # The next section should contain averything that was in ipmaker.
319 self.init_logstart()
319 self.init_logstart()
320
320
321 # The following was in post_config_initialization
321 # The following was in post_config_initialization
322 self.init_inspector()
322 self.init_inspector()
323 self.init_readline()
323 self.init_readline()
324 self.init_prompts()
324 self.init_prompts()
325 self.init_displayhook()
325 self.init_displayhook()
326 self.init_reload_doctest()
326 self.init_reload_doctest()
327 self.init_magics()
327 self.init_magics()
328 self.init_pdb()
328 self.init_pdb()
329 self.hooks.late_startup_hook()
329 self.hooks.late_startup_hook()
330
330
331 def get_ipython(self):
331 def get_ipython(self):
332 return self
332 return self
333
333
334 #-------------------------------------------------------------------------
334 #-------------------------------------------------------------------------
335 # Traitlet changed handlers
335 # Traitlet changed handlers
336 #-------------------------------------------------------------------------
336 #-------------------------------------------------------------------------
337
337
338 def _banner1_changed(self):
338 def _banner1_changed(self):
339 self.compute_banner()
339 self.compute_banner()
340
340
341 def _banner2_changed(self):
341 def _banner2_changed(self):
342 self.compute_banner()
342 self.compute_banner()
343
343
344 def _ipythondir_changed(self, name, new):
344 def _ipythondir_changed(self, name, new):
345 if not os.path.isdir(new):
345 if not os.path.isdir(new):
346 os.makedirs(new, mode = 0777)
346 os.makedirs(new, mode = 0777)
347 if not os.path.isdir(self.ipython_extension_dir):
347 if not os.path.isdir(self.ipython_extension_dir):
348 os.makedirs(self.ipython_extension_dir, mode = 0777)
348 os.makedirs(self.ipython_extension_dir, mode = 0777)
349
349
350 @property
350 @property
351 def ipython_extension_dir(self):
351 def ipython_extension_dir(self):
352 return os.path.join(self.ipythondir, 'extensions')
352 return os.path.join(self.ipythondir, 'extensions')
353
353
354 @property
354 @property
355 def usable_screen_length(self):
355 def usable_screen_length(self):
356 if self.screen_length == 0:
356 if self.screen_length == 0:
357 return 0
357 return 0
358 else:
358 else:
359 num_lines_bot = self.separate_in.count('\n')+1
359 num_lines_bot = self.separate_in.count('\n')+1
360 return self.screen_length - num_lines_bot
360 return self.screen_length - num_lines_bot
361
361
362 def _term_title_changed(self, name, new_value):
362 def _term_title_changed(self, name, new_value):
363 self.init_term_title()
363 self.init_term_title()
364
364
365 def set_autoindent(self,value=None):
365 def set_autoindent(self,value=None):
366 """Set the autoindent flag, checking for readline support.
366 """Set the autoindent flag, checking for readline support.
367
367
368 If called with no arguments, it acts as a toggle."""
368 If called with no arguments, it acts as a toggle."""
369
369
370 if not self.has_readline:
370 if not self.has_readline:
371 if os.name == 'posix':
371 if os.name == 'posix':
372 warn("The auto-indent feature requires the readline library")
372 warn("The auto-indent feature requires the readline library")
373 self.autoindent = 0
373 self.autoindent = 0
374 return
374 return
375 if value is None:
375 if value is None:
376 self.autoindent = not self.autoindent
376 self.autoindent = not self.autoindent
377 else:
377 else:
378 self.autoindent = value
378 self.autoindent = value
379
379
380 #-------------------------------------------------------------------------
380 #-------------------------------------------------------------------------
381 # init_* methods called by __init__
381 # init_* methods called by __init__
382 #-------------------------------------------------------------------------
382 #-------------------------------------------------------------------------
383
383
384 def init_ipythondir(self, ipythondir):
384 def init_ipythondir(self, ipythondir):
385 if ipythondir is not None:
385 if ipythondir is not None:
386 self.ipythondir = ipythondir
386 self.ipythondir = ipythondir
387 self.config.Global.ipythondir = self.ipythondir
387 self.config.Global.ipythondir = self.ipythondir
388 return
388 return
389
389
390 if hasattr(self.config.Global, 'ipythondir'):
390 if hasattr(self.config.Global, 'ipythondir'):
391 self.ipythondir = self.config.Global.ipythondir
391 self.ipythondir = self.config.Global.ipythondir
392 else:
392 else:
393 self.ipythondir = get_ipython_dir()
393 self.ipythondir = get_ipython_dir()
394
394
395 # All children can just read this
395 # All children can just read this
396 self.config.Global.ipythondir = self.ipythondir
396 self.config.Global.ipythondir = self.ipythondir
397
397
398 def init_instance_attrs(self):
398 def init_instance_attrs(self):
399 self.jobs = BackgroundJobManager()
399 self.jobs = BackgroundJobManager()
400 self.more = False
400 self.more = False
401
401
402 # command compiler
402 # command compiler
403 self.compile = codeop.CommandCompiler()
403 self.compile = codeop.CommandCompiler()
404
404
405 # User input buffer
405 # User input buffer
406 self.buffer = []
406 self.buffer = []
407
407
408 # Make an empty namespace, which extension writers can rely on both
408 # Make an empty namespace, which extension writers can rely on both
409 # existing and NEVER being used by ipython itself. This gives them a
409 # existing and NEVER being used by ipython itself. This gives them a
410 # convenient location for storing additional information and state
410 # convenient location for storing additional information and state
411 # their extensions may require, without fear of collisions with other
411 # their extensions may require, without fear of collisions with other
412 # ipython names that may develop later.
412 # ipython names that may develop later.
413 self.meta = Struct()
413 self.meta = Struct()
414
414
415 # Object variable to store code object waiting execution. This is
415 # Object variable to store code object waiting execution. This is
416 # used mainly by the multithreaded shells, but it can come in handy in
416 # used mainly by the multithreaded shells, but it can come in handy in
417 # other situations. No need to use a Queue here, since it's a single
417 # other situations. No need to use a Queue here, since it's a single
418 # item which gets cleared once run.
418 # item which gets cleared once run.
419 self.code_to_run = None
419 self.code_to_run = None
420
420
421 # Flag to mark unconditional exit
421 # Flag to mark unconditional exit
422 self.exit_now = False
422 self.exit_now = False
423
423
424 # Temporary files used for various purposes. Deleted at exit.
424 # Temporary files used for various purposes. Deleted at exit.
425 self.tempfiles = []
425 self.tempfiles = []
426
426
427 # Keep track of readline usage (later set by init_readline)
427 # Keep track of readline usage (later set by init_readline)
428 self.has_readline = False
428 self.has_readline = False
429
429
430 # keep track of where we started running (mainly for crash post-mortem)
430 # keep track of where we started running (mainly for crash post-mortem)
431 # This is not being used anywhere currently.
431 # This is not being used anywhere currently.
432 self.starting_dir = os.getcwd()
432 self.starting_dir = os.getcwd()
433
433
434 # Indentation management
434 # Indentation management
435 self.indent_current_nsp = 0
435 self.indent_current_nsp = 0
436
436
437 def init_term_title(self):
437 def init_term_title(self):
438 # Enable or disable the terminal title.
438 # Enable or disable the terminal title.
439 if self.term_title:
439 if self.term_title:
440 toggle_set_term_title(True)
440 toggle_set_term_title(True)
441 set_term_title('IPython: ' + abbrev_cwd())
441 set_term_title('IPython: ' + abbrev_cwd())
442 else:
442 else:
443 toggle_set_term_title(False)
443 toggle_set_term_title(False)
444
444
445 def init_usage(self, usage=None):
445 def init_usage(self, usage=None):
446 if usage is None:
446 if usage is None:
447 self.usage = interactive_usage
447 self.usage = interactive_usage
448 else:
448 else:
449 self.usage = usage
449 self.usage = usage
450
450
451 def init_encoding(self):
451 def init_encoding(self):
452 # Get system encoding at startup time. Certain terminals (like Emacs
452 # Get system encoding at startup time. Certain terminals (like Emacs
453 # under Win32 have it set to None, and we need to have a known valid
453 # under Win32 have it set to None, and we need to have a known valid
454 # encoding to use in the raw_input() method
454 # encoding to use in the raw_input() method
455 try:
455 try:
456 self.stdin_encoding = sys.stdin.encoding or 'ascii'
456 self.stdin_encoding = sys.stdin.encoding or 'ascii'
457 except AttributeError:
457 except AttributeError:
458 self.stdin_encoding = 'ascii'
458 self.stdin_encoding = 'ascii'
459
459
460 def init_syntax_highlighting(self):
460 def init_syntax_highlighting(self):
461 # Python source parser/formatter for syntax highlighting
461 # Python source parser/formatter for syntax highlighting
462 pyformat = PyColorize.Parser().format
462 pyformat = PyColorize.Parser().format
463 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
463 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
464
464
465 def init_pushd_popd_magic(self):
465 def init_pushd_popd_magic(self):
466 # for pushd/popd management
466 # for pushd/popd management
467 try:
467 try:
468 self.home_dir = get_home_dir()
468 self.home_dir = get_home_dir()
469 except HomeDirError, msg:
469 except HomeDirError, msg:
470 fatal(msg)
470 fatal(msg)
471
471
472 self.dir_stack = []
472 self.dir_stack = []
473
473
474 def init_logger(self):
474 def init_logger(self):
475 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
475 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
476 # local shortcut, this is used a LOT
476 # local shortcut, this is used a LOT
477 self.log = self.logger.log
477 self.log = self.logger.log
478
478
479 def init_logstart(self):
479 def init_logstart(self):
480 if self.logappend:
480 if self.logappend:
481 self.magic_logstart(self.logappend + ' append')
481 self.magic_logstart(self.logappend + ' append')
482 elif self.logfile:
482 elif self.logfile:
483 self.magic_logstart(self.logfile)
483 self.magic_logstart(self.logfile)
484 elif self.logstart:
484 elif self.logstart:
485 self.magic_logstart()
485 self.magic_logstart()
486
486
487 def init_builtins(self):
487 def init_builtins(self):
488 self.builtin_trap = BuiltinTrap(self)
488 self.builtin_trap = BuiltinTrap(self)
489
489
490 def init_inspector(self):
490 def init_inspector(self):
491 # Object inspector
491 # Object inspector
492 self.inspector = oinspect.Inspector(oinspect.InspectColors,
492 self.inspector = oinspect.Inspector(oinspect.InspectColors,
493 PyColorize.ANSICodeColors,
493 PyColorize.ANSICodeColors,
494 'NoColor',
494 'NoColor',
495 self.object_info_string_level)
495 self.object_info_string_level)
496
496
497 def init_prompts(self):
497 def init_prompts(self):
498 # Initialize cache, set in/out prompts and printing system
498 # Initialize cache, set in/out prompts and printing system
499 self.outputcache = CachedOutput(self,
499 self.outputcache = CachedOutput(self,
500 self.cache_size,
500 self.cache_size,
501 self.pprint,
501 self.pprint,
502 input_sep = self.separate_in,
502 input_sep = self.separate_in,
503 output_sep = self.separate_out,
503 output_sep = self.separate_out,
504 output_sep2 = self.separate_out2,
504 output_sep2 = self.separate_out2,
505 ps1 = self.prompt_in1,
505 ps1 = self.prompt_in1,
506 ps2 = self.prompt_in2,
506 ps2 = self.prompt_in2,
507 ps_out = self.prompt_out,
507 ps_out = self.prompt_out,
508 pad_left = self.prompts_pad_left)
508 pad_left = self.prompts_pad_left)
509
509
510 # user may have over-ridden the default print hook:
510 # user may have over-ridden the default print hook:
511 try:
511 try:
512 self.outputcache.__class__.display = self.hooks.display
512 self.outputcache.__class__.display = self.hooks.display
513 except AttributeError:
513 except AttributeError:
514 pass
514 pass
515
515
516 def init_displayhook(self):
516 def init_displayhook(self):
517 self.display_trap = DisplayTrap(self, self.outputcache)
517 self.display_trap = DisplayTrap(self, self.outputcache)
518
518
519 def init_reload_doctest(self):
519 def init_reload_doctest(self):
520 # Do a proper resetting of doctest, including the necessary displayhook
520 # Do a proper resetting of doctest, including the necessary displayhook
521 # monkeypatching
521 # monkeypatching
522 try:
522 try:
523 doctest_reload()
523 doctest_reload()
524 except ImportError:
524 except ImportError:
525 warn("doctest module does not exist.")
525 warn("doctest module does not exist.")
526
526
527 #-------------------------------------------------------------------------
527 #-------------------------------------------------------------------------
528 # Things related to the banner
528 # Things related to the banner
529 #-------------------------------------------------------------------------
529 #-------------------------------------------------------------------------
530
530
531 def init_banner(self, banner1, banner2, display_banner):
531 def init_banner(self, banner1, banner2, display_banner):
532 if banner1 is not None:
532 if banner1 is not None:
533 self.banner1 = banner1
533 self.banner1 = banner1
534 if banner2 is not None:
534 if banner2 is not None:
535 self.banner2 = banner2
535 self.banner2 = banner2
536 if display_banner is not None:
536 if display_banner is not None:
537 self.display_banner = display_banner
537 self.display_banner = display_banner
538 self.compute_banner()
538 self.compute_banner()
539
539
540 def show_banner(self, banner=None):
540 def show_banner(self, banner=None):
541 if banner is None:
541 if banner is None:
542 banner = self.banner
542 banner = self.banner
543 self.write(banner)
543 self.write(banner)
544
544
545 def compute_banner(self):
545 def compute_banner(self):
546 self.banner = self.banner1 + '\n'
546 self.banner = self.banner1 + '\n'
547 if self.profile:
547 if self.profile:
548 self.banner += '\nIPython profile: %s\n' % self.profile
548 self.banner += '\nIPython profile: %s\n' % self.profile
549 if self.banner2:
549 if self.banner2:
550 self.banner += '\n' + self.banner2 + '\n'
550 self.banner += '\n' + self.banner2 + '\n'
551
551
552 #-------------------------------------------------------------------------
552 #-------------------------------------------------------------------------
553 # Things related to injections into the sys module
553 # Things related to injections into the sys module
554 #-------------------------------------------------------------------------
554 #-------------------------------------------------------------------------
555
555
556 def save_sys_module_state(self):
556 def save_sys_module_state(self):
557 """Save the state of hooks in the sys module.
557 """Save the state of hooks in the sys module.
558
558
559 This has to be called after self.user_ns is created.
559 This has to be called after self.user_ns is created.
560 """
560 """
561 self._orig_sys_module_state = {}
561 self._orig_sys_module_state = {}
562 self._orig_sys_module_state['stdin'] = sys.stdin
562 self._orig_sys_module_state['stdin'] = sys.stdin
563 self._orig_sys_module_state['stdout'] = sys.stdout
563 self._orig_sys_module_state['stdout'] = sys.stdout
564 self._orig_sys_module_state['stderr'] = sys.stderr
564 self._orig_sys_module_state['stderr'] = sys.stderr
565 self._orig_sys_module_state['excepthook'] = sys.excepthook
565 self._orig_sys_module_state['excepthook'] = sys.excepthook
566 try:
566 try:
567 self._orig_sys_modules_main_name = self.user_ns['__name__']
567 self._orig_sys_modules_main_name = self.user_ns['__name__']
568 except KeyError:
568 except KeyError:
569 pass
569 pass
570
570
571 def restore_sys_module_state(self):
571 def restore_sys_module_state(self):
572 """Restore the state of the sys module."""
572 """Restore the state of the sys module."""
573 try:
573 try:
574 for k, v in self._orig_sys_module_state.items():
574 for k, v in self._orig_sys_module_state.items():
575 setattr(sys, k, v)
575 setattr(sys, k, v)
576 except AttributeError:
576 except AttributeError:
577 pass
577 pass
578 try:
578 try:
579 delattr(sys, 'ipcompleter')
579 delattr(sys, 'ipcompleter')
580 except AttributeError:
580 except AttributeError:
581 pass
581 pass
582 # Reset what what done in self.init_sys_modules
582 # Reset what what done in self.init_sys_modules
583 try:
583 try:
584 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
584 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
585 except (AttributeError, KeyError):
585 except (AttributeError, KeyError):
586 pass
586 pass
587
587
588 #-------------------------------------------------------------------------
588 #-------------------------------------------------------------------------
589 # Things related to hooks
589 # Things related to hooks
590 #-------------------------------------------------------------------------
590 #-------------------------------------------------------------------------
591
591
592 def init_hooks(self):
592 def init_hooks(self):
593 # hooks holds pointers used for user-side customizations
593 # hooks holds pointers used for user-side customizations
594 self.hooks = Struct()
594 self.hooks = Struct()
595
595
596 self.strdispatchers = {}
596 self.strdispatchers = {}
597
597
598 # Set all default hooks, defined in the IPython.hooks module.
598 # Set all default hooks, defined in the IPython.hooks module.
599 import IPython.core.hooks
599 import IPython.core.hooks
600 hooks = IPython.core.hooks
600 hooks = IPython.core.hooks
601 for hook_name in hooks.__all__:
601 for hook_name in hooks.__all__:
602 # default hooks have priority 100, i.e. low; user hooks should have
602 # default hooks have priority 100, i.e. low; user hooks should have
603 # 0-100 priority
603 # 0-100 priority
604 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
604 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
605
605
606 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
606 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
607 """set_hook(name,hook) -> sets an internal IPython hook.
607 """set_hook(name,hook) -> sets an internal IPython hook.
608
608
609 IPython exposes some of its internal API as user-modifiable hooks. By
609 IPython exposes some of its internal API as user-modifiable hooks. By
610 adding your function to one of these hooks, you can modify IPython's
610 adding your function to one of these hooks, you can modify IPython's
611 behavior to call at runtime your own routines."""
611 behavior to call at runtime your own routines."""
612
612
613 # At some point in the future, this should validate the hook before it
613 # At some point in the future, this should validate the hook before it
614 # accepts it. Probably at least check that the hook takes the number
614 # accepts it. Probably at least check that the hook takes the number
615 # of args it's supposed to.
615 # of args it's supposed to.
616
616
617 f = new.instancemethod(hook,self,self.__class__)
617 f = new.instancemethod(hook,self,self.__class__)
618
618
619 # check if the hook is for strdispatcher first
619 # check if the hook is for strdispatcher first
620 if str_key is not None:
620 if str_key is not None:
621 sdp = self.strdispatchers.get(name, StrDispatch())
621 sdp = self.strdispatchers.get(name, StrDispatch())
622 sdp.add_s(str_key, f, priority )
622 sdp.add_s(str_key, f, priority )
623 self.strdispatchers[name] = sdp
623 self.strdispatchers[name] = sdp
624 return
624 return
625 if re_key is not None:
625 if re_key is not None:
626 sdp = self.strdispatchers.get(name, StrDispatch())
626 sdp = self.strdispatchers.get(name, StrDispatch())
627 sdp.add_re(re.compile(re_key), f, priority )
627 sdp.add_re(re.compile(re_key), f, priority )
628 self.strdispatchers[name] = sdp
628 self.strdispatchers[name] = sdp
629 return
629 return
630
630
631 dp = getattr(self.hooks, name, None)
631 dp = getattr(self.hooks, name, None)
632 if name not in IPython.core.hooks.__all__:
632 if name not in IPython.core.hooks.__all__:
633 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
633 print "Warning! Hook '%s' is not one of %s" % (name, IPython.core.hooks.__all__ )
634 if not dp:
634 if not dp:
635 dp = IPython.core.hooks.CommandChainDispatcher()
635 dp = IPython.core.hooks.CommandChainDispatcher()
636
636
637 try:
637 try:
638 dp.add(f,priority)
638 dp.add(f,priority)
639 except AttributeError:
639 except AttributeError:
640 # it was not commandchain, plain old func - replace
640 # it was not commandchain, plain old func - replace
641 dp = f
641 dp = f
642
642
643 setattr(self.hooks,name, dp)
643 setattr(self.hooks,name, dp)
644
644
645 #-------------------------------------------------------------------------
645 #-------------------------------------------------------------------------
646 # Things related to the "main" module
646 # Things related to the "main" module
647 #-------------------------------------------------------------------------
647 #-------------------------------------------------------------------------
648
648
649 def new_main_mod(self,ns=None):
649 def new_main_mod(self,ns=None):
650 """Return a new 'main' module object for user code execution.
650 """Return a new 'main' module object for user code execution.
651 """
651 """
652 main_mod = self._user_main_module
652 main_mod = self._user_main_module
653 init_fakemod_dict(main_mod,ns)
653 init_fakemod_dict(main_mod,ns)
654 return main_mod
654 return main_mod
655
655
656 def cache_main_mod(self,ns,fname):
656 def cache_main_mod(self,ns,fname):
657 """Cache a main module's namespace.
657 """Cache a main module's namespace.
658
658
659 When scripts are executed via %run, we must keep a reference to the
659 When scripts are executed via %run, we must keep a reference to the
660 namespace of their __main__ module (a FakeModule instance) around so
660 namespace of their __main__ module (a FakeModule instance) around so
661 that Python doesn't clear it, rendering objects defined therein
661 that Python doesn't clear it, rendering objects defined therein
662 useless.
662 useless.
663
663
664 This method keeps said reference in a private dict, keyed by the
664 This method keeps said reference in a private dict, keyed by the
665 absolute path of the module object (which corresponds to the script
665 absolute path of the module object (which corresponds to the script
666 path). This way, for multiple executions of the same script we only
666 path). This way, for multiple executions of the same script we only
667 keep one copy of the namespace (the last one), thus preventing memory
667 keep one copy of the namespace (the last one), thus preventing memory
668 leaks from old references while allowing the objects from the last
668 leaks from old references while allowing the objects from the last
669 execution to be accessible.
669 execution to be accessible.
670
670
671 Note: we can not allow the actual FakeModule instances to be deleted,
671 Note: we can not allow the actual FakeModule instances to be deleted,
672 because of how Python tears down modules (it hard-sets all their
672 because of how Python tears down modules (it hard-sets all their
673 references to None without regard for reference counts). This method
673 references to None without regard for reference counts). This method
674 must therefore make a *copy* of the given namespace, to allow the
674 must therefore make a *copy* of the given namespace, to allow the
675 original module's __dict__ to be cleared and reused.
675 original module's __dict__ to be cleared and reused.
676
676
677
677
678 Parameters
678 Parameters
679 ----------
679 ----------
680 ns : a namespace (a dict, typically)
680 ns : a namespace (a dict, typically)
681
681
682 fname : str
682 fname : str
683 Filename associated with the namespace.
683 Filename associated with the namespace.
684
684
685 Examples
685 Examples
686 --------
686 --------
687
687
688 In [10]: import IPython
688 In [10]: import IPython
689
689
690 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
690 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
691
691
692 In [12]: IPython.__file__ in _ip._main_ns_cache
692 In [12]: IPython.__file__ in _ip._main_ns_cache
693 Out[12]: True
693 Out[12]: True
694 """
694 """
695 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
695 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
696
696
697 def clear_main_mod_cache(self):
697 def clear_main_mod_cache(self):
698 """Clear the cache of main modules.
698 """Clear the cache of main modules.
699
699
700 Mainly for use by utilities like %reset.
700 Mainly for use by utilities like %reset.
701
701
702 Examples
702 Examples
703 --------
703 --------
704
704
705 In [15]: import IPython
705 In [15]: import IPython
706
706
707 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
707 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
708
708
709 In [17]: len(_ip._main_ns_cache) > 0
709 In [17]: len(_ip._main_ns_cache) > 0
710 Out[17]: True
710 Out[17]: True
711
711
712 In [18]: _ip.clear_main_mod_cache()
712 In [18]: _ip.clear_main_mod_cache()
713
713
714 In [19]: len(_ip._main_ns_cache) == 0
714 In [19]: len(_ip._main_ns_cache) == 0
715 Out[19]: True
715 Out[19]: True
716 """
716 """
717 self._main_ns_cache.clear()
717 self._main_ns_cache.clear()
718
718
719 #-------------------------------------------------------------------------
719 #-------------------------------------------------------------------------
720 # Things related to debugging
720 # Things related to debugging
721 #-------------------------------------------------------------------------
721 #-------------------------------------------------------------------------
722
722
723 def init_pdb(self):
723 def init_pdb(self):
724 # Set calling of pdb on exceptions
724 # Set calling of pdb on exceptions
725 # self.call_pdb is a property
725 # self.call_pdb is a property
726 self.call_pdb = self.pdb
726 self.call_pdb = self.pdb
727
727
728 def _get_call_pdb(self):
728 def _get_call_pdb(self):
729 return self._call_pdb
729 return self._call_pdb
730
730
731 def _set_call_pdb(self,val):
731 def _set_call_pdb(self,val):
732
732
733 if val not in (0,1,False,True):
733 if val not in (0,1,False,True):
734 raise ValueError,'new call_pdb value must be boolean'
734 raise ValueError,'new call_pdb value must be boolean'
735
735
736 # store value in instance
736 # store value in instance
737 self._call_pdb = val
737 self._call_pdb = val
738
738
739 # notify the actual exception handlers
739 # notify the actual exception handlers
740 self.InteractiveTB.call_pdb = val
740 self.InteractiveTB.call_pdb = val
741 if self.isthreaded:
741 if self.isthreaded:
742 try:
742 try:
743 self.sys_excepthook.call_pdb = val
743 self.sys_excepthook.call_pdb = val
744 except:
744 except:
745 warn('Failed to activate pdb for threaded exception handler')
745 warn('Failed to activate pdb for threaded exception handler')
746
746
747 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
747 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
748 'Control auto-activation of pdb at exceptions')
748 'Control auto-activation of pdb at exceptions')
749
749
750 def debugger(self,force=False):
750 def debugger(self,force=False):
751 """Call the pydb/pdb debugger.
751 """Call the pydb/pdb debugger.
752
752
753 Keywords:
753 Keywords:
754
754
755 - force(False): by default, this routine checks the instance call_pdb
755 - force(False): by default, this routine checks the instance call_pdb
756 flag and does not actually invoke the debugger if the flag is false.
756 flag and does not actually invoke the debugger if the flag is false.
757 The 'force' option forces the debugger to activate even if the flag
757 The 'force' option forces the debugger to activate even if the flag
758 is false.
758 is false.
759 """
759 """
760
760
761 if not (force or self.call_pdb):
761 if not (force or self.call_pdb):
762 return
762 return
763
763
764 if not hasattr(sys,'last_traceback'):
764 if not hasattr(sys,'last_traceback'):
765 error('No traceback has been produced, nothing to debug.')
765 error('No traceback has been produced, nothing to debug.')
766 return
766 return
767
767
768 # use pydb if available
768 # use pydb if available
769 if debugger.has_pydb:
769 if debugger.has_pydb:
770 from pydb import pm
770 from pydb import pm
771 else:
771 else:
772 # fallback to our internal debugger
772 # fallback to our internal debugger
773 pm = lambda : self.InteractiveTB.debugger(force=True)
773 pm = lambda : self.InteractiveTB.debugger(force=True)
774 self.history_saving_wrapper(pm)()
774 self.history_saving_wrapper(pm)()
775
775
776 #-------------------------------------------------------------------------
776 #-------------------------------------------------------------------------
777 # Things related to IPython's various namespaces
777 # Things related to IPython's various namespaces
778 #-------------------------------------------------------------------------
778 #-------------------------------------------------------------------------
779
779
780 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
780 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
781 # Create the namespace where the user will operate. user_ns is
781 # Create the namespace where the user will operate. user_ns is
782 # normally the only one used, and it is passed to the exec calls as
782 # normally the only one used, and it is passed to the exec calls as
783 # the locals argument. But we do carry a user_global_ns namespace
783 # the locals argument. But we do carry a user_global_ns namespace
784 # given as the exec 'globals' argument, This is useful in embedding
784 # given as the exec 'globals' argument, This is useful in embedding
785 # situations where the ipython shell opens in a context where the
785 # situations where the ipython shell opens in a context where the
786 # distinction between locals and globals is meaningful. For
786 # distinction between locals and globals is meaningful. For
787 # non-embedded contexts, it is just the same object as the user_ns dict.
787 # non-embedded contexts, it is just the same object as the user_ns dict.
788
788
789 # FIXME. For some strange reason, __builtins__ is showing up at user
789 # FIXME. For some strange reason, __builtins__ is showing up at user
790 # level as a dict instead of a module. This is a manual fix, but I
790 # level as a dict instead of a module. This is a manual fix, but I
791 # should really track down where the problem is coming from. Alex
791 # should really track down where the problem is coming from. Alex
792 # Schmolck reported this problem first.
792 # Schmolck reported this problem first.
793
793
794 # A useful post by Alex Martelli on this topic:
794 # A useful post by Alex Martelli on this topic:
795 # Re: inconsistent value from __builtins__
795 # Re: inconsistent value from __builtins__
796 # Von: Alex Martelli <aleaxit@yahoo.com>
796 # Von: Alex Martelli <aleaxit@yahoo.com>
797 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
797 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
798 # Gruppen: comp.lang.python
798 # Gruppen: comp.lang.python
799
799
800 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
800 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
801 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
801 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
802 # > <type 'dict'>
802 # > <type 'dict'>
803 # > >>> print type(__builtins__)
803 # > >>> print type(__builtins__)
804 # > <type 'module'>
804 # > <type 'module'>
805 # > Is this difference in return value intentional?
805 # > Is this difference in return value intentional?
806
806
807 # Well, it's documented that '__builtins__' can be either a dictionary
807 # Well, it's documented that '__builtins__' can be either a dictionary
808 # or a module, and it's been that way for a long time. Whether it's
808 # or a module, and it's been that way for a long time. Whether it's
809 # intentional (or sensible), I don't know. In any case, the idea is
809 # intentional (or sensible), I don't know. In any case, the idea is
810 # that if you need to access the built-in namespace directly, you
810 # that if you need to access the built-in namespace directly, you
811 # should start with "import __builtin__" (note, no 's') which will
811 # should start with "import __builtin__" (note, no 's') which will
812 # definitely give you a module. Yeah, it's somewhat confusing:-(.
812 # definitely give you a module. Yeah, it's somewhat confusing:-(.
813
813
814 # These routines return properly built dicts as needed by the rest of
814 # These routines return properly built dicts as needed by the rest of
815 # the code, and can also be used by extension writers to generate
815 # the code, and can also be used by extension writers to generate
816 # properly initialized namespaces.
816 # properly initialized namespaces.
817 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
817 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
818 user_global_ns)
818 user_global_ns)
819
819
820 # Assign namespaces
820 # Assign namespaces
821 # This is the namespace where all normal user variables live
821 # This is the namespace where all normal user variables live
822 self.user_ns = user_ns
822 self.user_ns = user_ns
823 self.user_global_ns = user_global_ns
823 self.user_global_ns = user_global_ns
824
824
825 # An auxiliary namespace that checks what parts of the user_ns were
825 # An auxiliary namespace that checks what parts of the user_ns were
826 # loaded at startup, so we can list later only variables defined in
826 # loaded at startup, so we can list later only variables defined in
827 # actual interactive use. Since it is always a subset of user_ns, it
827 # actual interactive use. Since it is always a subset of user_ns, it
828 # doesn't need to be seaparately tracked in the ns_table
828 # doesn't need to be seaparately tracked in the ns_table
829 self.user_config_ns = {}
829 self.user_config_ns = {}
830
830
831 # A namespace to keep track of internal data structures to prevent
831 # A namespace to keep track of internal data structures to prevent
832 # them from cluttering user-visible stuff. Will be updated later
832 # them from cluttering user-visible stuff. Will be updated later
833 self.internal_ns = {}
833 self.internal_ns = {}
834
834
835 # Now that FakeModule produces a real module, we've run into a nasty
835 # Now that FakeModule produces a real module, we've run into a nasty
836 # problem: after script execution (via %run), the module where the user
836 # problem: after script execution (via %run), the module where the user
837 # code ran is deleted. Now that this object is a true module (needed
837 # code ran is deleted. Now that this object is a true module (needed
838 # so docetst and other tools work correctly), the Python module
838 # so docetst and other tools work correctly), the Python module
839 # teardown mechanism runs over it, and sets to None every variable
839 # teardown mechanism runs over it, and sets to None every variable
840 # present in that module. Top-level references to objects from the
840 # present in that module. Top-level references to objects from the
841 # script survive, because the user_ns is updated with them. However,
841 # script survive, because the user_ns is updated with them. However,
842 # calling functions defined in the script that use other things from
842 # calling functions defined in the script that use other things from
843 # the script will fail, because the function's closure had references
843 # the script will fail, because the function's closure had references
844 # to the original objects, which are now all None. So we must protect
844 # to the original objects, which are now all None. So we must protect
845 # these modules from deletion by keeping a cache.
845 # these modules from deletion by keeping a cache.
846 #
846 #
847 # To avoid keeping stale modules around (we only need the one from the
847 # To avoid keeping stale modules around (we only need the one from the
848 # last run), we use a dict keyed with the full path to the script, so
848 # last run), we use a dict keyed with the full path to the script, so
849 # only the last version of the module is held in the cache. Note,
849 # only the last version of the module is held in the cache. Note,
850 # however, that we must cache the module *namespace contents* (their
850 # however, that we must cache the module *namespace contents* (their
851 # __dict__). Because if we try to cache the actual modules, old ones
851 # __dict__). Because if we try to cache the actual modules, old ones
852 # (uncached) could be destroyed while still holding references (such as
852 # (uncached) could be destroyed while still holding references (such as
853 # those held by GUI objects that tend to be long-lived)>
853 # those held by GUI objects that tend to be long-lived)>
854 #
854 #
855 # The %reset command will flush this cache. See the cache_main_mod()
855 # The %reset command will flush this cache. See the cache_main_mod()
856 # and clear_main_mod_cache() methods for details on use.
856 # and clear_main_mod_cache() methods for details on use.
857
857
858 # This is the cache used for 'main' namespaces
858 # This is the cache used for 'main' namespaces
859 self._main_ns_cache = {}
859 self._main_ns_cache = {}
860 # And this is the single instance of FakeModule whose __dict__ we keep
860 # And this is the single instance of FakeModule whose __dict__ we keep
861 # copying and clearing for reuse on each %run
861 # copying and clearing for reuse on each %run
862 self._user_main_module = FakeModule()
862 self._user_main_module = FakeModule()
863
863
864 # A table holding all the namespaces IPython deals with, so that
864 # A table holding all the namespaces IPython deals with, so that
865 # introspection facilities can search easily.
865 # introspection facilities can search easily.
866 self.ns_table = {'user':user_ns,
866 self.ns_table = {'user':user_ns,
867 'user_global':user_global_ns,
867 'user_global':user_global_ns,
868 'internal':self.internal_ns,
868 'internal':self.internal_ns,
869 'builtin':__builtin__.__dict__
869 'builtin':__builtin__.__dict__
870 }
870 }
871
871
872 # Similarly, track all namespaces where references can be held and that
872 # Similarly, track all namespaces where references can be held and that
873 # we can safely clear (so it can NOT include builtin). This one can be
873 # we can safely clear (so it can NOT include builtin). This one can be
874 # a simple list.
874 # a simple list.
875 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
875 self.ns_refs_table = [ user_ns, user_global_ns, self.user_config_ns,
876 self.internal_ns, self._main_ns_cache ]
876 self.internal_ns, self._main_ns_cache ]
877
877
878 def init_sys_modules(self):
878 def init_sys_modules(self):
879 # We need to insert into sys.modules something that looks like a
879 # We need to insert into sys.modules something that looks like a
880 # module but which accesses the IPython namespace, for shelve and
880 # module but which accesses the IPython namespace, for shelve and
881 # pickle to work interactively. Normally they rely on getting
881 # pickle to work interactively. Normally they rely on getting
882 # everything out of __main__, but for embedding purposes each IPython
882 # everything out of __main__, but for embedding purposes each IPython
883 # instance has its own private namespace, so we can't go shoving
883 # instance has its own private namespace, so we can't go shoving
884 # everything into __main__.
884 # everything into __main__.
885
885
886 # note, however, that we should only do this for non-embedded
886 # note, however, that we should only do this for non-embedded
887 # ipythons, which really mimic the __main__.__dict__ with their own
887 # ipythons, which really mimic the __main__.__dict__ with their own
888 # namespace. Embedded instances, on the other hand, should not do
888 # namespace. Embedded instances, on the other hand, should not do
889 # this because they need to manage the user local/global namespaces
889 # this because they need to manage the user local/global namespaces
890 # only, but they live within a 'normal' __main__ (meaning, they
890 # only, but they live within a 'normal' __main__ (meaning, they
891 # shouldn't overtake the execution environment of the script they're
891 # shouldn't overtake the execution environment of the script they're
892 # embedded in).
892 # embedded in).
893
893
894 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
894 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
895
895
896 try:
896 try:
897 main_name = self.user_ns['__name__']
897 main_name = self.user_ns['__name__']
898 except KeyError:
898 except KeyError:
899 raise KeyError('user_ns dictionary MUST have a "__name__" key')
899 raise KeyError('user_ns dictionary MUST have a "__name__" key')
900 else:
900 else:
901 sys.modules[main_name] = FakeModule(self.user_ns)
901 sys.modules[main_name] = FakeModule(self.user_ns)
902
902
903 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
903 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
904 """Return a valid local and global user interactive namespaces.
904 """Return a valid local and global user interactive namespaces.
905
905
906 This builds a dict with the minimal information needed to operate as a
906 This builds a dict with the minimal information needed to operate as a
907 valid IPython user namespace, which you can pass to the various
907 valid IPython user namespace, which you can pass to the various
908 embedding classes in ipython. The default implementation returns the
908 embedding classes in ipython. The default implementation returns the
909 same dict for both the locals and the globals to allow functions to
909 same dict for both the locals and the globals to allow functions to
910 refer to variables in the namespace. Customized implementations can
910 refer to variables in the namespace. Customized implementations can
911 return different dicts. The locals dictionary can actually be anything
911 return different dicts. The locals dictionary can actually be anything
912 following the basic mapping protocol of a dict, but the globals dict
912 following the basic mapping protocol of a dict, but the globals dict
913 must be a true dict, not even a subclass. It is recommended that any
913 must be a true dict, not even a subclass. It is recommended that any
914 custom object for the locals namespace synchronize with the globals
914 custom object for the locals namespace synchronize with the globals
915 dict somehow.
915 dict somehow.
916
916
917 Raises TypeError if the provided globals namespace is not a true dict.
917 Raises TypeError if the provided globals namespace is not a true dict.
918
918
919 :Parameters:
919 :Parameters:
920 user_ns : dict-like, optional
920 user_ns : dict-like, optional
921 The current user namespace. The items in this namespace should
921 The current user namespace. The items in this namespace should
922 be included in the output. If None, an appropriate blank
922 be included in the output. If None, an appropriate blank
923 namespace should be created.
923 namespace should be created.
924 user_global_ns : dict, optional
924 user_global_ns : dict, optional
925 The current user global namespace. The items in this namespace
925 The current user global namespace. The items in this namespace
926 should be included in the output. If None, an appropriate
926 should be included in the output. If None, an appropriate
927 blank namespace should be created.
927 blank namespace should be created.
928
928
929 :Returns:
929 :Returns:
930 A tuple pair of dictionary-like object to be used as the local namespace
930 A tuple pair of dictionary-like object to be used as the local namespace
931 of the interpreter and a dict to be used as the global namespace.
931 of the interpreter and a dict to be used as the global namespace.
932 """
932 """
933
933
934 if user_ns is None:
934 if user_ns is None:
935 # Set __name__ to __main__ to better match the behavior of the
935 # Set __name__ to __main__ to better match the behavior of the
936 # normal interpreter.
936 # normal interpreter.
937 user_ns = {'__name__' :'__main__',
937 user_ns = {'__name__' :'__main__',
938 '__builtins__' : __builtin__,
938 '__builtins__' : __builtin__,
939 }
939 }
940 else:
940 else:
941 user_ns.setdefault('__name__','__main__')
941 user_ns.setdefault('__name__','__main__')
942 user_ns.setdefault('__builtins__',__builtin__)
942 user_ns.setdefault('__builtins__',__builtin__)
943
943
944 if user_global_ns is None:
944 if user_global_ns is None:
945 user_global_ns = user_ns
945 user_global_ns = user_ns
946 if type(user_global_ns) is not dict:
946 if type(user_global_ns) is not dict:
947 raise TypeError("user_global_ns must be a true dict; got %r"
947 raise TypeError("user_global_ns must be a true dict; got %r"
948 % type(user_global_ns))
948 % type(user_global_ns))
949
949
950 return user_ns, user_global_ns
950 return user_ns, user_global_ns
951
951
952 def init_user_ns(self):
952 def init_user_ns(self):
953 """Initialize all user-visible namespaces to their minimum defaults.
953 """Initialize all user-visible namespaces to their minimum defaults.
954
954
955 Certain history lists are also initialized here, as they effectively
955 Certain history lists are also initialized here, as they effectively
956 act as user namespaces.
956 act as user namespaces.
957
957
958 Notes
958 Notes
959 -----
959 -----
960 All data structures here are only filled in, they are NOT reset by this
960 All data structures here are only filled in, they are NOT reset by this
961 method. If they were not empty before, data will simply be added to
961 method. If they were not empty before, data will simply be added to
962 therm.
962 therm.
963 """
963 """
964 # Store myself as the public api!!!
964 # Store myself as the public api!!!
965 self.user_ns['get_ipython'] = self.get_ipython
965 self.user_ns['get_ipython'] = self.get_ipython
966
966
967 # make global variables for user access to the histories
967 # make global variables for user access to the histories
968 self.user_ns['_ih'] = self.input_hist
968 self.user_ns['_ih'] = self.input_hist
969 self.user_ns['_oh'] = self.output_hist
969 self.user_ns['_oh'] = self.output_hist
970 self.user_ns['_dh'] = self.dir_hist
970 self.user_ns['_dh'] = self.dir_hist
971
971
972 # user aliases to input and output histories
972 # user aliases to input and output histories
973 self.user_ns['In'] = self.input_hist
973 self.user_ns['In'] = self.input_hist
974 self.user_ns['Out'] = self.output_hist
974 self.user_ns['Out'] = self.output_hist
975
975
976 self.user_ns['_sh'] = shadowns
976 self.user_ns['_sh'] = shadowns
977
977
978 # Put 'help' in the user namespace
978 # Put 'help' in the user namespace
979 try:
979 try:
980 from site import _Helper
980 from site import _Helper
981 self.user_ns['help'] = _Helper()
981 self.user_ns['help'] = _Helper()
982 except ImportError:
982 except ImportError:
983 warn('help() not available - check site.py')
983 warn('help() not available - check site.py')
984
984
985 def reset(self):
985 def reset(self):
986 """Clear all internal namespaces.
986 """Clear all internal namespaces.
987
987
988 Note that this is much more aggressive than %reset, since it clears
988 Note that this is much more aggressive than %reset, since it clears
989 fully all namespaces, as well as all input/output lists.
989 fully all namespaces, as well as all input/output lists.
990 """
990 """
991 for ns in self.ns_refs_table:
991 for ns in self.ns_refs_table:
992 ns.clear()
992 ns.clear()
993
993
994 self.alias_manager.clear_aliases()
994 self.alias_manager.clear_aliases()
995
995
996 # Clear input and output histories
996 # Clear input and output histories
997 self.input_hist[:] = []
997 self.input_hist[:] = []
998 self.input_hist_raw[:] = []
998 self.input_hist_raw[:] = []
999 self.output_hist.clear()
999 self.output_hist.clear()
1000
1000
1001 # Restore the user namespaces to minimal usability
1001 # Restore the user namespaces to minimal usability
1002 self.init_user_ns()
1002 self.init_user_ns()
1003
1003
1004 # Restore the default and user aliases
1004 # Restore the default and user aliases
1005 self.alias_manager.init_aliases()
1005 self.alias_manager.init_aliases()
1006
1006
1007 def push(self, variables, interactive=True):
1007 def push(self, variables, interactive=True):
1008 """Inject a group of variables into the IPython user namespace.
1008 """Inject a group of variables into the IPython user namespace.
1009
1009
1010 Parameters
1010 Parameters
1011 ----------
1011 ----------
1012 variables : dict, str or list/tuple of str
1012 variables : dict, str or list/tuple of str
1013 The variables to inject into the user's namespace. If a dict,
1013 The variables to inject into the user's namespace. If a dict,
1014 a simple update is done. If a str, the string is assumed to
1014 a simple update is done. If a str, the string is assumed to
1015 have variable names separated by spaces. A list/tuple of str
1015 have variable names separated by spaces. A list/tuple of str
1016 can also be used to give the variable names. If just the variable
1016 can also be used to give the variable names. If just the variable
1017 names are give (list/tuple/str) then the variable values looked
1017 names are give (list/tuple/str) then the variable values looked
1018 up in the callers frame.
1018 up in the callers frame.
1019 interactive : bool
1019 interactive : bool
1020 If True (default), the variables will be listed with the ``who``
1020 If True (default), the variables will be listed with the ``who``
1021 magic.
1021 magic.
1022 """
1022 """
1023 vdict = None
1023 vdict = None
1024
1024
1025 # We need a dict of name/value pairs to do namespace updates.
1025 # We need a dict of name/value pairs to do namespace updates.
1026 if isinstance(variables, dict):
1026 if isinstance(variables, dict):
1027 vdict = variables
1027 vdict = variables
1028 elif isinstance(variables, (basestring, list, tuple)):
1028 elif isinstance(variables, (basestring, list, tuple)):
1029 if isinstance(variables, basestring):
1029 if isinstance(variables, basestring):
1030 vlist = variables.split()
1030 vlist = variables.split()
1031 else:
1031 else:
1032 vlist = variables
1032 vlist = variables
1033 vdict = {}
1033 vdict = {}
1034 cf = sys._getframe(1)
1034 cf = sys._getframe(1)
1035 for name in vlist:
1035 for name in vlist:
1036 try:
1036 try:
1037 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1037 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1038 except:
1038 except:
1039 print ('Could not get variable %s from %s' %
1039 print ('Could not get variable %s from %s' %
1040 (name,cf.f_code.co_name))
1040 (name,cf.f_code.co_name))
1041 else:
1041 else:
1042 raise ValueError('variables must be a dict/str/list/tuple')
1042 raise ValueError('variables must be a dict/str/list/tuple')
1043
1043
1044 # Propagate variables to user namespace
1044 # Propagate variables to user namespace
1045 self.user_ns.update(vdict)
1045 self.user_ns.update(vdict)
1046
1046
1047 # And configure interactive visibility
1047 # And configure interactive visibility
1048 config_ns = self.user_config_ns
1048 config_ns = self.user_config_ns
1049 if interactive:
1049 if interactive:
1050 for name, val in vdict.iteritems():
1050 for name, val in vdict.iteritems():
1051 config_ns.pop(name, None)
1051 config_ns.pop(name, None)
1052 else:
1052 else:
1053 for name,val in vdict.iteritems():
1053 for name,val in vdict.iteritems():
1054 config_ns[name] = val
1054 config_ns[name] = val
1055
1055
1056 #-------------------------------------------------------------------------
1056 #-------------------------------------------------------------------------
1057 # Things related to history management
1057 # Things related to history management
1058 #-------------------------------------------------------------------------
1058 #-------------------------------------------------------------------------
1059
1059
1060 def init_history(self):
1060 def init_history(self):
1061 # List of input with multi-line handling.
1061 # List of input with multi-line handling.
1062 self.input_hist = InputList()
1062 self.input_hist = InputList()
1063 # This one will hold the 'raw' input history, without any
1063 # This one will hold the 'raw' input history, without any
1064 # pre-processing. This will allow users to retrieve the input just as
1064 # pre-processing. This will allow users to retrieve the input just as
1065 # it was exactly typed in by the user, with %hist -r.
1065 # it was exactly typed in by the user, with %hist -r.
1066 self.input_hist_raw = InputList()
1066 self.input_hist_raw = InputList()
1067
1067
1068 # list of visited directories
1068 # list of visited directories
1069 try:
1069 try:
1070 self.dir_hist = [os.getcwd()]
1070 self.dir_hist = [os.getcwd()]
1071 except OSError:
1071 except OSError:
1072 self.dir_hist = []
1072 self.dir_hist = []
1073
1073
1074 # dict of output history
1074 # dict of output history
1075 self.output_hist = {}
1075 self.output_hist = {}
1076
1076
1077 # Now the history file
1077 # Now the history file
1078 if self.profile:
1078 if self.profile:
1079 histfname = 'history-%s' % self.profile
1079 histfname = 'history-%s' % self.profile
1080 else:
1080 else:
1081 histfname = 'history'
1081 histfname = 'history'
1082 self.histfile = os.path.join(self.ipythondir, histfname)
1082 self.histfile = os.path.join(self.ipythondir, histfname)
1083
1083
1084 # Fill the history zero entry, user counter starts at 1
1084 # Fill the history zero entry, user counter starts at 1
1085 self.input_hist.append('\n')
1085 self.input_hist.append('\n')
1086 self.input_hist_raw.append('\n')
1086 self.input_hist_raw.append('\n')
1087
1087
1088 def init_shadow_hist(self):
1088 def init_shadow_hist(self):
1089 try:
1089 try:
1090 self.db = pickleshare.PickleShareDB(self.ipythondir + "/db")
1090 self.db = pickleshare.PickleShareDB(self.ipythondir + "/db")
1091 except exceptions.UnicodeDecodeError:
1091 except exceptions.UnicodeDecodeError:
1092 print "Your ipythondir can't be decoded to unicode!"
1092 print "Your ipythondir can't be decoded to unicode!"
1093 print "Please set HOME environment variable to something that"
1093 print "Please set HOME environment variable to something that"
1094 print r"only has ASCII characters, e.g. c:\home"
1094 print r"only has ASCII characters, e.g. c:\home"
1095 print "Now it is", self.ipythondir
1095 print "Now it is", self.ipythondir
1096 sys.exit()
1096 sys.exit()
1097 self.shadowhist = ipcorehist.ShadowHist(self.db)
1097 self.shadowhist = ipcorehist.ShadowHist(self.db)
1098
1098
1099 def savehist(self):
1099 def savehist(self):
1100 """Save input history to a file (via readline library)."""
1100 """Save input history to a file (via readline library)."""
1101
1101
1102 if not self.has_readline:
1102 if not self.has_readline:
1103 return
1103 return
1104
1104
1105 try:
1105 try:
1106 self.readline.write_history_file(self.histfile)
1106 self.readline.write_history_file(self.histfile)
1107 except:
1107 except:
1108 print 'Unable to save IPython command history to file: ' + \
1108 print 'Unable to save IPython command history to file: ' + \
1109 `self.histfile`
1109 `self.histfile`
1110
1110
1111 def reloadhist(self):
1111 def reloadhist(self):
1112 """Reload the input history from disk file."""
1112 """Reload the input history from disk file."""
1113
1113
1114 if self.has_readline:
1114 if self.has_readline:
1115 try:
1115 try:
1116 self.readline.clear_history()
1116 self.readline.clear_history()
1117 self.readline.read_history_file(self.shell.histfile)
1117 self.readline.read_history_file(self.shell.histfile)
1118 except AttributeError:
1118 except AttributeError:
1119 pass
1119 pass
1120
1120
1121 def history_saving_wrapper(self, func):
1121 def history_saving_wrapper(self, func):
1122 """ Wrap func for readline history saving
1122 """ Wrap func for readline history saving
1123
1123
1124 Convert func into callable that saves & restores
1124 Convert func into callable that saves & restores
1125 history around the call """
1125 history around the call """
1126
1126
1127 if not self.has_readline:
1127 if not self.has_readline:
1128 return func
1128 return func
1129
1129
1130 def wrapper():
1130 def wrapper():
1131 self.savehist()
1131 self.savehist()
1132 try:
1132 try:
1133 func()
1133 func()
1134 finally:
1134 finally:
1135 readline.read_history_file(self.histfile)
1135 readline.read_history_file(self.histfile)
1136 return wrapper
1136 return wrapper
1137
1137
1138 #-------------------------------------------------------------------------
1138 #-------------------------------------------------------------------------
1139 # Things related to exception handling and tracebacks (not debugging)
1139 # Things related to exception handling and tracebacks (not debugging)
1140 #-------------------------------------------------------------------------
1140 #-------------------------------------------------------------------------
1141
1141
1142 def init_traceback_handlers(self, custom_exceptions):
1142 def init_traceback_handlers(self, custom_exceptions):
1143 # Syntax error handler.
1143 # Syntax error handler.
1144 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1144 self.SyntaxTB = SyntaxTB(color_scheme='NoColor')
1145
1145
1146 # The interactive one is initialized with an offset, meaning we always
1146 # The interactive one is initialized with an offset, meaning we always
1147 # want to remove the topmost item in the traceback, which is our own
1147 # want to remove the topmost item in the traceback, which is our own
1148 # internal code. Valid modes: ['Plain','Context','Verbose']
1148 # internal code. Valid modes: ['Plain','Context','Verbose']
1149 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1149 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1150 color_scheme='NoColor',
1150 color_scheme='NoColor',
1151 tb_offset = 1)
1151 tb_offset = 1)
1152
1152
1153 # IPython itself shouldn't crash. This will produce a detailed
1153 # IPython itself shouldn't crash. This will produce a detailed
1154 # post-mortem if it does. But we only install the crash handler for
1154 # post-mortem if it does. But we only install the crash handler for
1155 # non-threaded shells, the threaded ones use a normal verbose reporter
1155 # non-threaded shells, the threaded ones use a normal verbose reporter
1156 # and lose the crash handler. This is because exceptions in the main
1156 # and lose the crash handler. This is because exceptions in the main
1157 # thread (such as in GUI code) propagate directly to sys.excepthook,
1157 # thread (such as in GUI code) propagate directly to sys.excepthook,
1158 # and there's no point in printing crash dumps for every user exception.
1158 # and there's no point in printing crash dumps for every user exception.
1159 if self.isthreaded:
1159 if self.isthreaded:
1160 ipCrashHandler = ultratb.FormattedTB()
1160 ipCrashHandler = ultratb.FormattedTB()
1161 else:
1161 else:
1162 from IPython.core import crashhandler
1162 from IPython.core import crashhandler
1163 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
1163 ipCrashHandler = crashhandler.IPythonCrashHandler(self)
1164 self.set_crash_handler(ipCrashHandler)
1164 self.set_crash_handler(ipCrashHandler)
1165
1165
1166 # and add any custom exception handlers the user may have specified
1166 # and add any custom exception handlers the user may have specified
1167 self.set_custom_exc(*custom_exceptions)
1167 self.set_custom_exc(*custom_exceptions)
1168
1168
1169 def set_crash_handler(self, crashHandler):
1169 def set_crash_handler(self, crashHandler):
1170 """Set the IPython crash handler.
1170 """Set the IPython crash handler.
1171
1171
1172 This must be a callable with a signature suitable for use as
1172 This must be a callable with a signature suitable for use as
1173 sys.excepthook."""
1173 sys.excepthook."""
1174
1174
1175 # Install the given crash handler as the Python exception hook
1175 # Install the given crash handler as the Python exception hook
1176 sys.excepthook = crashHandler
1176 sys.excepthook = crashHandler
1177
1177
1178 # The instance will store a pointer to this, so that runtime code
1178 # The instance will store a pointer to this, so that runtime code
1179 # (such as magics) can access it. This is because during the
1179 # (such as magics) can access it. This is because during the
1180 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1180 # read-eval loop, it gets temporarily overwritten (to deal with GUI
1181 # frameworks).
1181 # frameworks).
1182 self.sys_excepthook = sys.excepthook
1182 self.sys_excepthook = sys.excepthook
1183
1183
1184 def set_custom_exc(self,exc_tuple,handler):
1184 def set_custom_exc(self,exc_tuple,handler):
1185 """set_custom_exc(exc_tuple,handler)
1185 """set_custom_exc(exc_tuple,handler)
1186
1186
1187 Set a custom exception handler, which will be called if any of the
1187 Set a custom exception handler, which will be called if any of the
1188 exceptions in exc_tuple occur in the mainloop (specifically, in the
1188 exceptions in exc_tuple occur in the mainloop (specifically, in the
1189 runcode() method.
1189 runcode() method.
1190
1190
1191 Inputs:
1191 Inputs:
1192
1192
1193 - exc_tuple: a *tuple* of valid exceptions to call the defined
1193 - exc_tuple: a *tuple* of valid exceptions to call the defined
1194 handler for. It is very important that you use a tuple, and NOT A
1194 handler for. It is very important that you use a tuple, and NOT A
1195 LIST here, because of the way Python's except statement works. If
1195 LIST here, because of the way Python's except statement works. If
1196 you only want to trap a single exception, use a singleton tuple:
1196 you only want to trap a single exception, use a singleton tuple:
1197
1197
1198 exc_tuple == (MyCustomException,)
1198 exc_tuple == (MyCustomException,)
1199
1199
1200 - handler: this must be defined as a function with the following
1200 - handler: this must be defined as a function with the following
1201 basic interface: def my_handler(self,etype,value,tb).
1201 basic interface: def my_handler(self,etype,value,tb).
1202
1202
1203 This will be made into an instance method (via new.instancemethod)
1203 This will be made into an instance method (via new.instancemethod)
1204 of IPython itself, and it will be called if any of the exceptions
1204 of IPython itself, and it will be called if any of the exceptions
1205 listed in the exc_tuple are caught. If the handler is None, an
1205 listed in the exc_tuple are caught. If the handler is None, an
1206 internal basic one is used, which just prints basic info.
1206 internal basic one is used, which just prints basic info.
1207
1207
1208 WARNING: by putting in your own exception handler into IPython's main
1208 WARNING: by putting in your own exception handler into IPython's main
1209 execution loop, you run a very good chance of nasty crashes. This
1209 execution loop, you run a very good chance of nasty crashes. This
1210 facility should only be used if you really know what you are doing."""
1210 facility should only be used if you really know what you are doing."""
1211
1211
1212 assert type(exc_tuple)==type(()) , \
1212 assert type(exc_tuple)==type(()) , \
1213 "The custom exceptions must be given AS A TUPLE."
1213 "The custom exceptions must be given AS A TUPLE."
1214
1214
1215 def dummy_handler(self,etype,value,tb):
1215 def dummy_handler(self,etype,value,tb):
1216 print '*** Simple custom exception handler ***'
1216 print '*** Simple custom exception handler ***'
1217 print 'Exception type :',etype
1217 print 'Exception type :',etype
1218 print 'Exception value:',value
1218 print 'Exception value:',value
1219 print 'Traceback :',tb
1219 print 'Traceback :',tb
1220 print 'Source code :','\n'.join(self.buffer)
1220 print 'Source code :','\n'.join(self.buffer)
1221
1221
1222 if handler is None: handler = dummy_handler
1222 if handler is None: handler = dummy_handler
1223
1223
1224 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1224 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1225 self.custom_exceptions = exc_tuple
1225 self.custom_exceptions = exc_tuple
1226
1226
1227 def excepthook(self, etype, value, tb):
1227 def excepthook(self, etype, value, tb):
1228 """One more defense for GUI apps that call sys.excepthook.
1228 """One more defense for GUI apps that call sys.excepthook.
1229
1229
1230 GUI frameworks like wxPython trap exceptions and call
1230 GUI frameworks like wxPython trap exceptions and call
1231 sys.excepthook themselves. I guess this is a feature that
1231 sys.excepthook themselves. I guess this is a feature that
1232 enables them to keep running after exceptions that would
1232 enables them to keep running after exceptions that would
1233 otherwise kill their mainloop. This is a bother for IPython
1233 otherwise kill their mainloop. This is a bother for IPython
1234 which excepts to catch all of the program exceptions with a try:
1234 which excepts to catch all of the program exceptions with a try:
1235 except: statement.
1235 except: statement.
1236
1236
1237 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1237 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1238 any app directly invokes sys.excepthook, it will look to the user like
1238 any app directly invokes sys.excepthook, it will look to the user like
1239 IPython crashed. In order to work around this, we can disable the
1239 IPython crashed. In order to work around this, we can disable the
1240 CrashHandler and replace it with this excepthook instead, which prints a
1240 CrashHandler and replace it with this excepthook instead, which prints a
1241 regular traceback using our InteractiveTB. In this fashion, apps which
1241 regular traceback using our InteractiveTB. In this fashion, apps which
1242 call sys.excepthook will generate a regular-looking exception from
1242 call sys.excepthook will generate a regular-looking exception from
1243 IPython, and the CrashHandler will only be triggered by real IPython
1243 IPython, and the CrashHandler will only be triggered by real IPython
1244 crashes.
1244 crashes.
1245
1245
1246 This hook should be used sparingly, only in places which are not likely
1246 This hook should be used sparingly, only in places which are not likely
1247 to be true IPython errors.
1247 to be true IPython errors.
1248 """
1248 """
1249 self.showtraceback((etype,value,tb),tb_offset=0)
1249 self.showtraceback((etype,value,tb),tb_offset=0)
1250
1250
1251 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1251 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None):
1252 """Display the exception that just occurred.
1252 """Display the exception that just occurred.
1253
1253
1254 If nothing is known about the exception, this is the method which
1254 If nothing is known about the exception, this is the method which
1255 should be used throughout the code for presenting user tracebacks,
1255 should be used throughout the code for presenting user tracebacks,
1256 rather than directly invoking the InteractiveTB object.
1256 rather than directly invoking the InteractiveTB object.
1257
1257
1258 A specific showsyntaxerror() also exists, but this method can take
1258 A specific showsyntaxerror() also exists, but this method can take
1259 care of calling it if needed, so unless you are explicitly catching a
1259 care of calling it if needed, so unless you are explicitly catching a
1260 SyntaxError exception, don't try to analyze the stack manually and
1260 SyntaxError exception, don't try to analyze the stack manually and
1261 simply call this method."""
1261 simply call this method."""
1262
1262
1263
1263
1264 # Though this won't be called by syntax errors in the input line,
1264 # Though this won't be called by syntax errors in the input line,
1265 # there may be SyntaxError cases whith imported code.
1265 # there may be SyntaxError cases whith imported code.
1266
1266
1267 try:
1267 try:
1268 if exc_tuple is None:
1268 if exc_tuple is None:
1269 etype, value, tb = sys.exc_info()
1269 etype, value, tb = sys.exc_info()
1270 else:
1270 else:
1271 etype, value, tb = exc_tuple
1271 etype, value, tb = exc_tuple
1272
1272
1273 if etype is SyntaxError:
1273 if etype is SyntaxError:
1274 self.showsyntaxerror(filename)
1274 self.showsyntaxerror(filename)
1275 elif etype is UsageError:
1275 elif etype is UsageError:
1276 print "UsageError:", value
1276 print "UsageError:", value
1277 else:
1277 else:
1278 # WARNING: these variables are somewhat deprecated and not
1278 # WARNING: these variables are somewhat deprecated and not
1279 # necessarily safe to use in a threaded environment, but tools
1279 # necessarily safe to use in a threaded environment, but tools
1280 # like pdb depend on their existence, so let's set them. If we
1280 # like pdb depend on their existence, so let's set them. If we
1281 # find problems in the field, we'll need to revisit their use.
1281 # find problems in the field, we'll need to revisit their use.
1282 sys.last_type = etype
1282 sys.last_type = etype
1283 sys.last_value = value
1283 sys.last_value = value
1284 sys.last_traceback = tb
1284 sys.last_traceback = tb
1285
1285
1286 if etype in self.custom_exceptions:
1286 if etype in self.custom_exceptions:
1287 self.CustomTB(etype,value,tb)
1287 self.CustomTB(etype,value,tb)
1288 else:
1288 else:
1289 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1289 self.InteractiveTB(etype,value,tb,tb_offset=tb_offset)
1290 if self.InteractiveTB.call_pdb and self.has_readline:
1290 if self.InteractiveTB.call_pdb and self.has_readline:
1291 # pdb mucks up readline, fix it back
1291 # pdb mucks up readline, fix it back
1292 self.set_completer()
1292 self.set_completer()
1293 except KeyboardInterrupt:
1293 except KeyboardInterrupt:
1294 self.write("\nKeyboardInterrupt\n")
1294 self.write("\nKeyboardInterrupt\n")
1295
1295
1296 def showsyntaxerror(self, filename=None):
1296 def showsyntaxerror(self, filename=None):
1297 """Display the syntax error that just occurred.
1297 """Display the syntax error that just occurred.
1298
1298
1299 This doesn't display a stack trace because there isn't one.
1299 This doesn't display a stack trace because there isn't one.
1300
1300
1301 If a filename is given, it is stuffed in the exception instead
1301 If a filename is given, it is stuffed in the exception instead
1302 of what was there before (because Python's parser always uses
1302 of what was there before (because Python's parser always uses
1303 "<string>" when reading from a string).
1303 "<string>" when reading from a string).
1304 """
1304 """
1305 etype, value, last_traceback = sys.exc_info()
1305 etype, value, last_traceback = sys.exc_info()
1306
1306
1307 # See note about these variables in showtraceback() below
1307 # See note about these variables in showtraceback() below
1308 sys.last_type = etype
1308 sys.last_type = etype
1309 sys.last_value = value
1309 sys.last_value = value
1310 sys.last_traceback = last_traceback
1310 sys.last_traceback = last_traceback
1311
1311
1312 if filename and etype is SyntaxError:
1312 if filename and etype is SyntaxError:
1313 # Work hard to stuff the correct filename in the exception
1313 # Work hard to stuff the correct filename in the exception
1314 try:
1314 try:
1315 msg, (dummy_filename, lineno, offset, line) = value
1315 msg, (dummy_filename, lineno, offset, line) = value
1316 except:
1316 except:
1317 # Not the format we expect; leave it alone
1317 # Not the format we expect; leave it alone
1318 pass
1318 pass
1319 else:
1319 else:
1320 # Stuff in the right filename
1320 # Stuff in the right filename
1321 try:
1321 try:
1322 # Assume SyntaxError is a class exception
1322 # Assume SyntaxError is a class exception
1323 value = SyntaxError(msg, (filename, lineno, offset, line))
1323 value = SyntaxError(msg, (filename, lineno, offset, line))
1324 except:
1324 except:
1325 # If that failed, assume SyntaxError is a string
1325 # If that failed, assume SyntaxError is a string
1326 value = msg, (filename, lineno, offset, line)
1326 value = msg, (filename, lineno, offset, line)
1327 self.SyntaxTB(etype,value,[])
1327 self.SyntaxTB(etype,value,[])
1328
1328
1329 def edit_syntax_error(self):
1329 def edit_syntax_error(self):
1330 """The bottom half of the syntax error handler called in the main loop.
1330 """The bottom half of the syntax error handler called in the main loop.
1331
1331
1332 Loop until syntax error is fixed or user cancels.
1332 Loop until syntax error is fixed or user cancels.
1333 """
1333 """
1334
1334
1335 while self.SyntaxTB.last_syntax_error:
1335 while self.SyntaxTB.last_syntax_error:
1336 # copy and clear last_syntax_error
1336 # copy and clear last_syntax_error
1337 err = self.SyntaxTB.clear_err_state()
1337 err = self.SyntaxTB.clear_err_state()
1338 if not self._should_recompile(err):
1338 if not self._should_recompile(err):
1339 return
1339 return
1340 try:
1340 try:
1341 # may set last_syntax_error again if a SyntaxError is raised
1341 # may set last_syntax_error again if a SyntaxError is raised
1342 self.safe_execfile(err.filename,self.user_ns)
1342 self.safe_execfile(err.filename,self.user_ns)
1343 except:
1343 except:
1344 self.showtraceback()
1344 self.showtraceback()
1345 else:
1345 else:
1346 try:
1346 try:
1347 f = file(err.filename)
1347 f = file(err.filename)
1348 try:
1348 try:
1349 # This should be inside a display_trap block and I
1349 # This should be inside a display_trap block and I
1350 # think it is.
1350 # think it is.
1351 sys.displayhook(f.read())
1351 sys.displayhook(f.read())
1352 finally:
1352 finally:
1353 f.close()
1353 f.close()
1354 except:
1354 except:
1355 self.showtraceback()
1355 self.showtraceback()
1356
1356
1357 def _should_recompile(self,e):
1357 def _should_recompile(self,e):
1358 """Utility routine for edit_syntax_error"""
1358 """Utility routine for edit_syntax_error"""
1359
1359
1360 if e.filename in ('<ipython console>','<input>','<string>',
1360 if e.filename in ('<ipython console>','<input>','<string>',
1361 '<console>','<BackgroundJob compilation>',
1361 '<console>','<BackgroundJob compilation>',
1362 None):
1362 None):
1363
1363
1364 return False
1364 return False
1365 try:
1365 try:
1366 if (self.autoedit_syntax and
1366 if (self.autoedit_syntax and
1367 not self.ask_yes_no('Return to editor to correct syntax error? '
1367 not self.ask_yes_no('Return to editor to correct syntax error? '
1368 '[Y/n] ','y')):
1368 '[Y/n] ','y')):
1369 return False
1369 return False
1370 except EOFError:
1370 except EOFError:
1371 return False
1371 return False
1372
1372
1373 def int0(x):
1373 def int0(x):
1374 try:
1374 try:
1375 return int(x)
1375 return int(x)
1376 except TypeError:
1376 except TypeError:
1377 return 0
1377 return 0
1378 # always pass integer line and offset values to editor hook
1378 # always pass integer line and offset values to editor hook
1379 try:
1379 try:
1380 self.hooks.fix_error_editor(e.filename,
1380 self.hooks.fix_error_editor(e.filename,
1381 int0(e.lineno),int0(e.offset),e.msg)
1381 int0(e.lineno),int0(e.offset),e.msg)
1382 except TryNext:
1382 except TryNext:
1383 warn('Could not open editor')
1383 warn('Could not open editor')
1384 return False
1384 return False
1385 return True
1385 return True
1386
1386
1387 #-------------------------------------------------------------------------
1387 #-------------------------------------------------------------------------
1388 # Things related to tab completion
1388 # Things related to tab completion
1389 #-------------------------------------------------------------------------
1389 #-------------------------------------------------------------------------
1390
1390
1391 def complete(self, text):
1391 def complete(self, text):
1392 """Return a sorted list of all possible completions on text.
1392 """Return a sorted list of all possible completions on text.
1393
1393
1394 Inputs:
1394 Inputs:
1395
1395
1396 - text: a string of text to be completed on.
1396 - text: a string of text to be completed on.
1397
1397
1398 This is a wrapper around the completion mechanism, similar to what
1398 This is a wrapper around the completion mechanism, similar to what
1399 readline does at the command line when the TAB key is hit. By
1399 readline does at the command line when the TAB key is hit. By
1400 exposing it as a method, it can be used by other non-readline
1400 exposing it as a method, it can be used by other non-readline
1401 environments (such as GUIs) for text completion.
1401 environments (such as GUIs) for text completion.
1402
1402
1403 Simple usage example:
1403 Simple usage example:
1404
1404
1405 In [7]: x = 'hello'
1405 In [7]: x = 'hello'
1406
1406
1407 In [8]: x
1407 In [8]: x
1408 Out[8]: 'hello'
1408 Out[8]: 'hello'
1409
1409
1410 In [9]: print x
1410 In [9]: print x
1411 hello
1411 hello
1412
1412
1413 In [10]: _ip.complete('x.l')
1413 In [10]: _ip.complete('x.l')
1414 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1414 Out[10]: ['x.ljust', 'x.lower', 'x.lstrip']
1415 """
1415 """
1416
1416
1417 # Inject names into __builtin__ so we can complete on the added names.
1417 # Inject names into __builtin__ so we can complete on the added names.
1418 with self.builtin_trap:
1418 with self.builtin_trap:
1419 complete = self.Completer.complete
1419 complete = self.Completer.complete
1420 state = 0
1420 state = 0
1421 # use a dict so we get unique keys, since ipyhton's multiple
1421 # use a dict so we get unique keys, since ipyhton's multiple
1422 # completers can return duplicates. When we make 2.4 a requirement,
1422 # completers can return duplicates. When we make 2.4 a requirement,
1423 # start using sets instead, which are faster.
1423 # start using sets instead, which are faster.
1424 comps = {}
1424 comps = {}
1425 while True:
1425 while True:
1426 newcomp = complete(text,state,line_buffer=text)
1426 newcomp = complete(text,state,line_buffer=text)
1427 if newcomp is None:
1427 if newcomp is None:
1428 break
1428 break
1429 comps[newcomp] = 1
1429 comps[newcomp] = 1
1430 state += 1
1430 state += 1
1431 outcomps = comps.keys()
1431 outcomps = comps.keys()
1432 outcomps.sort()
1432 outcomps.sort()
1433 #print "T:",text,"OC:",outcomps # dbg
1433 #print "T:",text,"OC:",outcomps # dbg
1434 #print "vars:",self.user_ns.keys()
1434 #print "vars:",self.user_ns.keys()
1435 return outcomps
1435 return outcomps
1436
1436
1437 def set_custom_completer(self,completer,pos=0):
1437 def set_custom_completer(self,completer,pos=0):
1438 """Adds a new custom completer function.
1438 """Adds a new custom completer function.
1439
1439
1440 The position argument (defaults to 0) is the index in the completers
1440 The position argument (defaults to 0) is the index in the completers
1441 list where you want the completer to be inserted."""
1441 list where you want the completer to be inserted."""
1442
1442
1443 newcomp = new.instancemethod(completer,self.Completer,
1443 newcomp = new.instancemethod(completer,self.Completer,
1444 self.Completer.__class__)
1444 self.Completer.__class__)
1445 self.Completer.matchers.insert(pos,newcomp)
1445 self.Completer.matchers.insert(pos,newcomp)
1446
1446
1447 def set_completer(self):
1447 def set_completer(self):
1448 """Reset readline's completer to be our own."""
1448 """Reset readline's completer to be our own."""
1449 self.readline.set_completer(self.Completer.complete)
1449 self.readline.set_completer(self.Completer.complete)
1450
1450
1451 def set_completer_frame(self, frame=None):
1451 def set_completer_frame(self, frame=None):
1452 """Set the frame of the completer."""
1452 """Set the frame of the completer."""
1453 if frame:
1453 if frame:
1454 self.Completer.namespace = frame.f_locals
1454 self.Completer.namespace = frame.f_locals
1455 self.Completer.global_namespace = frame.f_globals
1455 self.Completer.global_namespace = frame.f_globals
1456 else:
1456 else:
1457 self.Completer.namespace = self.user_ns
1457 self.Completer.namespace = self.user_ns
1458 self.Completer.global_namespace = self.user_global_ns
1458 self.Completer.global_namespace = self.user_global_ns
1459
1459
1460 #-------------------------------------------------------------------------
1460 #-------------------------------------------------------------------------
1461 # Things related to readline
1461 # Things related to readline
1462 #-------------------------------------------------------------------------
1462 #-------------------------------------------------------------------------
1463
1463
1464 def init_readline(self):
1464 def init_readline(self):
1465 """Command history completion/saving/reloading."""
1465 """Command history completion/saving/reloading."""
1466
1466
1467 self.rl_next_input = None
1467 self.rl_next_input = None
1468 self.rl_do_indent = False
1468 self.rl_do_indent = False
1469
1469
1470 if not self.readline_use:
1470 if not self.readline_use:
1471 return
1471 return
1472
1472
1473 import IPython.utils.rlineimpl as readline
1473 import IPython.utils.rlineimpl as readline
1474
1474
1475 if not readline.have_readline:
1475 if not readline.have_readline:
1476 self.has_readline = 0
1476 self.has_readline = 0
1477 self.readline = None
1477 self.readline = None
1478 # no point in bugging windows users with this every time:
1478 # no point in bugging windows users with this every time:
1479 warn('Readline services not available on this platform.')
1479 warn('Readline services not available on this platform.')
1480 else:
1480 else:
1481 sys.modules['readline'] = readline
1481 sys.modules['readline'] = readline
1482 import atexit
1482 import atexit
1483 from IPython.core.completer import IPCompleter
1483 from IPython.core.completer import IPCompleter
1484 self.Completer = IPCompleter(self,
1484 self.Completer = IPCompleter(self,
1485 self.user_ns,
1485 self.user_ns,
1486 self.user_global_ns,
1486 self.user_global_ns,
1487 self.readline_omit__names,
1487 self.readline_omit__names,
1488 self.alias_manager.alias_table)
1488 self.alias_manager.alias_table)
1489 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1489 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1490 self.strdispatchers['complete_command'] = sdisp
1490 self.strdispatchers['complete_command'] = sdisp
1491 self.Completer.custom_completers = sdisp
1491 self.Completer.custom_completers = sdisp
1492 # Platform-specific configuration
1492 # Platform-specific configuration
1493 if os.name == 'nt':
1493 if os.name == 'nt':
1494 self.readline_startup_hook = readline.set_pre_input_hook
1494 self.readline_startup_hook = readline.set_pre_input_hook
1495 else:
1495 else:
1496 self.readline_startup_hook = readline.set_startup_hook
1496 self.readline_startup_hook = readline.set_startup_hook
1497
1497
1498 # Load user's initrc file (readline config)
1498 # Load user's initrc file (readline config)
1499 # Or if libedit is used, load editrc.
1499 # Or if libedit is used, load editrc.
1500 inputrc_name = os.environ.get('INPUTRC')
1500 inputrc_name = os.environ.get('INPUTRC')
1501 if inputrc_name is None:
1501 if inputrc_name is None:
1502 home_dir = get_home_dir()
1502 home_dir = get_home_dir()
1503 if home_dir is not None:
1503 if home_dir is not None:
1504 inputrc_name = '.inputrc'
1504 inputrc_name = '.inputrc'
1505 if readline.uses_libedit:
1505 if readline.uses_libedit:
1506 inputrc_name = '.editrc'
1506 inputrc_name = '.editrc'
1507 inputrc_name = os.path.join(home_dir, inputrc_name)
1507 inputrc_name = os.path.join(home_dir, inputrc_name)
1508 if os.path.isfile(inputrc_name):
1508 if os.path.isfile(inputrc_name):
1509 try:
1509 try:
1510 readline.read_init_file(inputrc_name)
1510 readline.read_init_file(inputrc_name)
1511 except:
1511 except:
1512 warn('Problems reading readline initialization file <%s>'
1512 warn('Problems reading readline initialization file <%s>'
1513 % inputrc_name)
1513 % inputrc_name)
1514
1514
1515 self.has_readline = 1
1515 self.has_readline = 1
1516 self.readline = readline
1516 self.readline = readline
1517 # save this in sys so embedded copies can restore it properly
1517 # save this in sys so embedded copies can restore it properly
1518 sys.ipcompleter = self.Completer.complete
1518 sys.ipcompleter = self.Completer.complete
1519 self.set_completer()
1519 self.set_completer()
1520
1520
1521 # Configure readline according to user's prefs
1521 # Configure readline according to user's prefs
1522 # This is only done if GNU readline is being used. If libedit
1522 # This is only done if GNU readline is being used. If libedit
1523 # is being used (as on Leopard) the readline config is
1523 # is being used (as on Leopard) the readline config is
1524 # not run as the syntax for libedit is different.
1524 # not run as the syntax for libedit is different.
1525 if not readline.uses_libedit:
1525 if not readline.uses_libedit:
1526 for rlcommand in self.readline_parse_and_bind:
1526 for rlcommand in self.readline_parse_and_bind:
1527 #print "loading rl:",rlcommand # dbg
1527 #print "loading rl:",rlcommand # dbg
1528 readline.parse_and_bind(rlcommand)
1528 readline.parse_and_bind(rlcommand)
1529
1529
1530 # Remove some chars from the delimiters list. If we encounter
1530 # Remove some chars from the delimiters list. If we encounter
1531 # unicode chars, discard them.
1531 # unicode chars, discard them.
1532 delims = readline.get_completer_delims().encode("ascii", "ignore")
1532 delims = readline.get_completer_delims().encode("ascii", "ignore")
1533 delims = delims.translate(string._idmap,
1533 delims = delims.translate(string._idmap,
1534 self.readline_remove_delims)
1534 self.readline_remove_delims)
1535 readline.set_completer_delims(delims)
1535 readline.set_completer_delims(delims)
1536 # otherwise we end up with a monster history after a while:
1536 # otherwise we end up with a monster history after a while:
1537 readline.set_history_length(1000)
1537 readline.set_history_length(1000)
1538 try:
1538 try:
1539 #print '*** Reading readline history' # dbg
1539 #print '*** Reading readline history' # dbg
1540 readline.read_history_file(self.histfile)
1540 readline.read_history_file(self.histfile)
1541 except IOError:
1541 except IOError:
1542 pass # It doesn't exist yet.
1542 pass # It doesn't exist yet.
1543
1543
1544 atexit.register(self.atexit_operations)
1544 atexit.register(self.atexit_operations)
1545 del atexit
1545 del atexit
1546
1546
1547 # Configure auto-indent for all platforms
1547 # Configure auto-indent for all platforms
1548 self.set_autoindent(self.autoindent)
1548 self.set_autoindent(self.autoindent)
1549
1549
1550 def set_next_input(self, s):
1550 def set_next_input(self, s):
1551 """ Sets the 'default' input string for the next command line.
1551 """ Sets the 'default' input string for the next command line.
1552
1552
1553 Requires readline.
1553 Requires readline.
1554
1554
1555 Example:
1555 Example:
1556
1556
1557 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1557 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1558 [D:\ipython]|2> Hello Word_ # cursor is here
1558 [D:\ipython]|2> Hello Word_ # cursor is here
1559 """
1559 """
1560
1560
1561 self.rl_next_input = s
1561 self.rl_next_input = s
1562
1562
1563 def pre_readline(self):
1563 def pre_readline(self):
1564 """readline hook to be used at the start of each line.
1564 """readline hook to be used at the start of each line.
1565
1565
1566 Currently it handles auto-indent only."""
1566 Currently it handles auto-indent only."""
1567
1567
1568 #debugx('self.indent_current_nsp','pre_readline:')
1568 #debugx('self.indent_current_nsp','pre_readline:')
1569
1569
1570 if self.rl_do_indent:
1570 if self.rl_do_indent:
1571 self.readline.insert_text(self._indent_current_str())
1571 self.readline.insert_text(self._indent_current_str())
1572 if self.rl_next_input is not None:
1572 if self.rl_next_input is not None:
1573 self.readline.insert_text(self.rl_next_input)
1573 self.readline.insert_text(self.rl_next_input)
1574 self.rl_next_input = None
1574 self.rl_next_input = None
1575
1575
1576 def _indent_current_str(self):
1576 def _indent_current_str(self):
1577 """return the current level of indentation as a string"""
1577 """return the current level of indentation as a string"""
1578 return self.indent_current_nsp * ' '
1578 return self.indent_current_nsp * ' '
1579
1579
1580 #-------------------------------------------------------------------------
1580 #-------------------------------------------------------------------------
1581 # Things related to magics
1581 # Things related to magics
1582 #-------------------------------------------------------------------------
1582 #-------------------------------------------------------------------------
1583
1583
1584 def init_magics(self):
1584 def init_magics(self):
1585 # Set user colors (don't do it in the constructor above so that it
1585 # Set user colors (don't do it in the constructor above so that it
1586 # doesn't crash if colors option is invalid)
1586 # doesn't crash if colors option is invalid)
1587 self.magic_colors(self.colors)
1587 self.magic_colors(self.colors)
1588
1588
1589 def magic(self,arg_s):
1589 def magic(self,arg_s):
1590 """Call a magic function by name.
1590 """Call a magic function by name.
1591
1591
1592 Input: a string containing the name of the magic function to call and any
1592 Input: a string containing the name of the magic function to call and any
1593 additional arguments to be passed to the magic.
1593 additional arguments to be passed to the magic.
1594
1594
1595 magic('name -opt foo bar') is equivalent to typing at the ipython
1595 magic('name -opt foo bar') is equivalent to typing at the ipython
1596 prompt:
1596 prompt:
1597
1597
1598 In[1]: %name -opt foo bar
1598 In[1]: %name -opt foo bar
1599
1599
1600 To call a magic without arguments, simply use magic('name').
1600 To call a magic without arguments, simply use magic('name').
1601
1601
1602 This provides a proper Python function to call IPython's magics in any
1602 This provides a proper Python function to call IPython's magics in any
1603 valid Python code you can type at the interpreter, including loops and
1603 valid Python code you can type at the interpreter, including loops and
1604 compound statements.
1604 compound statements.
1605 """
1605 """
1606
1606
1607 args = arg_s.split(' ',1)
1607 args = arg_s.split(' ',1)
1608 magic_name = args[0]
1608 magic_name = args[0]
1609 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1609 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1610
1610
1611 try:
1611 try:
1612 magic_args = args[1]
1612 magic_args = args[1]
1613 except IndexError:
1613 except IndexError:
1614 magic_args = ''
1614 magic_args = ''
1615 fn = getattr(self,'magic_'+magic_name,None)
1615 fn = getattr(self,'magic_'+magic_name,None)
1616 if fn is None:
1616 if fn is None:
1617 error("Magic function `%s` not found." % magic_name)
1617 error("Magic function `%s` not found." % magic_name)
1618 else:
1618 else:
1619 magic_args = self.var_expand(magic_args,1)
1619 magic_args = self.var_expand(magic_args,1)
1620 with nested(self.builtin_trap,):
1620 with nested(self.builtin_trap,):
1621 result = fn(magic_args)
1621 result = fn(magic_args)
1622 return result
1622 return result
1623
1623
1624 def define_magic(self, magicname, func):
1624 def define_magic(self, magicname, func):
1625 """Expose own function as magic function for ipython
1625 """Expose own function as magic function for ipython
1626
1626
1627 def foo_impl(self,parameter_s=''):
1627 def foo_impl(self,parameter_s=''):
1628 'My very own magic!. (Use docstrings, IPython reads them).'
1628 'My very own magic!. (Use docstrings, IPython reads them).'
1629 print 'Magic function. Passed parameter is between < >:'
1629 print 'Magic function. Passed parameter is between < >:'
1630 print '<%s>' % parameter_s
1630 print '<%s>' % parameter_s
1631 print 'The self object is:',self
1631 print 'The self object is:',self
1632
1632
1633 self.define_magic('foo',foo_impl)
1633 self.define_magic('foo',foo_impl)
1634 """
1634 """
1635
1635
1636 import new
1636 import new
1637 im = new.instancemethod(func,self, self.__class__)
1637 im = new.instancemethod(func,self, self.__class__)
1638 old = getattr(self, "magic_" + magicname, None)
1638 old = getattr(self, "magic_" + magicname, None)
1639 setattr(self, "magic_" + magicname, im)
1639 setattr(self, "magic_" + magicname, im)
1640 return old
1640 return old
1641
1641
1642 #-------------------------------------------------------------------------
1642 #-------------------------------------------------------------------------
1643 # Things related to macros
1643 # Things related to macros
1644 #-------------------------------------------------------------------------
1644 #-------------------------------------------------------------------------
1645
1645
1646 def define_macro(self, name, themacro):
1646 def define_macro(self, name, themacro):
1647 """Define a new macro
1647 """Define a new macro
1648
1648
1649 Parameters
1649 Parameters
1650 ----------
1650 ----------
1651 name : str
1651 name : str
1652 The name of the macro.
1652 The name of the macro.
1653 themacro : str or Macro
1653 themacro : str or Macro
1654 The action to do upon invoking the macro. If a string, a new
1654 The action to do upon invoking the macro. If a string, a new
1655 Macro object is created by passing the string to it.
1655 Macro object is created by passing the string to it.
1656 """
1656 """
1657
1657
1658 from IPython.core import macro
1658 from IPython.core import macro
1659
1659
1660 if isinstance(themacro, basestring):
1660 if isinstance(themacro, basestring):
1661 themacro = macro.Macro(themacro)
1661 themacro = macro.Macro(themacro)
1662 if not isinstance(themacro, macro.Macro):
1662 if not isinstance(themacro, macro.Macro):
1663 raise ValueError('A macro must be a string or a Macro instance.')
1663 raise ValueError('A macro must be a string or a Macro instance.')
1664 self.user_ns[name] = themacro
1664 self.user_ns[name] = themacro
1665
1665
1666 #-------------------------------------------------------------------------
1666 #-------------------------------------------------------------------------
1667 # Things related to the running of system commands
1667 # Things related to the running of system commands
1668 #-------------------------------------------------------------------------
1668 #-------------------------------------------------------------------------
1669
1669
1670 def system(self, cmd):
1670 def system(self, cmd):
1671 """Make a system call, using IPython."""
1671 """Make a system call, using IPython."""
1672 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1672 return self.hooks.shell_hook(self.var_expand(cmd, depth=2))
1673
1673
1674 #-------------------------------------------------------------------------
1674 #-------------------------------------------------------------------------
1675 # Things related to aliases
1675 # Things related to aliases
1676 #-------------------------------------------------------------------------
1676 #-------------------------------------------------------------------------
1677
1677
1678 def init_alias(self):
1678 def init_alias(self):
1679 self.alias_manager = AliasManager(self, config=self.config)
1679 self.alias_manager = AliasManager(self, config=self.config)
1680 self.ns_table['alias'] = self.alias_manager.alias_table,
1680 self.ns_table['alias'] = self.alias_manager.alias_table,
1681
1681
1682 #-------------------------------------------------------------------------
1682 #-------------------------------------------------------------------------
1683 # Things related to the running of code
1683 # Things related to the running of code
1684 #-------------------------------------------------------------------------
1684 #-------------------------------------------------------------------------
1685
1685
1686 def ex(self, cmd):
1686 def ex(self, cmd):
1687 """Execute a normal python statement in user namespace."""
1687 """Execute a normal python statement in user namespace."""
1688 with nested(self.builtin_trap,):
1688 with nested(self.builtin_trap,):
1689 exec cmd in self.user_global_ns, self.user_ns
1689 exec cmd in self.user_global_ns, self.user_ns
1690
1690
1691 def ev(self, expr):
1691 def ev(self, expr):
1692 """Evaluate python expression expr in user namespace.
1692 """Evaluate python expression expr in user namespace.
1693
1693
1694 Returns the result of evaluation
1694 Returns the result of evaluation
1695 """
1695 """
1696 with nested(self.builtin_trap,):
1696 with nested(self.builtin_trap,):
1697 return eval(expr, self.user_global_ns, self.user_ns)
1697 return eval(expr, self.user_global_ns, self.user_ns)
1698
1698
1699 def mainloop(self, display_banner=None):
1699 def mainloop(self, display_banner=None):
1700 """Start the mainloop.
1700 """Start the mainloop.
1701
1701
1702 If an optional banner argument is given, it will override the
1702 If an optional banner argument is given, it will override the
1703 internally created default banner.
1703 internally created default banner.
1704 """
1704 """
1705
1705
1706 with nested(self.builtin_trap, self.display_trap):
1706 with nested(self.builtin_trap, self.display_trap):
1707
1707
1708 # if you run stuff with -c <cmd>, raw hist is not updated
1708 # if you run stuff with -c <cmd>, raw hist is not updated
1709 # ensure that it's in sync
1709 # ensure that it's in sync
1710 if len(self.input_hist) != len (self.input_hist_raw):
1710 if len(self.input_hist) != len (self.input_hist_raw):
1711 self.input_hist_raw = InputList(self.input_hist)
1711 self.input_hist_raw = InputList(self.input_hist)
1712
1712
1713 while 1:
1713 while 1:
1714 try:
1714 try:
1715 self.interact(display_banner=display_banner)
1715 self.interact(display_banner=display_banner)
1716 #self.interact_with_readline()
1716 #self.interact_with_readline()
1717 # XXX for testing of a readline-decoupled repl loop, call
1717 # XXX for testing of a readline-decoupled repl loop, call
1718 # interact_with_readline above
1718 # interact_with_readline above
1719 break
1719 break
1720 except KeyboardInterrupt:
1720 except KeyboardInterrupt:
1721 # this should not be necessary, but KeyboardInterrupt
1721 # this should not be necessary, but KeyboardInterrupt
1722 # handling seems rather unpredictable...
1722 # handling seems rather unpredictable...
1723 self.write("\nKeyboardInterrupt in interact()\n")
1723 self.write("\nKeyboardInterrupt in interact()\n")
1724
1724
1725 def interact_prompt(self):
1725 def interact_prompt(self):
1726 """ Print the prompt (in read-eval-print loop)
1726 """ Print the prompt (in read-eval-print loop)
1727
1727
1728 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1728 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1729 used in standard IPython flow.
1729 used in standard IPython flow.
1730 """
1730 """
1731 if self.more:
1731 if self.more:
1732 try:
1732 try:
1733 prompt = self.hooks.generate_prompt(True)
1733 prompt = self.hooks.generate_prompt(True)
1734 except:
1734 except:
1735 self.showtraceback()
1735 self.showtraceback()
1736 if self.autoindent:
1736 if self.autoindent:
1737 self.rl_do_indent = True
1737 self.rl_do_indent = True
1738
1738
1739 else:
1739 else:
1740 try:
1740 try:
1741 prompt = self.hooks.generate_prompt(False)
1741 prompt = self.hooks.generate_prompt(False)
1742 except:
1742 except:
1743 self.showtraceback()
1743 self.showtraceback()
1744 self.write(prompt)
1744 self.write(prompt)
1745
1745
1746 def interact_handle_input(self,line):
1746 def interact_handle_input(self,line):
1747 """ Handle the input line (in read-eval-print loop)
1747 """ Handle the input line (in read-eval-print loop)
1748
1748
1749 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1749 Provided for those who want to implement their own read-eval-print loop (e.g. GUIs), not
1750 used in standard IPython flow.
1750 used in standard IPython flow.
1751 """
1751 """
1752 if line.lstrip() == line:
1752 if line.lstrip() == line:
1753 self.shadowhist.add(line.strip())
1753 self.shadowhist.add(line.strip())
1754 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1754 lineout = self.prefilter_manager.prefilter_lines(line,self.more)
1755
1755
1756 if line.strip():
1756 if line.strip():
1757 if self.more:
1757 if self.more:
1758 self.input_hist_raw[-1] += '%s\n' % line
1758 self.input_hist_raw[-1] += '%s\n' % line
1759 else:
1759 else:
1760 self.input_hist_raw.append('%s\n' % line)
1760 self.input_hist_raw.append('%s\n' % line)
1761
1761
1762
1762
1763 self.more = self.push_line(lineout)
1763 self.more = self.push_line(lineout)
1764 if (self.SyntaxTB.last_syntax_error and
1764 if (self.SyntaxTB.last_syntax_error and
1765 self.autoedit_syntax):
1765 self.autoedit_syntax):
1766 self.edit_syntax_error()
1766 self.edit_syntax_error()
1767
1767
1768 def interact_with_readline(self):
1768 def interact_with_readline(self):
1769 """ Demo of using interact_handle_input, interact_prompt
1769 """ Demo of using interact_handle_input, interact_prompt
1770
1770
1771 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1771 This is the main read-eval-print loop. If you need to implement your own (e.g. for GUI),
1772 it should work like this.
1772 it should work like this.
1773 """
1773 """
1774 self.readline_startup_hook(self.pre_readline)
1774 self.readline_startup_hook(self.pre_readline)
1775 while not self.exit_now:
1775 while not self.exit_now:
1776 self.interact_prompt()
1776 self.interact_prompt()
1777 if self.more:
1777 if self.more:
1778 self.rl_do_indent = True
1778 self.rl_do_indent = True
1779 else:
1779 else:
1780 self.rl_do_indent = False
1780 self.rl_do_indent = False
1781 line = raw_input_original().decode(self.stdin_encoding)
1781 line = raw_input_original().decode(self.stdin_encoding)
1782 self.interact_handle_input(line)
1782 self.interact_handle_input(line)
1783
1783
1784 def interact(self, display_banner=None):
1784 def interact(self, display_banner=None):
1785 """Closely emulate the interactive Python console."""
1785 """Closely emulate the interactive Python console."""
1786
1786
1787 # batch run -> do not interact
1787 # batch run -> do not interact
1788 if self.exit_now:
1788 if self.exit_now:
1789 return
1789 return
1790
1790
1791 if display_banner is None:
1791 if display_banner is None:
1792 display_banner = self.display_banner
1792 display_banner = self.display_banner
1793 if display_banner:
1793 if display_banner:
1794 self.show_banner()
1794 self.show_banner()
1795
1795
1796 more = 0
1796 more = 0
1797
1797
1798 # Mark activity in the builtins
1798 # Mark activity in the builtins
1799 __builtin__.__dict__['__IPYTHON__active'] += 1
1799 __builtin__.__dict__['__IPYTHON__active'] += 1
1800
1800
1801 if self.has_readline:
1801 if self.has_readline:
1802 self.readline_startup_hook(self.pre_readline)
1802 self.readline_startup_hook(self.pre_readline)
1803 # exit_now is set by a call to %Exit or %Quit, through the
1803 # exit_now is set by a call to %Exit or %Quit, through the
1804 # ask_exit callback.
1804 # ask_exit callback.
1805
1805
1806 while not self.exit_now:
1806 while not self.exit_now:
1807 self.hooks.pre_prompt_hook()
1807 self.hooks.pre_prompt_hook()
1808 if more:
1808 if more:
1809 try:
1809 try:
1810 prompt = self.hooks.generate_prompt(True)
1810 prompt = self.hooks.generate_prompt(True)
1811 except:
1811 except:
1812 self.showtraceback()
1812 self.showtraceback()
1813 if self.autoindent:
1813 if self.autoindent:
1814 self.rl_do_indent = True
1814 self.rl_do_indent = True
1815
1815
1816 else:
1816 else:
1817 try:
1817 try:
1818 prompt = self.hooks.generate_prompt(False)
1818 prompt = self.hooks.generate_prompt(False)
1819 except:
1819 except:
1820 self.showtraceback()
1820 self.showtraceback()
1821 try:
1821 try:
1822 line = self.raw_input(prompt, more)
1822 line = self.raw_input(prompt, more)
1823 if self.exit_now:
1823 if self.exit_now:
1824 # quick exit on sys.std[in|out] close
1824 # quick exit on sys.std[in|out] close
1825 break
1825 break
1826 if self.autoindent:
1826 if self.autoindent:
1827 self.rl_do_indent = False
1827 self.rl_do_indent = False
1828
1828
1829 except KeyboardInterrupt:
1829 except KeyboardInterrupt:
1830 #double-guard against keyboardinterrupts during kbdint handling
1830 #double-guard against keyboardinterrupts during kbdint handling
1831 try:
1831 try:
1832 self.write('\nKeyboardInterrupt\n')
1832 self.write('\nKeyboardInterrupt\n')
1833 self.resetbuffer()
1833 self.resetbuffer()
1834 # keep cache in sync with the prompt counter:
1834 # keep cache in sync with the prompt counter:
1835 self.outputcache.prompt_count -= 1
1835 self.outputcache.prompt_count -= 1
1836
1836
1837 if self.autoindent:
1837 if self.autoindent:
1838 self.indent_current_nsp = 0
1838 self.indent_current_nsp = 0
1839 more = 0
1839 more = 0
1840 except KeyboardInterrupt:
1840 except KeyboardInterrupt:
1841 pass
1841 pass
1842 except EOFError:
1842 except EOFError:
1843 if self.autoindent:
1843 if self.autoindent:
1844 self.rl_do_indent = False
1844 self.rl_do_indent = False
1845 self.readline_startup_hook(None)
1845 self.readline_startup_hook(None)
1846 self.write('\n')
1846 self.write('\n')
1847 self.exit()
1847 self.exit()
1848 except bdb.BdbQuit:
1848 except bdb.BdbQuit:
1849 warn('The Python debugger has exited with a BdbQuit exception.\n'
1849 warn('The Python debugger has exited with a BdbQuit exception.\n'
1850 'Because of how pdb handles the stack, it is impossible\n'
1850 'Because of how pdb handles the stack, it is impossible\n'
1851 'for IPython to properly format this particular exception.\n'
1851 'for IPython to properly format this particular exception.\n'
1852 'IPython will resume normal operation.')
1852 'IPython will resume normal operation.')
1853 except:
1853 except:
1854 # exceptions here are VERY RARE, but they can be triggered
1854 # exceptions here are VERY RARE, but they can be triggered
1855 # asynchronously by signal handlers, for example.
1855 # asynchronously by signal handlers, for example.
1856 self.showtraceback()
1856 self.showtraceback()
1857 else:
1857 else:
1858 more = self.push_line(line)
1858 more = self.push_line(line)
1859 if (self.SyntaxTB.last_syntax_error and
1859 if (self.SyntaxTB.last_syntax_error and
1860 self.autoedit_syntax):
1860 self.autoedit_syntax):
1861 self.edit_syntax_error()
1861 self.edit_syntax_error()
1862
1862
1863 # We are off again...
1863 # We are off again...
1864 __builtin__.__dict__['__IPYTHON__active'] -= 1
1864 __builtin__.__dict__['__IPYTHON__active'] -= 1
1865
1865
1866 def safe_execfile(self, fname, *where, **kw):
1866 def safe_execfile(self, fname, *where, **kw):
1867 """A safe version of the builtin execfile().
1867 """A safe version of the builtin execfile().
1868
1868
1869 This version will never throw an exception, but instead print
1869 This version will never throw an exception, but instead print
1870 helpful error messages to the screen. This only works on pure
1870 helpful error messages to the screen. This only works on pure
1871 Python files with the .py extension.
1871 Python files with the .py extension.
1872
1872
1873 Parameters
1873 Parameters
1874 ----------
1874 ----------
1875 fname : string
1875 fname : string
1876 The name of the file to be executed.
1876 The name of the file to be executed.
1877 where : tuple
1877 where : tuple
1878 One or two namespaces, passed to execfile() as (globals,locals).
1878 One or two namespaces, passed to execfile() as (globals,locals).
1879 If only one is given, it is passed as both.
1879 If only one is given, it is passed as both.
1880 exit_ignore : bool (False)
1880 exit_ignore : bool (False)
1881 If True, then don't print errors for non-zero exit statuses.
1881 If True, then don't print errors for non-zero exit statuses.
1882 """
1882 """
1883 kw.setdefault('exit_ignore', False)
1883 kw.setdefault('exit_ignore', False)
1884
1884
1885 fname = os.path.abspath(os.path.expanduser(fname))
1885 fname = os.path.abspath(os.path.expanduser(fname))
1886
1886
1887 # Make sure we have a .py file
1887 # Make sure we have a .py file
1888 if not fname.endswith('.py'):
1888 if not fname.endswith('.py'):
1889 warn('File must end with .py to be run using execfile: <%s>' % fname)
1889 warn('File must end with .py to be run using execfile: <%s>' % fname)
1890
1890
1891 # Make sure we can open the file
1891 # Make sure we can open the file
1892 try:
1892 try:
1893 with open(fname) as thefile:
1893 with open(fname) as thefile:
1894 pass
1894 pass
1895 except:
1895 except:
1896 warn('Could not open file <%s> for safe execution.' % fname)
1896 warn('Could not open file <%s> for safe execution.' % fname)
1897 return
1897 return
1898
1898
1899 # Find things also in current directory. This is needed to mimic the
1899 # Find things also in current directory. This is needed to mimic the
1900 # behavior of running a script from the system command line, where
1900 # behavior of running a script from the system command line, where
1901 # Python inserts the script's directory into sys.path
1901 # Python inserts the script's directory into sys.path
1902 dname = os.path.dirname(fname)
1902 dname = os.path.dirname(fname)
1903
1903
1904 with prepended_to_syspath(dname):
1904 with prepended_to_syspath(dname):
1905 try:
1905 try:
1906 if sys.platform == 'win32' and sys.version_info < (2,5,1):
1906 if sys.platform == 'win32' and sys.version_info < (2,5,1):
1907 # Work around a bug in Python for Windows. The bug was
1907 # Work around a bug in Python for Windows. The bug was
1908 # fixed in in Python 2.5 r54159 and 54158, but that's still
1908 # fixed in in Python 2.5 r54159 and 54158, but that's still
1909 # SVN Python as of March/07. For details, see:
1909 # SVN Python as of March/07. For details, see:
1910 # http://projects.scipy.org/ipython/ipython/ticket/123
1910 # http://projects.scipy.org/ipython/ipython/ticket/123
1911 try:
1911 try:
1912 globs,locs = where[0:2]
1912 globs,locs = where[0:2]
1913 except:
1913 except:
1914 try:
1914 try:
1915 globs = locs = where[0]
1915 globs = locs = where[0]
1916 except:
1916 except:
1917 globs = locs = globals()
1917 globs = locs = globals()
1918 exec file(fname) in globs,locs
1918 exec file(fname) in globs,locs
1919 else:
1919 else:
1920 execfile(fname,*where)
1920 execfile(fname,*where)
1921 except SyntaxError:
1921 except SyntaxError:
1922 self.showsyntaxerror()
1922 self.showsyntaxerror()
1923 warn('Failure executing file: <%s>' % fname)
1923 warn('Failure executing file: <%s>' % fname)
1924 except SystemExit, status:
1924 except SystemExit, status:
1925 # Code that correctly sets the exit status flag to success (0)
1925 # Code that correctly sets the exit status flag to success (0)
1926 # shouldn't be bothered with a traceback. Note that a plain
1926 # shouldn't be bothered with a traceback. Note that a plain
1927 # sys.exit() does NOT set the message to 0 (it's empty) so that
1927 # sys.exit() does NOT set the message to 0 (it's empty) so that
1928 # will still get a traceback. Note that the structure of the
1928 # will still get a traceback. Note that the structure of the
1929 # SystemExit exception changed between Python 2.4 and 2.5, so
1929 # SystemExit exception changed between Python 2.4 and 2.5, so
1930 # the checks must be done in a version-dependent way.
1930 # the checks must be done in a version-dependent way.
1931 show = False
1931 show = False
1932 if status.args[0]==0 and not kw['exit_ignore']:
1932 if status.args[0]==0 and not kw['exit_ignore']:
1933 show = True
1933 show = True
1934 if show:
1934 if show:
1935 self.showtraceback()
1935 self.showtraceback()
1936 warn('Failure executing file: <%s>' % fname)
1936 warn('Failure executing file: <%s>' % fname)
1937 except:
1937 except:
1938 self.showtraceback()
1938 self.showtraceback()
1939 warn('Failure executing file: <%s>' % fname)
1939 warn('Failure executing file: <%s>' % fname)
1940
1940
1941 def safe_execfile_ipy(self, fname):
1941 def safe_execfile_ipy(self, fname):
1942 """Like safe_execfile, but for .ipy files with IPython syntax.
1942 """Like safe_execfile, but for .ipy files with IPython syntax.
1943
1943
1944 Parameters
1944 Parameters
1945 ----------
1945 ----------
1946 fname : str
1946 fname : str
1947 The name of the file to execute. The filename must have a
1947 The name of the file to execute. The filename must have a
1948 .ipy extension.
1948 .ipy extension.
1949 """
1949 """
1950 fname = os.path.abspath(os.path.expanduser(fname))
1950 fname = os.path.abspath(os.path.expanduser(fname))
1951
1951
1952 # Make sure we have a .py file
1952 # Make sure we have a .py file
1953 if not fname.endswith('.ipy'):
1953 if not fname.endswith('.ipy'):
1954 warn('File must end with .py to be run using execfile: <%s>' % fname)
1954 warn('File must end with .py to be run using execfile: <%s>' % fname)
1955
1955
1956 # Make sure we can open the file
1956 # Make sure we can open the file
1957 try:
1957 try:
1958 with open(fname) as thefile:
1958 with open(fname) as thefile:
1959 pass
1959 pass
1960 except:
1960 except:
1961 warn('Could not open file <%s> for safe execution.' % fname)
1961 warn('Could not open file <%s> for safe execution.' % fname)
1962 return
1962 return
1963
1963
1964 # Find things also in current directory. This is needed to mimic the
1964 # Find things also in current directory. This is needed to mimic the
1965 # behavior of running a script from the system command line, where
1965 # behavior of running a script from the system command line, where
1966 # Python inserts the script's directory into sys.path
1966 # Python inserts the script's directory into sys.path
1967 dname = os.path.dirname(fname)
1967 dname = os.path.dirname(fname)
1968
1968
1969 with prepended_to_syspath(dname):
1969 with prepended_to_syspath(dname):
1970 try:
1970 try:
1971 with open(fname) as thefile:
1971 with open(fname) as thefile:
1972 script = thefile.read()
1972 script = thefile.read()
1973 # self.runlines currently captures all exceptions
1973 # self.runlines currently captures all exceptions
1974 # raise in user code. It would be nice if there were
1974 # raise in user code. It would be nice if there were
1975 # versions of runlines, execfile that did raise, so
1975 # versions of runlines, execfile that did raise, so
1976 # we could catch the errors.
1976 # we could catch the errors.
1977 self.runlines(script, clean=True)
1977 self.runlines(script, clean=True)
1978 except:
1978 except:
1979 self.showtraceback()
1979 self.showtraceback()
1980 warn('Unknown failure executing file: <%s>' % fname)
1980 warn('Unknown failure executing file: <%s>' % fname)
1981
1981
1982 def _is_secondary_block_start(self, s):
1982 def _is_secondary_block_start(self, s):
1983 if not s.endswith(':'):
1983 if not s.endswith(':'):
1984 return False
1984 return False
1985 if (s.startswith('elif') or
1985 if (s.startswith('elif') or
1986 s.startswith('else') or
1986 s.startswith('else') or
1987 s.startswith('except') or
1987 s.startswith('except') or
1988 s.startswith('finally')):
1988 s.startswith('finally')):
1989 return True
1989 return True
1990
1990
1991 def cleanup_ipy_script(self, script):
1991 def cleanup_ipy_script(self, script):
1992 """Make a script safe for self.runlines()
1992 """Make a script safe for self.runlines()
1993
1993
1994 Currently, IPython is lines based, with blocks being detected by
1994 Currently, IPython is lines based, with blocks being detected by
1995 empty lines. This is a problem for block based scripts that may
1995 empty lines. This is a problem for block based scripts that may
1996 not have empty lines after blocks. This script adds those empty
1996 not have empty lines after blocks. This script adds those empty
1997 lines to make scripts safe for running in the current line based
1997 lines to make scripts safe for running in the current line based
1998 IPython.
1998 IPython.
1999 """
1999 """
2000 res = []
2000 res = []
2001 lines = script.splitlines()
2001 lines = script.splitlines()
2002 level = 0
2002 level = 0
2003
2003
2004 for l in lines:
2004 for l in lines:
2005 lstripped = l.lstrip()
2005 lstripped = l.lstrip()
2006 stripped = l.strip()
2006 stripped = l.strip()
2007 if not stripped:
2007 if not stripped:
2008 continue
2008 continue
2009 newlevel = len(l) - len(lstripped)
2009 newlevel = len(l) - len(lstripped)
2010 if level > 0 and newlevel == 0 and \
2010 if level > 0 and newlevel == 0 and \
2011 not self._is_secondary_block_start(stripped):
2011 not self._is_secondary_block_start(stripped):
2012 # add empty line
2012 # add empty line
2013 res.append('')
2013 res.append('')
2014 res.append(l)
2014 res.append(l)
2015 level = newlevel
2015 level = newlevel
2016
2016
2017 return '\n'.join(res) + '\n'
2017 return '\n'.join(res) + '\n'
2018
2018
2019 def runlines(self, lines, clean=False):
2019 def runlines(self, lines, clean=False):
2020 """Run a string of one or more lines of source.
2020 """Run a string of one or more lines of source.
2021
2021
2022 This method is capable of running a string containing multiple source
2022 This method is capable of running a string containing multiple source
2023 lines, as if they had been entered at the IPython prompt. Since it
2023 lines, as if they had been entered at the IPython prompt. Since it
2024 exposes IPython's processing machinery, the given strings can contain
2024 exposes IPython's processing machinery, the given strings can contain
2025 magic calls (%magic), special shell access (!cmd), etc.
2025 magic calls (%magic), special shell access (!cmd), etc.
2026 """
2026 """
2027
2027
2028 if isinstance(lines, (list, tuple)):
2028 if isinstance(lines, (list, tuple)):
2029 lines = '\n'.join(lines)
2029 lines = '\n'.join(lines)
2030
2030
2031 if clean:
2031 if clean:
2032 lines = self.cleanup_ipy_script(lines)
2032 lines = self.cleanup_ipy_script(lines)
2033
2033
2034 # We must start with a clean buffer, in case this is run from an
2034 # We must start with a clean buffer, in case this is run from an
2035 # interactive IPython session (via a magic, for example).
2035 # interactive IPython session (via a magic, for example).
2036 self.resetbuffer()
2036 self.resetbuffer()
2037 lines = lines.splitlines()
2037 lines = lines.splitlines()
2038 more = 0
2038 more = 0
2039
2039
2040 with nested(self.builtin_trap, self.display_trap):
2040 with nested(self.builtin_trap, self.display_trap):
2041 for line in lines:
2041 for line in lines:
2042 # skip blank lines so we don't mess up the prompt counter, but do
2042 # skip blank lines so we don't mess up the prompt counter, but do
2043 # NOT skip even a blank line if we are in a code block (more is
2043 # NOT skip even a blank line if we are in a code block (more is
2044 # true)
2044 # true)
2045
2045
2046 if line or more:
2046 if line or more:
2047 # push to raw history, so hist line numbers stay in sync
2047 # push to raw history, so hist line numbers stay in sync
2048 self.input_hist_raw.append("# " + line + "\n")
2048 self.input_hist_raw.append("# " + line + "\n")
2049 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
2049 prefiltered = self.prefilter_manager.prefilter_lines(line,more)
2050 more = self.push_line(prefiltered)
2050 more = self.push_line(prefiltered)
2051 # IPython's runsource returns None if there was an error
2051 # IPython's runsource returns None if there was an error
2052 # compiling the code. This allows us to stop processing right
2052 # compiling the code. This allows us to stop processing right
2053 # away, so the user gets the error message at the right place.
2053 # away, so the user gets the error message at the right place.
2054 if more is None:
2054 if more is None:
2055 break
2055 break
2056 else:
2056 else:
2057 self.input_hist_raw.append("\n")
2057 self.input_hist_raw.append("\n")
2058 # final newline in case the input didn't have it, so that the code
2058 # final newline in case the input didn't have it, so that the code
2059 # actually does get executed
2059 # actually does get executed
2060 if more:
2060 if more:
2061 self.push_line('\n')
2061 self.push_line('\n')
2062
2062
2063 def runsource(self, source, filename='<input>', symbol='single'):
2063 def runsource(self, source, filename='<input>', symbol='single'):
2064 """Compile and run some source in the interpreter.
2064 """Compile and run some source in the interpreter.
2065
2065
2066 Arguments are as for compile_command().
2066 Arguments are as for compile_command().
2067
2067
2068 One several things can happen:
2068 One several things can happen:
2069
2069
2070 1) The input is incorrect; compile_command() raised an
2070 1) The input is incorrect; compile_command() raised an
2071 exception (SyntaxError or OverflowError). A syntax traceback
2071 exception (SyntaxError or OverflowError). A syntax traceback
2072 will be printed by calling the showsyntaxerror() method.
2072 will be printed by calling the showsyntaxerror() method.
2073
2073
2074 2) The input is incomplete, and more input is required;
2074 2) The input is incomplete, and more input is required;
2075 compile_command() returned None. Nothing happens.
2075 compile_command() returned None. Nothing happens.
2076
2076
2077 3) The input is complete; compile_command() returned a code
2077 3) The input is complete; compile_command() returned a code
2078 object. The code is executed by calling self.runcode() (which
2078 object. The code is executed by calling self.runcode() (which
2079 also handles run-time exceptions, except for SystemExit).
2079 also handles run-time exceptions, except for SystemExit).
2080
2080
2081 The return value is:
2081 The return value is:
2082
2082
2083 - True in case 2
2083 - True in case 2
2084
2084
2085 - False in the other cases, unless an exception is raised, where
2085 - False in the other cases, unless an exception is raised, where
2086 None is returned instead. This can be used by external callers to
2086 None is returned instead. This can be used by external callers to
2087 know whether to continue feeding input or not.
2087 know whether to continue feeding input or not.
2088
2088
2089 The return value can be used to decide whether to use sys.ps1 or
2089 The return value can be used to decide whether to use sys.ps1 or
2090 sys.ps2 to prompt the next line."""
2090 sys.ps2 to prompt the next line."""
2091
2091
2092 # if the source code has leading blanks, add 'if 1:\n' to it
2092 # if the source code has leading blanks, add 'if 1:\n' to it
2093 # this allows execution of indented pasted code. It is tempting
2093 # this allows execution of indented pasted code. It is tempting
2094 # to add '\n' at the end of source to run commands like ' a=1'
2094 # to add '\n' at the end of source to run commands like ' a=1'
2095 # directly, but this fails for more complicated scenarios
2095 # directly, but this fails for more complicated scenarios
2096 source=source.encode(self.stdin_encoding)
2096 source=source.encode(self.stdin_encoding)
2097 if source[:1] in [' ', '\t']:
2097 if source[:1] in [' ', '\t']:
2098 source = 'if 1:\n%s' % source
2098 source = 'if 1:\n%s' % source
2099
2099
2100 try:
2100 try:
2101 code = self.compile(source,filename,symbol)
2101 code = self.compile(source,filename,symbol)
2102 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2102 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2103 # Case 1
2103 # Case 1
2104 self.showsyntaxerror(filename)
2104 self.showsyntaxerror(filename)
2105 return None
2105 return None
2106
2106
2107 if code is None:
2107 if code is None:
2108 # Case 2
2108 # Case 2
2109 return True
2109 return True
2110
2110
2111 # Case 3
2111 # Case 3
2112 # We store the code object so that threaded shells and
2112 # We store the code object so that threaded shells and
2113 # custom exception handlers can access all this info if needed.
2113 # custom exception handlers can access all this info if needed.
2114 # The source corresponding to this can be obtained from the
2114 # The source corresponding to this can be obtained from the
2115 # buffer attribute as '\n'.join(self.buffer).
2115 # buffer attribute as '\n'.join(self.buffer).
2116 self.code_to_run = code
2116 self.code_to_run = code
2117 # now actually execute the code object
2117 # now actually execute the code object
2118 if self.runcode(code) == 0:
2118 if self.runcode(code) == 0:
2119 return False
2119 return False
2120 else:
2120 else:
2121 return None
2121 return None
2122
2122
2123 def runcode(self,code_obj):
2123 def runcode(self,code_obj):
2124 """Execute a code object.
2124 """Execute a code object.
2125
2125
2126 When an exception occurs, self.showtraceback() is called to display a
2126 When an exception occurs, self.showtraceback() is called to display a
2127 traceback.
2127 traceback.
2128
2128
2129 Return value: a flag indicating whether the code to be run completed
2129 Return value: a flag indicating whether the code to be run completed
2130 successfully:
2130 successfully:
2131
2131
2132 - 0: successful execution.
2132 - 0: successful execution.
2133 - 1: an error occurred.
2133 - 1: an error occurred.
2134 """
2134 """
2135
2135
2136 # Set our own excepthook in case the user code tries to call it
2136 # Set our own excepthook in case the user code tries to call it
2137 # directly, so that the IPython crash handler doesn't get triggered
2137 # directly, so that the IPython crash handler doesn't get triggered
2138 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2138 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2139
2139
2140 # we save the original sys.excepthook in the instance, in case config
2140 # we save the original sys.excepthook in the instance, in case config
2141 # code (such as magics) needs access to it.
2141 # code (such as magics) needs access to it.
2142 self.sys_excepthook = old_excepthook
2142 self.sys_excepthook = old_excepthook
2143 outflag = 1 # happens in more places, so it's easier as default
2143 outflag = 1 # happens in more places, so it's easier as default
2144 try:
2144 try:
2145 try:
2145 try:
2146 self.hooks.pre_runcode_hook()
2146 self.hooks.pre_runcode_hook()
2147 exec code_obj in self.user_global_ns, self.user_ns
2147 exec code_obj in self.user_global_ns, self.user_ns
2148 finally:
2148 finally:
2149 # Reset our crash handler in place
2149 # Reset our crash handler in place
2150 sys.excepthook = old_excepthook
2150 sys.excepthook = old_excepthook
2151 except SystemExit:
2151 except SystemExit:
2152 self.resetbuffer()
2152 self.resetbuffer()
2153 self.showtraceback()
2153 self.showtraceback()
2154 warn("Type %exit or %quit to exit IPython "
2154 warn("Type %exit or %quit to exit IPython "
2155 "(%Exit or %Quit do so unconditionally).",level=1)
2155 "(%Exit or %Quit do so unconditionally).",level=1)
2156 except self.custom_exceptions:
2156 except self.custom_exceptions:
2157 etype,value,tb = sys.exc_info()
2157 etype,value,tb = sys.exc_info()
2158 self.CustomTB(etype,value,tb)
2158 self.CustomTB(etype,value,tb)
2159 except:
2159 except:
2160 self.showtraceback()
2160 self.showtraceback()
2161 else:
2161 else:
2162 outflag = 0
2162 outflag = 0
2163 if softspace(sys.stdout, 0):
2163 if softspace(sys.stdout, 0):
2164 print
2164 print
2165 # Flush out code object which has been run (and source)
2165 # Flush out code object which has been run (and source)
2166 self.code_to_run = None
2166 self.code_to_run = None
2167 return outflag
2167 return outflag
2168
2168
2169 def push_line(self, line):
2169 def push_line(self, line):
2170 """Push a line to the interpreter.
2170 """Push a line to the interpreter.
2171
2171
2172 The line should not have a trailing newline; it may have
2172 The line should not have a trailing newline; it may have
2173 internal newlines. The line is appended to a buffer and the
2173 internal newlines. The line is appended to a buffer and the
2174 interpreter's runsource() method is called with the
2174 interpreter's runsource() method is called with the
2175 concatenated contents of the buffer as source. If this
2175 concatenated contents of the buffer as source. If this
2176 indicates that the command was executed or invalid, the buffer
2176 indicates that the command was executed or invalid, the buffer
2177 is reset; otherwise, the command is incomplete, and the buffer
2177 is reset; otherwise, the command is incomplete, and the buffer
2178 is left as it was after the line was appended. The return
2178 is left as it was after the line was appended. The return
2179 value is 1 if more input is required, 0 if the line was dealt
2179 value is 1 if more input is required, 0 if the line was dealt
2180 with in some way (this is the same as runsource()).
2180 with in some way (this is the same as runsource()).
2181 """
2181 """
2182
2182
2183 # autoindent management should be done here, and not in the
2183 # autoindent management should be done here, and not in the
2184 # interactive loop, since that one is only seen by keyboard input. We
2184 # interactive loop, since that one is only seen by keyboard input. We
2185 # need this done correctly even for code run via runlines (which uses
2185 # need this done correctly even for code run via runlines (which uses
2186 # push).
2186 # push).
2187
2187
2188 #print 'push line: <%s>' % line # dbg
2188 #print 'push line: <%s>' % line # dbg
2189 for subline in line.splitlines():
2189 for subline in line.splitlines():
2190 self._autoindent_update(subline)
2190 self._autoindent_update(subline)
2191 self.buffer.append(line)
2191 self.buffer.append(line)
2192 more = self.runsource('\n'.join(self.buffer), self.filename)
2192 more = self.runsource('\n'.join(self.buffer), self.filename)
2193 if not more:
2193 if not more:
2194 self.resetbuffer()
2194 self.resetbuffer()
2195 return more
2195 return more
2196
2196
2197 def _autoindent_update(self,line):
2197 def _autoindent_update(self,line):
2198 """Keep track of the indent level."""
2198 """Keep track of the indent level."""
2199
2199
2200 #debugx('line')
2200 #debugx('line')
2201 #debugx('self.indent_current_nsp')
2201 #debugx('self.indent_current_nsp')
2202 if self.autoindent:
2202 if self.autoindent:
2203 if line:
2203 if line:
2204 inisp = num_ini_spaces(line)
2204 inisp = num_ini_spaces(line)
2205 if inisp < self.indent_current_nsp:
2205 if inisp < self.indent_current_nsp:
2206 self.indent_current_nsp = inisp
2206 self.indent_current_nsp = inisp
2207
2207
2208 if line[-1] == ':':
2208 if line[-1] == ':':
2209 self.indent_current_nsp += 4
2209 self.indent_current_nsp += 4
2210 elif dedent_re.match(line):
2210 elif dedent_re.match(line):
2211 self.indent_current_nsp -= 4
2211 self.indent_current_nsp -= 4
2212 else:
2212 else:
2213 self.indent_current_nsp = 0
2213 self.indent_current_nsp = 0
2214
2214
2215 def resetbuffer(self):
2215 def resetbuffer(self):
2216 """Reset the input buffer."""
2216 """Reset the input buffer."""
2217 self.buffer[:] = []
2217 self.buffer[:] = []
2218
2218
2219 def raw_input(self,prompt='',continue_prompt=False):
2219 def raw_input(self,prompt='',continue_prompt=False):
2220 """Write a prompt and read a line.
2220 """Write a prompt and read a line.
2221
2221
2222 The returned line does not include the trailing newline.
2222 The returned line does not include the trailing newline.
2223 When the user enters the EOF key sequence, EOFError is raised.
2223 When the user enters the EOF key sequence, EOFError is raised.
2224
2224
2225 Optional inputs:
2225 Optional inputs:
2226
2226
2227 - prompt(''): a string to be printed to prompt the user.
2227 - prompt(''): a string to be printed to prompt the user.
2228
2228
2229 - continue_prompt(False): whether this line is the first one or a
2229 - continue_prompt(False): whether this line is the first one or a
2230 continuation in a sequence of inputs.
2230 continuation in a sequence of inputs.
2231 """
2231 """
2232 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
2232 # growl.notify("raw_input: ", "prompt = %r\ncontinue_prompt = %s" % (prompt, continue_prompt))
2233
2233
2234 # Code run by the user may have modified the readline completer state.
2234 # Code run by the user may have modified the readline completer state.
2235 # We must ensure that our completer is back in place.
2235 # We must ensure that our completer is back in place.
2236
2236
2237 if self.has_readline:
2237 if self.has_readline:
2238 self.set_completer()
2238 self.set_completer()
2239
2239
2240 try:
2240 try:
2241 line = raw_input_original(prompt).decode(self.stdin_encoding)
2241 line = raw_input_original(prompt).decode(self.stdin_encoding)
2242 except ValueError:
2242 except ValueError:
2243 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2243 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
2244 " or sys.stdout.close()!\nExiting IPython!")
2244 " or sys.stdout.close()!\nExiting IPython!")
2245 self.ask_exit()
2245 self.ask_exit()
2246 return ""
2246 return ""
2247
2247
2248 # Try to be reasonably smart about not re-indenting pasted input more
2248 # Try to be reasonably smart about not re-indenting pasted input more
2249 # than necessary. We do this by trimming out the auto-indent initial
2249 # than necessary. We do this by trimming out the auto-indent initial
2250 # spaces, if the user's actual input started itself with whitespace.
2250 # spaces, if the user's actual input started itself with whitespace.
2251 #debugx('self.buffer[-1]')
2251 #debugx('self.buffer[-1]')
2252
2252
2253 if self.autoindent:
2253 if self.autoindent:
2254 if num_ini_spaces(line) > self.indent_current_nsp:
2254 if num_ini_spaces(line) > self.indent_current_nsp:
2255 line = line[self.indent_current_nsp:]
2255 line = line[self.indent_current_nsp:]
2256 self.indent_current_nsp = 0
2256 self.indent_current_nsp = 0
2257
2257
2258 # store the unfiltered input before the user has any chance to modify
2258 # store the unfiltered input before the user has any chance to modify
2259 # it.
2259 # it.
2260 if line.strip():
2260 if line.strip():
2261 if continue_prompt:
2261 if continue_prompt:
2262 self.input_hist_raw[-1] += '%s\n' % line
2262 self.input_hist_raw[-1] += '%s\n' % line
2263 if self.has_readline and self.readline_use:
2263 if self.has_readline and self.readline_use:
2264 try:
2264 try:
2265 histlen = self.readline.get_current_history_length()
2265 histlen = self.readline.get_current_history_length()
2266 if histlen > 1:
2266 if histlen > 1:
2267 newhist = self.input_hist_raw[-1].rstrip()
2267 newhist = self.input_hist_raw[-1].rstrip()
2268 self.readline.remove_history_item(histlen-1)
2268 self.readline.remove_history_item(histlen-1)
2269 self.readline.replace_history_item(histlen-2,
2269 self.readline.replace_history_item(histlen-2,
2270 newhist.encode(self.stdin_encoding))
2270 newhist.encode(self.stdin_encoding))
2271 except AttributeError:
2271 except AttributeError:
2272 pass # re{move,place}_history_item are new in 2.4.
2272 pass # re{move,place}_history_item are new in 2.4.
2273 else:
2273 else:
2274 self.input_hist_raw.append('%s\n' % line)
2274 self.input_hist_raw.append('%s\n' % line)
2275 # only entries starting at first column go to shadow history
2275 # only entries starting at first column go to shadow history
2276 if line.lstrip() == line:
2276 if line.lstrip() == line:
2277 self.shadowhist.add(line.strip())
2277 self.shadowhist.add(line.strip())
2278 elif not continue_prompt:
2278 elif not continue_prompt:
2279 self.input_hist_raw.append('\n')
2279 self.input_hist_raw.append('\n')
2280 try:
2280 try:
2281 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2281 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
2282 except:
2282 except:
2283 # blanket except, in case a user-defined prefilter crashes, so it
2283 # blanket except, in case a user-defined prefilter crashes, so it
2284 # can't take all of ipython with it.
2284 # can't take all of ipython with it.
2285 self.showtraceback()
2285 self.showtraceback()
2286 return ''
2286 return ''
2287 else:
2287 else:
2288 return lineout
2288 return lineout
2289
2289
2290 #-------------------------------------------------------------------------
2290 #-------------------------------------------------------------------------
2291 # Working with components
2291 # Working with components
2292 #-------------------------------------------------------------------------
2292 #-------------------------------------------------------------------------
2293
2293
2294 def get_component(self, name=None, klass=None):
2294 def get_component(self, name=None, klass=None):
2295 """Fetch a component by name and klass in my tree."""
2295 """Fetch a component by name and klass in my tree."""
2296 c = Component.get_instances(root=self, name=name, klass=klass)
2296 c = Component.get_instances(root=self, name=name, klass=klass)
2297 if len(c) == 0:
2298 return None
2297 if len(c) == 1:
2299 if len(c) == 1:
2298 return c[0]
2300 return c[0]
2299 else:
2301 else:
2300 return c
2302 return c
2301
2303
2302 #-------------------------------------------------------------------------
2304 #-------------------------------------------------------------------------
2303 # IPython extensions
2305 # IPython extensions
2304 #-------------------------------------------------------------------------
2306 #-------------------------------------------------------------------------
2305
2307
2306 def load_extension(self, module_str):
2308 def load_extension(self, module_str):
2307 """Load an IPython extension by its module name.
2309 """Load an IPython extension by its module name.
2308
2310
2309 An IPython extension is an importable Python module that has
2311 An IPython extension is an importable Python module that has
2310 a function with the signature::
2312 a function with the signature::
2311
2313
2312 def load_ipython_extension(ipython):
2314 def load_ipython_extension(ipython):
2313 # Do things with ipython
2315 # Do things with ipython
2314
2316
2315 This function is called after your extension is imported and the
2317 This function is called after your extension is imported and the
2316 currently active :class:`InteractiveShell` instance is passed as
2318 currently active :class:`InteractiveShell` instance is passed as
2317 the only argument. You can do anything you want with IPython at
2319 the only argument. You can do anything you want with IPython at
2318 that point, including defining new magic and aliases, adding new
2320 that point, including defining new magic and aliases, adding new
2319 components, etc.
2321 components, etc.
2320
2322
2321 The :func:`load_ipython_extension` will be called again is you
2323 The :func:`load_ipython_extension` will be called again is you
2322 load or reload the extension again. It is up to the extension
2324 load or reload the extension again. It is up to the extension
2323 author to add code to manage that.
2325 author to add code to manage that.
2324
2326
2325 You can put your extension modules anywhere you want, as long as
2327 You can put your extension modules anywhere you want, as long as
2326 they can be imported by Python's standard import mechanism. However,
2328 they can be imported by Python's standard import mechanism. However,
2327 to make it easy to write extensions, you can also put your extensions
2329 to make it easy to write extensions, you can also put your extensions
2328 in ``os.path.join(self.ipythondir, 'extensions')``. This directory
2330 in ``os.path.join(self.ipythondir, 'extensions')``. This directory
2329 is added to ``sys.path`` automatically.
2331 is added to ``sys.path`` automatically.
2330 """
2332 """
2331 from IPython.utils.syspathcontext import prepended_to_syspath
2333 from IPython.utils.syspathcontext import prepended_to_syspath
2332
2334
2333 if module_str not in sys.modules:
2335 if module_str not in sys.modules:
2334 with prepended_to_syspath(self.ipython_extension_dir):
2336 with prepended_to_syspath(self.ipython_extension_dir):
2335 __import__(module_str)
2337 __import__(module_str)
2336 mod = sys.modules[module_str]
2338 mod = sys.modules[module_str]
2337 self._call_load_ipython_extension(mod)
2339 self._call_load_ipython_extension(mod)
2338
2340
2339 def unload_extension(self, module_str):
2341 def unload_extension(self, module_str):
2340 """Unload an IPython extension by its module name.
2342 """Unload an IPython extension by its module name.
2341
2343
2342 This function looks up the extension's name in ``sys.modules`` and
2344 This function looks up the extension's name in ``sys.modules`` and
2343 simply calls ``mod.unload_ipython_extension(self)``.
2345 simply calls ``mod.unload_ipython_extension(self)``.
2344 """
2346 """
2345 if module_str in sys.modules:
2347 if module_str in sys.modules:
2346 mod = sys.modules[module_str]
2348 mod = sys.modules[module_str]
2347 self._call_unload_ipython_extension(mod)
2349 self._call_unload_ipython_extension(mod)
2348
2350
2349 def reload_extension(self, module_str):
2351 def reload_extension(self, module_str):
2350 """Reload an IPython extension by calling reload.
2352 """Reload an IPython extension by calling reload.
2351
2353
2352 If the module has not been loaded before,
2354 If the module has not been loaded before,
2353 :meth:`InteractiveShell.load_extension` is called. Otherwise
2355 :meth:`InteractiveShell.load_extension` is called. Otherwise
2354 :func:`reload` is called and then the :func:`load_ipython_extension`
2356 :func:`reload` is called and then the :func:`load_ipython_extension`
2355 function of the module, if it exists is called.
2357 function of the module, if it exists is called.
2356 """
2358 """
2357 from IPython.utils.syspathcontext import prepended_to_syspath
2359 from IPython.utils.syspathcontext import prepended_to_syspath
2358
2360
2359 with prepended_to_syspath(self.ipython_extension_dir):
2361 with prepended_to_syspath(self.ipython_extension_dir):
2360 if module_str in sys.modules:
2362 if module_str in sys.modules:
2361 mod = sys.modules[module_str]
2363 mod = sys.modules[module_str]
2362 reload(mod)
2364 reload(mod)
2363 self._call_load_ipython_extension(mod)
2365 self._call_load_ipython_extension(mod)
2364 else:
2366 else:
2365 self.load_extension(module_str)
2367 self.load_extension(module_str)
2366
2368
2367 def _call_load_ipython_extension(self, mod):
2369 def _call_load_ipython_extension(self, mod):
2368 if hasattr(mod, 'load_ipython_extension'):
2370 if hasattr(mod, 'load_ipython_extension'):
2369 mod.load_ipython_extension(self)
2371 mod.load_ipython_extension(self)
2370
2372
2371 def _call_unload_ipython_extension(self, mod):
2373 def _call_unload_ipython_extension(self, mod):
2372 if hasattr(mod, 'unload_ipython_extension'):
2374 if hasattr(mod, 'unload_ipython_extension'):
2373 mod.unload_ipython_extension(self)
2375 mod.unload_ipython_extension(self)
2374
2376
2375 #-------------------------------------------------------------------------
2377 #-------------------------------------------------------------------------
2376 # Things related to the prefilter
2378 # Things related to the prefilter
2377 #-------------------------------------------------------------------------
2379 #-------------------------------------------------------------------------
2378
2380
2379 def init_prefilter(self):
2381 def init_prefilter(self):
2380 self.prefilter_manager = PrefilterManager(self, config=self.config)
2382 self.prefilter_manager = PrefilterManager(self, config=self.config)
2381
2383
2382 #-------------------------------------------------------------------------
2384 #-------------------------------------------------------------------------
2383 # Utilities
2385 # Utilities
2384 #-------------------------------------------------------------------------
2386 #-------------------------------------------------------------------------
2385
2387
2386 def getoutput(self, cmd):
2388 def getoutput(self, cmd):
2387 return getoutput(self.var_expand(cmd,depth=2),
2389 return getoutput(self.var_expand(cmd,depth=2),
2388 header=self.system_header,
2390 header=self.system_header,
2389 verbose=self.system_verbose)
2391 verbose=self.system_verbose)
2390
2392
2391 def getoutputerror(self, cmd):
2393 def getoutputerror(self, cmd):
2392 return getoutputerror(self.var_expand(cmd,depth=2),
2394 return getoutputerror(self.var_expand(cmd,depth=2),
2393 header=self.system_header,
2395 header=self.system_header,
2394 verbose=self.system_verbose)
2396 verbose=self.system_verbose)
2395
2397
2396 def var_expand(self,cmd,depth=0):
2398 def var_expand(self,cmd,depth=0):
2397 """Expand python variables in a string.
2399 """Expand python variables in a string.
2398
2400
2399 The depth argument indicates how many frames above the caller should
2401 The depth argument indicates how many frames above the caller should
2400 be walked to look for the local namespace where to expand variables.
2402 be walked to look for the local namespace where to expand variables.
2401
2403
2402 The global namespace for expansion is always the user's interactive
2404 The global namespace for expansion is always the user's interactive
2403 namespace.
2405 namespace.
2404 """
2406 """
2405
2407
2406 return str(ItplNS(cmd,
2408 return str(ItplNS(cmd,
2407 self.user_ns, # globals
2409 self.user_ns, # globals
2408 # Skip our own frame in searching for locals:
2410 # Skip our own frame in searching for locals:
2409 sys._getframe(depth+1).f_locals # locals
2411 sys._getframe(depth+1).f_locals # locals
2410 ))
2412 ))
2411
2413
2412 def mktempfile(self,data=None):
2414 def mktempfile(self,data=None):
2413 """Make a new tempfile and return its filename.
2415 """Make a new tempfile and return its filename.
2414
2416
2415 This makes a call to tempfile.mktemp, but it registers the created
2417 This makes a call to tempfile.mktemp, but it registers the created
2416 filename internally so ipython cleans it up at exit time.
2418 filename internally so ipython cleans it up at exit time.
2417
2419
2418 Optional inputs:
2420 Optional inputs:
2419
2421
2420 - data(None): if data is given, it gets written out to the temp file
2422 - data(None): if data is given, it gets written out to the temp file
2421 immediately, and the file is closed again."""
2423 immediately, and the file is closed again."""
2422
2424
2423 filename = tempfile.mktemp('.py','ipython_edit_')
2425 filename = tempfile.mktemp('.py','ipython_edit_')
2424 self.tempfiles.append(filename)
2426 self.tempfiles.append(filename)
2425
2427
2426 if data:
2428 if data:
2427 tmp_file = open(filename,'w')
2429 tmp_file = open(filename,'w')
2428 tmp_file.write(data)
2430 tmp_file.write(data)
2429 tmp_file.close()
2431 tmp_file.close()
2430 return filename
2432 return filename
2431
2433
2432 def write(self,data):
2434 def write(self,data):
2433 """Write a string to the default output"""
2435 """Write a string to the default output"""
2434 Term.cout.write(data)
2436 Term.cout.write(data)
2435
2437
2436 def write_err(self,data):
2438 def write_err(self,data):
2437 """Write a string to the default error output"""
2439 """Write a string to the default error output"""
2438 Term.cerr.write(data)
2440 Term.cerr.write(data)
2439
2441
2440 def ask_yes_no(self,prompt,default=True):
2442 def ask_yes_no(self,prompt,default=True):
2441 if self.quiet:
2443 if self.quiet:
2442 return True
2444 return True
2443 return ask_yes_no(prompt,default)
2445 return ask_yes_no(prompt,default)
2444
2446
2445 #-------------------------------------------------------------------------
2447 #-------------------------------------------------------------------------
2446 # Things related to IPython exiting
2448 # Things related to IPython exiting
2447 #-------------------------------------------------------------------------
2449 #-------------------------------------------------------------------------
2448
2450
2449 def ask_exit(self):
2451 def ask_exit(self):
2450 """ Call for exiting. Can be overiden and used as a callback. """
2452 """ Call for exiting. Can be overiden and used as a callback. """
2451 self.exit_now = True
2453 self.exit_now = True
2452
2454
2453 def exit(self):
2455 def exit(self):
2454 """Handle interactive exit.
2456 """Handle interactive exit.
2455
2457
2456 This method calls the ask_exit callback."""
2458 This method calls the ask_exit callback."""
2457 if self.confirm_exit:
2459 if self.confirm_exit:
2458 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2460 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
2459 self.ask_exit()
2461 self.ask_exit()
2460 else:
2462 else:
2461 self.ask_exit()
2463 self.ask_exit()
2462
2464
2463 def atexit_operations(self):
2465 def atexit_operations(self):
2464 """This will be executed at the time of exit.
2466 """This will be executed at the time of exit.
2465
2467
2466 Saving of persistent data should be performed here.
2468 Saving of persistent data should be performed here.
2467 """
2469 """
2468 self.savehist()
2470 self.savehist()
2469
2471
2470 # Cleanup all tempfiles left around
2472 # Cleanup all tempfiles left around
2471 for tfile in self.tempfiles:
2473 for tfile in self.tempfiles:
2472 try:
2474 try:
2473 os.unlink(tfile)
2475 os.unlink(tfile)
2474 except OSError:
2476 except OSError:
2475 pass
2477 pass
2476
2478
2477 # Clear all user namespaces to release all references cleanly.
2479 # Clear all user namespaces to release all references cleanly.
2478 self.reset()
2480 self.reset()
2479
2481
2480 # Run user hooks
2482 # Run user hooks
2481 self.hooks.shutdown_hook()
2483 self.hooks.shutdown_hook()
2482
2484
2483 def cleanup(self):
2485 def cleanup(self):
2484 self.restore_sys_module_state()
2486 self.restore_sys_module_state()
2485
2487
2486
2488
@@ -1,963 +1,967 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 # -*- test-case-name: IPython.kernel.test.test_multiengineclient -*-
2 # -*- test-case-name: IPython.kernel.test.test_multiengineclient -*-
3
3
4 """General Classes for IMultiEngine clients."""
4 """General Classes for IMultiEngine clients."""
5
5
6 __docformat__ = "restructuredtext en"
6 __docformat__ = "restructuredtext en"
7
7
8 #-------------------------------------------------------------------------------
8 #-------------------------------------------------------------------------------
9 # Copyright (C) 2008 The IPython Development Team
9 # Copyright (C) 2008 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 sys
19 import sys
20 import linecache
20 import linecache
21 import warnings
21 import warnings
22
22
23 from twisted.python import components
23 from twisted.python import components
24 from twisted.python.failure import Failure
24 from twisted.python.failure import Failure
25 from zope.interface import Interface, implements, Attribute
25 from zope.interface import Interface, implements, Attribute
26
26
27 from IPython.utils.coloransi import TermColors
27 from IPython.utils.coloransi import TermColors
28
28
29 from IPython.kernel.twistedutil import blockingCallFromThread
29 from IPython.kernel.twistedutil import blockingCallFromThread
30 from IPython.kernel import error
30 from IPython.kernel import error
31 from IPython.kernel.parallelfunction import ParallelFunction
31 from IPython.kernel.parallelfunction import ParallelFunction
32 from IPython.kernel.mapper import (
32 from IPython.kernel.mapper import (
33 MultiEngineMapper,
33 MultiEngineMapper,
34 IMultiEngineMapperFactory,
34 IMultiEngineMapperFactory,
35 IMapper
35 IMapper
36 )
36 )
37
37
38 from IPython.kernel.multiengine import IFullSynchronousMultiEngine
38 from IPython.kernel.multiengine import IFullSynchronousMultiEngine
39
39
40
40
41 #-------------------------------------------------------------------------------
41 #-------------------------------------------------------------------------------
42 # Pending Result things
42 # Pending Result things
43 #-------------------------------------------------------------------------------
43 #-------------------------------------------------------------------------------
44
44
45 class IPendingResult(Interface):
45 class IPendingResult(Interface):
46 """A representation of a result that is pending.
46 """A representation of a result that is pending.
47
47
48 This class is similar to Twisted's `Deferred` object, but is designed to be
48 This class is similar to Twisted's `Deferred` object, but is designed to be
49 used in a synchronous context.
49 used in a synchronous context.
50 """
50 """
51
51
52 result_id=Attribute("ID of the deferred on the other side")
52 result_id=Attribute("ID of the deferred on the other side")
53 client=Attribute("A client that I came from")
53 client=Attribute("A client that I came from")
54 r=Attribute("An attribute that is a property that calls and returns get_result")
54 r=Attribute("An attribute that is a property that calls and returns get_result")
55
55
56 def get_result(default=None, block=True):
56 def get_result(default=None, block=True):
57 """
57 """
58 Get a result that is pending.
58 Get a result that is pending.
59
59
60 :Parameters:
60 :Parameters:
61 default
61 default
62 The value to return if the result is not ready.
62 The value to return if the result is not ready.
63 block : boolean
63 block : boolean
64 Should I block for the result.
64 Should I block for the result.
65
65
66 :Returns: The actual result or the default value.
66 :Returns: The actual result or the default value.
67 """
67 """
68
68
69 def add_callback(f, *args, **kwargs):
69 def add_callback(f, *args, **kwargs):
70 """
70 """
71 Add a callback that is called with the result.
71 Add a callback that is called with the result.
72
72
73 If the original result is foo, adding a callback will cause
73 If the original result is foo, adding a callback will cause
74 f(foo, *args, **kwargs) to be returned instead. If multiple
74 f(foo, *args, **kwargs) to be returned instead. If multiple
75 callbacks are registered, they are chained together: the result of
75 callbacks are registered, they are chained together: the result of
76 one is passed to the next and so on.
76 one is passed to the next and so on.
77
77
78 Unlike Twisted's Deferred object, there is no errback chain. Thus
78 Unlike Twisted's Deferred object, there is no errback chain. Thus
79 any exception raised will not be caught and handled. User must
79 any exception raised will not be caught and handled. User must
80 catch these by hand when calling `get_result`.
80 catch these by hand when calling `get_result`.
81 """
81 """
82
82
83
83
84 class PendingResult(object):
84 class PendingResult(object):
85 """A representation of a result that is not yet ready.
85 """A representation of a result that is not yet ready.
86
86
87 A user should not create a `PendingResult` instance by hand.
87 A user should not create a `PendingResult` instance by hand.
88
88
89 Methods:
89 Methods:
90
90
91 * `get_result`
91 * `get_result`
92 * `add_callback`
92 * `add_callback`
93
93
94 Properties:
94 Properties:
95
95
96 * `r`
96 * `r`
97 """
97 """
98
98
99 def __init__(self, client, result_id):
99 def __init__(self, client, result_id):
100 """Create a PendingResult with a result_id and a client instance.
100 """Create a PendingResult with a result_id and a client instance.
101
101
102 The client should implement `_getPendingResult(result_id, block)`.
102 The client should implement `_getPendingResult(result_id, block)`.
103 """
103 """
104 self.client = client
104 self.client = client
105 self.result_id = result_id
105 self.result_id = result_id
106 self.called = False
106 self.called = False
107 self.raised = False
107 self.raised = False
108 self.callbacks = []
108 self.callbacks = []
109
109
110 def get_result(self, default=None, block=True):
110 def get_result(self, default=None, block=True):
111 """Get a result that is pending.
111 """Get a result that is pending.
112
112
113 This method will connect to an IMultiEngine adapted controller
113 This method will connect to an IMultiEngine adapted controller
114 and see if the result is ready. If the action triggers an exception
114 and see if the result is ready. If the action triggers an exception
115 raise it and record it. This method records the result/exception once it is
115 raise it and record it. This method records the result/exception once it is
116 retrieved. Calling `get_result` again will get this cached result or will
116 retrieved. Calling `get_result` again will get this cached result or will
117 re-raise the exception. The .r attribute is a property that calls
117 re-raise the exception. The .r attribute is a property that calls
118 `get_result` with block=True.
118 `get_result` with block=True.
119
119
120 :Parameters:
120 :Parameters:
121 default
121 default
122 The value to return if the result is not ready.
122 The value to return if the result is not ready.
123 block : boolean
123 block : boolean
124 Should I block for the result.
124 Should I block for the result.
125
125
126 :Returns: The actual result or the default value.
126 :Returns: The actual result or the default value.
127 """
127 """
128
128
129 if self.called:
129 if self.called:
130 if self.raised:
130 if self.raised:
131 raise self.result[0], self.result[1], self.result[2]
131 raise self.result[0], self.result[1], self.result[2]
132 else:
132 else:
133 return self.result
133 return self.result
134 try:
134 try:
135 result = self.client.get_pending_deferred(self.result_id, block)
135 result = self.client.get_pending_deferred(self.result_id, block)
136 except error.ResultNotCompleted:
136 except error.ResultNotCompleted:
137 return default
137 return default
138 except:
138 except:
139 # Reraise other error, but first record them so they can be reraised
139 # Reraise other error, but first record them so they can be reraised
140 # later if .r or get_result is called again.
140 # later if .r or get_result is called again.
141 self.result = sys.exc_info()
141 self.result = sys.exc_info()
142 self.called = True
142 self.called = True
143 self.raised = True
143 self.raised = True
144 raise
144 raise
145 else:
145 else:
146 for cb in self.callbacks:
146 for cb in self.callbacks:
147 result = cb[0](result, *cb[1], **cb[2])
147 result = cb[0](result, *cb[1], **cb[2])
148 self.result = result
148 self.result = result
149 self.called = True
149 self.called = True
150 return result
150 return result
151
151
152 def add_callback(self, f, *args, **kwargs):
152 def add_callback(self, f, *args, **kwargs):
153 """Add a callback that is called with the result.
153 """Add a callback that is called with the result.
154
154
155 If the original result is result, adding a callback will cause
155 If the original result is result, adding a callback will cause
156 f(result, *args, **kwargs) to be returned instead. If multiple
156 f(result, *args, **kwargs) to be returned instead. If multiple
157 callbacks are registered, they are chained together: the result of
157 callbacks are registered, they are chained together: the result of
158 one is passed to the next and so on.
158 one is passed to the next and so on.
159
159
160 Unlike Twisted's Deferred object, there is no errback chain. Thus
160 Unlike Twisted's Deferred object, there is no errback chain. Thus
161 any exception raised will not be caught and handled. User must
161 any exception raised will not be caught and handled. User must
162 catch these by hand when calling `get_result`.
162 catch these by hand when calling `get_result`.
163 """
163 """
164 assert callable(f)
164 assert callable(f)
165 self.callbacks.append((f, args, kwargs))
165 self.callbacks.append((f, args, kwargs))
166
166
167 def __cmp__(self, other):
167 def __cmp__(self, other):
168 if self.result_id < other.result_id:
168 if self.result_id < other.result_id:
169 return -1
169 return -1
170 else:
170 else:
171 return 1
171 return 1
172
172
173 def _get_r(self):
173 def _get_r(self):
174 return self.get_result(block=True)
174 return self.get_result(block=True)
175
175
176 r = property(_get_r)
176 r = property(_get_r)
177 """This property is a shortcut to a `get_result(block=True)`."""
177 """This property is a shortcut to a `get_result(block=True)`."""
178
178
179
179
180 #-------------------------------------------------------------------------------
180 #-------------------------------------------------------------------------------
181 # Pretty printing wrappers for certain lists
181 # Pretty printing wrappers for certain lists
182 #-------------------------------------------------------------------------------
182 #-------------------------------------------------------------------------------
183
183
184 class ResultList(list):
184 class ResultList(list):
185 """A subclass of list that pretty prints the output of `execute`/`get_result`."""
185 """A subclass of list that pretty prints the output of `execute`/`get_result`."""
186
186
187 def __repr__(self):
187 def __repr__(self):
188 output = []
188 output = []
189 # These colored prompts were not working on Windows
189 # These colored prompts were not working on Windows
190 if sys.platform == 'win32':
190 if sys.platform == 'win32':
191 blue = normal = red = green = ''
191 blue = normal = red = green = ''
192 else:
192 else:
193 blue = TermColors.Blue
193 blue = TermColors.Blue
194 normal = TermColors.Normal
194 normal = TermColors.Normal
195 red = TermColors.Red
195 red = TermColors.Red
196 green = TermColors.Green
196 green = TermColors.Green
197 output.append("<Results List>\n")
197 output.append("<Results List>\n")
198 for cmd in self:
198 for cmd in self:
199 if isinstance(cmd, Failure):
199 if isinstance(cmd, Failure):
200 output.append(cmd)
200 output.append(cmd)
201 else:
201 else:
202 target = cmd.get('id',None)
202 target = cmd.get('id',None)
203 cmd_num = cmd.get('number',None)
203 cmd_num = cmd.get('number',None)
204 cmd_stdin = cmd.get('input',{}).get('translated','No Input')
204 cmd_stdin = cmd.get('input',{}).get('translated','No Input')
205 cmd_stdout = cmd.get('stdout', None)
205 cmd_stdout = cmd.get('stdout', None)
206 cmd_stderr = cmd.get('stderr', None)
206 cmd_stderr = cmd.get('stderr', None)
207 output.append("%s[%i]%s In [%i]:%s %s\n" % \
207 output.append("%s[%i]%s In [%i]:%s %s\n" % \
208 (green, target,
208 (green, target,
209 blue, cmd_num, normal, cmd_stdin))
209 blue, cmd_num, normal, cmd_stdin))
210 if cmd_stdout:
210 if cmd_stdout:
211 output.append("%s[%i]%s Out[%i]:%s %s\n" % \
211 output.append("%s[%i]%s Out[%i]:%s %s\n" % \
212 (green, target,
212 (green, target,
213 red, cmd_num, normal, cmd_stdout))
213 red, cmd_num, normal, cmd_stdout))
214 if cmd_stderr:
214 if cmd_stderr:
215 output.append("%s[%i]%s Err[%i]:\n%s %s" % \
215 output.append("%s[%i]%s Err[%i]:\n%s %s" % \
216 (green, target,
216 (green, target,
217 red, cmd_num, normal, cmd_stderr))
217 red, cmd_num, normal, cmd_stderr))
218 return ''.join(output)
218 return ''.join(output)
219
219
220
220
221 def wrapResultList(result):
221 def wrapResultList(result):
222 """A function that wraps the output of `execute`/`get_result` -> `ResultList`."""
222 """A function that wraps the output of `execute`/`get_result` -> `ResultList`."""
223 if len(result) == 0:
223 if len(result) == 0:
224 result = [result]
224 result = [result]
225 return ResultList(result)
225 return ResultList(result)
226
226
227
227
228 class QueueStatusList(list):
228 class QueueStatusList(list):
229 """A subclass of list that pretty prints the output of `queue_status`."""
229 """A subclass of list that pretty prints the output of `queue_status`."""
230
230
231 def __repr__(self):
231 def __repr__(self):
232 output = []
232 output = []
233 output.append("<Queue Status List>\n")
233 output.append("<Queue Status List>\n")
234 for e in self:
234 for e in self:
235 output.append("Engine: %s\n" % repr(e[0]))
235 output.append("Engine: %s\n" % repr(e[0]))
236 output.append(" Pending: %s\n" % repr(e[1]['pending']))
236 output.append(" Pending: %s\n" % repr(e[1]['pending']))
237 for q in e[1]['queue']:
237 for q in e[1]['queue']:
238 output.append(" Command: %s\n" % repr(q))
238 output.append(" Command: %s\n" % repr(q))
239 return ''.join(output)
239 return ''.join(output)
240
240
241
241
242 #-------------------------------------------------------------------------------
242 #-------------------------------------------------------------------------------
243 # InteractiveMultiEngineClient
243 # InteractiveMultiEngineClient
244 #-------------------------------------------------------------------------------
244 #-------------------------------------------------------------------------------
245
245
246 class InteractiveMultiEngineClient(object):
246 class InteractiveMultiEngineClient(object):
247 """A mixin class that add a few methods to a multiengine client.
247 """A mixin class that add a few methods to a multiengine client.
248
248
249 The methods in this mixin class are designed for interactive usage.
249 The methods in this mixin class are designed for interactive usage.
250 """
250 """
251
251
252 def activate(self):
252 def activate(self):
253 """Make this `MultiEngineClient` active for parallel magic commands.
253 """Make this `MultiEngineClient` active for parallel magic commands.
254
254
255 IPython has a magic command syntax to work with `MultiEngineClient` objects.
255 IPython has a magic command syntax to work with `MultiEngineClient` objects.
256 In a given IPython session there is a single active one. While
256 In a given IPython session there is a single active one. While
257 there can be many `MultiEngineClient` created and used by the user,
257 there can be many `MultiEngineClient` created and used by the user,
258 there is only one active one. The active `MultiEngineClient` is used whenever
258 there is only one active one. The active `MultiEngineClient` is used whenever
259 the magic commands %px and %autopx are used.
259 the magic commands %px and %autopx are used.
260
260
261 The activate() method is called on a given `MultiEngineClient` to make it
261 The activate() method is called on a given `MultiEngineClient` to make it
262 active. Once this has been done, the magic commands can be used.
262 active. Once this has been done, the magic commands can be used.
263 """
263 """
264
264
265 try:
265 try:
266 # This is injected into __builtins__.
266 # This is injected into __builtins__.
267 ip = get_ipython()
267 ip = get_ipython()
268 except NameError:
268 except NameError:
269 print "The IPython parallel magics (%result, %px, %autopx) only work within IPython."
269 print "The IPython parallel magics (%result, %px, %autopx) only work within IPython."
270 else:
270 else:
271 pmagic = ip.get_component('parallel_magic')
271 pmagic = ip.get_component('parallel_magic')
272 if pmagic is not None:
272 pmagic.active_multiengine_client = self
273 pmagic.active_multiengine_client = self
274 else:
275 print "You must first load the parallelmagic extension " \
276 "by doing '%load_ext parallelmagic'"
273
277
274 def __setitem__(self, key, value):
278 def __setitem__(self, key, value):
275 """Add a dictionary interface for pushing/pulling.
279 """Add a dictionary interface for pushing/pulling.
276
280
277 This functions as a shorthand for `push`.
281 This functions as a shorthand for `push`.
278
282
279 :Parameters:
283 :Parameters:
280 key : str
284 key : str
281 What to call the remote object.
285 What to call the remote object.
282 value : object
286 value : object
283 The local Python object to push.
287 The local Python object to push.
284 """
288 """
285 targets, block = self._findTargetsAndBlock()
289 targets, block = self._findTargetsAndBlock()
286 return self.push({key:value}, targets=targets, block=block)
290 return self.push({key:value}, targets=targets, block=block)
287
291
288 def __getitem__(self, key):
292 def __getitem__(self, key):
289 """Add a dictionary interface for pushing/pulling.
293 """Add a dictionary interface for pushing/pulling.
290
294
291 This functions as a shorthand to `pull`.
295 This functions as a shorthand to `pull`.
292
296
293 :Parameters:
297 :Parameters:
294 - `key`: A string representing the key.
298 - `key`: A string representing the key.
295 """
299 """
296 if isinstance(key, str):
300 if isinstance(key, str):
297 targets, block = self._findTargetsAndBlock()
301 targets, block = self._findTargetsAndBlock()
298 return self.pull(key, targets=targets, block=block)
302 return self.pull(key, targets=targets, block=block)
299 else:
303 else:
300 raise TypeError("__getitem__ only takes strs")
304 raise TypeError("__getitem__ only takes strs")
301
305
302 def __len__(self):
306 def __len__(self):
303 """Return the number of available engines."""
307 """Return the number of available engines."""
304 return len(self.get_ids())
308 return len(self.get_ids())
305
309
306 #---------------------------------------------------------------------------
310 #---------------------------------------------------------------------------
307 # Make this a context manager for with
311 # Make this a context manager for with
308 #---------------------------------------------------------------------------
312 #---------------------------------------------------------------------------
309
313
310 def findsource_file(self,f):
314 def findsource_file(self,f):
311 linecache.checkcache()
315 linecache.checkcache()
312 s = findsource(f.f_code) # findsource is not defined!
316 s = findsource(f.f_code) # findsource is not defined!
313 lnum = f.f_lineno
317 lnum = f.f_lineno
314 wsource = s[0][f.f_lineno:]
318 wsource = s[0][f.f_lineno:]
315 return strip_whitespace(wsource)
319 return strip_whitespace(wsource)
316
320
317 def findsource_ipython(self,f):
321 def findsource_ipython(self,f):
318 from IPython.core import ipapi
322 from IPython.core import ipapi
319 self.ip = ipapi.get()
323 self.ip = ipapi.get()
320 wsource = [l+'\n' for l in
324 wsource = [l+'\n' for l in
321 self.ip.input_hist_raw[-1].splitlines()[1:]]
325 self.ip.input_hist_raw[-1].splitlines()[1:]]
322 return strip_whitespace(wsource)
326 return strip_whitespace(wsource)
323
327
324 def __enter__(self):
328 def __enter__(self):
325 f = sys._getframe(1)
329 f = sys._getframe(1)
326 local_ns = f.f_locals
330 local_ns = f.f_locals
327 global_ns = f.f_globals
331 global_ns = f.f_globals
328 if f.f_code.co_filename == '<ipython console>':
332 if f.f_code.co_filename == '<ipython console>':
329 s = self.findsource_ipython(f)
333 s = self.findsource_ipython(f)
330 else:
334 else:
331 s = self.findsource_file(f)
335 s = self.findsource_file(f)
332
336
333 self._with_context_result = self.execute(s)
337 self._with_context_result = self.execute(s)
334
338
335 def __exit__ (self, etype, value, tb):
339 def __exit__ (self, etype, value, tb):
336 if issubclass(etype,error.StopLocalExecution):
340 if issubclass(etype,error.StopLocalExecution):
337 return True
341 return True
338
342
339
343
340 def remote():
344 def remote():
341 m = 'Special exception to stop local execution of parallel code.'
345 m = 'Special exception to stop local execution of parallel code.'
342 raise error.StopLocalExecution(m)
346 raise error.StopLocalExecution(m)
343
347
344 def strip_whitespace(source):
348 def strip_whitespace(source):
345 # Expand tabs to avoid any confusion.
349 # Expand tabs to avoid any confusion.
346 wsource = [l.expandtabs(4) for l in source]
350 wsource = [l.expandtabs(4) for l in source]
347 # Detect the indentation level
351 # Detect the indentation level
348 done = False
352 done = False
349 for line in wsource:
353 for line in wsource:
350 if line.isspace():
354 if line.isspace():
351 continue
355 continue
352 for col,char in enumerate(line):
356 for col,char in enumerate(line):
353 if char != ' ':
357 if char != ' ':
354 done = True
358 done = True
355 break
359 break
356 if done:
360 if done:
357 break
361 break
358 # Now we know how much leading space there is in the code. Next, we
362 # Now we know how much leading space there is in the code. Next, we
359 # extract up to the first line that has less indentation.
363 # extract up to the first line that has less indentation.
360 # WARNINGS: we skip comments that may be misindented, but we do NOT yet
364 # WARNINGS: we skip comments that may be misindented, but we do NOT yet
361 # detect triple quoted strings that may have flush left text.
365 # detect triple quoted strings that may have flush left text.
362 for lno,line in enumerate(wsource):
366 for lno,line in enumerate(wsource):
363 lead = line[:col]
367 lead = line[:col]
364 if lead.isspace():
368 if lead.isspace():
365 continue
369 continue
366 else:
370 else:
367 if not lead.lstrip().startswith('#'):
371 if not lead.lstrip().startswith('#'):
368 break
372 break
369 # The real 'with' source is up to lno
373 # The real 'with' source is up to lno
370 src_lines = [l[col:] for l in wsource[:lno+1]]
374 src_lines = [l[col:] for l in wsource[:lno+1]]
371
375
372 # Finally, check that the source's first non-comment line begins with the
376 # Finally, check that the source's first non-comment line begins with the
373 # special call 'remote()'
377 # special call 'remote()'
374 for nline,line in enumerate(src_lines):
378 for nline,line in enumerate(src_lines):
375 if line.isspace() or line.startswith('#'):
379 if line.isspace() or line.startswith('#'):
376 continue
380 continue
377 if 'remote()' in line:
381 if 'remote()' in line:
378 break
382 break
379 else:
383 else:
380 raise ValueError('remote() call missing at the start of code')
384 raise ValueError('remote() call missing at the start of code')
381 src = ''.join(src_lines[nline+1:])
385 src = ''.join(src_lines[nline+1:])
382 #print 'SRC:\n<<<<<<<>>>>>>>\n%s<<<<<>>>>>>' % src # dbg
386 #print 'SRC:\n<<<<<<<>>>>>>>\n%s<<<<<>>>>>>' % src # dbg
383 return src
387 return src
384
388
385
389
386 #-------------------------------------------------------------------------------
390 #-------------------------------------------------------------------------------
387 # The top-level MultiEngine client adaptor
391 # The top-level MultiEngine client adaptor
388 #-------------------------------------------------------------------------------
392 #-------------------------------------------------------------------------------
389
393
390
394
391 _prop_warn = """\
395 _prop_warn = """\
392
396
393 We are currently refactoring the task dependency system. This might
397 We are currently refactoring the task dependency system. This might
394 involve the removal of this method and other methods related to engine
398 involve the removal of this method and other methods related to engine
395 properties. Please see the docstrings for IPython.kernel.TaskRejectError
399 properties. Please see the docstrings for IPython.kernel.TaskRejectError
396 for more information."""
400 for more information."""
397
401
398
402
399 class IFullBlockingMultiEngineClient(Interface):
403 class IFullBlockingMultiEngineClient(Interface):
400 pass
404 pass
401
405
402
406
403 class FullBlockingMultiEngineClient(InteractiveMultiEngineClient):
407 class FullBlockingMultiEngineClient(InteractiveMultiEngineClient):
404 """
408 """
405 A blocking client to the `IMultiEngine` controller interface.
409 A blocking client to the `IMultiEngine` controller interface.
406
410
407 This class allows users to use a set of engines for a parallel
411 This class allows users to use a set of engines for a parallel
408 computation through the `IMultiEngine` interface. In this interface,
412 computation through the `IMultiEngine` interface. In this interface,
409 each engine has a specific id (an int) that is used to refer to the
413 each engine has a specific id (an int) that is used to refer to the
410 engine, run code on it, etc.
414 engine, run code on it, etc.
411 """
415 """
412
416
413 implements(
417 implements(
414 IFullBlockingMultiEngineClient,
418 IFullBlockingMultiEngineClient,
415 IMultiEngineMapperFactory,
419 IMultiEngineMapperFactory,
416 IMapper
420 IMapper
417 )
421 )
418
422
419 def __init__(self, smultiengine):
423 def __init__(self, smultiengine):
420 self.smultiengine = smultiengine
424 self.smultiengine = smultiengine
421 self.block = True
425 self.block = True
422 self.targets = 'all'
426 self.targets = 'all'
423
427
424 def _findBlock(self, block=None):
428 def _findBlock(self, block=None):
425 if block is None:
429 if block is None:
426 return self.block
430 return self.block
427 else:
431 else:
428 if block in (True, False):
432 if block in (True, False):
429 return block
433 return block
430 else:
434 else:
431 raise ValueError("block must be True or False")
435 raise ValueError("block must be True or False")
432
436
433 def _findTargets(self, targets=None):
437 def _findTargets(self, targets=None):
434 if targets is None:
438 if targets is None:
435 return self.targets
439 return self.targets
436 else:
440 else:
437 if not isinstance(targets, (str,list,tuple,int)):
441 if not isinstance(targets, (str,list,tuple,int)):
438 raise ValueError("targets must be a str, list, tuple or int")
442 raise ValueError("targets must be a str, list, tuple or int")
439 return targets
443 return targets
440
444
441 def _findTargetsAndBlock(self, targets=None, block=None):
445 def _findTargetsAndBlock(self, targets=None, block=None):
442 return self._findTargets(targets), self._findBlock(block)
446 return self._findTargets(targets), self._findBlock(block)
443
447
444 def _blockFromThread(self, function, *args, **kwargs):
448 def _blockFromThread(self, function, *args, **kwargs):
445 block = kwargs.get('block', None)
449 block = kwargs.get('block', None)
446 if block is None:
450 if block is None:
447 raise error.MissingBlockArgument("'block' keyword argument is missing")
451 raise error.MissingBlockArgument("'block' keyword argument is missing")
448 result = blockingCallFromThread(function, *args, **kwargs)
452 result = blockingCallFromThread(function, *args, **kwargs)
449 if not block:
453 if not block:
450 result = PendingResult(self, result)
454 result = PendingResult(self, result)
451 return result
455 return result
452
456
453 def get_pending_deferred(self, deferredID, block):
457 def get_pending_deferred(self, deferredID, block):
454 return blockingCallFromThread(self.smultiengine.get_pending_deferred, deferredID, block)
458 return blockingCallFromThread(self.smultiengine.get_pending_deferred, deferredID, block)
455
459
456 def barrier(self, pendingResults):
460 def barrier(self, pendingResults):
457 """Synchronize a set of `PendingResults`.
461 """Synchronize a set of `PendingResults`.
458
462
459 This method is a synchronization primitive that waits for a set of
463 This method is a synchronization primitive that waits for a set of
460 `PendingResult` objects to complete. More specifically, barier does
464 `PendingResult` objects to complete. More specifically, barier does
461 the following.
465 the following.
462
466
463 * The `PendingResult`s are sorted by result_id.
467 * The `PendingResult`s are sorted by result_id.
464 * The `get_result` method is called for each `PendingResult` sequentially
468 * The `get_result` method is called for each `PendingResult` sequentially
465 with block=True.
469 with block=True.
466 * If a `PendingResult` gets a result that is an exception, it is
470 * If a `PendingResult` gets a result that is an exception, it is
467 trapped and can be re-raised later by calling `get_result` again.
471 trapped and can be re-raised later by calling `get_result` again.
468 * The `PendingResult`s are flushed from the controller.
472 * The `PendingResult`s are flushed from the controller.
469
473
470 After barrier has been called on a `PendingResult`, its results can
474 After barrier has been called on a `PendingResult`, its results can
471 be retrieved by calling `get_result` again or accesing the `r` attribute
475 be retrieved by calling `get_result` again or accesing the `r` attribute
472 of the instance.
476 of the instance.
473 """
477 """
474
478
475 # Convert to list for sorting and check class type
479 # Convert to list for sorting and check class type
476 prList = list(pendingResults)
480 prList = list(pendingResults)
477 for pr in prList:
481 for pr in prList:
478 if not isinstance(pr, PendingResult):
482 if not isinstance(pr, PendingResult):
479 raise error.NotAPendingResult("Objects passed to barrier must be PendingResult instances")
483 raise error.NotAPendingResult("Objects passed to barrier must be PendingResult instances")
480
484
481 # Sort the PendingResults so they are in order
485 # Sort the PendingResults so they are in order
482 prList.sort()
486 prList.sort()
483 # Block on each PendingResult object
487 # Block on each PendingResult object
484 for pr in prList:
488 for pr in prList:
485 try:
489 try:
486 result = pr.get_result(block=True)
490 result = pr.get_result(block=True)
487 except Exception:
491 except Exception:
488 pass
492 pass
489
493
490 def flush(self):
494 def flush(self):
491 """
495 """
492 Clear all pending deferreds/results from the controller.
496 Clear all pending deferreds/results from the controller.
493
497
494 For each `PendingResult` that is created by this client, the controller
498 For each `PendingResult` that is created by this client, the controller
495 holds on to the result for that `PendingResult`. This can be a problem
499 holds on to the result for that `PendingResult`. This can be a problem
496 if there are a large number of `PendingResult` objects that are created.
500 if there are a large number of `PendingResult` objects that are created.
497
501
498 Once the result of the `PendingResult` has been retrieved, the result
502 Once the result of the `PendingResult` has been retrieved, the result
499 is removed from the controller, but if a user doesn't get a result (
503 is removed from the controller, but if a user doesn't get a result (
500 they just ignore the `PendingResult`) the result is kept forever on the
504 they just ignore the `PendingResult`) the result is kept forever on the
501 controller. This method allows the user to clear out all un-retrieved
505 controller. This method allows the user to clear out all un-retrieved
502 results on the controller.
506 results on the controller.
503 """
507 """
504 r = blockingCallFromThread(self.smultiengine.clear_pending_deferreds)
508 r = blockingCallFromThread(self.smultiengine.clear_pending_deferreds)
505 return r
509 return r
506
510
507 clear_pending_results = flush
511 clear_pending_results = flush
508
512
509 #---------------------------------------------------------------------------
513 #---------------------------------------------------------------------------
510 # IEngineMultiplexer related methods
514 # IEngineMultiplexer related methods
511 #---------------------------------------------------------------------------
515 #---------------------------------------------------------------------------
512
516
513 def execute(self, lines, targets=None, block=None):
517 def execute(self, lines, targets=None, block=None):
514 """
518 """
515 Execute code on a set of engines.
519 Execute code on a set of engines.
516
520
517 :Parameters:
521 :Parameters:
518 lines : str
522 lines : str
519 The Python code to execute as a string
523 The Python code to execute as a string
520 targets : id or list of ids
524 targets : id or list of ids
521 The engine to use for the execution
525 The engine to use for the execution
522 block : boolean
526 block : boolean
523 If False, this method will return the actual result. If False,
527 If False, this method will return the actual result. If False,
524 a `PendingResult` is returned which can be used to get the result
528 a `PendingResult` is returned which can be used to get the result
525 at a later time.
529 at a later time.
526 """
530 """
527 targets, block = self._findTargetsAndBlock(targets, block)
531 targets, block = self._findTargetsAndBlock(targets, block)
528 result = blockingCallFromThread(self.smultiengine.execute, lines,
532 result = blockingCallFromThread(self.smultiengine.execute, lines,
529 targets=targets, block=block)
533 targets=targets, block=block)
530 if block:
534 if block:
531 result = ResultList(result)
535 result = ResultList(result)
532 else:
536 else:
533 result = PendingResult(self, result)
537 result = PendingResult(self, result)
534 result.add_callback(wrapResultList)
538 result.add_callback(wrapResultList)
535 return result
539 return result
536
540
537 def push(self, namespace, targets=None, block=None):
541 def push(self, namespace, targets=None, block=None):
538 """
542 """
539 Push a dictionary of keys and values to engines namespace.
543 Push a dictionary of keys and values to engines namespace.
540
544
541 Each engine has a persistent namespace. This method is used to push
545 Each engine has a persistent namespace. This method is used to push
542 Python objects into that namespace.
546 Python objects into that namespace.
543
547
544 The objects in the namespace must be pickleable.
548 The objects in the namespace must be pickleable.
545
549
546 :Parameters:
550 :Parameters:
547 namespace : dict
551 namespace : dict
548 A dict that contains Python objects to be injected into
552 A dict that contains Python objects to be injected into
549 the engine persistent namespace.
553 the engine persistent namespace.
550 targets : id or list of ids
554 targets : id or list of ids
551 The engine to use for the execution
555 The engine to use for the execution
552 block : boolean
556 block : boolean
553 If False, this method will return the actual result. If False,
557 If False, this method will return the actual result. If False,
554 a `PendingResult` is returned which can be used to get the result
558 a `PendingResult` is returned which can be used to get the result
555 at a later time.
559 at a later time.
556 """
560 """
557 targets, block = self._findTargetsAndBlock(targets, block)
561 targets, block = self._findTargetsAndBlock(targets, block)
558 return self._blockFromThread(self.smultiengine.push, namespace,
562 return self._blockFromThread(self.smultiengine.push, namespace,
559 targets=targets, block=block)
563 targets=targets, block=block)
560
564
561 def pull(self, keys, targets=None, block=None):
565 def pull(self, keys, targets=None, block=None):
562 """
566 """
563 Pull Python objects by key out of engines namespaces.
567 Pull Python objects by key out of engines namespaces.
564
568
565 :Parameters:
569 :Parameters:
566 keys : str or list of str
570 keys : str or list of str
567 The names of the variables to be pulled
571 The names of the variables to be pulled
568 targets : id or list of ids
572 targets : id or list of ids
569 The engine to use for the execution
573 The engine to use for the execution
570 block : boolean
574 block : boolean
571 If False, this method will return the actual result. If False,
575 If False, this method will return the actual result. If False,
572 a `PendingResult` is returned which can be used to get the result
576 a `PendingResult` is returned which can be used to get the result
573 at a later time.
577 at a later time.
574 """
578 """
575 targets, block = self._findTargetsAndBlock(targets, block)
579 targets, block = self._findTargetsAndBlock(targets, block)
576 return self._blockFromThread(self.smultiengine.pull, keys, targets=targets, block=block)
580 return self._blockFromThread(self.smultiengine.pull, keys, targets=targets, block=block)
577
581
578 def push_function(self, namespace, targets=None, block=None):
582 def push_function(self, namespace, targets=None, block=None):
579 """
583 """
580 Push a Python function to an engine.
584 Push a Python function to an engine.
581
585
582 This method is used to push a Python function to an engine. This
586 This method is used to push a Python function to an engine. This
583 method can then be used in code on the engines. Closures are not supported.
587 method can then be used in code on the engines. Closures are not supported.
584
588
585 :Parameters:
589 :Parameters:
586 namespace : dict
590 namespace : dict
587 A dict whose values are the functions to be pushed. The keys give
591 A dict whose values are the functions to be pushed. The keys give
588 that names that the function will appear as in the engines
592 that names that the function will appear as in the engines
589 namespace.
593 namespace.
590 targets : id or list of ids
594 targets : id or list of ids
591 The engine to use for the execution
595 The engine to use for the execution
592 block : boolean
596 block : boolean
593 If False, this method will return the actual result. If False,
597 If False, this method will return the actual result. If False,
594 a `PendingResult` is returned which can be used to get the result
598 a `PendingResult` is returned which can be used to get the result
595 at a later time.
599 at a later time.
596 """
600 """
597 targets, block = self._findTargetsAndBlock(targets, block)
601 targets, block = self._findTargetsAndBlock(targets, block)
598 return self._blockFromThread(self.smultiengine.push_function, namespace, targets=targets, block=block)
602 return self._blockFromThread(self.smultiengine.push_function, namespace, targets=targets, block=block)
599
603
600 def pull_function(self, keys, targets=None, block=None):
604 def pull_function(self, keys, targets=None, block=None):
601 """
605 """
602 Pull a Python function from an engine.
606 Pull a Python function from an engine.
603
607
604 This method is used to pull a Python function from an engine.
608 This method is used to pull a Python function from an engine.
605 Closures are not supported.
609 Closures are not supported.
606
610
607 :Parameters:
611 :Parameters:
608 keys : str or list of str
612 keys : str or list of str
609 The names of the functions to be pulled
613 The names of the functions to be pulled
610 targets : id or list of ids
614 targets : id or list of ids
611 The engine to use for the execution
615 The engine to use for the execution
612 block : boolean
616 block : boolean
613 If False, this method will return the actual result. If False,
617 If False, this method will return the actual result. If False,
614 a `PendingResult` is returned which can be used to get the result
618 a `PendingResult` is returned which can be used to get the result
615 at a later time.
619 at a later time.
616 """
620 """
617 targets, block = self._findTargetsAndBlock(targets, block)
621 targets, block = self._findTargetsAndBlock(targets, block)
618 return self._blockFromThread(self.smultiengine.pull_function, keys, targets=targets, block=block)
622 return self._blockFromThread(self.smultiengine.pull_function, keys, targets=targets, block=block)
619
623
620 def push_serialized(self, namespace, targets=None, block=None):
624 def push_serialized(self, namespace, targets=None, block=None):
621 targets, block = self._findTargetsAndBlock(targets, block)
625 targets, block = self._findTargetsAndBlock(targets, block)
622 return self._blockFromThread(self.smultiengine.push_serialized, namespace, targets=targets, block=block)
626 return self._blockFromThread(self.smultiengine.push_serialized, namespace, targets=targets, block=block)
623
627
624 def pull_serialized(self, keys, targets=None, block=None):
628 def pull_serialized(self, keys, targets=None, block=None):
625 targets, block = self._findTargetsAndBlock(targets, block)
629 targets, block = self._findTargetsAndBlock(targets, block)
626 return self._blockFromThread(self.smultiengine.pull_serialized, keys, targets=targets, block=block)
630 return self._blockFromThread(self.smultiengine.pull_serialized, keys, targets=targets, block=block)
627
631
628 def get_result(self, i=None, targets=None, block=None):
632 def get_result(self, i=None, targets=None, block=None):
629 """
633 """
630 Get a previous result.
634 Get a previous result.
631
635
632 When code is executed in an engine, a dict is created and returned. This
636 When code is executed in an engine, a dict is created and returned. This
633 method retrieves that dict for previous commands.
637 method retrieves that dict for previous commands.
634
638
635 :Parameters:
639 :Parameters:
636 i : int
640 i : int
637 The number of the result to get
641 The number of the result to get
638 targets : id or list of ids
642 targets : id or list of ids
639 The engine to use for the execution
643 The engine to use for the execution
640 block : boolean
644 block : boolean
641 If False, this method will return the actual result. If False,
645 If False, this method will return the actual result. If False,
642 a `PendingResult` is returned which can be used to get the result
646 a `PendingResult` is returned which can be used to get the result
643 at a later time.
647 at a later time.
644 """
648 """
645 targets, block = self._findTargetsAndBlock(targets, block)
649 targets, block = self._findTargetsAndBlock(targets, block)
646 result = blockingCallFromThread(self.smultiengine.get_result, i, targets=targets, block=block)
650 result = blockingCallFromThread(self.smultiengine.get_result, i, targets=targets, block=block)
647 if block:
651 if block:
648 result = ResultList(result)
652 result = ResultList(result)
649 else:
653 else:
650 result = PendingResult(self, result)
654 result = PendingResult(self, result)
651 result.add_callback(wrapResultList)
655 result.add_callback(wrapResultList)
652 return result
656 return result
653
657
654 def reset(self, targets=None, block=None):
658 def reset(self, targets=None, block=None):
655 """
659 """
656 Reset an engine.
660 Reset an engine.
657
661
658 This method clears out the namespace of an engine.
662 This method clears out the namespace of an engine.
659
663
660 :Parameters:
664 :Parameters:
661 targets : id or list of ids
665 targets : id or list of ids
662 The engine to use for the execution
666 The engine to use for the execution
663 block : boolean
667 block : boolean
664 If False, this method will return the actual result. If False,
668 If False, this method will return the actual result. If False,
665 a `PendingResult` is returned which can be used to get the result
669 a `PendingResult` is returned which can be used to get the result
666 at a later time.
670 at a later time.
667 """
671 """
668 targets, block = self._findTargetsAndBlock(targets, block)
672 targets, block = self._findTargetsAndBlock(targets, block)
669 return self._blockFromThread(self.smultiengine.reset, targets=targets, block=block)
673 return self._blockFromThread(self.smultiengine.reset, targets=targets, block=block)
670
674
671 def keys(self, targets=None, block=None):
675 def keys(self, targets=None, block=None):
672 """
676 """
673 Get a list of all the variables in an engine's namespace.
677 Get a list of all the variables in an engine's namespace.
674
678
675 :Parameters:
679 :Parameters:
676 targets : id or list of ids
680 targets : id or list of ids
677 The engine to use for the execution
681 The engine to use for the execution
678 block : boolean
682 block : boolean
679 If False, this method will return the actual result. If False,
683 If False, this method will return the actual result. If False,
680 a `PendingResult` is returned which can be used to get the result
684 a `PendingResult` is returned which can be used to get the result
681 at a later time.
685 at a later time.
682 """
686 """
683 targets, block = self._findTargetsAndBlock(targets, block)
687 targets, block = self._findTargetsAndBlock(targets, block)
684 return self._blockFromThread(self.smultiengine.keys, targets=targets, block=block)
688 return self._blockFromThread(self.smultiengine.keys, targets=targets, block=block)
685
689
686 def kill(self, controller=False, targets=None, block=None):
690 def kill(self, controller=False, targets=None, block=None):
687 """
691 """
688 Kill the engines and controller.
692 Kill the engines and controller.
689
693
690 This method is used to stop the engine and controller by calling
694 This method is used to stop the engine and controller by calling
691 `reactor.stop`.
695 `reactor.stop`.
692
696
693 :Parameters:
697 :Parameters:
694 controller : boolean
698 controller : boolean
695 If True, kill the engines and controller. If False, just the
699 If True, kill the engines and controller. If False, just the
696 engines
700 engines
697 targets : id or list of ids
701 targets : id or list of ids
698 The engine to use for the execution
702 The engine to use for the execution
699 block : boolean
703 block : boolean
700 If False, this method will return the actual result. If False,
704 If False, this method will return the actual result. If False,
701 a `PendingResult` is returned which can be used to get the result
705 a `PendingResult` is returned which can be used to get the result
702 at a later time.
706 at a later time.
703 """
707 """
704 targets, block = self._findTargetsAndBlock(targets, block)
708 targets, block = self._findTargetsAndBlock(targets, block)
705 return self._blockFromThread(self.smultiengine.kill, controller, targets=targets, block=block)
709 return self._blockFromThread(self.smultiengine.kill, controller, targets=targets, block=block)
706
710
707 def clear_queue(self, targets=None, block=None):
711 def clear_queue(self, targets=None, block=None):
708 """
712 """
709 Clear out the controller's queue for an engine.
713 Clear out the controller's queue for an engine.
710
714
711 The controller maintains a queue for each engine. This clear it out.
715 The controller maintains a queue for each engine. This clear it out.
712
716
713 :Parameters:
717 :Parameters:
714 targets : id or list of ids
718 targets : id or list of ids
715 The engine to use for the execution
719 The engine to use for the execution
716 block : boolean
720 block : boolean
717 If False, this method will return the actual result. If False,
721 If False, this method will return the actual result. If False,
718 a `PendingResult` is returned which can be used to get the result
722 a `PendingResult` is returned which can be used to get the result
719 at a later time.
723 at a later time.
720 """
724 """
721 targets, block = self._findTargetsAndBlock(targets, block)
725 targets, block = self._findTargetsAndBlock(targets, block)
722 return self._blockFromThread(self.smultiengine.clear_queue, targets=targets, block=block)
726 return self._blockFromThread(self.smultiengine.clear_queue, targets=targets, block=block)
723
727
724 def queue_status(self, targets=None, block=None):
728 def queue_status(self, targets=None, block=None):
725 """
729 """
726 Get the status of an engines queue.
730 Get the status of an engines queue.
727
731
728 :Parameters:
732 :Parameters:
729 targets : id or list of ids
733 targets : id or list of ids
730 The engine to use for the execution
734 The engine to use for the execution
731 block : boolean
735 block : boolean
732 If False, this method will return the actual result. If False,
736 If False, this method will return the actual result. If False,
733 a `PendingResult` is returned which can be used to get the result
737 a `PendingResult` is returned which can be used to get the result
734 at a later time.
738 at a later time.
735 """
739 """
736 targets, block = self._findTargetsAndBlock(targets, block)
740 targets, block = self._findTargetsAndBlock(targets, block)
737 return self._blockFromThread(self.smultiengine.queue_status, targets=targets, block=block)
741 return self._blockFromThread(self.smultiengine.queue_status, targets=targets, block=block)
738
742
739 def set_properties(self, properties, targets=None, block=None):
743 def set_properties(self, properties, targets=None, block=None):
740 warnings.warn(_prop_warn)
744 warnings.warn(_prop_warn)
741 targets, block = self._findTargetsAndBlock(targets, block)
745 targets, block = self._findTargetsAndBlock(targets, block)
742 return self._blockFromThread(self.smultiengine.set_properties, properties, targets=targets, block=block)
746 return self._blockFromThread(self.smultiengine.set_properties, properties, targets=targets, block=block)
743
747
744 def get_properties(self, keys=None, targets=None, block=None):
748 def get_properties(self, keys=None, targets=None, block=None):
745 warnings.warn(_prop_warn)
749 warnings.warn(_prop_warn)
746 targets, block = self._findTargetsAndBlock(targets, block)
750 targets, block = self._findTargetsAndBlock(targets, block)
747 return self._blockFromThread(self.smultiengine.get_properties, keys, targets=targets, block=block)
751 return self._blockFromThread(self.smultiengine.get_properties, keys, targets=targets, block=block)
748
752
749 def has_properties(self, keys, targets=None, block=None):
753 def has_properties(self, keys, targets=None, block=None):
750 warnings.warn(_prop_warn)
754 warnings.warn(_prop_warn)
751 targets, block = self._findTargetsAndBlock(targets, block)
755 targets, block = self._findTargetsAndBlock(targets, block)
752 return self._blockFromThread(self.smultiengine.has_properties, keys, targets=targets, block=block)
756 return self._blockFromThread(self.smultiengine.has_properties, keys, targets=targets, block=block)
753
757
754 def del_properties(self, keys, targets=None, block=None):
758 def del_properties(self, keys, targets=None, block=None):
755 warnings.warn(_prop_warn)
759 warnings.warn(_prop_warn)
756 targets, block = self._findTargetsAndBlock(targets, block)
760 targets, block = self._findTargetsAndBlock(targets, block)
757 return self._blockFromThread(self.smultiengine.del_properties, keys, targets=targets, block=block)
761 return self._blockFromThread(self.smultiengine.del_properties, keys, targets=targets, block=block)
758
762
759 def clear_properties(self, targets=None, block=None):
763 def clear_properties(self, targets=None, block=None):
760 warnings.warn(_prop_warn)
764 warnings.warn(_prop_warn)
761 targets, block = self._findTargetsAndBlock(targets, block)
765 targets, block = self._findTargetsAndBlock(targets, block)
762 return self._blockFromThread(self.smultiengine.clear_properties, targets=targets, block=block)
766 return self._blockFromThread(self.smultiengine.clear_properties, targets=targets, block=block)
763
767
764 #---------------------------------------------------------------------------
768 #---------------------------------------------------------------------------
765 # IMultiEngine related methods
769 # IMultiEngine related methods
766 #---------------------------------------------------------------------------
770 #---------------------------------------------------------------------------
767
771
768 def get_ids(self):
772 def get_ids(self):
769 """
773 """
770 Returns the ids of currently registered engines.
774 Returns the ids of currently registered engines.
771 """
775 """
772 result = blockingCallFromThread(self.smultiengine.get_ids)
776 result = blockingCallFromThread(self.smultiengine.get_ids)
773 return result
777 return result
774
778
775 #---------------------------------------------------------------------------
779 #---------------------------------------------------------------------------
776 # IMultiEngineCoordinator
780 # IMultiEngineCoordinator
777 #---------------------------------------------------------------------------
781 #---------------------------------------------------------------------------
778
782
779 def scatter(self, key, seq, dist='b', flatten=False, targets=None, block=None):
783 def scatter(self, key, seq, dist='b', flatten=False, targets=None, block=None):
780 """
784 """
781 Partition a Python sequence and send the partitions to a set of engines.
785 Partition a Python sequence and send the partitions to a set of engines.
782 """
786 """
783 targets, block = self._findTargetsAndBlock(targets, block)
787 targets, block = self._findTargetsAndBlock(targets, block)
784 return self._blockFromThread(self.smultiengine.scatter, key, seq,
788 return self._blockFromThread(self.smultiengine.scatter, key, seq,
785 dist, flatten, targets=targets, block=block)
789 dist, flatten, targets=targets, block=block)
786
790
787 def gather(self, key, dist='b', targets=None, block=None):
791 def gather(self, key, dist='b', targets=None, block=None):
788 """
792 """
789 Gather a partitioned sequence on a set of engines as a single local seq.
793 Gather a partitioned sequence on a set of engines as a single local seq.
790 """
794 """
791 targets, block = self._findTargetsAndBlock(targets, block)
795 targets, block = self._findTargetsAndBlock(targets, block)
792 return self._blockFromThread(self.smultiengine.gather, key, dist,
796 return self._blockFromThread(self.smultiengine.gather, key, dist,
793 targets=targets, block=block)
797 targets=targets, block=block)
794
798
795 def raw_map(self, func, seq, dist='b', targets=None, block=None):
799 def raw_map(self, func, seq, dist='b', targets=None, block=None):
796 """
800 """
797 A parallelized version of Python's builtin map.
801 A parallelized version of Python's builtin map.
798
802
799 This has a slightly different syntax than the builtin `map`.
803 This has a slightly different syntax than the builtin `map`.
800 This is needed because we need to have keyword arguments and thus
804 This is needed because we need to have keyword arguments and thus
801 can't use *args to capture all the sequences. Instead, they must
805 can't use *args to capture all the sequences. Instead, they must
802 be passed in a list or tuple.
806 be passed in a list or tuple.
803
807
804 raw_map(func, seqs) -> map(func, seqs[0], seqs[1], ...)
808 raw_map(func, seqs) -> map(func, seqs[0], seqs[1], ...)
805
809
806 Most users will want to use parallel functions or the `mapper`
810 Most users will want to use parallel functions or the `mapper`
807 and `map` methods for an API that follows that of the builtin
811 and `map` methods for an API that follows that of the builtin
808 `map`.
812 `map`.
809 """
813 """
810 targets, block = self._findTargetsAndBlock(targets, block)
814 targets, block = self._findTargetsAndBlock(targets, block)
811 return self._blockFromThread(self.smultiengine.raw_map, func, seq,
815 return self._blockFromThread(self.smultiengine.raw_map, func, seq,
812 dist, targets=targets, block=block)
816 dist, targets=targets, block=block)
813
817
814 def map(self, func, *sequences):
818 def map(self, func, *sequences):
815 """
819 """
816 A parallel version of Python's builtin `map` function.
820 A parallel version of Python's builtin `map` function.
817
821
818 This method applies a function to sequences of arguments. It
822 This method applies a function to sequences of arguments. It
819 follows the same syntax as the builtin `map`.
823 follows the same syntax as the builtin `map`.
820
824
821 This method creates a mapper objects by calling `self.mapper` with
825 This method creates a mapper objects by calling `self.mapper` with
822 no arguments and then uses that mapper to do the mapping. See
826 no arguments and then uses that mapper to do the mapping. See
823 the documentation of `mapper` for more details.
827 the documentation of `mapper` for more details.
824 """
828 """
825 return self.mapper().map(func, *sequences)
829 return self.mapper().map(func, *sequences)
826
830
827 def mapper(self, dist='b', targets='all', block=None):
831 def mapper(self, dist='b', targets='all', block=None):
828 """
832 """
829 Create a mapper object that has a `map` method.
833 Create a mapper object that has a `map` method.
830
834
831 This method returns an object that implements the `IMapper`
835 This method returns an object that implements the `IMapper`
832 interface. This method is a factory that is used to control how
836 interface. This method is a factory that is used to control how
833 the map happens.
837 the map happens.
834
838
835 :Parameters:
839 :Parameters:
836 dist : str
840 dist : str
837 What decomposition to use, 'b' is the only one supported
841 What decomposition to use, 'b' is the only one supported
838 currently
842 currently
839 targets : str, int, sequence of ints
843 targets : str, int, sequence of ints
840 Which engines to use for the map
844 Which engines to use for the map
841 block : boolean
845 block : boolean
842 Should calls to `map` block or not
846 Should calls to `map` block or not
843 """
847 """
844 return MultiEngineMapper(self, dist, targets, block)
848 return MultiEngineMapper(self, dist, targets, block)
845
849
846 def parallel(self, dist='b', targets=None, block=None):
850 def parallel(self, dist='b', targets=None, block=None):
847 """
851 """
848 A decorator that turns a function into a parallel function.
852 A decorator that turns a function into a parallel function.
849
853
850 This can be used as:
854 This can be used as:
851
855
852 @parallel()
856 @parallel()
853 def f(x, y)
857 def f(x, y)
854 ...
858 ...
855
859
856 f(range(10), range(10))
860 f(range(10), range(10))
857
861
858 This causes f(0,0), f(1,1), ... to be called in parallel.
862 This causes f(0,0), f(1,1), ... to be called in parallel.
859
863
860 :Parameters:
864 :Parameters:
861 dist : str
865 dist : str
862 What decomposition to use, 'b' is the only one supported
866 What decomposition to use, 'b' is the only one supported
863 currently
867 currently
864 targets : str, int, sequence of ints
868 targets : str, int, sequence of ints
865 Which engines to use for the map
869 Which engines to use for the map
866 block : boolean
870 block : boolean
867 Should calls to `map` block or not
871 Should calls to `map` block or not
868 """
872 """
869 targets, block = self._findTargetsAndBlock(targets, block)
873 targets, block = self._findTargetsAndBlock(targets, block)
870 mapper = self.mapper(dist, targets, block)
874 mapper = self.mapper(dist, targets, block)
871 pf = ParallelFunction(mapper)
875 pf = ParallelFunction(mapper)
872 return pf
876 return pf
873
877
874 #---------------------------------------------------------------------------
878 #---------------------------------------------------------------------------
875 # IMultiEngineExtras
879 # IMultiEngineExtras
876 #---------------------------------------------------------------------------
880 #---------------------------------------------------------------------------
877
881
878 def zip_pull(self, keys, targets=None, block=None):
882 def zip_pull(self, keys, targets=None, block=None):
879 targets, block = self._findTargetsAndBlock(targets, block)
883 targets, block = self._findTargetsAndBlock(targets, block)
880 return self._blockFromThread(self.smultiengine.zip_pull, keys,
884 return self._blockFromThread(self.smultiengine.zip_pull, keys,
881 targets=targets, block=block)
885 targets=targets, block=block)
882
886
883 def run(self, filename, targets=None, block=None):
887 def run(self, filename, targets=None, block=None):
884 """
888 """
885 Run a Python code in a file on the engines.
889 Run a Python code in a file on the engines.
886
890
887 :Parameters:
891 :Parameters:
888 filename : str
892 filename : str
889 The name of the local file to run
893 The name of the local file to run
890 targets : id or list of ids
894 targets : id or list of ids
891 The engine to use for the execution
895 The engine to use for the execution
892 block : boolean
896 block : boolean
893 If False, this method will return the actual result. If False,
897 If False, this method will return the actual result. If False,
894 a `PendingResult` is returned which can be used to get the result
898 a `PendingResult` is returned which can be used to get the result
895 at a later time.
899 at a later time.
896 """
900 """
897 targets, block = self._findTargetsAndBlock(targets, block)
901 targets, block = self._findTargetsAndBlock(targets, block)
898 return self._blockFromThread(self.smultiengine.run, filename,
902 return self._blockFromThread(self.smultiengine.run, filename,
899 targets=targets, block=block)
903 targets=targets, block=block)
900
904
901 def benchmark(self, push_size=10000):
905 def benchmark(self, push_size=10000):
902 """
906 """
903 Run performance benchmarks for the current IPython cluster.
907 Run performance benchmarks for the current IPython cluster.
904
908
905 This method tests both the latency of sending command and data to the
909 This method tests both the latency of sending command and data to the
906 engines as well as the throughput of sending large objects to the
910 engines as well as the throughput of sending large objects to the
907 engines using push. The latency is measured by having one or more
911 engines using push. The latency is measured by having one or more
908 engines execute the command 'pass'. The throughput is measure by
912 engines execute the command 'pass'. The throughput is measure by
909 sending an NumPy array of size `push_size` to one or more engines.
913 sending an NumPy array of size `push_size` to one or more engines.
910
914
911 These benchmarks will vary widely on different hardware and networks
915 These benchmarks will vary widely on different hardware and networks
912 and thus can be used to get an idea of the performance characteristics
916 and thus can be used to get an idea of the performance characteristics
913 of a particular configuration of an IPython controller and engines.
917 of a particular configuration of an IPython controller and engines.
914
918
915 This function is not testable within our current testing framework.
919 This function is not testable within our current testing framework.
916 """
920 """
917 import timeit, __builtin__
921 import timeit, __builtin__
918 __builtin__._mec_self = self
922 __builtin__._mec_self = self
919 benchmarks = {}
923 benchmarks = {}
920 repeat = 3
924 repeat = 3
921 count = 10
925 count = 10
922
926
923 timer = timeit.Timer('_mec_self.execute("pass",0)')
927 timer = timeit.Timer('_mec_self.execute("pass",0)')
924 result = 1000*min(timer.repeat(repeat,count))/count
928 result = 1000*min(timer.repeat(repeat,count))/count
925 benchmarks['single_engine_latency'] = (result,'msec')
929 benchmarks['single_engine_latency'] = (result,'msec')
926
930
927 timer = timeit.Timer('_mec_self.execute("pass")')
931 timer = timeit.Timer('_mec_self.execute("pass")')
928 result = 1000*min(timer.repeat(repeat,count))/count
932 result = 1000*min(timer.repeat(repeat,count))/count
929 benchmarks['all_engine_latency'] = (result,'msec')
933 benchmarks['all_engine_latency'] = (result,'msec')
930
934
931 try:
935 try:
932 import numpy as np
936 import numpy as np
933 except:
937 except:
934 pass
938 pass
935 else:
939 else:
936 timer = timeit.Timer(
940 timer = timeit.Timer(
937 "_mec_self.push(d)",
941 "_mec_self.push(d)",
938 "import numpy as np; d = dict(a=np.zeros(%r,dtype='float64'))" % push_size
942 "import numpy as np; d = dict(a=np.zeros(%r,dtype='float64'))" % push_size
939 )
943 )
940 result = min(timer.repeat(repeat,count))/count
944 result = min(timer.repeat(repeat,count))/count
941 benchmarks['all_engine_push'] = (1e-6*push_size*8/result, 'MB/sec')
945 benchmarks['all_engine_push'] = (1e-6*push_size*8/result, 'MB/sec')
942
946
943 try:
947 try:
944 import numpy as np
948 import numpy as np
945 except:
949 except:
946 pass
950 pass
947 else:
951 else:
948 timer = timeit.Timer(
952 timer = timeit.Timer(
949 "_mec_self.push(d,0)",
953 "_mec_self.push(d,0)",
950 "import numpy as np; d = dict(a=np.zeros(%r,dtype='float64'))" % push_size
954 "import numpy as np; d = dict(a=np.zeros(%r,dtype='float64'))" % push_size
951 )
955 )
952 result = min(timer.repeat(repeat,count))/count
956 result = min(timer.repeat(repeat,count))/count
953 benchmarks['single_engine_push'] = (1e-6*push_size*8/result, 'MB/sec')
957 benchmarks['single_engine_push'] = (1e-6*push_size*8/result, 'MB/sec')
954
958
955 return benchmarks
959 return benchmarks
956
960
957
961
958 components.registerAdapter(FullBlockingMultiEngineClient,
962 components.registerAdapter(FullBlockingMultiEngineClient,
959 IFullSynchronousMultiEngine, IFullBlockingMultiEngineClient)
963 IFullSynchronousMultiEngine, IFullBlockingMultiEngineClient)
960
964
961
965
962
966
963
967
General Comments 0
You need to be logged in to leave comments. Login now