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