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