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