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