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