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