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