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