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