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