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