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