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