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