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