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