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