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