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