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