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