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