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