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